1 // Copyright (c) 2013-2016 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 // MsgGetHeaders implements the Message interface and represents a bitcoin
15 // getheaders message. It is used to request a list of block headers for
16 // blocks starting after the last known hash in the slice of block locator
17 // hashes. The list is returned via a headers message (MsgHeaders) and is
18 // limited by a specific hash to stop at or the maximum number of block headers
19 // per message, which is currently 2000.
20 //
21 // Set the HashStop field to the hash at which to stop and use
22 // AddBlockLocatorHash to build up the list of block locator hashes.
23 //
24 // The algorithm for building the block locator hashes should be to add the
25 // hashes in reverse order until you reach the genesis block. In order to keep
26 // the list of locator hashes to a reasonable number of entries, first add the
27 // most recent 10 block hashes, then double the step each loop iteration to
28 // exponentially decrease the number of hashes the further away from head and
29 // closer to the genesis block you get.
30 type MsgGetHeaders struct {
31 ProtocolVersion uint32
32 BlockLocatorHashes []*chainhash.Hash
33 HashStop chainhash.Hash
34 }
35 36 // AddBlockLocatorHash adds a new block locator hash to the message.
37 func (msg *MsgGetHeaders) AddBlockLocatorHash(hash *chainhash.Hash) error {
38 if len(msg.BlockLocatorHashes)+1 > MaxBlockLocatorsPerMsg {
39 str := fmt.Sprintf("too many block locator hashes for message [max %v]",
40 MaxBlockLocatorsPerMsg)
41 return messageError("MsgGetHeaders.AddBlockLocatorHash", str)
42 }
43 44 msg.BlockLocatorHashes = append(msg.BlockLocatorHashes, 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 *MsgGetHeaders) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
51 buf := binarySerializer.Borrow()
52 defer binarySerializer.Return(buf)
53 54 if _, err := io.ReadFull(r, buf[:4]); err != nil {
55 return err
56 }
57 msg.ProtocolVersion = littleEndian.Uint32(buf[:4])
58 59 // Read num block locator hashes and limit to max.
60 count, err := ReadVarIntBuf(r, pver, buf)
61 if err != nil {
62 return err
63 }
64 65 if count > MaxBlockLocatorsPerMsg {
66 str := fmt.Sprintf("too many block locator hashes for message "+
67 "[count %v, max %v]", count, MaxBlockLocatorsPerMsg)
68 return messageError("MsgGetHeaders.BtcDecode", str)
69 }
70 if err := validateElementCount(
71 r, count, chainhash.HashSize,
72 ); err != nil {
73 return err
74 }
75 76 // Create a contiguous slice of hashes to deserialize into in order to
77 // reduce the number of allocations.
78 locatorHashes := make([]chainhash.Hash, count)
79 msg.BlockLocatorHashes = make([]*chainhash.Hash, 0, count)
80 for i := uint64(0); i < count; i++ {
81 hash := &locatorHashes[i]
82 _, err := io.ReadFull(r, hash[:])
83 if err != nil {
84 return err
85 }
86 msg.AddBlockLocatorHash(hash)
87 }
88 89 _, err = io.ReadFull(r, msg.HashStop[:])
90 return err
91 }
92 93 // BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
94 // This is part of the Message interface implementation.
95 func (msg *MsgGetHeaders) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
96 // Limit to max block locator hashes per message.
97 count := len(msg.BlockLocatorHashes)
98 if count > MaxBlockLocatorsPerMsg {
99 str := fmt.Sprintf("too many block locator hashes for message "+
100 "[count %v, max %v]", count, MaxBlockLocatorsPerMsg)
101 return messageError("MsgGetHeaders.BtcEncode", str)
102 }
103 104 buf := binarySerializer.Borrow()
105 defer binarySerializer.Return(buf)
106 107 littleEndian.PutUint32(buf[:4], msg.ProtocolVersion)
108 if _, err := w.Write(buf[:4]); err != nil {
109 return err
110 }
111 112 err := WriteVarIntBuf(w, pver, uint64(count), buf)
113 if err != nil {
114 return err
115 }
116 117 for _, hash := range msg.BlockLocatorHashes {
118 _, err := w.Write(hash[:])
119 if err != nil {
120 return err
121 }
122 }
123 124 _, err = w.Write(msg.HashStop[:])
125 return err
126 }
127 128 // Command returns the protocol command string for the message. This is part
129 // of the Message interface implementation.
130 func (msg *MsgGetHeaders) Command() string {
131 return CmdGetHeaders
132 }
133 134 // MaxPayloadLength returns the maximum length the payload can be for the
135 // receiver. This is part of the Message interface implementation.
136 func (msg *MsgGetHeaders) MaxPayloadLength(pver uint32) uint32 {
137 // Version 4 bytes + num block locator hashes (varInt) + max allowed block
138 // locators + hash stop.
139 return 4 + MaxVarIntPayload + (MaxBlockLocatorsPerMsg *
140 chainhash.HashSize) + chainhash.HashSize
141 }
142 143 // NewMsgGetHeaders returns a new bitcoin getheaders message that conforms to
144 // the Message interface. See MsgGetHeaders for details.
145 func NewMsgGetHeaders() *MsgGetHeaders {
146 return &MsgGetHeaders{
147 BlockLocatorHashes: make([]*chainhash.Hash, 0,
148 MaxBlockLocatorsPerMsg),
149 }
150 }
151