msgcfcheckpt.go raw

   1  // Copyright (c) 2018 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  	"errors"
   9  	"fmt"
  10  	"io"
  11  
  12  	"github.com/btcsuite/btcd/chainhash/v2"
  13  )
  14  
  15  const (
  16  	// CFCheckptInterval is the gap (in number of blocks) between each
  17  	// filter header checkpoint.
  18  	CFCheckptInterval = 1000
  19  
  20  	// maxCFHeadersLen is the max number of filter headers we will attempt
  21  	// to decode.
  22  	maxCFHeadersLen = 100000
  23  
  24  	// maxCFCheckptPayload calculates the maximum reasonable payload size
  25  	// for CF checkpoint messages.
  26  	//
  27  	// Calculation: 1 byte (filter type) + 32 bytes (stop hash) +
  28  	// 5 bytes (max varint) + (maxCFHeadersLen * 32 bytes per hash)
  29  	maxCFCheckptPayload = 1 + 32 + 5 + (maxCFHeadersLen * 32)
  30  )
  31  
  32  // ErrInsaneCFHeaderCount signals that we were asked to decode an
  33  // unreasonable number of cfilter headers.
  34  var ErrInsaneCFHeaderCount = errors.New(
  35  	"refusing to decode unreasonable number of filter headers")
  36  
  37  // MsgCFCheckpt implements the Message interface and represents a bitcoin
  38  // cfcheckpt message.  It is used to deliver committed filter header information
  39  // in response to a getcfcheckpt message (MsgGetCFCheckpt). See MsgGetCFCheckpt
  40  // for details on requesting the headers.
  41  type MsgCFCheckpt struct {
  42  	FilterType    FilterType
  43  	StopHash      chainhash.Hash
  44  	FilterHeaders []*chainhash.Hash
  45  }
  46  
  47  // AddCFHeader adds a new committed filter header to the message.
  48  func (msg *MsgCFCheckpt) AddCFHeader(header *chainhash.Hash) error {
  49  	if len(msg.FilterHeaders) == cap(msg.FilterHeaders) {
  50  		str := fmt.Sprintf("FilterHeaders has insufficient capacity for "+
  51  			"additional header: len = %d", len(msg.FilterHeaders))
  52  		return messageError("MsgCFCheckpt.AddCFHeader", str)
  53  	}
  54  
  55  	msg.FilterHeaders = append(msg.FilterHeaders, header)
  56  	return nil
  57  }
  58  
  59  // BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
  60  // This is part of the Message interface implementation.
  61  func (msg *MsgCFCheckpt) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
  62  	buf := binarySerializer.Borrow()
  63  	defer binarySerializer.Return(buf)
  64  
  65  	// Read filter type
  66  	if _, err := io.ReadFull(r, buf[:1]); err != nil {
  67  		return err
  68  	}
  69  	msg.FilterType = FilterType(buf[0])
  70  
  71  	// Read stop hash
  72  	if _, err := io.ReadFull(r, msg.StopHash[:]); err != nil {
  73  		return err
  74  	}
  75  
  76  	// Read number of filter headers
  77  	count, err := ReadVarIntBuf(r, pver, buf)
  78  	if err != nil {
  79  		return err
  80  	}
  81  
  82  	// Refuse to decode an insane number of cfheaders.
  83  	if count > maxCFHeadersLen {
  84  		return ErrInsaneCFHeaderCount
  85  	}
  86  	preallocate, err := canPreallocateElements(
  87  		r, count, chainhash.HashSize,
  88  	)
  89  	if err != nil {
  90  		return err
  91  	}
  92  
  93  	if count == 0 {
  94  		msg.FilterHeaders = make([]*chainhash.Hash, 0)
  95  		return nil
  96  	}
  97  
  98  	// Optimize memory allocation by creating a single backing array for all
  99  	// hashes. Buffered readers reserve the exact count, while streaming
 100  	// readers grow the array as hashes arrive.
 101  	var hashes []chainhash.Hash
 102  	if preallocate {
 103  		hashes = make([]chainhash.Hash, count)
 104  		msg.FilterHeaders = make([]*chainhash.Hash, count)
 105  	} else {
 106  		hashes = make(
 107  			[]chainhash.Hash, 0,
 108  			min(count, defaultStreamingElementCap),
 109  		)
 110  		msg.FilterHeaders = nil
 111  	}
 112  
 113  	// Now we'll read all the hashes directly into the backing array we've
 114  	// created above. We'll then point the underlying filter header hashes
 115  	// into this backing array.
 116  	for i := uint64(0); i < count; i++ {
 117  		if !preallocate {
 118  			hashes = append(hashes, chainhash.Hash{})
 119  		}
 120  		if _, err := io.ReadFull(r, hashes[i][:]); err != nil {
 121  			return err
 122  		}
 123  		if preallocate {
 124  			msg.FilterHeaders[i] = &hashes[i]
 125  		}
 126  	}
 127  	if !preallocate {
 128  		msg.FilterHeaders = make([]*chainhash.Hash, len(hashes))
 129  		for i := range hashes {
 130  			msg.FilterHeaders[i] = &hashes[i]
 131  		}
 132  	}
 133  
 134  	return nil
 135  }
 136  
 137  // BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
 138  // This is part of the Message interface implementation.
 139  func (msg *MsgCFCheckpt) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error {
 140  	buf := binarySerializer.Borrow()
 141  	defer binarySerializer.Return(buf)
 142  
 143  	// Write filter type
 144  	buf[0] = byte(msg.FilterType)
 145  	if _, err := w.Write(buf[:1]); err != nil {
 146  		return err
 147  	}
 148  
 149  	// Write stop hash
 150  	if _, err := w.Write(msg.StopHash[:]); err != nil {
 151  		return err
 152  	}
 153  
 154  	// Write length of FilterHeaders slice
 155  	count := len(msg.FilterHeaders)
 156  	err := WriteVarIntBuf(w, pver, uint64(count), buf)
 157  	if err != nil {
 158  		return err
 159  	}
 160  
 161  	for _, cfh := range msg.FilterHeaders {
 162  		_, err := w.Write(cfh[:])
 163  		if err != nil {
 164  			return err
 165  		}
 166  	}
 167  
 168  	return nil
 169  }
 170  
 171  // Deserialize decodes a filter header from r into the receiver using a format
 172  // that is suitable for long-term storage such as a database. This function
 173  // differs from BtcDecode in that BtcDecode decodes from the bitcoin wire
 174  // protocol as it was sent across the network.  The wire encoding can
 175  // technically differ depending on the protocol version and doesn't even really
 176  // need to match the format of a stored filter header at all. As of the time
 177  // this comment was written, the encoded filter header is the same in both
 178  // instances, but there is a distinct difference and separating the two allows
 179  // the API to be flexible enough to deal with changes.
 180  func (msg *MsgCFCheckpt) Deserialize(r io.Reader) error {
 181  	// At the current time, there is no difference between the wire encoding
 182  	// and the stable long-term storage format.  As a result, make use of
 183  	// BtcDecode.
 184  	return msg.BtcDecode(r, 0, BaseEncoding)
 185  }
 186  
 187  // Command returns the protocol command string for the message.  This is part
 188  // of the Message interface implementation.
 189  func (msg *MsgCFCheckpt) Command() string {
 190  	return CmdCFCheckpt
 191  }
 192  
 193  // MaxPayloadLength returns the maximum length the payload can be for the
 194  // receiver. This is part of the Message interface implementation.
 195  func (msg *MsgCFCheckpt) MaxPayloadLength(pver uint32) uint32 {
 196  	// Use a more precise calculation based on the maximum number of
 197  	// filter headers we support. No no reason to read more than we'll
 198  	// process in BtcDecode.
 199  	return maxCFCheckptPayload
 200  }
 201  
 202  // NewMsgCFCheckpt returns a new bitcoin cfheaders message that conforms to the
 203  // Message interface. See MsgCFCheckpt for details.
 204  func NewMsgCFCheckpt(filterType FilterType, stopHash *chainhash.Hash,
 205  	headersCount int) *MsgCFCheckpt {
 206  
 207  	// We pre-allocate with an exact capacity when count is known to avoid
 208  	// slice growth during message construction.
 209  	return &MsgCFCheckpt{
 210  		FilterType:    filterType,
 211  		StopHash:      *stopHash,
 212  		FilterHeaders: make([]*chainhash.Hash, 0, headersCount),
 213  	}
 214  }
 215