headers

package
v0.16.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package headers follows a BRC-135 header lane and serves it to an overlay engine as that engine's chain tracker.

The lane carries bare 80-byte headers with no height on the wire, so height is derived by chaining from a known anchor. The result is the host's own view of the chain: every object the engine admits is verified against headers this host received itself, from the same network that delivered the object, with no third-party header service in the loop and no rate limit to be subject to. That is the whole point, and it is why this package enforces rather than reports.

This is the SPV root of trust

An engine verifies every BUMP against what this package answers. A header accepted here that should not have been is a merkle root the engine will trust. So:

  • Proof of work is ENFORCED, not labelled. A header that does not meet its target is rejected and never chains.
  • Proof of work is checked against a configured floor, not only against the header's own declared target. A header carries the target it claims to meet, so checking it against itself is a check an attacker writes the answer to. MinBits is the floor the operator sets from the network they are on.
  • A height may be claimed by more than one header. Competing headers are all retained and the canonical chain is tracked explicitly, so a fork does not silently overwrite the root a previous header committed to.

Index

Constants

View Source
const DefaultChaintracksPrefix = "/chaintracks/v2"

DefaultChaintracksPrefix is where a stock overlay-express host looks for the chaintracks read surface. It is NOT "/v2": the client's own default carries the "/chaintracks" segment, and an operator who wants a bare "/v2" passes an explicit prefix on their side.

View Source
const DefaultWarmDepth = 2016

DefaultWarmDepth is how many heights below and at the anchor a warm-up loads by default: one mainnet difficulty period, about two weeks of blocks. The objects a host verifies prove against recent blocks (a funding parent mined minutes to days ago); a proof older than this pays one anchor round trip on first use, as every proof did before warm-up existed.

View Source
const Size = 80

Size is a serialised block header.

Variables

View Source
var ErrHeaderSize = errors.New("headers: not 80 bytes")

ErrHeaderSize reports a header that is not exactly 80 bytes.

View Source
var ErrProofOfWork = errors.New("headers: insufficient proof of work")

ErrProofOfWork reports a header that does not meet its target, or that declares a target easier than the configured floor.

View Source
var ErrTruncated = errors.New("headers: object ends mid-structure")

ErrTruncated reports an object that ends mid-structure.

View Source
var ErrUnsatisfiableLength = errors.New("headers: declared length exceeds the bytes present")

ErrUnsatisfiableLength reports a declared length the remaining bytes could not possibly encode: the signature of an allocation attack.

Functions

func GuardBUMPs

func GuardBUMPs(obj []byte) error

GuardBUMPs bounds every declared length in an object's BUMP section against the bytes actually present, allocating nothing.

Why this exists

A BEEF reader that sizes a merkle path straight from the wire can be made to demand an arbitrary allocation by a very small object: the declared leaf count is a claim about bytes, and nothing checks that claim against the bytes that remain. That failure is NOT catchable in the usual way. A count large enough to be representable but too large to satisfy ends the process with a fatal out-of-memory error that no recover sees.

This lane is reachable by anyone who can put an object on the plane, so a verifying consumer is otherwise killable on demand for the cost of a few bytes. Call this before handing bytes to a parser. After it returns nil, every count the parser is about to allocate against has been bounded by the object's own length.

What this is not

It is not a second BEEF parser and it makes no validity claim: it returns nil for anything it cannot classify as a BUMP-carrying encoding, and the real parser remains the authority on whether an object is valid. It is also not made redundant by pinning a fixed parser version. A pin fixes the known case; the rule it enforces is the general one, for any length-prefixed field read from an untrusted source. Bound first, then parse, and keep the recover as the third layer rather than the first.

Types

type API

type API struct {
	// Listen is one or more addresses to serve on, typically the machine's
	// admin address and loopback.
	Listen []string
	// Store answers every route.
	Store *Store
	// ChaintracksPrefix overrides DefaultChaintracksPrefix.
	ChaintracksPrefix string
	Log               *slog.Logger
	// contains filtered or unexported fields
}

API is the header read surface. Two shapes are served from one store.

The native shape (GET /v1/tip, GET /v1/root/{height}) is this repository's own contract, consumed by the Go chain-tracker client in ./chainclient. It ships first and the bridge's own tests use it.

The chaintracks shape exists because a stock TypeScript host is pointed at a header service with one configuration call, and that call speaks this dialect. Serving it is what makes "point the engine at the bridge" a single line rather than a patch.

func (*API) Handler

func (a *API) Handler() http.Handler

Handler builds the mux.

func (*API) Listening

func (a *API) Listening() bool

Listening reports whether at least one listener is up.

func (*API) Serve

func (a *API) Serve(ctx context.Context) error

Serve runs the API on every configured address until ctx is cancelled.

type Anchor

type Anchor struct {
	Hash   chainhash.Hash
	Height uint32
}

Anchor is the known point the chain derives heights from.

type HeaderLookup

type HeaderLookup interface {
	HeaderAt(ctx context.Context, hash chainhash.Hash) (height uint32, root chainhash.Hash, err error)
}

HeaderLookup resolves a header the lane did not carry, so the chain can re-anchor across a gap instead of orphaning every header that follows. The lane is a live tail: a consumer that connects late, or loses its connection across a restart, sees headers whose parents it never received.

type HeaderSource

type HeaderSource interface {
	RootSource
	HeaderForHeight(ctx context.Context, height uint32) (hash, root chainhash.Hash, err error)
}

HeaderSource is a RootSource that can also name the block at a height. The read API needs it to serve a height the lane never carried without inventing a hash: a fallback that answers only roots leaves the hash unknown, and the API then answers 404 rather than guess.

type Observation

type Observation struct {
	Hash     chainhash.Hash
	Height   uint32
	Root     chainhash.Hash
	Chained  bool // its parent was known
	Reanchor bool // its parent was resolved through Lookup (a gap in the tail)
	Tip      bool // it became the best tip
	Replaced bool // another header already claimed this height
}

Observation is what one delivered header turned out to be.

type Options

type Options struct {
	// Anchor is the known starting point. Required.
	Anchor Anchor
	// Fallback answers roots below the anchor and across gaps.
	Fallback RootSource
	// Lookup re-anchors the chain after a gap in the tail.
	Lookup HeaderLookup
	// LookupTimeout bounds each Lookup call. Default 5s. It is never
	// unbounded: the lookup happens on the lane's hot path, and an
	// unbounded call there stalls the lane behind a slow third party.
	LookupTimeout time.Duration
	// MinBits is the compact-target floor. A header declaring an easier
	// target than this is rejected before its hash is even compared. Zero
	// disables the floor, which is only correct where the operator knows the
	// lane is trusted end to end.
	MinBits uint32
	// Window is the retained height window behind the tip. Zero is unbounded,
	// which is only appropriate for a short-lived process.
	Window uint32
	Log    *slog.Logger
}

Options configures a Store.

type RootSource

type RootSource interface {
	RootAt(ctx context.Context, height uint32) (*chainhash.Hash, error)
}

RootSource answers which merkle root a height commits to.

type Stats

type Stats struct {
	// Observed counts headers accepted off the lane, including re-deliveries.
	Observed uint64
	// Rejected counts headers refused on proof of work. A non-zero value is
	// not noise: this lane carries only headers, and a rejection means
	// something upstream sent one that does not meet the floor.
	Rejected uint64
	// Orphaned counts headers whose parent this tail never saw and could not
	// resolve. A burst is the expected shape after a reconnect.
	Orphaned uint64
	// Reanchored counts gaps closed through the lookup.
	Reanchored uint64
	// Replaced counts headers arriving for a height already claimed: a fork,
	// retained rather than overwritten.
	Replaced uint64
	// Pruned counts heights dropped out of the retention window.
	Pruned uint64
	// TipHeight is the best height the chain has reached. It reads zero until
	// the first header chains, which is the signal that the lane is not
	// feeding: an engine asking how far the chain has got would be told zero.
	TipHeight uint32
	// Heights is the number of retained canonical heights.
	Heights int
	// FromLane, FromHistory, FromFallback and Misses book where every root
	// answered came from. This is the discriminator for the claim that
	// verification is fed by the lane: a run in which every root was served by
	// the fallback has not demonstrated it, and without counting the sources
	// apart nobody can tell the difference after the fact.
	//
	// FromLane: a header this host received on its lane. FromHistory: the
	// anchor's answer for a height the lane could not have carried to this
	// process (at or below the startup anchor, or pruned out of the window),
	// which every object with an older ancestor needs and which says nothing
	// about the lane. FromFallback: the anchor's answer for a height the lane
	// should have carried (a gap, a re-anchored parent, a lane that stopped):
	// the posture change. Misses: no answer.
	FromLane, FromHistory, FromFallback, Misses uint64
}

Stats is a point-in-time snapshot of the header store.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the header chain. It is safe for concurrent use.

func New

func New(o Options) (*Store, error)

New returns a Store anchored at o.Anchor.

func (*Store) Handle

func (s *Store) Handle(ctx context.Context, hdr []byte) error

Handle consumes one header off the lane. It satisfies lanes.Handler for objfmt.ClassBlockHeader.

func (*Store) HeaderByHash added in v0.2.0

func (s *Store) HeaderByHash(hash chainhash.Hash) (height uint32, root chainhash.Hash, received, ok bool)

HeaderByHash resolves a header this store holds to its height and root.

It answers ONLY from what this store holds and never consults the anchor: a bridge asked to resolve a parent it does not have must say so, because the caller's next move is to keep the header orphaned and wait, and an answer relayed from a third party would re-anchor that caller onto a chain neither host received. This is the route a bridge's own anchor must serve, and serving it here is what lets one bridge anchor another instead of needing a separate header service.

received reports whether this header came off the lane rather than being re-anchored from the anchor, so a caller can tell a first-hand answer from a relayed one.

func (*Store) HeaderForHeight

func (s *Store) HeaderForHeight(ctx context.Context, height uint32) (hash, root chainhash.Hash, known bool, err error)

HeaderForHeight names the block at a height and its root. For a height on the lane the hash is the canonical one. For any other height the fallback must be a HeaderSource that can name the block; otherwise the hash is unknown and this reports so, because a read API that fills the gap with the tip's hash hands a client a fabricated header identity with a 200.

func (*Store) Known

func (s *Store) Known(height uint32) bool

Known reports whether the height's root came off the lane rather than the fallback. It is the discriminator for the claim that verification is fed by the lane: a run in which every root was served by the fallback has not demonstrated it.

func (*Store) Observe

func (s *Store) Observe(ctx context.Context, hdr []byte) (Observation, error)

Observe records one header.

A header that fails proof of work is rejected and never chains. A header whose parent is unknown is an orphan: it is reported, counted, and not chained, because a tail cannot assign it a height.

func (*Store) RootAt

func (s *Store) RootAt(ctx context.Context, height uint32) (*chainhash.Hash, error)

RootAt serves the canonical chain's root for a height, falling back below the anchor and across gaps. Fallback answers are cached, and every answer is booked by where it came from: lane (a header this host received on its lane), history or fallback (the anchor's answer, below or above historyTop), or miss.

func (*Store) Stats

func (s *Store) Stats() Stats

Stats returns a counter snapshot.

func (*Store) Tip

func (s *Store) Tip() (chainhash.Hash, uint32)

Tip returns the best header seen so far.

func (*Store) Warm added in v0.4.2

func (s *Store) Warm(ctx context.Context, depth uint32, workers int) error

Warm loads the roots of the depth heights ending at the anchor (anchor-depth+1 through the anchor itself) from the fallback into the store's fallback cache, with workers concurrent requests.

Why: the lane is a live tail, so every height at or below the anchor is answered by the fallback, and before this the first verification to name such a height paid that round trip on the verification path. Live, that put the bridge's verify p99 at 21 ms against a p50 of 0.66 ms. Loading them before the lanes open moves the round trips off the path.

Provenance: a warmed root is the anchor's answer for a height at or below the anchor, so it is booked as history when it is read. The bridge did not receive it, so it is never booked as lane; and the lane, a live tail from the anchor, could not have carried it, so it is not booked as fallback either, which would report a lane gap on every host that verifies an older ancestor. A height the lane later delivers is answered from the lane, as before: the canonical chain is consulted before the cache.

Warm never fails the bridge. A height the fallback cannot answer is counted and left to be fetched on first use; a cancelled ctx stops the warm-up where it is. The returned error is ctx's, or an error when there is no fallback.

func (*Store) WarmStats added in v0.4.2

func (s *Store) WarmStats() WarmStats

WarmStats returns the warm-up's progress.

type Tracker

type Tracker struct {
	// contains filtered or unexported fields
}

Tracker adapts a RootSource to the SDK's ChainTracker for an in-process Go consumer.

It holds NO cache of roots. An earlier version cached every root the lane delivered, and that cache could diverge from the store's canonical chain in two ways that a chain tracker must never allow: a competing header at a height already held overwrote the cached root although the store's canonical chain had not changed, and a reorganisation rewrote the store's canonical chain while the cache kept the old roots for ever. Either way the tracker would answer true for a root the chain no longer commits to. The store already answers a root in one map lookup and already caches fallback answers, so there is nothing for a second cache to buy that is worth that.

Provenance of answers is booked by the store, not here, because the path the engine's reads actually take is the read API over the store, which never touches this adapter.

func NewTracker

func NewTracker(src RootSource) *Tracker

NewTracker returns a tracker over src.

func (*Tracker) CurrentHeight

func (t *Tracker) CurrentHeight(_ context.Context) (uint32, error)

CurrentHeight reports the best height this host has reached.

This is live, not decorative: the round-one host reads it on its unproven eviction paths and serves it to its own callers.

func (*Tracker) IsValidRootForHeight

func (t *Tracker) IsValidRootForHeight(ctx context.Context, root *chainhash.Hash, height uint32) (bool, error)

IsValidRootForHeight reports whether root is the merkle root committed at height, asking the source every time so the answer always follows the canonical chain.

func (*Tracker) Learn

func (t *Tracker) Learn(height uint32)

Learn advances the reported height. Call it when a header becomes the TIP, not for every header that chains: a competing header at a height already held is chained but is not the tip, and must not be reported as progress.

The lane reader MUST call this. It is the only writer of the tracker's height, and an engine asking how far the chain has got is told zero until it is called: a host that answers roots but reports height zero looks to an engine like a chain that has not started.

type WarmStats added in v0.4.2

type WarmStats struct {
	// Target is the number of heights the warm-up set out to load.
	Target uint64
	// Loaded and Failed count heights answered and not answered by the
	// fallback. A failed height is not an error for the bridge: it is fetched
	// on first use, exactly as without warm-up.
	Loaded, Failed uint64
	// Done is true once the warm-up has finished, whether or not every height
	// loaded. Duration is its wall time, zero until Done.
	Done     bool
	Duration time.Duration
}

WarmStats is the progress of the startup warm-up.

Directories

Path Synopsis
Package chainclient is a chain tracker backed by an overlay-bridge header read API.
Package chainclient is a chain tracker backed by an overlay-bridge header read API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL