filler.go raw

   1  // Package filler pulls blocks from peers and files them in a body store.
   2  //
   3  // It is a downloader, not a validator: it is handed the chain's header store,
   4  // it asks for the block at a height by the hash the header store already
   5  // verified, and it refuses a body whose header does not hash to that. Nothing
   6  // in it checks scripts or transactions, which is the plan's premise: a body is
   7  // bytes whose position in the chain the header chain fixed.
   8  //
   9  // One lane is one peer connection. A lane asks for one block at a time so that
  10  // a peer's answer is traceable to a request and a slow peer delays only itself.
  11  //
  12  // The connection is its own. Neutrino's p2p.Conn sends a version and then reads
  13  // for a reply, and against Bitcoin Core 30.3 that reply never comes: the node
  14  // closes the socket after the client's first frame, and the handshake ends in
  15  // "waiting for version: EOF". No frame byte in the client's message differs
  16  // from the specification, so rather than patch a connection type this package
  17  // does not own, the lane speaks the protocol itself: connect, version, wait for
  18  // the node's version and verack, then getdata one block at a time.
  19  package filler
  20  
  21  import (
  22  	"context"
  23  	"encoding/binary"
  24  	"errors"
  25  	"fmt"
  26  	"net"
  27  	"sync"
  28  	"sync/atomic"
  29  	"time"
  30  
  31  	btcdhash "github.com/btcsuite/btcd/chainhash/v2"
  32  
  33  	"git.smesh.lol/nostrino/pkg/btcwire"
  34  	"git.smesh.lol/nostrino/pkg/chain"
  35  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  36  
  37  	"git.smesh.lol/btcd-lite/internal/chains"
  38  	"git.smesh.lol/btcd-lite/internal/staging"
  39  	"git.smesh.lol/btcd-lite/internal/store"
  40  	"git.smesh.lol/btcd-lite/internal/v2peer"
  41  )
  42  
  43  // Peer is one address the pool may dial.
  44  type Peer struct {
  45  	Addr string
  46  }
  47  
  48  // Pool pulls blocks for one chain into a body store.
  49  type Pool struct {
  50  	cfg PoolConfig
  51  
  52  	mu      sync.Mutex
  53  	claimed map[uint32]bool
  54  	// reuse holds connections a caller handed over, by address, until a lane
  55  	// takes one.
  56  	reuse map[string]*conn
  57  	// stored is every height this instance holds, whether the body store or
  58  	// the staging log has it, so the walk knows where it has been.
  59  	stored map[uint32]bool
  60  	// closeReuse closes connections a caller handed over and no worker took.
  61  	closeReuse []*conn
  62  
  63  	// cursor is where the next scan for work starts. It moves past heights
  64  	// that are stored, and not past heights another worker is fetching, so a
  65  	// height that fails is looked at again by whoever is free.
  66  	cursor atomic.Uint32
  67  	// target is how many heights the header store had when the run started,
  68  	// which is what a percentage and an estimate are against.
  69  	target atomic.Uint32
  70  	done   atomic.Uint64
  71  	failed atomic.Uint64
  72  }
  73  
  74  // PoolConfig is what a pool is made of.
  75  type PoolConfig struct {
  76  	// Chain names the chain in the log lines, so a run that fills two chains
  77  	// says which one a line is about. It is not used to select anything: the
  78  	// header store it is given is the chain.
  79  	Chain string
  80  	// Profile is the chain being followed; it carries the magic and the header
  81  	// form.
  82  	Profile *chain.Profile
  83  	// Headers is the header store the chain's hashes come from.
  84  	Headers *store.HeaderStore
  85  	// Bodies is the store a block ends up in once a processing pass has
  86  	// checked it. The pool does not write to it: it reads it to know which
  87  	// heights are already done.
  88  	Bodies *store.BlockStore
  89  	// Staging is where the bodies go. A downloaded body is unverified bytes,
  90  	// so it lands in a log nothing serves and the processing pass moves it.
  91  	Staging *staging.Log
  92  	// Peers are the addresses to dial, in preference order.
  93  	Peers []Peer
  94  	// Lanes is how many peers pull at once. Zero means one per peer, at most 8.
  95  	Lanes int
  96  	// UserAgent is advertised in version.
  97  	UserAgent string
  98  	// Logf receives lifecycle and progress lines; nil discards them.
  99  	Logf func(string, ...any)
 100  	// Tracef receives one line per block asked for. A full fill is a million
 101  	// of them, so this is the debug seam: nil keeps them off.
 102  	Tracef func(string, ...any)
 103  	// Warnf receives the lines about a peer that failed. Nil sends them to
 104  	// Logf.
 105  	Warnf func(string, ...any)
 106  	// V2 asks for BIP324 on a lane. Plaintext v1 is what every node accepts,
 107  	// and the v2 path closes connections part way through a sync against some
 108  	// real peers, so it is off unless a caller asks.
 109  	V2 bool
 110  	// ProgressEvery is how often a progress line is written while filling.
 111  	// Zero means one minute.
 112  	ProgressEvery time.Duration
 113  	// Dial opens a connection to an address. Nil means TCP.
 114  	Dial func(ctx context.Context, addr string) (net.Conn, error)
 115  	// ReadTimeout bounds one frame read. Zero means two minutes.
 116  	ReadTimeout time.Duration
 117  }
 118  
 119  type lane struct {
 120  	addr   string
 121  	conn   *conn
 122  	failed bool
 123  }
 124  
 125  // NewPool returns a pool. It does not dial.
 126  func NewPool(cfg PoolConfig) (*Pool, error) {
 127  	if cfg.Profile == nil || cfg.Headers == nil || cfg.Bodies == nil || cfg.Staging == nil {
 128  		return nil, errors.New("filler: profile, headers, bodies and staging are required")
 129  	}
 130  	if len(cfg.Peers) == 0 {
 131  		return nil, errors.New("filler: no peers")
 132  	}
 133  	if cfg.Lanes <= 0 || cfg.Lanes > len(cfg.Peers) {
 134  		cfg.Lanes = len(cfg.Peers)
 135  		if cfg.Lanes > 8 {
 136  			cfg.Lanes = 8
 137  		}
 138  	}
 139  	if cfg.UserAgent == "" {
 140  		cfg.UserAgent = "/btcd-lite:0.1.0/"
 141  	}
 142  	if cfg.ReadTimeout == 0 {
 143  		cfg.ReadTimeout = 2 * time.Minute
 144  	}
 145  	if cfg.Logf == nil {
 146  		cfg.Logf = func(string, ...any) {}
 147  	}
 148  	if cfg.Tracef == nil {
 149  		cfg.Tracef = func(string, ...any) {}
 150  	}
 151  	if cfg.Warnf == nil {
 152  		cfg.Warnf = cfg.Logf
 153  	}
 154  	if cfg.ProgressEvery == 0 {
 155  		cfg.ProgressEvery = time.Minute
 156  	}
 157  	p := &Pool{cfg: cfg, claimed: map[uint32]bool{}, stored: map[uint32]bool{}, reuse: map[string]*conn{}}
 158  	// Heights already in the store are not asked for again: a restart
 159  	// resumes where the last run stopped.
 160  	tip, _, ok := cfg.Headers.HeaderTip()
 161  	if ok {
 162  		for h := uint32(0); h <= tip; h++ {
 163  			hash, ok := p.hashAt(h)
 164  			if !ok {
 165  				continue
 166  			}
 167  			if cfg.Bodies.HasBlock(hash) || cfg.Staging.Has(h) {
 168  				p.stored[h] = true
 169  			}
 170  		}
 171  	}
 172  	return p, nil
 173  }
 174  
 175  // Reuse hands a pool a connection to a peer it already has open. The first
 176  // lane that asks for a connection to that address takes it; a lane that finds
 177  // none dials. A connection handed over is the pool's to close.
 178  func (p *Pool) Reuse(addr string, pc *v2peer.Peer) {
 179  	p.mu.Lock()
 180  	defer p.mu.Unlock()
 181  	p.reuse[addr] = connFrom(pc)
 182  }
 183  
 184  // Run pulls every height the header store has, one worker per peer, and
 185  // returns when there is nothing left to fetch or nothing left to fetch it with.
 186  //
 187  // One request is in flight per peer. That is what makes the fill a day's work
 188  // and not a week's on a chain of a million blocks: a sequential walk costs one
 189  // round trip per block, which at a hundred milliseconds is more than a day on
 190  // its own, and the network has nothing to do with it.
 191  func (p *Pool) Run(ctx context.Context) error {
 192  	tip, _, ok := p.cfg.Headers.HeaderTip()
 193  	if !ok {
 194  		return errors.New("filler: the header store has no tip")
 195  	}
 196  	p.target.Store(tip + 1)
 197  	stop := make(chan struct{})
 198  	go p.progressLoop(ctx, stop)
 199  	var wg sync.WaitGroup
 200  	for _, peer := range p.cfg.Peers[:min(p.cfg.Lanes, len(p.cfg.Peers))] {
 201  		wg.Add(1)
 202  		go func(addr string) {
 203  			defer wg.Done()
 204  			p.work(ctx, addr)
 205  		}(peer.Addr)
 206  	}
 207  	wg.Wait()
 208  	close(stop)
 209  	if ctx.Err() != nil {
 210  		return ctx.Err()
 211  	}
 212  	if first, n := p.holes(); n > 0 {
 213  		return fmt.Errorf("filler: %d heights are not stored, the first at %d", n, first)
 214  	}
 215  	return nil
 216  }
 217  
 218  // work owns one peer for the run: dial it, then ask for work until there is
 219  // none. A peer that fails is done for the run, which is the rule the pool has
 220  // always had: one bad answer is one bad answer, and the height goes back for
 221  // another worker.
 222  func (p *Pool) work(ctx context.Context, addr string) {
 223  	conn, err := p.dial(ctx, addr)
 224  	if err != nil {
 225  		p.cfg.Warnf("filler: %s: %v", addr, err)
 226  		return
 227  	}
 228  	defer func() { _ = conn.close() }()
 229  	l := &lane{addr: addr, conn: conn}
 230  	for {
 231  		if ctx.Err() != nil {
 232  			return
 233  		}
 234  		h, ok := p.next()
 235  		if !ok {
 236  			return
 237  		}
 238  		p.cfg.Tracef("filler: asking %s for %d", l.addr, h)
 239  		if err := p.fetch(ctx, l, h); err != nil {
 240  			p.fail(l, h, err)
 241  			return
 242  		}
 243  		p.complete(h)
 244  	}
 245  }
 246  
 247  // next hands out the next height nothing has stored and nothing is fetching,
 248  // skipping the heights other workers hold. Heights are independent bodies
 249  // keyed by hash, so fetching them out of order costs nothing: the staging log
 250  // records the height each body was asked for, and the processing pass files it
 251  // by hash.
 252  func (p *Pool) next() (uint32, bool) {
 253  	p.mu.Lock()
 254  	defer p.mu.Unlock()
 255  	target := p.target.Load()
 256  	for h := p.cursor.Load(); h < target; h++ {
 257  		if p.stored[h] {
 258  			p.cursor.Store(h + 1)
 259  			continue
 260  		}
 261  		if p.claimed[h] {
 262  			continue
 263  		}
 264  		p.claimed[h] = true
 265  		return h, true
 266  	}
 267  	return 0, false
 268  }
 269  
 270  // complete records a stored height.
 271  func (p *Pool) complete(h uint32) {
 272  	p.mu.Lock()
 273  	delete(p.claimed, h)
 274  	p.stored[h] = true
 275  	p.mu.Unlock()
 276  	p.done.Add(1)
 277  }
 278  
 279  // have is how many heights this instance holds.
 280  func (p *Pool) have() int {
 281  	p.mu.Lock()
 282  	defer p.mu.Unlock()
 283  	return len(p.stored)
 284  }
 285  
 286  // holes is the lowest height not stored and how many there are.
 287  func (p *Pool) holes() (uint32, int) {
 288  	p.mu.Lock()
 289  	defer p.mu.Unlock()
 290  	target := p.target.Load()
 291  	var first uint32
 292  	n := 0
 293  	for h := uint32(0); h < target; h++ {
 294  		if p.stored[h] {
 295  			continue
 296  		}
 297  		if n == 0 {
 298  			first = h
 299  		}
 300  		n++
 301  	}
 302  	return first, n
 303  }
 304  
 305  // progressLoop writes one line per period while a fill runs, on a timer rather
 306  // than on each block: the line that matters when a fill has stopped making
 307  // progress is the one that says it has, and a line driven by completions never
 308  // appears when there are none.
 309  func (p *Pool) progressLoop(ctx context.Context, stop <-chan struct{}) {
 310  	period := p.cfg.ProgressEvery
 311  	if period <= 0 {
 312  		return
 313  	}
 314  	t := time.NewTicker(period)
 315  	defer t.Stop()
 316  	lastDone, lastAt := uint64(0), time.Now()
 317  	for {
 318  		select {
 319  		case <-stop:
 320  			return
 321  		case <-ctx.Done():
 322  			return
 323  		case <-t.C:
 324  			done := p.done.Load()
 325  			rate := float64(done-lastDone) / time.Since(lastAt).Seconds()
 326  			lastDone, lastAt = done, time.Now()
 327  			target := p.target.Load()
 328  			have := p.have()
 329  			pct := 0.0
 330  			if target > 0 {
 331  				pct = 100 * float64(have) / float64(target)
 332  			}
 333  			eta := "never"
 334  			if rate > 0 && uint64(have) < uint64(target) {
 335  				left := float64(uint64(target) - uint64(have))
 336  				eta = time.Duration(left / rate * float64(time.Second)).Round(time.Second).String()
 337  			}
 338  			p.cfg.Logf("filler: %d/%d (%.1f%%) %.0f blocks/s, eta %s, %d failed, %d workers",
 339  				have, target, pct, rate, eta, p.failed.Load(), min(p.cfg.Lanes, len(p.cfg.Peers)))
 340  		}
 341  	}
 342  }
 343  
 344  func (p *Pool) hashAt(h uint32) (chainhash.Hash, bool) {
 345  	hdr, ok := p.cfg.Headers.Header(h)
 346  	if !ok {
 347  		return chainhash.Hash{}, false
 348  	}
 349  	return hdr.BlockHash(), true
 350  }
 351  
 352  func (p *Pool) dial(ctx context.Context, addr string) (*conn, error) {
 353  	// A caller that already has a connection to this peer hands it over: an
 354  	// instance syncs headers over one connection and wants the bodies over the
 355  	// same one. The pop is under the lock and the connect is not, so workers
 356  	// dial in parallel.
 357  	p.mu.Lock()
 358  	if c, ok := p.reuse[addr]; ok {
 359  		delete(p.reuse, addr)
 360  		p.mu.Unlock()
 361  		return c, nil
 362  	}
 363  	p.mu.Unlock()
 364  	last := int32(0)
 365  	if tip, _, ok := p.cfg.Headers.HeaderTip(); ok {
 366  		last = int32(tip)
 367  	}
 368  	c, err := connect(ctx, dialConfig{
 369  		net: chains.WireMagic(p.cfg.Profile), ua: p.cfg.UserAgent,
 370  		// The header chain is already on disk, so nothing about the node's
 371  		// services is needed to ask it for blocks: a node with no
 372  		// NODE_NETWORK still serves what it has.
 373  		services: 0, dial: p.cfg.Dial, logf: p.cfg.Logf, v2: p.cfg.V2,
 374  	}, addr, last, handshakeTimeout(p.cfg.ReadTimeout))
 375  	if err != nil {
 376  		return nil, err
 377  	}
 378  	return c, nil
 379  }
 380  
 381  // fetch asks one lane for one block and stores it.
 382  func (p *Pool) fetch(ctx context.Context, l *lane, height uint32) error {
 383  	hash, ok := p.hashAt(height)
 384  	if !ok {
 385  		return fmt.Errorf("filler: height %d has no header", height)
 386  	}
 387  	deadline := time.Now().Add(p.cfg.ReadTimeout)
 388  	if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
 389  		deadline = d
 390  	}
 391  	if err := l.conn.request(btcdhash.Hash(hash), time.Until(deadline)); err != nil {
 392  		return err
 393  	}
 394  	if err := p.accept(height, hash, l.conn.block); err != nil {
 395  		return err
 396  	}
 397  	return nil
 398  }
 399  
 400  // handshakeTimeout bounds a peer's negotiation, which is not the same as how
 401  // long a block may take: a peer that never completes a handshake must not hold
 402  // a worker for the request timeout.
 403  func handshakeTimeout(read time.Duration) time.Duration {
 404  	if read <= 0 || read > maxHandshake {
 405  		return maxHandshake
 406  	}
 407  	return read
 408  }
 409  
 410  // maxHandshake is the longest a peer's negotiation may take.
 411  const maxHandshake = 20 * time.Second
 412  
 413  // toBtcd is the same 32-byte hash in btcd's type. The byte order is the one
 414  // both types document as internal, so this is a copy and not a reversal.
 415  func toBtcd(h chainhash.Hash) btcdhash.Hash { return btcdhash.Hash(h) }
 416  
 417  // accept writes a block to the staging log under the height and hash it was
 418  // asked for.
 419  //
 420  // It does not hash the bytes and it does not touch the body store. The claim it
 421  // writes is what the processing pass checks the body against, and until that
 422  // pass runs the bytes are not a stored block: hashing inside the network loop
 423  // is the work the split exists to move out of it.
 424  func (p *Pool) accept(height uint32, want chainhash.Hash, raw []byte) error {
 425  	if len(raw) < 80 {
 426  		return fmt.Errorf("filler: block %d is %d bytes", height, len(raw))
 427  	}
 428  	return p.cfg.Staging.Append(height, want, raw)
 429  }
 430  
 431  // headerHash computes the hash a block's own header commits to, honouring the
 432  // fork's 164-byte form. The pool no longer calls it: the processing pass does,
 433  // on every body it takes out of the log.
 434  func headerHash(raw []byte) chainhash.Hash {
 435  	if len(raw) >= 4 && binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 && len(raw) >= btcwire.BlockHeaderV2Size {
 436  		var h btcwire.BlockHeader
 437  		if err := h.DeserializeV2(raw[:btcwire.BlockHeaderV2Size]); err == nil {
 438  			return h.BlockHash()
 439  		}
 440  	}
 441  	return chainhash.DoubleHashH(raw[:80])
 442  }
 443  
 444  func (p *Pool) fail(l *lane, height uint32, err error) {
 445  	p.failed.Add(1)
 446  	p.cfg.Warnf("filler: %s failed on %d: %v", l.addr, height, err)
 447  	p.mu.Lock()
 448  	delete(p.claimed, height)
 449  	// The cursor goes back to the height that failed so another worker looks
 450  	// at it: one peer failing on a block is not every peer failing on it.
 451  	if p.cursor.Load() > height {
 452  		p.cursor.Store(height)
 453  	}
 454  	p.mu.Unlock()
 455  	l.failed = true
 456  }
 457  
 458  // Done is the number of blocks stored.
 459  func (p *Pool) Done() uint64 { return p.done.Load() }
 460  
 461  // Failed is the number of failed block attempts.
 462  func (p *Pool) Failed() uint64 { return p.failed.Load() }
 463  
 464  // Close closes connections a caller handed over that no worker took. The
 465  // workers close their own.
 466  func (p *Pool) Close() error {
 467  	p.mu.Lock()
 468  	defer p.mu.Unlock()
 469  	var errs []error
 470  	for addr, c := range p.reuse {
 471  		if err := c.close(); err != nil {
 472  			errs = append(errs, err)
 473  		}
 474  		delete(p.reuse, addr)
 475  	}
 476  	return errors.Join(errs...)
 477  }
 478