headers.go raw

   1  package v2peer
   2  
   3  import (
   4  	"fmt"
   5  	"time"
   6  
   7  	"github.com/btcsuite/btcd/chainhash/v2"
   8  	"github.com/btcsuite/btcd/wire/v2"
   9  )
  10  
  11  // Headers asks for the headers above the given hashes and returns them.
  12  //
  13  // It walks the chain forward from the best hash the caller has: one getheaders
  14  // gives up to two thousand headers, and the walk repeats until the peer has
  15  // nothing more, which is how a header sync continues from where it stopped.
  16  // The headers are returned as they were sent; a caller that stores them checks
  17  // the linkage and the proof of work, which is where those belong.
  18  func (p *Peer) Headers(locator []chainhash.Hash, timeout time.Duration) ([]*wire.BlockHeader, error) {
  19  	var out []*wire.BlockHeader
  20  	last := chainhash.Hash{}
  21  	for {
  22  		gh := wire.NewMsgGetHeaders()
  23  		if len(out) == 0 {
  24  			for i := range locator {
  25  				gh.AddBlockLocatorHash(&locator[i])
  26  			}
  27  		} else {
  28  			gh.AddBlockLocatorHash(&last)
  29  		}
  30  		if err := p.Write(gh); err != nil {
  31  			return out, err
  32  		}
  33  		msg, err := p.awaitHeaders(timeout)
  34  		if err != nil {
  35  			return out, err
  36  		}
  37  		if len(msg.Headers) == 0 {
  38  			return out, nil
  39  		}
  40  		out = append(out, msg.Headers...)
  41  		last = msg.Headers[len(msg.Headers)-1].BlockHash()
  42  	}
  43  }
  44  
  45  func (p *Peer) awaitHeaders(timeout time.Duration) (*wire.MsgHeaders, error) {
  46  	timer := time.NewTimer(timeout)
  47  	defer timer.Stop()
  48  	for {
  49  		select {
  50  		case <-timer.C:
  51  			return nil, fmt.Errorf("v2peer: no headers within %s", timeout)
  52  		case <-p.done:
  53  			return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err())
  54  		case m, ok := <-p.recv:
  55  			if !ok {
  56  				return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err())
  57  			}
  58  			if h, ok := m.Message.(*wire.MsgHeaders); ok {
  59  				return h, nil
  60  			}
  61  		}
  62  	}
  63  }
  64