ac5ea1489a00cf6f3b4fdb2db9f568788612bfaa
[electrum-nvc.git] / lib / blockchain.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 class Blockchain(threading.Thread):
26
27     def __init__(self, config, network):
28         threading.Thread.__init__(self)
29         self.daemon = True
30         self.config = config
31         self.network = network
32         self.lock = threading.Lock()
33         self.local_height = 0
34         self.running = False
35         self.headers_url = 'http://headers.electrum.org/blockchain_headers'
36         self.set_local_height()
37         self.queue = Queue.Queue()
38
39     
40     def height(self):
41         return self.local_height
42
43
44     def stop(self):
45         with self.lock: self.running = False
46
47
48     def is_running(self):
49         with self.lock: return self.running
50
51
52     def run(self):
53         self.init_headers_file()
54         self.set_local_height()
55         print_error( "blocks:", self.local_height )
56
57         with self.lock:
58             self.running = True
59
60         while self.is_running():
61
62             try:
63                 result = self.queue.get()
64             except Queue.Empty:
65                 continue
66
67             if not result: continue
68
69             i, header = result
70             if not header: continue
71             
72             height = header.get('block_height')
73
74             if height <= self.local_height:
75                 continue
76
77             if height > self.local_height + 50:
78                 if not self.get_and_verify_chunks(i, header, height):
79                     continue
80
81             if height > self.local_height:
82                 # get missing parts from interface (until it connects to my chain)
83                 chain = self.get_chain( i, header )
84
85                 # skip that server if the result is not consistent
86                 if not chain: 
87                     print_error('e')
88                     continue
89                 
90                 # verify the chain
91                 if self.verify_chain( chain ):
92                     print_error("height:", height, i.server)
93                     for header in chain:
94                         self.save_header(header)
95                 else:
96                     print_error("error", i.server)
97                     # todo: dismiss that server
98                     continue
99
100
101             self.network.new_blockchain_height(height, i)
102
103
104                     
105             
106     def verify_chain(self, chain):
107
108         first_header = chain[0]
109         prev_header = self.read_header(first_header.get('block_height') -1)
110         
111         for header in chain:
112
113             height = header.get('block_height')
114
115             prev_hash = self.hash_header(prev_header)
116             bits, target = self.get_target(height/2016, chain)
117             _hash = self.hash_header(header)
118             try:
119                 assert prev_hash == header.get('prev_block_hash')
120                 assert bits == header.get('bits')
121                 assert int('0x'+_hash,16) < target
122             except Exception:
123                 return False
124
125             prev_header = header
126
127         return True
128
129
130
131     def verify_chunk(self, index, hexdata):
132         data = hexdata.decode('hex')
133         height = index*2016
134         num = len(data)/80
135
136         if index == 0:  
137             previous_hash = ("0"*64)
138         else:
139             prev_header = self.read_header(index*2016-1)
140             if prev_header is None: raise
141             previous_hash = self.hash_header(prev_header)
142
143         bits, target = self.get_target(index)
144
145         for i in range(num):
146             height = index*2016 + i
147             raw_header = data[i*80:(i+1)*80]
148             header = self.header_from_string(raw_header)
149             _hash = self.hash_header(header)
150             assert previous_hash == header.get('prev_block_hash')
151             assert bits == header.get('bits')
152             assert int('0x'+_hash,16) < target
153
154             previous_header = header
155             previous_hash = _hash 
156
157         self.save_chunk(index, data)
158         print_error("validated chunk %d"%height)
159
160         
161
162     def header_to_string(self, res):
163         s = int_to_hex(res.get('version'),4) \
164             + rev_hex(res.get('prev_block_hash')) \
165             + rev_hex(res.get('merkle_root')) \
166             + int_to_hex(int(res.get('timestamp')),4) \
167             + int_to_hex(int(res.get('bits')),4) \
168             + int_to_hex(int(res.get('nonce')),4)
169         return s
170
171
172     def header_from_string(self, s):
173         hex_to_int = lambda s: int('0x' + s[::-1].encode('hex'), 16)
174         h = {}
175         h['version'] = hex_to_int(s[0:4])
176         h['prev_block_hash'] = hash_encode(s[4:36])
177         h['merkle_root'] = hash_encode(s[36:68])
178         h['timestamp'] = hex_to_int(s[68:72])
179         h['bits'] = hex_to_int(s[72:76])
180         h['nonce'] = hex_to_int(s[76:80])
181         return h
182
183     def hash_header(self, header):
184         return rev_hex(Hash(self.header_to_string(header).decode('hex')).encode('hex'))
185
186     def path(self):
187         return os.path.join( self.config.path, 'blockchain_headers')
188
189     def init_headers_file(self):
190         filename = self.path()
191         if os.path.exists(filename):
192             return
193         
194         try:
195             import urllib, socket
196             socket.setdefaulttimeout(30)
197             print_error("downloading ", self.headers_url )
198             urllib.urlretrieve(self.headers_url, filename)
199             print_error("done.")
200         except Exception:
201             print_error( "download failed. creating file", filename )
202             open(filename,'wb+').close()
203
204     def save_chunk(self, index, chunk):
205         filename = self.path()
206         f = open(filename,'rb+')
207         f.seek(index*2016*80)
208         h = f.write(chunk)
209         f.close()
210         self.set_local_height()
211
212     def save_header(self, header):
213         data = self.header_to_string(header).decode('hex')
214         assert len(data) == 80
215         height = header.get('block_height')
216         filename = self.path()
217         f = open(filename,'rb+')
218         f.seek(height*80)
219         h = f.write(data)
220         f.close()
221         self.set_local_height()
222
223
224     def set_local_height(self):
225         name = self.path()
226         if os.path.exists(name):
227             h = os.path.getsize(name)/80 - 1
228             if self.local_height != h:
229                 self.local_height = h
230
231
232     def read_header(self, block_height):
233         name = self.path()
234         if os.path.exists(name):
235             f = open(name,'rb')
236             f.seek(block_height*80)
237             h = f.read(80)
238             f.close()
239             if len(h) == 80:
240                 h = self.header_from_string(h)
241                 return h 
242
243
244     def get_target(self, index, chain=None):
245         if chain is None:
246             chain = []  # Do not use mutables as default values!
247
248         max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
249         if index == 0: return 0x1d00ffff, max_target
250
251         first = self.read_header((index-1)*2016)
252         last = self.read_header(index*2016-1)
253         if last is None:
254             for h in chain:
255                 if h.get('block_height') == index*2016-1:
256                     last = h
257  
258         nActualTimespan = last.get('timestamp') - first.get('timestamp')
259         nTargetTimespan = 14*24*60*60
260         nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
261         nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
262
263         bits = last.get('bits') 
264         # convert to bignum
265         MM = 256*256*256
266         a = bits%MM
267         if a < 0x8000:
268             a *= 256
269         target = (a) * pow(2, 8 * (bits/MM - 3))
270
271         # new target
272         new_target = min( max_target, (target * nActualTimespan)/nTargetTimespan )
273         
274         # convert it to bits
275         c = ("%064X"%new_target)[2:]
276         i = 31
277         while c[0:2]=="00":
278             c = c[2:]
279             i -= 1
280
281         c = int('0x'+c[0:6],16)
282         if c >= 0x800000: 
283             c /= 256
284             i += 1
285
286         new_bits = c + MM * i
287         return new_bits, new_target
288
289
290     def request_header(self, i, h, queue):
291         print_error("requesting header %d from %s"%(h, i.server))
292         i.send([ ('blockchain.block.get_header',[h])], lambda i,r: queue.put((i,r)))
293
294     def retrieve_header(self, i, queue):
295         while True:
296             try:
297                 ir = queue.get(timeout=1)
298             except Queue.Empty:
299                 print_error('timeout')
300                 continue
301
302             if not ir: 
303                 continue
304
305             i, r = ir
306
307             if r.get('error'):
308                 print_error('Verifier received an error:', r)
309                 continue
310
311             # 3. handle response
312             method = r['method']
313             params = r['params']
314             result = r['result']
315
316             if method == 'blockchain.block.get_header':
317                 return result
318                 
319
320
321     def get_chain(self, interface, final_header):
322
323         header = final_header
324         chain = [ final_header ]
325         requested_header = False
326         queue = Queue.Queue()
327
328         while self.is_running():
329
330             if requested_header:
331                 header = self.retrieve_header(interface, queue)
332                 if not header: return
333                 chain = [ header ] + chain
334                 requested_header = False
335
336             height = header.get('block_height')
337             previous_header = self.read_header(height -1)
338             if not previous_header:
339                 self.request_header(interface, height - 1, queue)
340                 requested_header = True
341                 continue
342
343             # verify that it connects to my chain
344             prev_hash = self.hash_header(previous_header)
345             if prev_hash != header.get('prev_block_hash'):
346                 print_error("reorg")
347                 self.request_header(interface, height - 1, queue)
348                 requested_header = True
349                 continue
350
351             else:
352                 # the chain is complete
353                 return chain
354
355
356     def get_and_verify_chunks(self, i, header, height):
357
358         queue = Queue.Queue()
359         min_index = (self.local_height + 1)/2016
360         max_index = (height + 1)/2016
361         n = min_index
362         while n < max_index + 1:
363             print_error( "Requesting chunk:", n )
364             r = i.synchronous_get([ ('blockchain.block.get_chunk',[n])])[0]
365             if not r: 
366                 continue
367             try:
368                 self.verify_chunk(n, r)
369                 n = n + 1
370             except Exception:
371                 print_error('Verify chunk failed!')
372                 n = n - 1
373                 if n < 0:
374                     return False
375
376         return True
377