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

@ -32,12 +32,13 @@ func (e OutOfRangeError) Error() string {
// transactions on their first access so subsequent accesses don't have to // transactions on their first access so subsequent accesses don't have to
// repeat the relatively expensive hashing operations. // repeat the relatively expensive hashing operations.
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
blockHash *chainhash.Hash // Cached block hash serializedBlockNoWitness []byte // Serialized bytes for block w/o witness data
blockHeight int32 // Height in the main block chain blockHash *chainhash.Hash // Cached block hash
transactions []*Tx // Transactions blockHeight int32 // Height in the main block chain
txnsGenerated bool // ALL wrapped transactions generated transactions []*Tx // Transactions
txnsGenerated bool // ALL wrapped transactions generated
} }
// MsgBlock returns the underlying wire.MsgBlock for the Block. // MsgBlock returns the underlying wire.MsgBlock for the Block.
@ -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.