// Package filler pulls blocks from peers and files them in a body store. // // It is a downloader, not a validator: it is handed the chain's header store, // it asks for the block at a height by the hash the header store already // verified, and it refuses a body whose header does not hash to that. Nothing // in it checks scripts or transactions, which is the plan's premise: a body is // bytes whose position in the chain the header chain fixed. // // One lane is one peer connection. A lane asks for one block at a time so that // a peer's answer is traceable to a request and a slow peer delays only itself. // // The connection is its own. Neutrino's p2p.Conn sends a version and then reads // for a reply, and against Bitcoin Core 30.3 that reply never comes: the node // closes the socket after the client's first frame, and the handshake ends in // "waiting for version: EOF". No frame byte in the client's message differs // from the specification, so rather than patch a connection type this package // does not own, the lane speaks the protocol itself: connect, version, wait for // the node's version and verack, then getdata one block at a time. package filler import ( "context" "encoding/binary" "errors" "fmt" "net" "sync" "sync/atomic" "time" btcdhash "github.com/btcsuite/btcd/chainhash/v2" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/chains" "git.smesh.lol/btcd-lite/internal/staging" "git.smesh.lol/btcd-lite/internal/store" "git.smesh.lol/btcd-lite/internal/v2peer" ) // Peer is one address the pool may dial. type Peer struct { Addr string } // Pool pulls blocks for one chain into a body store. type Pool struct { cfg PoolConfig mu sync.Mutex claimed map[uint32]bool // reuse holds connections a caller handed over, by address, until a lane // takes one. reuse map[string]*conn // stored is every height this instance holds, whether the body store or // the staging log has it, so the walk knows where it has been. stored map[uint32]bool // closeReuse closes connections a caller handed over and no worker took. closeReuse []*conn // cursor is where the next scan for work starts. It moves past heights // that are stored, and not past heights another worker is fetching, so a // height that fails is looked at again by whoever is free. cursor atomic.Uint32 // target is how many heights the header store had when the run started, // which is what a percentage and an estimate are against. target atomic.Uint32 done atomic.Uint64 failed atomic.Uint64 } // PoolConfig is what a pool is made of. type PoolConfig struct { // Chain names the chain in the log lines, so a run that fills two chains // says which one a line is about. It is not used to select anything: the // header store it is given is the chain. Chain string // Profile is the chain being followed; it carries the magic and the header // form. Profile *chain.Profile // Headers is the header store the chain's hashes come from. Headers *store.HeaderStore // Bodies is the store a block ends up in once a processing pass has // checked it. The pool does not write to it: it reads it to know which // heights are already done. Bodies *store.BlockStore // Staging is where the bodies go. A downloaded body is unverified bytes, // so it lands in a log nothing serves and the processing pass moves it. Staging *staging.Log // Peers are the addresses to dial, in preference order. Peers []Peer // Lanes is how many peers pull at once. Zero means one per peer, at most 8. Lanes int // UserAgent is advertised in version. UserAgent string // Logf receives lifecycle and progress lines; nil discards them. Logf func(string, ...any) // Tracef receives one line per block asked for. A full fill is a million // of them, so this is the debug seam: nil keeps them off. Tracef func(string, ...any) // Warnf receives the lines about a peer that failed. Nil sends them to // Logf. Warnf func(string, ...any) // V2 asks for BIP324 on a lane. Plaintext v1 is what every node accepts, // and the v2 path closes connections part way through a sync against some // real peers, so it is off unless a caller asks. V2 bool // ProgressEvery is how often a progress line is written while filling. // Zero means one minute. ProgressEvery time.Duration // Dial opens a connection to an address. Nil means TCP. Dial func(ctx context.Context, addr string) (net.Conn, error) // ReadTimeout bounds one frame read. Zero means two minutes. ReadTimeout time.Duration } type lane struct { addr string conn *conn failed bool } // NewPool returns a pool. It does not dial. func NewPool(cfg PoolConfig) (*Pool, error) { if cfg.Profile == nil || cfg.Headers == nil || cfg.Bodies == nil || cfg.Staging == nil { return nil, errors.New("filler: profile, headers, bodies and staging are required") } if len(cfg.Peers) == 0 { return nil, errors.New("filler: no peers") } if cfg.Lanes <= 0 || cfg.Lanes > len(cfg.Peers) { cfg.Lanes = len(cfg.Peers) if cfg.Lanes > 8 { cfg.Lanes = 8 } } if cfg.UserAgent == "" { cfg.UserAgent = "/btcd-lite:0.1.0/" } if cfg.ReadTimeout == 0 { cfg.ReadTimeout = 2 * time.Minute } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } if cfg.Tracef == nil { cfg.Tracef = func(string, ...any) {} } if cfg.Warnf == nil { cfg.Warnf = cfg.Logf } if cfg.ProgressEvery == 0 { cfg.ProgressEvery = time.Minute } p := &Pool{cfg: cfg, claimed: map[uint32]bool{}, stored: map[uint32]bool{}, reuse: map[string]*conn{}} // Heights already in the store are not asked for again: a restart // resumes where the last run stopped. tip, _, ok := cfg.Headers.HeaderTip() if ok { for h := uint32(0); h <= tip; h++ { hash, ok := p.hashAt(h) if !ok { continue } if cfg.Bodies.HasBlock(hash) || cfg.Staging.Has(h) { p.stored[h] = true } } } return p, nil } // Reuse hands a pool a connection to a peer it already has open. The first // lane that asks for a connection to that address takes it; a lane that finds // none dials. A connection handed over is the pool's to close. func (p *Pool) Reuse(addr string, pc *v2peer.Peer) { p.mu.Lock() defer p.mu.Unlock() p.reuse[addr] = connFrom(pc) } // Run pulls every height the header store has, one worker per peer, and // returns when there is nothing left to fetch or nothing left to fetch it with. // // One request is in flight per peer. That is what makes the fill a day's work // and not a week's on a chain of a million blocks: a sequential walk costs one // round trip per block, which at a hundred milliseconds is more than a day on // its own, and the network has nothing to do with it. func (p *Pool) Run(ctx context.Context) error { tip, _, ok := p.cfg.Headers.HeaderTip() if !ok { return errors.New("filler: the header store has no tip") } p.target.Store(tip + 1) stop := make(chan struct{}) go p.progressLoop(ctx, stop) var wg sync.WaitGroup for _, peer := range p.cfg.Peers[:min(p.cfg.Lanes, len(p.cfg.Peers))] { wg.Add(1) go func(addr string) { defer wg.Done() p.work(ctx, addr) }(peer.Addr) } wg.Wait() close(stop) if ctx.Err() != nil { return ctx.Err() } if first, n := p.holes(); n > 0 { return fmt.Errorf("filler: %d heights are not stored, the first at %d", n, first) } return nil } // work owns one peer for the run: dial it, then ask for work until there is // none. A peer that fails is done for the run, which is the rule the pool has // always had: one bad answer is one bad answer, and the height goes back for // another worker. func (p *Pool) work(ctx context.Context, addr string) { conn, err := p.dial(ctx, addr) if err != nil { p.cfg.Warnf("filler: %s: %v", addr, err) return } defer func() { _ = conn.close() }() l := &lane{addr: addr, conn: conn} for { if ctx.Err() != nil { return } h, ok := p.next() if !ok { return } p.cfg.Tracef("filler: asking %s for %d", l.addr, h) if err := p.fetch(ctx, l, h); err != nil { p.fail(l, h, err) return } p.complete(h) } } // next hands out the next height nothing has stored and nothing is fetching, // skipping the heights other workers hold. Heights are independent bodies // keyed by hash, so fetching them out of order costs nothing: the staging log // records the height each body was asked for, and the processing pass files it // by hash. func (p *Pool) next() (uint32, bool) { p.mu.Lock() defer p.mu.Unlock() target := p.target.Load() for h := p.cursor.Load(); h < target; h++ { if p.stored[h] { p.cursor.Store(h + 1) continue } if p.claimed[h] { continue } p.claimed[h] = true return h, true } return 0, false } // complete records a stored height. func (p *Pool) complete(h uint32) { p.mu.Lock() delete(p.claimed, h) p.stored[h] = true p.mu.Unlock() p.done.Add(1) } // have is how many heights this instance holds. func (p *Pool) have() int { p.mu.Lock() defer p.mu.Unlock() return len(p.stored) } // holes is the lowest height not stored and how many there are. func (p *Pool) holes() (uint32, int) { p.mu.Lock() defer p.mu.Unlock() target := p.target.Load() var first uint32 n := 0 for h := uint32(0); h < target; h++ { if p.stored[h] { continue } if n == 0 { first = h } n++ } return first, n } // progressLoop writes one line per period while a fill runs, on a timer rather // than on each block: the line that matters when a fill has stopped making // progress is the one that says it has, and a line driven by completions never // appears when there are none. func (p *Pool) progressLoop(ctx context.Context, stop <-chan struct{}) { period := p.cfg.ProgressEvery if period <= 0 { return } t := time.NewTicker(period) defer t.Stop() lastDone, lastAt := uint64(0), time.Now() for { select { case <-stop: return case <-ctx.Done(): return case <-t.C: done := p.done.Load() rate := float64(done-lastDone) / time.Since(lastAt).Seconds() lastDone, lastAt = done, time.Now() target := p.target.Load() have := p.have() pct := 0.0 if target > 0 { pct = 100 * float64(have) / float64(target) } eta := "never" if rate > 0 && uint64(have) < uint64(target) { left := float64(uint64(target) - uint64(have)) eta = time.Duration(left / rate * float64(time.Second)).Round(time.Second).String() } p.cfg.Logf("filler: %d/%d (%.1f%%) %.0f blocks/s, eta %s, %d failed, %d workers", have, target, pct, rate, eta, p.failed.Load(), min(p.cfg.Lanes, len(p.cfg.Peers))) } } } func (p *Pool) hashAt(h uint32) (chainhash.Hash, bool) { hdr, ok := p.cfg.Headers.Header(h) if !ok { return chainhash.Hash{}, false } return hdr.BlockHash(), true } func (p *Pool) dial(ctx context.Context, addr string) (*conn, error) { // A caller that already has a connection to this peer hands it over: an // instance syncs headers over one connection and wants the bodies over the // same one. The pop is under the lock and the connect is not, so workers // dial in parallel. p.mu.Lock() if c, ok := p.reuse[addr]; ok { delete(p.reuse, addr) p.mu.Unlock() return c, nil } p.mu.Unlock() last := int32(0) if tip, _, ok := p.cfg.Headers.HeaderTip(); ok { last = int32(tip) } c, err := connect(ctx, dialConfig{ net: chains.WireMagic(p.cfg.Profile), ua: p.cfg.UserAgent, // The header chain is already on disk, so nothing about the node's // services is needed to ask it for blocks: a node with no // NODE_NETWORK still serves what it has. services: 0, dial: p.cfg.Dial, logf: p.cfg.Logf, v2: p.cfg.V2, }, addr, last, handshakeTimeout(p.cfg.ReadTimeout)) if err != nil { return nil, err } return c, nil } // fetch asks one lane for one block and stores it. func (p *Pool) fetch(ctx context.Context, l *lane, height uint32) error { hash, ok := p.hashAt(height) if !ok { return fmt.Errorf("filler: height %d has no header", height) } deadline := time.Now().Add(p.cfg.ReadTimeout) if d, ok := ctx.Deadline(); ok && d.Before(deadline) { deadline = d } if err := l.conn.request(btcdhash.Hash(hash), time.Until(deadline)); err != nil { return err } if err := p.accept(height, hash, l.conn.block); err != nil { return err } return nil } // handshakeTimeout bounds a peer's negotiation, which is not the same as how // long a block may take: a peer that never completes a handshake must not hold // a worker for the request timeout. func handshakeTimeout(read time.Duration) time.Duration { if read <= 0 || read > maxHandshake { return maxHandshake } return read } // maxHandshake is the longest a peer's negotiation may take. const maxHandshake = 20 * time.Second // toBtcd is the same 32-byte hash in btcd's type. The byte order is the one // both types document as internal, so this is a copy and not a reversal. func toBtcd(h chainhash.Hash) btcdhash.Hash { return btcdhash.Hash(h) } // accept writes a block to the staging log under the height and hash it was // asked for. // // It does not hash the bytes and it does not touch the body store. The claim it // writes is what the processing pass checks the body against, and until that // pass runs the bytes are not a stored block: hashing inside the network loop // is the work the split exists to move out of it. func (p *Pool) accept(height uint32, want chainhash.Hash, raw []byte) error { if len(raw) < 80 { return fmt.Errorf("filler: block %d is %d bytes", height, len(raw)) } return p.cfg.Staging.Append(height, want, raw) } // headerHash computes the hash a block's own header commits to, honouring the // fork's 164-byte form. The pool no longer calls it: the processing pass does, // on every body it takes out of the log. func headerHash(raw []byte) chainhash.Hash { if len(raw) >= 4 && binary.LittleEndian.Uint32(raw[:4])&btcwire.HeaderV2Flag != 0 && len(raw) >= btcwire.BlockHeaderV2Size { var h btcwire.BlockHeader if err := h.DeserializeV2(raw[:btcwire.BlockHeaderV2Size]); err == nil { return h.BlockHash() } } return chainhash.DoubleHashH(raw[:80]) } func (p *Pool) fail(l *lane, height uint32, err error) { p.failed.Add(1) p.cfg.Warnf("filler: %s failed on %d: %v", l.addr, height, err) p.mu.Lock() delete(p.claimed, height) // The cursor goes back to the height that failed so another worker looks // at it: one peer failing on a block is not every peer failing on it. if p.cursor.Load() > height { p.cursor.Store(height) } p.mu.Unlock() l.failed = true } // Done is the number of blocks stored. func (p *Pool) Done() uint64 { return p.done.Load() } // Failed is the number of failed block attempts. func (p *Pool) Failed() uint64 { return p.failed.Load() } // Close closes connections a caller handed over that no worker took. The // workers close their own. func (p *Pool) Close() error { p.mu.Lock() defer p.mu.Unlock() var errs []error for addr, c := range p.reuse { if err := c.close(); err != nil { errs = append(errs, err) } delete(p.reuse, addr) } return errors.Join(errs...) }