From 7736b2464b75bbccf54c644c201449d0487cc29d Mon Sep 17 00:00:00 2001 From: George Tankersley Date: Sat, 17 Nov 2018 00:02:56 +0000 Subject: [PATCH] parser: extract height from coinbase transaction --- parser/block.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/parser/block.go b/parser/block.go index 827e052..5f79816 100644 --- a/parser/block.go +++ b/parser/block.go @@ -24,6 +24,28 @@ func (b *block) GetTxCount() int { return len(b.vtx) } +// GetHeight() extracts the block height from the coinbase transaction. See +// BIP34. Returns block height on success, or -1 on error. +func (b *block) GetHeight() int { + coinbaseScript := bytestring.String(b.vtx[0].transparentInputs[0].ScriptSig) + var heightByte byte + if ok := coinbaseScript.ReadByte(&heightByte); !ok { + return -1 + } + heightLen := int(heightByte) + var heightBytes = make([]byte, heightLen) + if ok := coinbaseScript.ReadBytes(&heightBytes, heightLen); !ok { + return -1 + } + // uint32 should last us a while (Nov 2018) + var blockHeight uint32 + for i := heightLen - 1; i >= 0; i-- { + blockHeight <<= 8 + blockHeight = blockHeight | uint32(heightBytes[i]) + } + return int(blockHeight) +} + func (b *block) ParseFromSlice(data []byte) (rest []byte, err error) { hdr := NewBlockHeader() data, err = hdr.ParseFromSlice(data)