3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2012 thomasv@ecdsa.org
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.
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.
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/>.
20 import threading, time, Queue, os, sys, shutil
21 from util import user_dir, appdata_dir, print_error
27 class WalletVerifier(threading.Thread):
28 """ Simple Payment Verification """
30 def __init__(self, interface, config):
31 threading.Thread.__init__(self)
34 self.interface = interface
35 self.transactions = {} # requested verifications (with height sent by the requestor)
36 self.interface.register_channel('verifier')
38 self.verified_tx = config.get('verified_tx2',{}) # height, timestamp of verified transactions
39 self.merkle_roots = config.get('merkle_roots',{}) # hashed by me
41 self.targets = config.get('targets',{}) # compute targets
42 self.lock = threading.Lock()
43 self.pending_headers = [] # headers that have not been verified
46 self.init_headers_file()
47 self.set_local_height()
50 def get_confirmations(self, tx):
51 """ return the number of confirmations of a monitored transaction. """
53 if tx in self.transactions.keys():
54 if tx in self.verified_tx:
55 height, timestamp = self.verified_tx[tx]
56 conf = (self.local_height - height + 1)
60 #print "verifier: tx not in list", tx
66 return conf, timestamp
69 def add(self, tx_hash, tx_height):
70 """ add a transaction to the list of monitored transactions. """
73 if tx_hash not in self.transactions.keys():
74 self.transactions[tx_hash] = tx_height
77 with self.lock: self.running = False
78 self.interface.poke('verifier')
81 with self.lock: return self.running
88 requested_headers = []
91 # subscribe to block headers
92 self.interface.send([ ('blockchain.headers.subscribe',[])], 'verifier')
94 while self.is_running():
95 # request missing chunks
96 if not all_chunks and self.height and not requested_chunks:
98 if self.local_height + 50 < self.height:
99 min_index = (self.local_height + 1)/2016
100 max_index = (self.height + 1)/2016
101 for i in range(min_index, max_index + 1):
102 print_error( "requesting chunk", i )
103 self.interface.send([ ('blockchain.block.get_chunk',[i])], 'verifier')
104 requested_chunks.append(i)
108 print_error("downloaded all chunks")
112 for tx_hash, tx_height in self.transactions.items():
113 if tx_hash not in self.verified_tx:
114 if self.merkle_roots.get(tx_hash) is None and tx_hash not in requested_merkle:
115 print_error('requesting merkle', tx_hash)
116 self.interface.send([ ('blockchain.transaction.get_merkle',[tx_hash, tx_height]) ], 'verifier')
117 requested_merkle.append(tx_hash)
119 # process pending headers
120 if self.pending_headers and all_chunks:
122 for header in self.pending_headers:
123 if self.verify_header(header):
126 # request previous header
127 i = header.get('block_height') - 1
128 if i not in requested_headers:
129 print_error("requesting header %d"%i)
130 self.interface.send([ ('blockchain.block.get_header',[i])], 'verifier')
131 requested_headers.append(i)
132 # no point continuing
135 self.interface.trigger_callback('updated')
137 self.pending_headers.remove(header)
140 r = self.interface.get_response('verifier',timeout=1)
150 if method == 'blockchain.transaction.get_merkle':
152 self.verify_merkle(tx_hash, result)
153 requested_merkle.remove(tx_hash)
155 elif method == 'blockchain.block.get_chunk':
157 self.verify_chunk(index, result)
158 requested_chunks.remove(index)
160 elif method in ['blockchain.headers.subscribe', 'blockchain.block.get_header']:
162 self.pending_headers.append(result)
163 if method == 'blockchain.block.get_header':
164 requested_headers.remove(result.get('block_height'))
166 self.height = result.get('block_height')
168 self.pending_headers.sort(key=lambda x: x.get('block_height'))
169 # print "pending headers", map(lambda x: x.get('block_height'), self.pending_headers)
173 def verify_merkle(self, tx_hash, result):
174 tx_height = result.get('block_height')
175 self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash, result.get('pos'))
176 header = self.read_header(tx_height)
177 if not header: return
178 assert header.get('merkle_root') == self.merkle_roots[tx_hash]
179 # we passed all the tests
180 header = self.read_header(tx_height)
181 timestamp = header.get('timestamp')
182 self.verified_tx[tx_hash] = (tx_height, timestamp)
183 print_error("verified %s"%tx_hash)
184 self.config.set_key('verified_tx2', self.verified_tx, True)
185 self.interface.trigger_callback('updated')
188 def verify_chunk(self, index, hexdata):
189 data = hexdata.decode('hex')
192 print_error("validating headers %d"%height)
195 previous_hash = ("0"*64)
197 prev_header = self.read_header(index*2016-1)
198 if prev_header is None: raise
199 previous_hash = self.hash_header(prev_header)
201 bits, target = self.get_target(index)
204 height = index*2016 + i
205 raw_header = data[i*80:(i+1)*80]
206 header = self.header_from_string(raw_header)
207 _hash = self.hash_header(header)
208 assert previous_hash == header.get('prev_block_hash')
209 assert bits == header.get('bits')
210 assert eval('0x'+_hash) < target
212 previous_header = header
213 previous_hash = _hash
215 self.save_chunk(index, data)
218 def verify_header(self, header):
219 # add header to the blockchain file
220 # if there is a reorg, push it in a stack
222 height = header.get('block_height')
224 prev_header = self.read_header(height -1)
226 # return False to request previous header
229 prev_hash = self.hash_header(prev_header)
230 bits, target = self.get_target(height/2016)
231 _hash = self.hash_header(header)
233 assert prev_hash == header.get('prev_block_hash')
234 assert bits == header.get('bits')
235 assert eval('0x'+_hash) < target
237 # this can be caused by a reorg.
238 print_error("verify header failed"+ repr(header))
240 for tx_hash, item in self.verified_tx.items():
241 tx_height, timestamp = item
242 if tx_height >= height:
243 print_error("redoing", tx_hash)
244 self.verified_tx.pop(tx_hash)
245 if tx_hash in self.merkle_roots: self.merkle_roots.pop(tx_hash)
246 # return False to request previous header.
249 self.save_header(header)
250 print_error("verify header:", _hash, height)
256 def header_to_string(self, res):
257 s = int_to_hex(res.get('version'),4) \
258 + rev_hex(res.get('prev_block_hash')) \
259 + rev_hex(res.get('merkle_root')) \
260 + int_to_hex(int(res.get('timestamp')),4) \
261 + int_to_hex(int(res.get('bits')),4) \
262 + int_to_hex(int(res.get('nonce')),4)
266 def header_from_string(self, s):
267 hex_to_int = lambda s: eval('0x' + s[::-1].encode('hex'))
269 h['version'] = hex_to_int(s[0:4])
270 h['prev_block_hash'] = hash_encode(s[4:36])
271 h['merkle_root'] = hash_encode(s[36:68])
272 h['timestamp'] = hex_to_int(s[68:72])
273 h['bits'] = hex_to_int(s[72:76])
274 h['nonce'] = hex_to_int(s[76:80])
277 def hash_header(self, header):
278 return rev_hex(Hash(self.header_to_string(header).decode('hex')).encode('hex'))
280 def hash_merkle_root(self, merkle_s, target_hash, pos):
281 h = hash_decode(target_hash)
282 for i in range(len(merkle_s)):
284 h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
285 return hash_encode(h)
288 wdir = self.config.get('blockchain_headers_path', user_dir())
289 if not os.path.exists( wdir ): os.mkdir(wdir)
290 return os.path.join( wdir, 'blockchain_headers')
292 def init_headers_file(self):
293 filename = self.path()
294 if os.path.exists(filename):
296 src = os.path.join(appdata_dir(), 'blockchain_headers')
297 if os.path.exists(src):
298 # copy it from appdata dir
299 print_error( "copying headers to", filename )
300 shutil.copy(src, filename)
302 print_error( "creating headers file", filename )
303 open(filename,'wb+').close()
305 def save_chunk(self, index, chunk):
306 filename = self.path()
307 f = open(filename,'rb+')
308 f.seek(index*2016*80)
311 self.set_local_height()
313 def save_header(self, header):
314 data = self.header_to_string(header).decode('hex')
315 assert len(data) == 80
316 height = header.get('block_height')
317 filename = self.path()
318 f = open(filename,'rb+')
322 self.set_local_height()
325 def set_local_height(self):
327 if os.path.exists(name):
328 h = os.path.getsize(name)/80 - 1
329 if self.local_height != h:
330 self.local_height = h
333 def read_header(self, block_height):
335 if os.path.exists(name):
337 f.seek(block_height*80)
341 h = self.header_from_string(h)
345 def get_target(self, index):
347 max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
348 if index == 0: return 0x1d00ffff, max_target
350 first = self.read_header((index-1)*2016)
351 last = self.read_header(index*2016-1)
353 nActualTimespan = last.get('timestamp') - first.get('timestamp')
354 nTargetTimespan = 14*24*60*60
355 nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
356 nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
358 bits = last.get('bits')
364 target = (a) * pow(2, 8 * (bits/MM - 3))
367 new_target = min( max_target, (target * nActualTimespan)/nTargetTimespan )
370 c = ("%064X"%new_target)[2:]
376 c = eval('0x'+c[0:6])
381 new_bits = c + MM * i
382 return new_bits, new_target