module

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 28 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 module is the bbox overlay module in Go: tm_bbox_<name>_<suffix> for each configured office and ls_bbox for all of them, written to bcommon's engine-neutral contract (github.com/lightwebinc/bcommon/module) so that any Go overlay host that carries the adapter mounts it. It is the twin of the TypeScript module under host/src (frozen), built from the Go core: the admission rules are boxrec.Admit, the questions boxrec's classes, and the index the TypeScript module's statuses, rows and retention, with its journal byte for byte.

Configuration is the TypeScript module's, read from the environment when the host calls the factory (docs/host.md): BBOX_OFFICES, BBOX_STATE_DIR, BBOX_RETENTION_DAYS, BBOX_MAX_BEEF, BBOX_LISTEN, BBOX_PRICES, BBOX_PAYEE_KEY, BBOX_HEADERS_URL (OVERLAY_CHAIN_TRACKER_URL when unset), BBOX_SESSIONS, BBOX_SESSION_TTL, the handshake and response budgets, BBOX_ARCADE_URL, BBOX_ASSET_URL, BBOX_CHAIN, BBOX_WOC_KEY and the BBOX_ACCEPT_* rule, and one of its own, BBOX_JOURNAL_SYNC_MS (the rows journal's group commit window). Every mistake is an error, and the host refuses to start.

Index

Examples

Constants

View Source
const (
	DefaultJournalSyncMs = 100
	MaxJournalSyncMs     = 60_000
)

The rows journal's group commit window (BBOX_JOURNAL_SYNC_MS): lines are written at once and fsynced together this often, off the lookup service's lock; 0 fsyncs each line before the admission goes on, as the TypeScript module does. The default and the bound are a timed write-ahead log's usual ones.

View Source
const (
	WindowBefore = 30 * 86400
	WindowAfter  = 3600
)

The answer window (spec section 8.3): 30 days before the host's time, one hour after.

View Source
const (
	Evidence             = 8
	EvidenceAcknowledged = 64
)

Evidence is how many superseded carriers are kept per outpoint, and EvidenceAcknowledged how many when its winner is acknowledged.

View Source
const (
	StatusRetracted    = "retracted"
	StatusSuperseded   = "superseded"
	StatusAcknowledged = "acknowledged"
	StatusHeld         = "held"
)

The statuses of spec section 8.2.

View Source
const (
	PruneEvery = time.Hour
	TickEvery  = 30 * time.Second
)

PruneEvery is how often retention runs; TickEvery how often the background tick runs (the payment watch; retention every PruneEvery).

View Source
const FloorDays = 31

FloorDays is the retention floor for receipts and sweeps, from first sight (spec section 8.4).

View Source
const JournalFile = "outpoints.jsonl"

JournalFile is the journal's file name in the state directory: the TypeScript module's, so one state directory reads under either.

View Source
const Name = "bbox"

Name is the module's name, as a host's module list names it.

View Source
const RecentAdmissions = 4096

RecentAdmissions is how many admitted txids a manager remembers to count each once.

Variables

View Source
var AdmitKinds = []string{"envelope", "receipt", "sweep", "spend"}

AdmitKinds are what an admitted transaction was.

View Source
var Build = "unversioned"

Build is the version the host logs; a binary sets it.

View Source
var Classes = func() []termsroute.PricedClass {
	out := make([]termsroute.PricedClass, len(boxrec.Classes))
	for i, c := range boxrec.Classes {
		out[i] = termsroute.PricedClass{Name: c.Name, Free: c.Free}
	}
	return out
}()

Classes are the lookup classes as the route prices them.

View Source
var ErrNoSubmission = errors.New("bbox: the host did not hand the manager the submission's bytes (bcommon module.WithSubmission)")

ErrNoSubmission is a host that hands the manager a parsed BEEF without the submission's bytes (bcommon module.WithSubmission): the manager decides on the wire form (the counts a BEEF declares, which proofs it carries), which a parsed and merged BEEF no longer shows.

View Source
var Reasons = []string{
	"too-large", "cbor", "key-type", "missing", "type", "range", "identity", "office", "box", "expires", "acks",
	"content-json", "content-shape", "content-cipher", "content-signature",
	"carrier-shape", "beef", "mineable", "unlock", "lock", "signature", "funding", "unmined", "not-bbox",
}

Reasons are every label a host counts a refused submission by (spec sections 3.1, 4.6, 5 and 8.1). The record rule magic is not among them: an output claims a record only by its magic, so admission never reaches it.

Functions

func ParseOffices

func ParseOffices(raw string) ([]string, error)

ParseOffices parses BBOX_OFFICES: office identifiers, once each.

Types

type Classified

type Classified struct {
	Q      *boxrec.Question
	Priced bool
}

Classified is a question, validated, and whether this host prices it.

type Config

type Config struct {
	Offices       []string
	StateDir      string
	RetentionDays int
	MaxBEEF       int
	// JournalSync is the rows journal's group commit window; 0 syncs every
	// line.
	JournalSync time.Duration
	// Listen is the terms route's host:port; empty for none.
	Listen   string
	Prices   map[string]uint64
	PayeeKey *ec.PrivateKey
	// HeadersURL is the header source payments verify against; empty for
	// none.
	HeadersURL string
	Sessions   termsroute.SessionBound
	Budget     termsroute.BudgetConfig
	Response   termsroute.ResponseBudgetConfig
	Accept     termsroute.AcceptConfig
}

Config is the module's configuration.

func ParseConfig

func ParseConfig(getenv func(string) string) (*Config, error)

ParseConfig reads the whole configuration through getenv.

type Counts

type Counts struct {
	Envelopes, Receipts, Sweeps, Rows, Lines, PendingDeletes int
}

Counts are what the index holds, the gauges' values.

type Deleter

type Deleter interface {
	DeleteOutput(ctx context.Context, outpoint *transaction.Outpoint, topic string) error
}

Deleter is a storage that can delete an output: what retention and the evidence cap need beyond the contract's RestoreStorage. A host whose storage cannot delete keeps what the index dropped, unanswered.

type EngineVerified

type EngineVerified struct{}

EngineVerified is the chain tracker the managers read a sweep's proof with. The engine has verified a submission's proofs against the host's headers before it calls a topic manager; what the sweep rule still needs is that the proof is present and names the transaction, which MerklePath.Verify checks before it asks a tracker. This tracker answers yes to what the engine already checked, as the TypeScript module's does.

func (EngineVerified) CurrentHeight

func (EngineVerified) CurrentHeight(context.Context) (uint32, error)

CurrentHeight implements chaintracker.ChainTracker.

func (EngineVerified) IsValidRootForHeight

func (EngineVerified) IsValidRootForHeight(context.Context, *chainhash.Hash, uint32) (bool, error)

IsValidRootForHeight implements chaintracker.ChainTracker.

type FileJournal

type FileJournal struct {
	Path string
	// SyncEvery is the group commit window; zero syncs every line.
	SyncEvery time.Duration
	// OnSync, when set, is called after each timed fsync with the lines it
	// covered, how long it took and its error. It runs on the timer's
	// goroutine, holding no lock of the journal's.
	OnSync func(lines int, took time.Duration, err error)
	// contains filtered or unexported fields
}

FileJournal is the journal as a file, outpoints.jsonl in a directory. Each line is written to the file before Append returns, so a process that dies loses nothing (the line is in the page cache). When it reaches the disk is SyncEvery: zero flushes each line before Append returns, as the TypeScript module does; more is a group commit, one fsync for every line written in the window, run by a timer off the caller's path, so a power loss loses at most the window (the posture of the engine's store, which syncs its write-ahead log on a timer). Close flushes. A last line cut short by a crash is cut off on load; any other line that does not parse stops the load, because a row silently skipped could let a funding output pay twice.

func NewFileJournal

func NewFileJournal(dir string) (*FileJournal, error)

NewFileJournal makes the directory and names the file. The journal syncs every line until SyncEvery is set.

func (*FileJournal) Append

func (j *FileJournal) Append(l Line) error

Append implements Journal: the line is in the file when it returns, and on disk too when SyncEvery is zero; otherwise a timed fsync takes it there within SyncEvery. An error of an earlier timed fsync is returned once, by the next Append, after its line is written.

func (*FileJournal) Close

func (j *FileJournal) Close() error

Close flushes what is pending and closes the file. A later Append opens it again.

func (*FileJournal) Load

func (j *FileJournal) Load() ([]Line, error)

Load implements Journal.

func (*FileJournal) Sync

func (j *FileJournal) Sync() error

Sync flushes every line written so far to disk now.

type Front

type Front struct {
	*termsroute.Front
	Addr string
}

Front is the terms route and where it listens.

type Journal

type Journal interface {
	Load() ([]Line, error)
	Append(l Line) error
}

Journal is where the rows live. Append is durable when it returns or within the journal's sync window (FileJournal.SyncEvery).

type Line

type Line struct {
	K      string   `json:"k"`
	Op     string   `json:"op,omitempty"`
	C      string   `json:"c,omitempty"`
	Txid   string   `json:"txid,omitempty"`
	Kind   string   `json:"kind,omitempty"`
	Office string   `json:"office,omitempty"`
	To     string   `json:"to,omitempty"`
	By     string   `json:"by,omitempty"`
	Acks   []string `json:"acks,omitempty"`
	At     *int64   `json:"at,omitempty"`
	W      *bool    `json:"w,omitempty"`
	S      string   `json:"s,omitempty"`
	H      *int64   `json:"h,omitempty"`
}

Line is one journal line: the outpoint rows ls_bbox keeps for the host's life (spec sections 8.2 and 8.4) beside the engine's storage, as an append-only journal. The engine's storage holds the outputs a host still keeps; it cannot hold what the rows must outlive: a dropped carrier, a dropped sweep, and which carrier won an outpoint. One JSON object a line:

{"k":"c","op":"<txid>.<vout>","c":"<C>","txid":"<txid>","kind":"e","office":"...","to":"<hex>","at":<s>}
{"k":"c",...,"kind":"r","by":"<hex>","acks":["<C>",...],"at":<s>}
{"k":"d","op":"...","c":"<C>","w":true}
{"k":"s","op":"...","s":"<sweep txid>","office":"...","h":<height>,"at":<s>}

c lines are every carrier any office admitted, with what the winner rule reads (an envelope's to, a receipt's by and acks); d lines are drops, w when the dropped carrier was its outpoint's winner; s lines are the outpoints admitted sweeps spent. Commitments are in hash byte order and txids in display order, both lowercase hex; at is the host's time of first sight in Unix seconds. The bytes are the TypeScript module's, key for key, so one journal reads under either.

type MemoryJournal

type MemoryJournal struct {
	Lines []Line
	// contains filtered or unexported fields
}

MemoryJournal is a journal in memory, for tests and for a host that accepts losing it.

func (*MemoryJournal) Append

func (m *MemoryJournal) Append(l Line) error

Append implements Journal.

func (*MemoryJournal) Load

func (m *MemoryJournal) Load() ([]Line, error)

Load implements Journal.

type Mounted

type Mounted struct {
	Module bmodule.Module
	LS     *Service
	// Front is the terms route, when configured.
	Front *Front
	// contains filtered or unexported fields
}

Mounted is the module for one configuration: the contract's Module, the lookup service, and what Start runs.

func Mount

func Mount(host bmodule.Host, c *Config, overlayTopics []string, journal Journal, hdrs chaintracker.ChainTracker, now func() time.Time) (*Mounted, error)

Mount builds the module for c. overlayTopics is OVERLAY_TOPICS, when known; journal replaces the state directory's, hdrs the configured header source and now the host's clock, for tests.

func New

func New(host bmodule.Host, getenv func(string) string) (*Mounted, error)

New is the factory a host calls: the configuration from getenv, checked against OVERLAY_TOPICS.

Example

A host builds the module from its environment: one topic manager per office and ls_bbox for all of them.

package main

import (
	"fmt"
	"os"
	"sort"

	bmodule "github.com/lightwebinc/bcommon/module"

	"github.com/lightwebinc/bbox/module"
)

// quiet is a host that keeps no log or metrics.
type quiet struct{}

func (quiet) Log(string, map[string]any)             {}
func (quiet) Metrics() bmodule.Metrics               { return quiet{} }
func (quiet) Inc(string, map[string]string, float64) {}
func (quiet) Preset(string, map[string]string)       {}
func (quiet) Gauge(string, func() float64)           {}

// A host builds the module from its environment: one topic manager per
// office and ls_bbox for all of them.
func main() {
	dir, err := os.MkdirTemp("", "bbox-module-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	env := map[string]string{
		"BBOX_OFFICES":   "example_office_qzxkvbmwtr",
		"BBOX_STATE_DIR": dir,
		"OVERLAY_TOPICS": "tm_bbox_example_office_qzxkvbmwtr",
	}
	m, err := module.New(quiet{}, func(k string) string { return env[k] })
	if err != nil {
		panic(err)
	}
	defer m.Close()
	var names []string
	for t := range m.Module.Topics {
		names = append(names, t)
	}
	for l := range m.Module.Lookups {
		names = append(names, l)
	}
	sort.Strings(names)
	fmt.Println(names)
}
Output:
[ls_bbox tm_bbox_example_office_qzxkvbmwtr]

func (*Mounted) Close

func (m *Mounted) Close() error

Close flushes the rows journal and closes it (Start does when its context ends). A host that stops without it leaves at most the last sync window's lines in the page cache: written, not yet on disk.

func (*Mounted) Start

func (m *Mounted) Start(ctx context.Context) error

Start serves the terms route (when configured) until ctx ends, and runs the background tick: the payment watch every TickEvery and retention every PruneEvery once the index is restored. It returns when ctx ends, after closing the rows journal (Close).

type Options

type Options struct {
	// Offices are the office identifiers the host carries.
	Offices []string
	Host    bmodule.Host
	Journal Journal
	// Priced are the priceable classes this host prices: asked through the
	// engine, they are refused.
	Priced map[string]bool
	// RetentionDays is how long a host keeps what it no longer answers,
	// from first sight; at least FloorDays, and FloorDays when zero.
	RetentionDays int
	// Now is the host's clock; time.Now when nil.
	Now func() time.Time
}

Options build a Service.

type OutputJSON

type OutputJSON struct {
	Beef        byteArray `json:"beef"`
	OutputIndex uint32    `json:"outputIndex"`
}

OutputJSON is one output of an answer as JSON.

type OutputList

type OutputList struct {
	Type    string       `json:"type"`
	Outputs []OutputJSON `json:"outputs"`
}

OutputList is the engine's lookup answer as JSON.

type Refused

type Refused struct {
	Reason string
	Detail string
}

Refused is raised for every refusal. The engine counts it as a failed topic for this submission and stores nothing.

func (*Refused) Error

func (r *Refused) Error() string

type RouteAnswerer

type RouteAnswerer struct{ LS *Service }

RouteAnswerer is ls_bbox as the terms route asks its questions: an answer is hydrated as the engine hydrates one.

func (RouteAnswerer) Answer

Answer implements termsroute.Answerer: a priced question reaches it only once paid.

func (RouteAnswerer) Classify

Classify implements termsroute.Answerer.

func (RouteAnswerer) Restored

func (r RouteAnswerer) Restored() bool

Restored implements termsroute.Answerer.

type Service

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

Service is ls_bbox: one lookup service for every office a host carries (spec sections 7.2, 7.3 and 8.2 to 8.5), the twin of the TypeScript module's ls_bbox.ts.

Two stores back it. The engine's storage holds the outputs the host keeps: envelope and receipt carriers and sweep tombstones, which this service indexes in memory by office and key and rebuilds from storage on start. The journal holds the outpoint rows the host keeps for its life: every carrier any office admitted, with the outpoint it spent; every drop; every outpoint an admitted sweep spent. Every status (spec section 8.2) is a function of the rows, never of arrival order:

  • retracted: a sweep spends the carrier's funding outpoint;
  • superseded: the carrier is not its outpoint's winner, or the winner was dropped;
  • acknowledged: an envelope a receipt acknowledges, the receipt being by the envelope's to, not retracted, and its own outpoint's winner;
  • held: otherwise.

The winner of an outpoint is the lowest commitment among its envelopes a receipt acknowledges, or else among all its carriers. A dropped receipt keeps acknowledging (its row outlives it), so a drop can never hand an outpoint a new winner.

func NewService

func NewService(o Options) (*Service, error)

NewService makes the lookup service and loads the journal.

func (*Service) AdmissionMode

func (*Service) AdmissionMode() bmodule.AdmissionMode

AdmissionMode implements module.LookupService: the whole transaction, as a carrier's funding outpoint and a sweep's spends are its inputs.

func (*Service) Answer

func (s *Service) Answer(c *Classified, paid bool) ([]string, error)

Answer answers a validated question: the txids of the outputs it names, each output 0. paid says the question was paid for (or asked where no payment is due); a class this host prices is refused otherwise.

func (*Service) Classify

func (s *Service) Classify(service string, query json.RawMessage) (*Classified, error)

Classify validates a question and names its class, as the terms route and the engine ask it. A question for another service, one no class has, or one naming an office the host does not carry is an error.

func (*Service) Counts

func (s *Service) Counts() Counts

Counts reads the index's sizes.

func (*Service) Dropped

func (s *Service) Dropped(c string) bool

Dropped is whether the carrier with commitment c was dropped.

func (*Service) GetDocumentation

func (*Service) GetDocumentation() string

GetDocumentation implements module.LookupService.

func (*Service) GetMetaData

func (*Service) GetMetaData() *overlay.MetaData

GetMetaData implements module.LookupService.

func (*Service) Hydrate

func (s *Service) Hydrate(ctx context.Context, txids []string) ([]bmodule.HydratedOutput, error)

Hydrate is an answer with each output's BEEF, as the engine hydrates one, read from the host's storage: for the terms route, which answers outside the engine.

func (*Service) Lookup

Lookup implements module.LookupService: asked through the engine, a class the host prices is refused here. The answer is a formula the engine hydrates from its storage, as the TypeScript engine hydrates one.

func (*Service) OutputAdmittedByTopic

func (s *Service) OutputAdmittedByTopic(ctx context.Context, p *bmodule.OutputAdmittedByTopic) error

OutputAdmittedByTopic implements module.LookupService: it indexes an admitted output, then deletes what was dropped from storage. An admission that meets a restore in flight waits for it (the restore holds the service's lock), so that it is decided as any other.

func (*Service) OutputEvicted

func (s *Service) OutputEvicted(_ context.Context, op *transaction.Outpoint) error

OutputEvicted implements module.LookupService.

func (*Service) OutputNoLongerRetainedInHistory

func (s *Service) OutputNoLongerRetainedInHistory(_ context.Context, op *transaction.Outpoint, topic string) error

OutputNoLongerRetainedInHistory implements module.RetentionListener: the output leaves that office's answers; its rows stay.

func (*Service) Prune

func (s *Service) Prune(ctx context.Context) int

Prune applies retention at the host's time: it drops every carrier and sweep past its keep, then deletes what was dropped from storage. What is kept: an open envelope, and one dated ahead of the host's clock, always; any other carrier or sweep for the retention period from first sight, at least 31 days. It returns how many were dropped.

func (*Service) Restore

func (s *Service) Restore(ctx context.Context, outputs []bmodule.Output, storage bmodule.RestoreStorage) (int, error)

Restore implements module.Restorer: it rebuilds the index. The rows from the journal, then every output of this module's topics the host hands over (a row handed without its BEEF is read again from storage with it), then every carrier and sweep the rows name that the unspent rows did not carry (a spent tombstone, say), read from storage. A carrier the rows say was dropped is not indexed, and its output is deleted. Statuses are functions of the set, so the order storage returns rows in changes nothing. A storage failure propagates: a restore that skipped a sweep would serve retracted envelopes. The service's lock is held throughout, so an admission waits for the restore.

func (*Service) Restored

func (s *Service) Restored() bool

Restored is whether the index was rebuilt from storage.

func (*Service) SpendNotificationMode

func (*Service) SpendNotificationMode() bmodule.SpendNotificationMode

SpendNotificationMode implements module.LookupService: spends are read from admitted transactions, never from the engine's notices.

func (*Service) Status

func (s *Service) Status(c string) string

Status is the status of the carrier with commitment c (hash byte order hex), "" when the rows do not know it.

type TopicManager

type TopicManager struct {
	Topic  string
	Office string
	// contains filtered or unexported fields
}

TopicManager is tm_bbox_<name>_<suffix>: the topic manager of one office (spec section 8.1), one for each configured office. The rules are boxrec.Admit's; this is the engine seam: it runs them on the submission and turns the verdict into admittance instructions.

The engine records every transaction a topic manager returns instructions for as applied, empty instructions included: a later submission of the same txid is a duplicate no topic manager is shown again, and every held output it spends is marked spent. A refusal returned as empty instructions would therefore be permanent for that txid; anyone could suppress a genuine carrier by submitting it first in a different BEEF. So every refusal is raised, and the engine records nothing and marks nothing spent: a refused transaction offered again is decided again.

func NewTopicManager

func NewTopicManager(topic string, host bmodule.Host, headers chaintracker.ChainTracker, maxBEEF int) (*TopicManager, error)

NewTopicManager makes the manager of one topic. headers nil reads a sweep's proof as EngineVerified does; maxBEEF zero is the floor.

func (*TopicManager) Admit

func (t *TopicManager) Admit(ctx context.Context, raw []byte, held []int) (overlay.AdmittanceInstructions, error)

Admit applies the rules to the submission's bytes with the held inputs, as the TypeScript manager's identifyAdmissibleOutputs does.

func (*TopicManager) GetDocumentation

func (t *TopicManager) GetDocumentation() string

GetDocumentation implements module.TopicManager.

func (*TopicManager) GetMetaData

func (t *TopicManager) GetMetaData() *overlay.MetaData

GetMetaData implements module.TopicManager.

func (*TopicManager) IdentifyAdmissibleOutputs

func (t *TopicManager) IdentifyAdmissibleOutputs(ctx context.Context, _ *transaction.Beef, _ *chainhash.Hash, previousCoins []uint32) (overlay.AdmittanceInstructions, error)

IdentifyAdmissibleOutputs implements bcommon's module.TopicManager over the submission's bytes in ctx.

Jump to

Keyboard shortcuts

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