Skip to content

Instantly share code, notes, and snippets.

@eldondev
Created October 25, 2015 05:08
Show Gist options
  • Save eldondev/f1e12beede5e40614f22 to your computer and use it in GitHub Desktop.
Save eldondev/f1e12beede5e40614f22 to your computer and use it in GitHub Desktop.
Some basic code to parse some blocks
import struct, sys, io
from hashlib import sha256
from binascii import b2a_hex
blkfile = open("blk00000.dat", 'rb')
block_hashes = [b'\x00' * 32]
trans_hashes = [b'\x00' * 32]
def get_var(reader):
firstbyte = reader.read(1)
if ord(firstbyte) <= 0xfc:
return struct.unpack("<B", firstbyte)[0], 1
if ord(firstbyte) == 0xfd:
return struct.unpack("<H", reader.read(2))[0], 3
if ord(firstbyte) == 0xfe:
return struct.unpack("<I", reader.read(4))[0], 5
if ord(firstbyte) == 0xff:
return struct.unpack("<Q", reader.read(8))[0], 9
def get_transactions(block_contents, count):
for transaction in range(count):
reader = io.BytesIO(block_contents)
vernum = struct.unpack("<I", reader.read(4))
input_count, _ = get_var(reader)
print("%i inputs" % input_count)
for idx in range(input_count):
get_input(reader)
output_count, _ = get_var(reader)
for idx in range(output_count):
get_output(reader)
locktime = struct.unpack("<I", reader.read(4))
s1, s2 = sha256(), sha256()
s1.update(block_contents[:reader.tell()])
block_contents = block_contents[reader.tell():]
s2.update(s1.digest())
trans_hashes.append( s2.digest() )
def get_output(reader):
value = struct.unpack("<Q", reader.read(8))
script_length, _ = get_var(reader)
sequence = reader.read(script_length)
def get_input(reader):
transaction_hash, transactionindex = struct.unpack("<32sI", reader.read(36))
assert transaction_hash in trans_hashes
#print("Confusing input hash: %s" % b2a_hex(transaction_hash))
script_length, _ = get_var(reader)
script = reader.read(script_length)
sequence = reader.read(4)
if not 4294967295 == sequence:
print(sequence)
while True:
header_bytes = blkfile.read(88)
if not header_bytes:
sys.exit(0)
magic, block_length, version, prev, merkle, timestamp, bits, nonce = struct.unpack("<III32s32sIII", header_bytes)
print((magic, block_length, version, b2a_hex(prev), b2a_hex(merkle), timestamp, bits, nonce))
assert prev == block_hashes[-1]
h = sha256()
h.update(header_bytes[8:])
hh = sha256()
hh.update(h.digest())
block_hashes += [ hh.digest() ]
print(hh.hexdigest())
transacts, varbytes = get_var(blkfile)
print(transacts, varbytes)
block_contents = blkfile.read(block_length - 80 - varbytes)
get_transactions(block_contents, transacts)
if magic != 3652501241:
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment