From 6950f39a70f0cfa97d8121788a8d3fa0091a15b3 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Thu, 13 Oct 2016 12:55:05 -0700 Subject: [PATCH] add new BytesNoWitness method to Block This commit adds a new method to btcutil.Block for obtaining the serialization of a Block *without* any witness data (if any). --- block.go | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/block.go b/block.go index 5d06c4a..2749353 100644 --- a/block.go +++ b/block.go @@ -32,12 +32,13 @@ func (e OutOfRangeError) Error() string { // transactions on their first access so subsequent accesses don't have to // repeat the relatively expensive hashing operations. type Block struct { - msgBlock *wire.MsgBlock // Underlying MsgBlock - serializedBlock []byte // Serialized bytes for the block - blockHash *chainhash.Hash // Cached block hash - blockHeight int32 // Height in the main block chain - transactions []*Tx // Transactions - txnsGenerated bool // ALL wrapped transactions generated + msgBlock *wire.MsgBlock // Underlying MsgBlock + serializedBlock []byte // Serialized bytes for the block + serializedBlockNoWitness []byte // Serialized bytes for block w/o witness data + blockHash *chainhash.Hash // Cached block hash + blockHeight int32 // Height in the main block chain + transactions []*Tx // Transactions + txnsGenerated bool // ALL wrapped transactions generated } // MsgBlock returns the underlying wire.MsgBlock for the Block. @@ -68,6 +69,27 @@ func (b *Block) Bytes() ([]byte, error) { return serializedBlock, nil } +// BytesNoWitness returns the serialized bytes for the block with transactions +// encoded without any witness data. +func (b *Block) BytesNoWitness() ([]byte, error) { + // Return the cached serialized bytes if it has already been generated. + if len(b.serializedBlockNoWitness) != 0 { + return b.serializedBlockNoWitness, nil + } + + // Serialize the MsgBlock. + var w bytes.Buffer + err := b.msgBlock.SerializeNoWitness(&w) + if err != nil { + return nil, err + } + serializedBlock := w.Bytes() + + // Cache the serialized bytes and return them. + b.serializedBlockNoWitness = serializedBlock + return serializedBlock, nil +} + // Hash returns the block identifier hash for the Block. This is equivalent to // calling BlockHash on the underlying wire.MsgBlock, however it caches the // result so subsequent calls are more efficient.