"""Check the archived Litecoin block headers and print nine difficulty changes. Usage: python verify.py.txt headers.csv (Python 3, standard library only) """ import csv import hashlib import sys from datetime import datetime, timezone from pathlib import Path PERIOD = 2_016 SECONDS = 302_400 LIMIT = (1 << 236) - 1 FIRST = 3_205_440 LAST = 3_221_568 def require(condition, message): if not condition: raise ValueError(message) def target(bits): exponent = bits >> 24 coefficient = bits & 0x007fffff require(not bits & 0x00800000 and coefficient, 'invalid compact target') shift = 8 * (exponent - 3) return coefficient << shift if shift >= 0 else coefficient >> -shift def compact(value): size = (value.bit_length() + 7) // 8 shift = 8 * (size - 3) mantissa = value >> shift if shift >= 0 else value << -shift if mantissa & 0x00800000: mantissa >>= 8 size += 1 return (size << 24) | mantissa def check(path): blocks = {} with Path(path).open(encoding='utf-8', newline='') as stream: for row in csv.DictReader(stream): h = int(row['height']) header = bytes.fromhex(row['header_hex']) require(len(header) == 80 and h not in blocks, f'bad row at {h}') block_id = hashlib.sha256(hashlib.sha256(header).digest()).digest()[::-1].hex() bits = int.from_bytes(header[72:76], 'little') threshold = target(bits) work = hashlib.scrypt(header, salt=header, n=1024, r=1, p=1, dklen=32) require(block_id == row['block_hash'], f'ID mismatch at {h}') require(0 < threshold <= LIMIT and int.from_bytes(work, 'little') <= threshold, f'work mismatch at {h}') blocks[h] = (block_id, header[4:36][::-1].hex(), int.from_bytes(header[68:72], 'little'), bits) reference = target(0x1d00ffff) changes = [] for h in range(FIRST, LAST + 1, PERIOD): start, end, new = blocks[h - PERIOD - 1], blocks[h - 1], blocks[h] require(new[1] == end[0], f'broken boundary link at {h}') span = end[2] - start[2] clipped = min(SECONDS * 4, max(SECONDS // 4, span)) old_target = target(end[3]) # All nine observed targets are small enough for the unshifted Core branch. require(old_target.bit_length() <= LIMIT.bit_length() - 1, 'outside this sample') expected = compact(min(LIMIT, old_target * clipped // SECONDS)) require(expected == new[3], f'retarget mismatch at {h}') new_target = target(new[3]) changes.append(dict(height=h, utc=datetime.fromtimestamp(new[2], timezone.utc).isoformat(), seconds=span, start_utc=datetime.fromtimestamp(start[2], timezone.utc).isoformat(), end_utc=datetime.fromtimestamp(end[2], timezone.utc).isoformat(), previous=reference / old_target, difficulty=reference / new_target, change_pct=100 * (old_target / new_target - 1), per_hash_change_pct=100 * ((new_target + 1) / (old_target + 1) - 1), old_bits=f'{end[3]:08x}', new_bits=f'{expected:08x}', boundary_header_gap=new[2] - end[2])) return changes if __name__ == '__main__': for change in check(sys.argv[1]): print('{utc} {height:,} {difficulty:,.2f} {change_pct:+.2f}% {seconds:,} s {new_bits}'.format(**change))