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_tx3',{}) # 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
47 self.headers_url = 'http://headers.electrum.org/blockchain_headers'
49 def get_confirmations(self, tx):
50 """ return the number of confirmations of a monitored transaction. """
52 if tx in self.verified_tx:
53 height, timestamp, pos = self.verified_tx[tx]
54 conf = (self.local_height - height + 1)
55 if conf <= 0: timestamp = None
57 elif tx in self.transactions:
65 return conf, timestamp
68 def get_txpos(self, tx_hash):
69 "return position, even if the tx is unverified"
71 x = self.verified_tx.get(tx_hash)
72 y = self.transactions.get(tx_hash)
74 height, timestamp, pos = x
82 def get_height(self, tx_hash):
84 v = self.verified_tx.get(tx_hash)
85 height = v[0] if v else None
89 def add(self, tx_hash, tx_height):
90 """ add a transaction to the list of monitored transactions. """
93 if tx_hash not in self.transactions.keys():
94 self.transactions[tx_hash] = tx_height
97 with self.lock: self.running = False
98 self.interface.poke('verifier')
100 def is_running(self):
101 with self.lock: return self.running
105 self.init_headers_file()
106 self.set_local_height()
110 requested_merkle = []
111 requested_chunks = []
112 requested_headers = []
115 # subscribe to block headers
116 self.interface.send([ ('blockchain.headers.subscribe',[])], 'verifier')
118 while self.is_running():
119 # request missing chunks
120 if not all_chunks and self.height and not requested_chunks:
122 if self.local_height + 50 < self.height:
123 min_index = (self.local_height + 1)/2016
124 max_index = (self.height + 1)/2016
125 for i in range(min_index, max_index + 1):
126 print_error( "requesting chunk", i )
127 self.interface.send([ ('blockchain.block.get_chunk',[i])], 'verifier')
128 requested_chunks.append(i)
132 print_error("downloaded all chunks")
136 for tx_hash, tx_height in self.transactions.items():
137 if tx_hash not in self.verified_tx:
138 if self.merkle_roots.get(tx_hash) is None and tx_hash not in requested_merkle:
139 print_error('requesting merkle', tx_hash)
140 self.interface.send([ ('blockchain.transaction.get_merkle',[tx_hash, tx_height]) ], 'verifier')
141 requested_merkle.append(tx_hash)
143 # process pending headers
144 if self.pending_headers and all_chunks:
146 for header in self.pending_headers:
147 if self.verify_header(header):
150 # request previous header
151 i = header.get('block_height') - 1
152 if i not in requested_headers:
153 print_error("requesting header %d"%i)
154 self.interface.send([ ('blockchain.block.get_header',[i])], 'verifier')
155 requested_headers.append(i)
156 # no point continuing
159 self.interface.trigger_callback('updated')
161 self.pending_headers.remove(header)
164 r = self.interface.get_response('verifier',timeout=1)
170 print_error('Verifier received an error:', r)
178 if method == 'blockchain.transaction.get_merkle':
180 self.verify_merkle(tx_hash, result)
181 requested_merkle.remove(tx_hash)
183 elif method == 'blockchain.block.get_chunk':
185 self.verify_chunk(index, result)
186 requested_chunks.remove(index)
188 elif method in ['blockchain.headers.subscribe', 'blockchain.block.get_header']:
190 self.pending_headers.append(result)
191 if method == 'blockchain.block.get_header':
192 requested_headers.remove(result.get('block_height'))
194 self.height = result.get('block_height')
195 self.interface.poke('synchronizer')
197 self.pending_headers.sort(key=lambda x: x.get('block_height'))
198 # print "pending headers", map(lambda x: x.get('block_height'), self.pending_headers)
202 def verify_merkle(self, tx_hash, result):
203 tx_height = result.get('block_height')
204 pos = result.get('pos')
205 self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash, pos)
206 header = self.read_header(tx_height)
207 if not header: return
208 assert header.get('merkle_root') == self.merkle_roots[tx_hash]
209 # we passed all the tests
210 header = self.read_header(tx_height)
211 timestamp = header.get('timestamp')
213 self.verified_tx[tx_hash] = (tx_height, timestamp, pos)
214 print_error("verified %s"%tx_hash)
215 self.config.set_key('verified_tx3', self.verified_tx, True)
216 self.interface.trigger_callback('updated')
219 def verify_chunk(self, index, hexdata):
220 data = hexdata.decode('hex')
223 print_error("validating headers %d"%height)
226 previous_hash = ("0"*64)
228 prev_header = self.read_header(index*2016-1)
229 if prev_header is None: raise
230 previous_hash = self.hash_header(prev_header)
232 bits, target = self.get_target(index)
235 height = index*2016 + i
236 raw_header = data[i*80:(i+1)*80]
237 header = self.header_from_string(raw_header)
238 _hash = self.hash_header(header)
239 assert previous_hash == header.get('prev_block_hash')
240 assert bits == header.get('bits')
241 assert eval('0x'+_hash) < target
243 previous_header = header
244 previous_hash = _hash
246 self.save_chunk(index, data)
249 def verify_header(self, header):
250 # add header to the blockchain file
251 # if there is a reorg, push it in a stack
253 height = header.get('block_height')
255 prev_header = self.read_header(height -1)
257 # return False to request previous header
260 prev_hash = self.hash_header(prev_header)
261 bits, target = self.get_target(height/2016)
262 _hash = self.hash_header(header)
264 assert prev_hash == header.get('prev_block_hash')
265 assert bits == header.get('bits')
266 assert eval('0x'+_hash) < target
268 # this can be caused by a reorg.
269 print_error("verify header failed"+ repr(header))
272 items = self.verified_tx.items()[:]
273 for tx_hash, item in items:
274 tx_height, timestamp, pos = item
275 if tx_height >= height:
276 print_error("redoing", tx_hash)
278 self.verified_tx.pop(tx_hash)
279 if tx_hash in self.merkle_roots:
280 self.merkle_roots.pop(tx_hash)
281 # return False to request previous header.
284 self.save_header(header)
285 print_error("verify header:", _hash, height)
291 def header_to_string(self, res):
292 s = int_to_hex(res.get('version'),4) \
293 + rev_hex(res.get('prev_block_hash')) \
294 + rev_hex(res.get('merkle_root')) \
295 + int_to_hex(int(res.get('timestamp')),4) \
296 + int_to_hex(int(res.get('bits')),4) \
297 + int_to_hex(int(res.get('nonce')),4)
301 def header_from_string(self, s):
302 hex_to_int = lambda s: eval('0x' + s[::-1].encode('hex'))
304 h['version'] = hex_to_int(s[0:4])
305 h['prev_block_hash'] = hash_encode(s[4:36])
306 h['merkle_root'] = hash_encode(s[36:68])
307 h['timestamp'] = hex_to_int(s[68:72])
308 h['bits'] = hex_to_int(s[72:76])
309 h['nonce'] = hex_to_int(s[76:80])
312 def hash_header(self, header):
313 return rev_hex(Hash(self.header_to_string(header).decode('hex')).encode('hex'))
315 def hash_merkle_root(self, merkle_s, target_hash, pos):
316 h = hash_decode(target_hash)
317 for i in range(len(merkle_s)):
319 h = Hash( hash_decode(item) + h ) if ((pos >> i) & 1) else Hash( h + hash_decode(item) )
320 return hash_encode(h)
323 wdir = self.config.get('blockchain_headers_path', user_dir())
324 if wdir and not os.path.exists( wdir ): os.mkdir(wdir)
325 return os.path.join( wdir, 'blockchain_headers')
327 def init_headers_file(self):
328 filename = self.path()
329 if os.path.exists(filename):
333 import urllib, socket
334 socket.setdefaulttimeout(30)
335 print_error("downloading ", self.headers_url )
336 urllib.urlretrieve(self.headers_url, filename)
338 print_error( "download failed. creating file", filename )
339 open(filename,'wb+').close()
341 def save_chunk(self, index, chunk):
342 filename = self.path()
343 f = open(filename,'rb+')
344 f.seek(index*2016*80)
347 self.set_local_height()
349 def save_header(self, header):
350 data = self.header_to_string(header).decode('hex')
351 assert len(data) == 80
352 height = header.get('block_height')
353 filename = self.path()
354 f = open(filename,'rb+')
358 self.set_local_height()
361 def set_local_height(self):
363 if os.path.exists(name):
364 h = os.path.getsize(name)/80 - 1
365 if self.local_height != h:
366 self.local_height = h
369 def read_header(self, block_height):
371 if os.path.exists(name):
373 f.seek(block_height*80)
377 h = self.header_from_string(h)
381 def get_target(self, index):
383 max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
384 if index == 0: return 0x1d00ffff, max_target
386 first = self.read_header((index-1)*2016)
387 last = self.read_header(index*2016-1)
389 nActualTimespan = last.get('timestamp') - first.get('timestamp')
390 nTargetTimespan = 14*24*60*60
391 nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
392 nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
394 bits = last.get('bits')
400 target = (a) * pow(2, 8 * (bits/MM - 3))
403 new_target = min( max_target, (target * nActualTimespan)/nTargetTimespan )
406 c = ("%064X"%new_target)[2:]
412 c = eval('0x'+c[0:6])
417 new_bits = c + MM * i
418 return new_bits, new_target