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
21 from util import user_dir
27 class WalletVerifier(threading.Thread):
28 """ Simple Verification Protocol """
30 def __init__(self, interface, config):
31 threading.Thread.__init__(self)
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
44 self.set_local_height()
46 def get_confirmations(self, tx):
47 """ return the number of confirmations of a monitored transaction. """
49 assert tx in self.transactions
50 return (self.local_height - self.verified_tx[tx] + 1) if tx in self.verified_tx else 0
53 """ add a transaction to the list of monitored transactions. """
55 if tx not in self.transactions:
56 self.transactions.append(tx)
61 requested_headers = []
62 pending_headers_changed = False
64 # subscribe to block headers
65 self.interface.send([ ('blockchain.headers.subscribe',[])], 'verifier')
68 # request missing chunks
69 max_index = (self.height+1)/2016
70 if not requested_chunks:
71 for i in range(0, max_index + 1):
72 # test if we can read the first header of the chunk
73 if self.read_header(i*2016): continue
74 print "requesting chunk", i
75 self.interface.send([ ('blockchain.block.get_chunk',[i])], 'verifier')
76 requested_chunks.append(i)
79 # request missing headers
80 if not requested_chunks and self.local_height:
81 for i in range(self.local_height + 1, self.height + 1):
82 if i not in requested_headers:
83 print "requesting header", i
84 self.interface.send([ ('blockchain.block.get_header',[i])], 'verifier')
85 requested_headers.append(i)
87 # request missing tx merkle
88 for tx in self.transactions:
89 if tx not in self.verified_tx:
90 if tx not in requested_merkle:
91 requested_merkle.append(tx)
92 self.request_merkle(tx)
96 r = self.interface.get_response('verifier',timeout=1)
106 if method == 'blockchain.transaction.get_merkle':
108 self.verify_merkle(tx_hash, result)
109 requested_merkle.remove(tx_hash)
111 elif method == 'blockchain.block.get_chunk':
113 self.verify_chunk(index, result)
114 requested_chunks.remove(index)
116 elif method == 'blockchain.headers.subscribe':
117 self.height = result.get('block_height')
118 self.pending_headers.append(result)
119 pending_headers_changed = True
121 elif method == 'blockchain.block.get_header':
122 height = result.get('block_height')
123 requested_headers.remove(height)
124 self.pending_headers.append(result)
125 pending_headers_changed = True
127 # process pending headers
128 if pending_headers_changed:
129 self.pending_headers.sort(key=lambda x: x.get('block_height'))
130 print "pending headers", map(lambda x: x.get('block_height'), self.pending_headers)
131 for header in self.pending_headers:
132 if self.verify_header(header):
133 self.pending_headers.remove(header)
136 pending_headers_changed = False
138 self.interface.trigger_callback('updated')
141 def request_merkle(self, tx_hash):
142 self.interface.send([ ('blockchain.transaction.get_merkle',[tx_hash]) ], 'verifier')
145 def verify_merkle(self, tx_hash, result):
146 tx_height = result.get('block_height')
147 self.merkle_roots[tx_hash] = self.hash_merkle_root(result['merkle'], tx_hash)
148 header = self.read_header(tx_height)
150 assert header.get('merkle_root') == self.merkle_roots[tx_hash]
151 self.verified_tx[tx_hash] = tx_height
152 print "verified", tx_hash
153 self.config.set_key('verified_tx', self.verified_tx, True)
156 def verify_chunk(self, index, hexdata):
157 data = hexdata.decode('hex')
160 print "validate_chunk", index, num
163 previous_hash = ("0"*64)
165 prev_header = self.read_header(index*2016-1)
166 if prev_header is None: raise
167 previous_hash = self.hash_header(prev_header)
169 bits, target = self.get_target(index)
172 height = index*2016 + i
173 raw_header = data[i*80:(i+1)*80]
174 header = self.header_from_string(raw_header)
175 _hash = self.hash_header(header)
176 assert previous_hash == header.get('prev_block_hash')
177 assert bits == header.get('bits')
178 assert eval('0x'+_hash) < target
180 previous_header = header
181 previous_hash = _hash
183 self.save_chunk(index, data)
186 def verify_header(self, header):
187 # add header to the blockchain file
188 # if there is a reorg, push it in a stack
190 height = header.get('block_height')
192 prev_header = self.read_header(height -1)
194 print "no previous header", height
197 #prev_hash = prev_header.get('block_height')
198 prev_hash = self.hash_header(prev_header)
199 bits, target = self.get_target(height/2016)
200 _hash = self.hash_header(header)
202 assert prev_hash == header.get('prev_block_hash')
203 assert bits == header.get('bits')
204 assert eval('0x'+_hash) < target
207 print "verify header failed", header
209 # this could be caused by a reorg. request the previous header
211 #request previous one
214 self.save_header(header)
215 print "verify header: ok", height
221 def header_to_string(self, res):
222 s = int_to_hex(res.get('version'),4) \
223 + rev_hex(res.get('prev_block_hash')) \
224 + rev_hex(res.get('merkle_root')) \
225 + int_to_hex(int(res.get('timestamp')),4) \
226 + int_to_hex(int(res.get('bits')),4) \
227 + int_to_hex(int(res.get('nonce')),4)
231 def header_from_string(self, s):
232 hex_to_int = lambda s: eval('0x' + s[::-1].encode('hex'))
234 h['version'] = hex_to_int(s[0:4])
235 h['prev_block_hash'] = hash_encode(s[4:36])
236 h['merkle_root'] = hash_encode(s[36:68])
237 h['timestamp'] = hex_to_int(s[68:72])
238 h['bits'] = hex_to_int(s[72:76])
239 h['nonce'] = hex_to_int(s[76:80])
243 def hash_header(self, header):
244 return rev_hex(Hash(self.header_to_string(header).decode('hex')).encode('hex'))
247 def hash_merkle_root(self, merkle_s, target_hash):
248 h = hash_decode(target_hash)
249 for item in merkle_s:
250 is_left = item[0] == 'L'
251 h = Hash( h + hash_decode(item[1:]) ) if is_left else Hash( hash_decode(item[1:]) + h )
252 return hash_encode(h)
256 if not os.path.exists( wdir ):
257 wdir = os.path.dirname(self.config.path)
258 return os.path.join( wdir, 'blockchain_headers')
260 def save_chunk(self, index, chunk):
261 filename = self.path()
262 if os.path.exists(filename):
263 f = open(filename,'rw+')
265 print "creating file", filename
266 f = open(filename,'w+')
267 f.seek(index*2016*80)
270 self.set_local_height()
272 def save_header(self, header):
273 data = self.header_to_string(header).decode('hex')
274 assert len(data) == 80
275 height = header.get('block_height')
276 filename = self.path()
277 f = open(filename,'rw+')
281 self.set_local_height()
284 def set_local_height(self):
286 if os.path.exists(name):
287 h = os.path.getsize(name)/80 - 1
288 if self.local_height != h:
289 self.local_height = h
292 def read_header(self, block_height):
294 if os.path.exists(name):
296 f.seek(block_height*80)
300 h = self.header_from_string(h)
304 def get_target(self, index):
306 max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
307 if index == 0: return 0x1d00ffff, max_target
309 first = self.read_header((index-1)*2016)
310 last = self.read_header(index*2016-1)
312 nActualTimespan = last.get('timestamp') - first.get('timestamp')
313 nTargetTimespan = 14*24*60*60
314 nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
315 nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
317 bits = last.get('bits')
323 target = (a) * pow(2, 8 * (bits/MM - 3))
326 new_target = min( max_target, (target * nActualTimespan)/nTargetTimespan )
329 c = ("%064X"%new_target)[2:]
335 c = eval('0x'+c[0:6])
340 new_bits = c + MM * i
341 # print "%3d"%index, "%8x"%bits, "%64X"%new_target, hex(c)[2:].upper(), hex(new_bits)
342 return new_bits, new_target