Skip to content

Instantly share code, notes, and snippets.

@ottosch
Last active May 8, 2023 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ottosch/2681610b8ed46f8cbb718e918e2ac0fc to your computer and use it in GitHub Desktop.
Save ottosch/2681610b8ed46f8cbb718e918e2ac0fc to your computer and use it in GitHub Desktop.
Finds which .dat file contains the block
#! /usr/bin/env python
# Finds which .dat file contains the block.
# Warning: this will most likely corrupt the block index. You are strongly advised to copy the index (around 100MB) to a different location and
# run the script in that location (change path below).
#
# Path to index: $datadir/blocks/index
import sys
import plyvel
index_path = "/path/to/index-copy"
block_prefix = "62"
if len(sys.argv) < 2:
print(f"usage: {sys.argv[0]} <blockhash>", file = sys.stderr)
sys.exit(1)
blockhash = sys.argv[1]
def read_varint(asInt):
global pos
global raw
value = bytearray()
while raw[pos] >> 7 == 1:
if asInt:
value.append(raw[pos] + 1)
else:
value.append(raw[pos])
pos += 1
value.append(raw[pos])
pos += 1
return bytes(value)
def varint_as_int():
data = read_varint(True)
number = 0
for b in data:
bits = b & 0b01111111
number = number << 7 | bits
return number
def varint_as_raw():
return read_varint(False)
db = plyvel.DB(index_path, create_if_missing = False)
key = bytes.fromhex(f"{block_prefix}{blockhash}")
raw = db.get(key)
if raw is None:
rev = bytearray.fromhex(f"{blockhash}{block_prefix}")
rev.reverse()
raw = db.get(bytes(rev))
if raw is None:
print("Block not found")
sys.exit(0)
db.close()
print(f"Raw data: {raw.hex()}")
print()
pos = 0
client = varint_as_raw()
print(f"Block recorded by client version {client.hex()}")
print()
height = varint_as_int()
print(f"Height: {height}")
varint_as_raw() # flags
txCount = varint_as_int()
print(f"Transactions in block: {txCount}")
fileNumber = str(varint_as_int()).rjust(5, "0")
print(f"Filename: blk{fileNumber}.dat")
offset = varint_as_int()
print(f"File offset: {offset}")
varint_as_int() # offset rev file
print()
header = raw[pos : pos + 80]
print(f"Header: {header.hex()}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment