produce

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: Apache-2.0 Imports: 31 Imported by: 0 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 produce is a blogs producer: it turns batches of log lines into signed carriers on one stream, publishes each once, and anchors the stream's batches in one mined token per interval (docs/spec.md sections 3 to 6 and 12).

It is built on bcommon's producer package. A Payer pays for funding trees from the home's coin pool. Two Trees mint them, both with Ahead: one of small outputs that carriers spend, one of larger outputs that pay each anchor's fee (an anchor spends only its predecessor and funding outputs, so its fee comes from a funding output). Payer.Async is off: a tree is settled and waited for, and published only once it has mined, because a host admits funding outputs only from mined transactions. A Collector collects each anchor's proof, and the anchor is published once, after it mines. Kept holds the one copy of every tree and anchor in use.

Every tree is recorded with its fee coin before it reaches the settlement leg (Trees.Prepare), and a run's start settles the records an earlier run left (recover.go), so a run that stops between a tree's signing and its adoption loses neither the coin nor the tree.

The state file (package state) is written before every publish, so a crash never makes the producer build a second carrier for a seq it may already have published: the persisted carrier is published again instead.

Index

Constants

View Source
const MaxLine = 64 << 10

MaxLine is the longest line a batch carries, LF included; a longer input line is carried as several lines.

Variables

View Source
var ErrNotWorthIt = errors.New("the unused outputs cannot pay the fee to spend them")

ErrNotWorthIt is a retirement whose outputs cannot pay its own fee.

View Source
var ErrSweepInFlight = errors.New("a sweep is still in flight; finish it first")

ErrSweepInFlight is a new sweep asked for while one is still in flight.

View Source
var Params = carrier.Params{
	Derivation: logrec.BatchDerivation,
	FundingTag: logrec.TagFunding,
	ValidatePayload: func(p []byte) error {
		_, err := logrec.DecodeBatch(p)
		return err
	},
}

Params are the carrier parameters of every blogs carrier.

View Source
var Profile = bwallet.Profile{
	FundProtocol:   logrec.Protocol,
	FundKeyID:      logrec.KeyFund,
	FundBasket:     "blogs fund",
	Version:        "blogs-1",
	LegacyPoolFile: "blogs-pool.json",
}

Profile is the embedded wallet's profile: the fund key under [1, "blogs"] key id fund, and the registered basket.

View Source
var Retries = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second}

Retries are the waits between the tries of a publish before the run stops with the carrier persisted.

Functions

func FeeError

func FeeError(err error) error

FeeError words the library's refusals to find a fee input for an operator. Every other error passes as it is.

func FileID

func FileID(fi os.FileInfo) (dev, ino uint64)

FileID is a file's device and inode.

func Follow

func Follow(ctx context.Context, path string, offset int64, poll time.Duration, follow bool, note func(string, ...any)) (<-chan Line, <-chan error, error)

Follow reads path from offset, each line carrying the file's position after it. Without follow it stops at the end of the file, a partial last line given an LF. With follow it tails the file: every complete line as it is appended, waiting poll between reads at the end; a file that shrinks below the offset (truncated) is read again from the start, and a path that names a new file (rotated) is switched to, from the new file's start, once the old one is read to its end. A partial line waits for its LF. The channel closes at the end, or when ctx ends.

func IsSweepRefused

func IsSweepRefused(err error) bool

IsSweepRefused reports whether err is a sweep the network refused.

func ReadLines

func ReadLines(r io.Reader) (<-chan Line, <-chan error)

ReadLines sends r's lines on the returned channel, each LF-terminated (a last line without one gets one), parts of a line longer than MaxLine as lines of their own, and closes it at EOF. A read error is sent on the error channel before the close.

func ValidURLPrefix

func ValidURLPrefix(prefix string) error

ValidURLPrefix checks that a locator hint built from prefix is one the locator rules accept: https, printable ASCII, and room for the digest.

Types

type Batch

type Batch struct {
	Raw   []byte
	Count int
	// Tail is the followed file's position after the batch's last line.
	Tail *state.Tail
}

Batch is one batch's content before encoding: LF-terminated lines.

type Cut

type Cut struct {
	MaxBytes int
	MaxLines int
	MaxWait  time.Duration
	MinGap   time.Duration
}

Cut is when a batch is closed: at MaxBytes bytes or MaxLines lines, whichever comes first, or MaxWait after its first line. MinGap, when set, is the least time between two published batches: a batch cut sooner waits, and meanwhile the input is not read.

type Engine

type Engine struct {
	St     *state.Stream
	Signer *bwallet.Signer
	Pool   *bwallet.Pool
	Legs   Legs
	Opts   Options
	// Now is the clock records are stamped with.
	Now func() time.Time
	// Note receives progress lines; Verbose adds one per batch.
	Note    func(format string, args ...any)
	Verbose bool
	// Published, when set, is told of each batch this run builds and
	// publishes: its seq, its carrier (the commitment, as a txid) and its
	// lines. A carrier a previous run persisted and this one republishes
	// is not reported.
	Published func(seq uint64, carrier string, raw []byte)
	// contains filtered or unexported fields
}

Engine is one producer run on one stream.

func New

func New(st *state.Stream, signer *bwallet.Signer, pool *bwallet.Pool, legs Legs, o Options) (*Engine, error)

New builds an engine over a stream's state.

func (*Engine) Close

func (e *Engine) Close(ctx context.Context) error

Close collects any tree still being minted ahead, so its change reaches the pool, and records every tree that is settled and was never adopted (minted ahead, or recovered while the current tree had outputs left) in the state's Ahead list, so a sweep finds it. Such a tree keeps the record made when it was signed, and the next run's start holds it again.

func (*Engine) Drain

func (e *Engine) Drain(ctx context.Context) error

Drain anchors every batch built so far and waits until the anchors are mined and published, or ctx ends.

func (*Engine) FinishSweeps

func (e *Engine) FinishSweeps(ctx context.Context) error

FinishSweeps settles every sweep in flight, waits for it to mine, adds its change to the pool, and publishes it once, with its proof, to the stream's topic when the hosts hold what it spends. A sweep the network refuses for good (the node names another transaction as the spender of one of its inputs) is marked failed, its fee coin given back when the node shows it unspent, and a *SweepRefusedError returned: it is no longer in flight, so the next sweep goes on. Any other error leaves the sweep in flight for the next run.

func (*Engine) InFlight

func (e *Engine) InFlight() bool

InFlight reports whether a sweep is built and neither finished nor given up on.

func (*Engine) Prime added in v0.4.0

func (e *Engine) Prime(ctx context.Context) error

Prime publishes a carrier a previous run persisted, and makes sure the stream has a batch funding tree with an output to spend, minting one and waiting for it to mine when it has none. It spends nothing: the next batch takes that output. A sidecar primes before it takes records, so no sender waits for a block.

func (*Engine) Publish

func (e *Engine) Publish(ctx context.Context, b Batch) error

Publish encodes b, splits it while its encoding is over the record's bound, and publishes each part as one batch.

func (*Engine) PublishTrees

func (e *Engine) PublishTrees(ctx context.Context) error

PublishTrees publishes every adopted tree whose publish failed, the same bytes, so a host that already holds one answers a duplicate. A tree that still cannot be published stays publish pending and is the error: the run stops, as it does for a carrier it cannot publish, and the next command starts here.

func (*Engine) RecoverTrees

func (e *Engine) RecoverTrees(ctx context.Context) error

RecoverTrees settles every tree an earlier run signed for a coin and did not adopt, before anything is spent:

  • a tree the chain holds is adopted and published, or, while the current tree of its kind has outputs left, held for the switch, and its change is taken. A held tree is recorded among the trees minted ahead, and its record stays until the switch adopts it;
  • a tree with no proof whose coin another transaction spent is gone, whether the node does not know it or still serves it after it lost a double spend, and its record is dropped;
  • a tree the node does not know whose coin is unspent never reached the chain as far as the node can say now. The coin goes back to the pool, and the record is kept for one more command: a tree handed to the leg an instant before the run stopped can reach the node later. The second such answer drops the record;
  • a node that cannot answer, or a tree that has not mined in time, decides nothing: the record stays, the next command asks again, and this one goes on.

Payer.Async is off, so a tree found on the chain and not yet mined is waited for. The wait for all the records together is bounded by the wait for one proof (Options.Wait), so a start never waits without end; a tree still unmined then keeps its record. When ctx itself ends, the error says so and the command stops. Otherwise only a failure to save the state is returned.

func (*Engine) Resume

func (e *Engine) Resume(ctx context.Context) error

Resume publishes the persisted carrier, if there is one: the same bytes, so a host that already holds it answers a duplicate.

func (*Engine) Retirable

func (e *Engine) Retirable() []TreeInfo

Retirable lists the trees a retirement would sweep: every tree not in use with unused outputs.

func (*Engine) Retire

func (e *Engine) Retire(ctx context.Context, txid string) (*state.Sweep, error)

Retire builds and persists one sweep of the unused outputs of the tree txid, which must not be in use, paying their value less the fee back to the coin pool. ErrNotWorthIt means the value cannot pay the fee.

func (*Engine) Retract

func (e *Engine) Retract(ctx context.Context, txid string, vouts []uint32, seqs []uint64) (*state.Sweep, error)

Retract builds and persists one sweep of the batch tree txid over vouts (every output of the tree when vouts is empty), with its fee from the coin pool. seqs, when known, are the batches it retracts.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, src <-chan Line, srcErr <-chan error, cut Cut, grace time.Duration) error

Run reads lines until src closes or ctx ends, cuts them into batches and publishes each, and ticks the anchor chain every Poll. When src closes, the last batch is published. When ctx ends, the batch being built is published under a context of its own, bounded by grace, and Run returns ctx's error. A batch of a followed file records the position its last line ends at.

func (*Engine) Settled

func (e *Engine) Settled() bool

Settled reports whether every batch is anchored and nothing is in flight.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context) error

Start reads the chain tip for coinbase maturity, collects the proofs of what the pool holds back until mined, settles the funding trees an earlier run signed and did not adopt, publishes the trees an earlier run adopted and could not publish, and publishes the carrier a previous run persisted and may not have published. Nothing is spent before it returns.

func (*Engine) Tick

func (e *Engine) Tick(ctx context.Context, force bool) error

Tick advances the anchor chain by what can be done without waiting: it collects the proof of the anchor in flight and publishes it once mined, and builds and settles the next anchor when none is in flight, a batch is unanchored and the interval has passed (or force is set).

func (*Engine) Topic

func (e *Engine) Topic() string

Topic is the stream's topic.

func (*Engine) Tree

func (e *Engine) Tree(txid string) (TreeInfo, bool)

Tree finds one recorded tree by txid.

func (*Engine) Trees

func (e *Engine) Trees() []TreeInfo

Trees lists every funding tree the stream recorded, once each, in the order batch trees, anchor fee trees, trees minted ahead.

func (*Engine) Unanchored

func (e *Engine) Unanchored() int

Unanchored is how many batches no published anchor covers yet.

type Legs

type Legs struct {
	Settler publish.Settler
	// Chain is the chain view proofs, parents and spends are read from: a
	// node, WhatsOnChain, or both (nodeapi.ParseChain).
	Chain nodeapi.Chain
	// Tip answers the chain's height, for coinbase maturity: the header
	// source.
	Tip interface {
		CurrentHeight(ctx context.Context) (uint32, error)
	}
	Arcade     *publish.Arcade
	Facade     *publish.Facade
	Hosts      *unicast.Set
	SweepHosts *unicast.Set
}

Legs are the endpoints a producer talks to. Objects go to exactly one of Facade (plane mode: one submit, which the plane delivers to every subscribed host) and Hosts (unicast mode: one submit to each host). SweepHosts, in plane mode, are hosts every sweep is also submitted to directly: no lookup class names the sweep of a batch, so a host off the plane receives one only this way.

type Line

type Line struct {
	B    []byte
	Tail *state.Tail
	// Split is set on every part of an input line longer than MaxLine.
	Split bool
}

Line is one input line, LF-terminated, and for a followed file the file's position just after it.

type Options

type Options struct {
	// Profile is logrec.ProfileFull or logrec.ProfileDigest; Encoding is
	// logrec.EncodingLines or logrec.EncodingLinesGzip.
	Profile  uint64
	Encoding uint64
	// ContentDir is where a digest-only batch's content is written, named
	// by its SHA-256 in hex; URLs are prefixes the digest's hex is appended
	// to for the locator's fetch hints. Digest-only only.
	ContentDir string
	URLs       []string
	// Interval is the anchor cadence: an anchor is built once Interval has
	// passed since the last one and a batch is unanchored.
	Interval time.Duration
	// AnchorBatches anchors early, once this many batches are unanchored,
	// and is the most one anchor covers; zero is the record's bound,
	// logrec.MaxIntervalBatches.
	AnchorBatches int
	// Poll is how often proofs are asked for.
	Poll time.Duration
	// ObjectBound is the plane's object bound, in bytes.
	ObjectBound int
	// TreeCount and TreeSats size the batch funding trees; AnchorTreeCount
	// and AnchorTreeSats the anchor fee trees. Ahead and AnchorAhead are
	// how few outputs a tree has left when the next is minted ahead.
	TreeCount       int
	TreeSats        uint64
	AnchorTreeCount int
	AnchorTreeSats  uint64
	Ahead           uint32
	AnchorAhead     uint32
	// Fees is the fee policy of trees and anchors.
	Fees mint.Fees
	// Wait bounds a wait for one proof.
	Wait time.Duration
}

Options are a producer's choices. None of them is frozen (docs/frozen.md section 8).

type SweepRefusedError

type SweepRefusedError struct {
	Txid string
	Kind string
	// Why is the refusal, as the evidence said it.
	Why string
	// Coin is what became of the fee coin.
	Coin string
}

SweepRefusedError is a sweep the network refused. The sweep is marked failed in the stream's state, its fee coin is back in the pool when the node shows it unspent, and the next sweep of the stream goes on.

func (*SweepRefusedError) Error

func (e *SweepRefusedError) Error() string

type TreeInfo

type TreeInfo struct {
	Kind    TreeKind
	Current bool
	Tree    funding.Tree
}

TreeInfo is one funding tree the stream recorded.

type TreeKind

type TreeKind string

TreeKind is which of the stream's lists a tree is recorded in.

const (
	BatchTree  TreeKind = "batch"
	AnchorTree TreeKind = "anchor"
	AheadTree  TreeKind = "ahead"
)

The tree kinds.

Jump to

Keyboard shortcuts

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