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