compatibility with 0.6 protocol
[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 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
38         self.verified_tx     = config.get('verified_tx',{})       # height of verified tx
39         self.merkle_roots    = config.get('merkle_roots',{})      # hashed by me
40         
41         self.targets         = config.get('targets',{})           # compute targets
42         self.lock = threading.Lock()
43         self.pending_headers = [] # headers that have not been verified
44         self.height = 0
45         self.local_height = 0
46         self.init_headers_file()
47         self.set_local_height()
48
49     def get_confirmations(self, tx):
50         """ return the number of confirmations of a monitored transaction. """
51         with self.lock:
52             if tx in self.transactions.keys():
53                 return (self.local_height - self.verified_tx[tx] + 1) if tx in self.verified_tx else 0
54             else:
55                 return 0
56
57     def add(self, tx_hash, tx_height):
58         """ add a transaction to the list of monitored transactions. """
59         with self.lock:
60             if tx_hash not in self.transactions.keys():
61                 self.transactions[tx_hash] = tx_height
62
63     def run(self):
64         requested_merkle = []
65         requested_chunks = []
66         requested_headers = []
67         all_chunks = False
68         
69         # subscribe to block headers
70         self.interface.send([ ('blockchain.headers.subscribe',[])], 'verifier')
71
72         while True:
73             # request missing chunks
74             if not all_chunks and self.height and not requested_chunks:
75
76                 if self.local_height + 50 < self.height:
77                     min_index = (self.local_height + 1)/2016
78                     max_index = (self.height + 1)/2016
79                     for i in range(min_index, max_index + 1):
80                         print_error( "requesting chunk", i )
81                         self.interface.send([ ('blockchain.block.get_chunk',[i])], 'verifier')
82                         requested_chunks.append(i)
83                         break
84                 else:
85                     all_chunks = True
86                     print_error("downloaded all chunks")
87
88             # request missing tx
89             if all_chunks:
90                 for tx_hash, tx_height in self.transactions.items():
91                     if tx_hash not in self.verified_tx:
92                         if self.merkle_roots.get(tx_hash) is None and tx_hash not in requested_merkle:
93                             print_error('requesting merkle', tx_hash)
94                             self.interface.send([ ('blockchain.transaction.get_merkle',[tx_hash, tx_height]) ], 'verifier')
95                             requested_merkle.append(tx_hash)
96
97             # process pending headers
98             if self.pending_headers and all_chunks:
99                 done = []
100                 for header in self.pending_headers:
101                     if self.verify_header(header):
102                         done.append(header)
103                     else:
104                         # request previous header
105                         i = header.get('block_height') - 1
106                         if i not in requested_headers:
107                             print_error("requesting header %d"%i)
108                             self.interface.send([ ('blockchain.block.get_header',[i])], 'verifier')
109                             requested_headers.append(i)
110                         # no point continuing
111                         break
112                 if done:
113                     self.interface.trigger_callback('updated')
114                     for header in done: 
115                         self.pending_headers.remove(header)
116
117             try:
118                 r = self.interface.get_response('verifier',timeout=1)
119             except Queue.Empty:
120                 time.sleep(1)
121                 continue
122
123             # 3. handle response
124             method = r['method']
125             params = r['params']
126             result = r['result']
127
128             if method == 'blockchain.transaction.get_merkle':
129                 tx_hash = params[0]
130                 self.verify_merkle(tx_hash, result)
131                 requested_merkle.remove(tx_hash)
132
133             elif method == 'blockchain.block.get_chunk':
134                 index = params[0]
135                 self.verify_chunk(index, result)
136                 requested_chunks.remove(index)
137
138             elif method in ['blockchain.headers.subscribe', 'blockchain.block.get_header']:
139
140                 self.pending_headers.append(result)
141                 if method == 'blockchain.block.get_header':
142                     requested_headers.remove(result.get('block_height'))
143                 else:
144                     self.height = result.get('block_height')
145                 
146                 self.pending_headers.sort(key=lambda x: x.get('block_height'))
147                 # print "pending headers", map(lambda x: x.get('block_height'), self.pending_headers)
148
149
150
151     def verify_merkle(self, tx_hash, result):
152         tx_height = result.get('block_height')
153         self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash, result.get('pos'))
154         header = self.read_header(tx_height)
155         if not header: return
156         assert header.get('merkle_root') == self.merkle_roots[tx_hash]
157         # we passed all the tests
158         self.verified_tx[tx_hash] = tx_height
159         print_error("verified %s"%tx_hash)
160         self.config.set_key('verified_tx', self.verified_tx, True)
161         self.interface.trigger_callback('updated')
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_error("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 init_headers_file(self):
268         filename = self.path()
269         if os.path.exists(filename):
270             return
271         src = os.path.join(appdata_dir(), 'blockchain_headers')
272         if os.path.exists(src):
273             # copy it from appdata dir
274             print_error( "copying headers to", filename )
275             shutil.copy(src, filename)
276         else:
277             print_error( "creating headers file", filename )
278             open(filename,'wb+').close()
279
280     def save_chunk(self, index, chunk):
281         filename = self.path()
282         f = open(filename,'rb+')
283         f.seek(index*2016*80)
284         h = f.write(chunk)
285         f.close()
286         self.set_local_height()
287
288     def save_header(self, header):
289         data = self.header_to_string(header).decode('hex')
290         assert len(data) == 80
291         height = header.get('block_height')
292         filename = self.path()
293         f = open(filename,'rb+')
294         f.seek(height*80)
295         h = f.write(data)
296         f.close()
297         self.set_local_height()
298
299
300     def set_local_height(self):
301         name = self.path()
302         if os.path.exists(name):
303             h = os.path.getsize(name)/80 - 1
304             if self.local_height != h:
305                 self.local_height = h
306
307
308     def read_header(self, block_height):
309         name = self.path()
310         if os.path.exists(name):
311             f = open(name,'rb')
312             f.seek(block_height*80)
313             h = f.read(80)
314             f.close()
315             if len(h) == 80:
316                 h = self.header_from_string(h)
317                 return h 
318
319
320     def get_target(self, index):
321
322         max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
323         if index == 0: return 0x1d00ffff, max_target
324
325         first = self.read_header((index-1)*2016)
326         last = self.read_header(index*2016-1)
327         
328         nActualTimespan = last.get('timestamp') - first.get('timestamp')
329         nTargetTimespan = 14*24*60*60
330         nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
331         nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
332
333         bits = last.get('bits') 
334         # convert to bignum
335         MM = 256*256*256
336         a = bits%MM
337         if a < 0x8000:
338             a *= 256
339         target = (a) * pow(2, 8 * (bits/MM - 3))
340
341         # new target
342         new_target = min( max_target, (target * nActualTimespan)/nTargetTimespan )
343         
344         # convert it to bits
345         c = ("%064X"%new_target)[2:]
346         i = 31
347         while c[0:2]=="00":
348             c = c[2:]
349             i -= 1
350
351         c = eval('0x'+c[0:6])
352         if c > 0x800000: 
353             c /= 256
354             i += 1
355
356         new_bits = c + MM * i
357         return new_bits, new_target
358
359     def get_timestamp(self, tx_height):
360         if tx_height>0:
361             header = self.read_header(tx_height)
362             timestamp = header.get('timestamp') if header else 0
363         else:
364             timestamp = 1e12
365         return timestamp
366