|
|
@ -28,7 +28,7 @@ class Blockchain(util.PrintError): |
|
|
|
def __init__(self, config, network): |
|
|
|
self.config = config |
|
|
|
self.network = network |
|
|
|
self.headers_url = 'https://headers.electrum.org/blockchain_headers' |
|
|
|
self.headers_url = "https://headers.electrum.org/blockchain_headers" |
|
|
|
self.local_height = 0 |
|
|
|
self.set_local_height() |
|
|
|
|
|
|
@ -40,7 +40,7 @@ class Blockchain(util.PrintError): |
|
|
|
self.set_local_height() |
|
|
|
self.print_error("%d blocks" % self.local_height) |
|
|
|
|
|
|
|
def verify_headers(self, header, prev_header, bits, target): |
|
|
|
def verify_header(self, header, prev_header, bits, target): |
|
|
|
prev_hash = self.hash_header(prev_header) |
|
|
|
assert prev_hash == header.get('prev_block_hash'), "prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')) |
|
|
|
assert bits == header.get('bits'), "bits mismatch: %s vs %s" % (bits, header.get('bits')) |
|
|
@ -53,21 +53,21 @@ class Blockchain(util.PrintError): |
|
|
|
for header in chain: |
|
|
|
height = header.get('block_height') |
|
|
|
bits, target = self.get_target(height / 2016, chain) |
|
|
|
self.verify_headers(header, prev_header, bits, target) |
|
|
|
self.verify_header(header, prev_header, bits, target) |
|
|
|
prev_header = header |
|
|
|
|
|
|
|
def verify_chunk(self, index, hexdata): |
|
|
|
data = hexdata.decode('hex') |
|
|
|
num = len(data) / 80 |
|
|
|
prev_header = None if index == 0 else self.read_header(index*2016-1) |
|
|
|
prev_header = None |
|
|
|
if index != 0: |
|
|
|
prev_header = self.read_header(index*2016 - 1) |
|
|
|
bits, target = self.get_target(index) |
|
|
|
for i in range(num): |
|
|
|
raw_header = data[i*80:(i+1) * 80] |
|
|
|
header = self.deserialize_header(raw_header) |
|
|
|
self.verify_headers(header, prev_header, bits, target) |
|
|
|
self.verify_header(header, prev_header, bits, target) |
|
|
|
prev_header = header |
|
|
|
self.save_chunk(index, data) |
|
|
|
self.print_error("validated chunk %d" % index) |
|
|
|
|
|
|
|
def serialize_header(self, res): |
|
|
|
s = int_to_hex(res.get('version'), 4) \ |
|
|
@ -90,7 +90,9 @@ class Blockchain(util.PrintError): |
|
|
|
return h |
|
|
|
|
|
|
|
def hash_header(self, header): |
|
|
|
return "0"*64 if header is None else rev_hex(Hash(self.serialize_header(header).decode('hex')).encode('hex')) |
|
|
|
if header is None: |
|
|
|
return '0' * 64 |
|
|
|
return hash_encode(Hash(self.serialize_header(header).decode('hex'))) |
|
|
|
|
|
|
|
def path(self): |
|
|
|
return os.path.join(self.config.path, 'blockchain_headers') |
|
|
@ -213,6 +215,8 @@ class Blockchain(util.PrintError): |
|
|
|
def connect_chunk(self, idx, chunk): |
|
|
|
try: |
|
|
|
self.verify_chunk(idx, chunk) |
|
|
|
self.print_error("validated chunk %d" % index) |
|
|
|
self.save_chunk(index, data) |
|
|
|
return idx + 1 |
|
|
|
except BaseException as e: |
|
|
|
self.print_error('verify_chunk failed', str(e)) |
|
|
|