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).
This commit is contained in:
Olaoluwa Osuntokun 2016-10-13 12:55:05 -07:00
parent fd898ec77a
commit 6950f39a70
No known key found for this signature in database
GPG key ID: 9CC5B105D03521A2

View file

@ -34,6 +34,7 @@ func (e OutOfRangeError) Error() string {
type Block struct { type Block struct {
msgBlock *wire.MsgBlock // Underlying MsgBlock msgBlock *wire.MsgBlock // Underlying MsgBlock
serializedBlock []byte // Serialized bytes for the block serializedBlock []byte // Serialized bytes for the block
serializedBlockNoWitness []byte // Serialized bytes for block w/o witness data
blockHash *chainhash.Hash // Cached block hash blockHash *chainhash.Hash // Cached block hash
blockHeight int32 // Height in the main block chain blockHeight int32 // Height in the main block chain
transactions []*Tx // Transactions transactions []*Tx // Transactions
@ -68,6 +69,27 @@ func (b *Block) Bytes() ([]byte, error) {
return serializedBlock, nil 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 // Hash returns the block identifier hash for the Block. This is equivalent to
// calling BlockHash on the underlying wire.MsgBlock, however it caches the // calling BlockHash on the underlying wire.MsgBlock, however it caches the
// result so subsequent calls are more efficient. // result so subsequent calls are more efficient.