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)