sync.go raw

   1  package v2peer
   2  
   3  import (
   4  	"fmt"
   5  	"time"
   6  
   7  	btcdhash "github.com/btcsuite/btcd/chainhash/v2"
   8  	"github.com/btcsuite/btcd/wire/v2"
   9  
  10  	"git.smesh.lol/nostrino/pkg/btcwire"
  11  
  12  	"git.smesh.lol/btcd-lite/internal/store"
  13  )
  14  
  15  // SyncHeaders brings a header store up to what the peer has: the headers above
  16  // the store's tip, written in the store's own record.
  17  //
  18  // The store refuses a record that does not link to the one before it, so what
  19  // this adds is the walk: ask, check the linkage in the answer, write, ask
  20  // again from the new tip. Nothing is trusted because a peer sent it; the store
  21  // is what accepts a header.
  22  //
  23  // logf receives one progress line per hundred thousand headers and the line
  24  // that says the peer is at its tip. An error carries the height it stopped at,
  25  // because "the sync failed" without the height says nothing about where.
  26  func (p *Peer) SyncHeaders(headers *store.HeaderStore, logf func(string, ...any)) error {
  27  	if logf == nil {
  28  		logf = func(string, ...any) {}
  29  	}
  30  	tip, tipHash, ok := headers.HeaderTip()
  31  	if !ok {
  32  		return fmt.Errorf("v2peer: the header store has no tip")
  33  	}
  34  	startTip, start := tip, time.Now()
  35  	lastReport := uint32(0)
  36  	// prev is the tip in btcd's order: that is what a locator carries and what
  37  	// an incoming header holds in its PrevBlock, so the comparison is made
  38  	// there and the store's order only appears in what is written down.
  39  	prev := toVendor(tipHash)
  40  	for {
  41  		got, err := p.Headers([]btcdhash.Hash{prev}, 2*time.Minute)
  42  		if err != nil {
  43  			return fmt.Errorf("v2peer: header sync stopped at %d after %d headers in %s: %w",
  44  				tip, tip-startTip, time.Since(start).Round(time.Second), err)
  45  		}
  46  		// getheaders from a locator repeats the locator's own header in the
  47  		// first answer; a record above the tip starts after it.
  48  		if len(got) > 0 && got[0].BlockHash() == prev {
  49  			got = got[1:]
  50  		}
  51  		if len(got) == 0 {
  52  			logf("v2peer: headers to %d, the peer's tip, %d headers in %s", tip, tip-startTip, time.Since(start).Round(time.Second))
  53  			return nil
  54  		}
  55  		batch := make([]btcwire.BlockHeader, 0, len(got))
  56  		for i, hdr := range got {
  57  			if hdr.PrevBlock != prev {
  58  				return fmt.Errorf("v2peer: header %d links to %v, the tip is %v",
  59  					tip+uint32(i)+1, hdr.PrevBlock, btcdhash.Hash(prev))
  60  			}
  61  			prev = hdr.BlockHash()
  62  			batch = append(batch, headerFromVendor(hdr))
  63  		}
  64  		if err := headers.PutHeaders(tip+1, batch); err != nil {
  65  			return fmt.Errorf("v2peer: header store at %d: %w", tip+1, err)
  66  		}
  67  		tip += uint32(len(batch))
  68  		// One line per hundred thousand headers: a full sync from genesis is
  69  		// about ten of them, which is enough to see it working and to see the
  70  		// rate, and few enough to leave in a log.
  71  		if tip-lastReport >= headerReportEvery {
  72  			logf("v2peer: headers to %d, %.0f/s, %d in %s",
  73  				tip, float64(tip-startTip)/time.Since(start).Seconds(), tip-startTip, time.Since(start).Round(time.Second))
  74  			lastReport = tip
  75  		}
  76  	}
  77  }
  78  
  79  // headerReportEvery is how many headers one progress line accounts for.
  80  const headerReportEvery uint32 = 100000
  81  
  82  // fromVendor is toVendor the other way: a copy, for the same reason.
  83  func fromVendor(h [32]byte) [32]byte { return [32]byte(h) }
  84  
  85  // The two hash types hold the same bytes: btcd's String reverses them for
  86  // display and nostrino's does not, which is a difference in printing and not
  87  // in storage. A hash moving between them is a copy.
  88  func toVendor(h [32]byte) btcdhash.Hash { return btcdhash.Hash(h) }
  89  
  90  // fromVendor is btcd's header record in the form the store keeps, which is the
  91  // same eighty bytes.
  92  func headerFromVendor(hdr *wire.BlockHeader) btcwire.BlockHeader {
  93  	var out btcwire.BlockHeader
  94  	out.Version = hdr.Version
  95  	out.PrevBlock = fromVendor([32]byte(hdr.PrevBlock))
  96  	out.MerkleRoot = fromVendor([32]byte(hdr.MerkleRoot))
  97  	out.Timestamp = uint32(hdr.Timestamp.Unix())
  98  	out.Bits = hdr.Bits
  99  	out.Nonce = hdr.Nonce
 100  	return out
 101  }
 102