msgcfheaders.go raw

   1  // Copyright (c) 2017 The btcsuite developers
   2  // Use of this source code is governed by an ISC
   3  // license that can be found in the LICENSE file.
   4  
   5  package wire
   6  
   7  import (
   8  	"fmt"
   9  	"io"
  10  
  11  	"github.com/btcsuite/btcd/chainhash/v2"
  12  )
  13  
  14  const (
  15  	// MaxCFHeaderPayload is the maximum byte size of a committed
  16  	// filter header.
  17  	MaxCFHeaderPayload = chainhash.HashSize
  18  
  19  	// MaxCFHeadersPerMsg is the maximum number of committed filter headers
  20  	// that can be in a single bitcoin cfheaders message.
  21  	MaxCFHeadersPerMsg = 2000
  22  )
  23  
  24  // MsgCFHeaders implements the Message interface and represents a bitcoin
  25  // cfheaders message.  It is used to deliver committed filter header information
  26  // in response to a getcfheaders message (MsgGetCFHeaders). The maximum number
  27  // of committed filter headers per message is currently 2000. See
  28  // MsgGetCFHeaders for details on requesting the headers.
  29  type MsgCFHeaders struct {
  30  	FilterType       FilterType
  31  	StopHash         chainhash.Hash
  32  	PrevFilterHeader chainhash.Hash
  33  	FilterHashes     []*chainhash.Hash
  34  }
  35  
  36  // AddCFHash adds a new filter hash to the message.
  37  func (msg *MsgCFHeaders) AddCFHash(hash *chainhash.Hash) error {
  38  	if len(msg.FilterHashes)+1 > MaxCFHeadersPerMsg {
  39  		str := fmt.Sprintf("too many block headers in message [max %v]",
  40  			MaxBlockHeadersPerMsg)
  41  		return messageError("MsgCFHeaders.AddCFHash", str)
  42  	}
  43  
  44  	msg.FilterHashes = append(msg.FilterHashes, hash)
  45  	return nil
  46  }
  47  
  48  // BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
  49  // This is part of the Message interface implementation.
  50  func (msg *MsgCFHeaders) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
  51  	buf := binarySerializer.Borrow()
  52  	defer binarySerializer.Return(buf)
  53  
  54  	// Read filter type
  55  	if _, err := io.ReadFull(r, buf[:1]); err != nil {
  56  		return err
  57  	}
  58  	msg.FilterType = FilterType(buf[0])
  59  
  60  	// Read stop hash
  61  	if _, err := io.ReadFull(r, msg.StopHash[:]); err != nil {
  62  		return err
  63  	}
  64  
  65  	// Read prev filter header
  66  	if _, err := io.ReadFull(r, msg.PrevFilterHeader[:]); err != nil {
  67  		return err
  68  	}
  69  
  70  	// Read number of filter headers
  71  	count, err := ReadVarIntBuf(r, pver, buf)
  72  	if err != nil {
  73  		return err
  74  	}
  75  
  76  	// Limit to max committed filter headers per message.
  77  	if count > MaxCFHeadersPerMsg {
  78  		str := fmt.Sprintf("too many committed filter headers for "+
  79  			"message [count %v, max %v]", count,
  80  			MaxBlockHeadersPerMsg)
  81  		return messageError("MsgCFHeaders.BtcDecode", str)
  82  	}
  83  	if err := validateElementCount(
  84  		r, count, chainhash.HashSize,
  85  	); err != nil {
  86  		return err
  87  	}
  88  
  89  	// Create a contiguous slice of hashes to deserialize into in order to
  90  	// reduce the number of allocations.
  91  	msg.FilterHashes = make([]*chainhash.Hash, 0, count)
  92  	for i := uint64(0); i < count; i++ {
  93  		var cfh chainhash.Hash
  94  		_, err := io.ReadFull(r, cfh[:])
  95  		if err != nil {
  96  			return err
  97  		}
  98  		msg.AddCFHash(&cfh)
  99  	}
 100  
 101  	return nil
 102  }
 103  
 104  // BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
 105  // This is part of the Message interface implementation.
 106  func (msg *MsgCFHeaders) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
 107  	count := len(msg.FilterHashes)
 108  	if count > MaxCFHeadersPerMsg {
 109  		str := fmt.Sprintf("too many committed filter headers for "+
 110  			"message [count %v, max %v]", count,
 111  			MaxBlockHeadersPerMsg)
 112  		return messageError("MsgCFHeaders.BtcEncode", str)
 113  	}
 114  
 115  	buf := binarySerializer.Borrow()
 116  	defer binarySerializer.Return(buf)
 117  
 118  	// Write filter type
 119  	buf[0] = byte(msg.FilterType)
 120  	if _, err := w.Write(buf[:1]); err != nil {
 121  		return err
 122  	}
 123  
 124  	// Write stop hash
 125  	if _, err := w.Write(msg.StopHash[:]); err != nil {
 126  		return err
 127  	}
 128  
 129  	// Write prev filter header
 130  	if _, err := w.Write(msg.PrevFilterHeader[:]); err != nil {
 131  		return err
 132  	}
 133  
 134  	err := WriteVarIntBuf(w, pver, uint64(count), buf)
 135  	if err != nil {
 136  		return err
 137  	}
 138  
 139  	for _, cfh := range msg.FilterHashes {
 140  		_, err := w.Write(cfh[:])
 141  		if err != nil {
 142  			return err
 143  		}
 144  	}
 145  
 146  	return nil
 147  }
 148  
 149  // Deserialize decodes a filter header from r into the receiver using a format
 150  // that is suitable for long-term storage such as a database. This function
 151  // differs from BtcDecode in that BtcDecode decodes from the bitcoin wire
 152  // protocol as it was sent across the network.  The wire encoding can
 153  // technically differ depending on the protocol version and doesn't even really
 154  // need to match the format of a stored filter header at all. As of the time
 155  // this comment was written, the encoded filter header is the same in both
 156  // instances, but there is a distinct difference and separating the two allows
 157  // the API to be flexible enough to deal with changes.
 158  func (msg *MsgCFHeaders) Deserialize(r io.Reader) error {
 159  	// At the current time, there is no difference between the wire encoding
 160  	// and the stable long-term storage format.  As a result, make use of
 161  	// BtcDecode.
 162  	return msg.BtcDecode(r, 0, BaseEncoding)
 163  }
 164  
 165  // Command returns the protocol command string for the message.  This is part
 166  // of the Message interface implementation.
 167  func (msg *MsgCFHeaders) Command() string {
 168  	return CmdCFHeaders
 169  }
 170  
 171  // MaxPayloadLength returns the maximum length the payload can be for the
 172  // receiver. This is part of the Message interface implementation.
 173  func (msg *MsgCFHeaders) MaxPayloadLength(pver uint32) uint32 {
 174  	// Hash size + filter type + num headers (varInt) +
 175  	// (header size * max headers).
 176  	return 1 + chainhash.HashSize + chainhash.HashSize + MaxVarIntPayload +
 177  		(MaxCFHeaderPayload * MaxCFHeadersPerMsg)
 178  }
 179  
 180  // NewMsgCFHeaders returns a new bitcoin cfheaders message that conforms to
 181  // the Message interface. See MsgCFHeaders for details.
 182  func NewMsgCFHeaders() *MsgCFHeaders {
 183  	return &MsgCFHeaders{
 184  		FilterHashes: make([]*chainhash.Hash, 0, MaxCFHeadersPerMsg),
 185  	}
 186  }
 187