package v2peer import ( "fmt" "time" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" ) // Headers asks for the headers above the given hashes and returns them. // // It walks the chain forward from the best hash the caller has: one getheaders // gives up to two thousand headers, and the walk repeats until the peer has // nothing more, which is how a header sync continues from where it stopped. // The headers are returned as they were sent; a caller that stores them checks // the linkage and the proof of work, which is where those belong. func (p *Peer) Headers(locator []chainhash.Hash, timeout time.Duration) ([]*wire.BlockHeader, error) { var out []*wire.BlockHeader last := chainhash.Hash{} for { gh := wire.NewMsgGetHeaders() if len(out) == 0 { for i := range locator { gh.AddBlockLocatorHash(&locator[i]) } } else { gh.AddBlockLocatorHash(&last) } if err := p.Write(gh); err != nil { return out, err } msg, err := p.awaitHeaders(timeout) if err != nil { return out, err } if len(msg.Headers) == 0 { return out, nil } out = append(out, msg.Headers...) last = msg.Headers[len(msg.Headers)-1].BlockHash() } } func (p *Peer) awaitHeaders(timeout time.Duration) (*wire.MsgHeaders, error) { timer := time.NewTimer(timeout) defer timer.Stop() for { select { case <-timer.C: return nil, fmt.Errorf("v2peer: no headers within %s", timeout) case <-p.done: return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err()) case m, ok := <-p.recv: if !ok { return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err()) } if h, ok := m.Message.(*wire.MsgHeaders); ok { return h, nil } } } }