Skip to content

Instantly share code, notes, and snippets.

@keis
Created June 4, 2013 05:44
Show Gist options
  • Save keis/5703841 to your computer and use it in GitHub Desktop.
Save keis/5703841 to your computer and use it in GitHub Desktop.
construct description of bitcoin block https://en.bitcoin.it/wiki/Protocol_specification
'''Description of bitcoin binary protocol fragments'''
from construct import (Construct, ConstructError, Struct, Bytes, Array,
ULInt8, ULInt16, ULInt32, ULInt64)
class VarInt(Construct):
def __init__(self, name):
Construct.__init__(self, name)
def _parse(self, stream, context):
first = ULInt8('first')._parse(stream, context)
if first < 0xfd:
return first
if first == 0xfd:
return ULInt16('value')._parse(stream, context)
if first == 0xfe:
return ULInt32('value')._parse(stream, context)
if first == 0xff:
return ULInt64('value')._parse(stream, context)
raise ConstructError('invalid value %r' % first)
def _build(self, obj, stream, context):
if obj < 0xfd:
ULInt8('first')._build(obj, stream, context)
elif obj < 2 ** 16:
ULInt8('first')._build(0xfd, stream, context)
ULInt16('value')._build(obj, stream, context)
elif obj < 2 ** 32:
ULInt8('first')._build(0xfe, stream, context)
ULInt32('value')._build(obj, stream, context)
else:
ULInt8('first')._build(0xff, stream, context)
ULInt64('value')._build(obj, stream, context)
TxInput = Struct(
'txin',
Bytes('prev_tx', 32),
ULInt32('output_idx'),
VarInt('script_length'),
Bytes('script', lambda ctx: ctx.script_length),
ULInt32('sequence')
)
TxOutput = Struct(
'txout',
ULInt64('value'),
VarInt('script_length'),
Bytes('script', lambda ctx: ctx.script_length)
)
Transaction = Struct(
'tx',
ULInt32('version'),
VarInt('in_count'),
Array(lambda ctx: ctx.in_count, TxInput),
VarInt('out_count'),
Array(lambda ctx: ctx.out_count, TxOutput),
ULInt32('locktime')
)
Block = Struct(
'block',
ULInt32('version'),
Bytes('prev_block', 32),
Bytes('merkle_root', 32),
ULInt32('unix_time'),
ULInt32('difficulty'),
ULInt32('nonce'),
VarInt('tx_count'),
Array(lambda ctx: ctx.tx_count, Transaction)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment