module

package
v0.7.9 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 34 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 borg overlay module in Go: tm_borg_<name>_<suffix> for each configured hall and ls_borg 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 borgrec.Admit, the folds and statuses borgrec's, the questions borgrec's classes, and the index the TypeScript module's chains, outpoint rows, bounded spend table and retention, with its journal byte for byte. Its lookup service is also a bcommon module.Replayer: a host repairs a hall it missed part of by ordered replay from a sibling host (spec section 11.6), never by an unordered synchronization of unspent outputs.

Configuration is the TypeScript module's, read from the environment when the host calls the factory (docs/host.md): BORG_HALLS, BORG_STATE_DIR, BORG_HEADERS_URL (OVERLAY_CHAIN_TRACKER_URL when that is a native source), BORG_RETENTION_DAYS, BORG_MAX_BEEF, BORG_MAX_SWEEP_INPUTS, BORG_SPEND_TABLE, BORG_LISTEN, BORG_PRICES, BORG_PAYEE_KEY, BORG_SESSIONS, BORG_SESSION_TTL, the handshake and response budgets, BORG_ARCADE_URL, BORG_ASSET_URL (also the chain source a replay reads a chain's first parent from), BORG_CHAIN, BORG_WOC_KEY and the BORG_ACCEPT_* rule, and one of its own, BORG_JOURNAL_SYNC_MS (the rows journal's group commit window). Every mistake is an error, and the host refuses to start.

Index

Constants

View Source
const (
	// FloorDays is the retention floor, from the moment the floor's clock
	// starts (spec section 11.3).
	FloorDays = 31
	// MinSpendTable is the floor of the bounded table of spends of
	// outpoints no carrier used (spec section 11.1).
	MinSpendTable = 65536
)

The floors an operator cannot go under (docs/spec.md sections 11.1 to 11.3).

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

The rows journal's group commit window (BORG_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 (
	// EvidenceWraps and EvidenceGrants are the superseded carriers kept per
	// outpoint as evidence: wraps, and grants and policy records.
	EvidenceWraps  = 8
	EvidenceGrants = 64
	// MaxPerSeq is how many tokens are kept at one seq of one chain.
	MaxPerSeq = 8
)

The index's bounds (spec section 11.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 JournalFile = "borg-rows.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 = "borg"

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

View Source
const PageSize = 64

PageSize is the most outputs a page of the roll, policy and wraps classes holds (spec section 10.2).

View Source
const RecentAdmissions = 4096

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

Variables

View Source
var AdmitKinds = []string{"grant", "policy", "wrap", "org-token", "group-token", "sweep"}

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(borgrec.Classes))
	for i, c := range borgrec.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("borg: 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 KindsReplayed = []string{replay.KindToken, "grant", "policy", "wrap", "sweep"}

KindsReplayed are the kinds a walk answers objects as.

View Source
var Reasons = []string{
	"too-large", "cbor", "key-type", "magic", "missing", "type", "range", "identity", "hall", "name", "list", "chain", "members", "fields",
	"signature-form", "entry", "role", "permission", "binding", "count", "grant-revocation", "grant-signature", "grant-reveal", "transition",
	"rotation", "shape", "beef", "mineable", "unlock", "lock", "signature", "funding", "unmined", "token-input", "not-borg",
}

Reasons are every label a host counts a refused submission by: the record rules of spec section 3.1 (a token's record is read by its tag, so even magic is reachable), the grant's content rules, and the transaction rules of section 11.1. The member's labels (token, undecryptable, commitment), the grant's field-value labels (scope, expiry, role, which admission reports as grant-reveal) and query are never an admission verdict.

TokenStatuses are the token statuses the index reports (spec section 11.2), each counted.

Functions

func ParseHalls

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

ParseHalls parses BORG_HALLS: hall identifiers, once each.

Types

type Classified

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

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

type Config

type Config struct {
	Halls          []string
	StateDir       string
	HeadersURL     string
	RetentionDays  int
	MaxBEEF        int
	MaxSweepInputs int
	SpendTable     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
	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 {
	Tokens, PendingTokens, Grants, Policies, Wraps, Sweeps, Rows, Lines, Forgotten, Table, PendingDeletes int
}

Counts are what the gauges read.

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 outpoint rows need beyond the contract's RestoreStorage. A host whose storage cannot delete keeps what the index dropped, unanswered.

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, borg-rows.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 swept or superseded carrier be answered again.

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 Formula

type Formula struct {
	Txid    string
	Vout    uint32
	Context []byte
}

Formula is one output an answer names, with its context when the class gives one.

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"`
	Hall string `json:"hall,omitempty"`
	At   *int64 `json:"at,omitempty"`
	W    *bool  `json:"w,omitempty"`
	S    string `json:"s,omitempty"`
	H    *int64 `json:"h,omitempty"`
	Vout *int64 `json:"vout,omitempty"`
}

Line is one journal line: what ls_borg keeps for the host's life beside the engine's storage (spec sections 11.2 and 11.3), as an append-only journal. The engine's storage holds the outputs a host still keeps; it cannot hold what must outlive them: a dropped carrier, which carrier won an outpoint, the sweeps that spent it, and when the host first saw each token. One JSON object a line:

{"k":"c","op":"<txid>.<vout>","c":"<C>","txid":"<txid>","kind":"g","hall":"...","at":<s>}
{"k":"d","op":"...","c":"<C>","w":true}
{"k":"s","op":"...","s":"<sweep txid>","hall":"...","h":<height>,"at":<s>}
{"k":"t","txid":"<txid>","vout":<n>,"hall":"...","at":<s>}
{"k":"w","txid":"<sweep txid>","hall":"..."}

c lines are every carrier any hall admitted that its row keeps (kind g a grant, p a policy record, w a wrap) with the funding outpoint it spent; d lines are drops, w when the dropped carrier was its outpoint's winner; s lines are admitted sweeps' spends of outpoints a carrier spent (spends of any other outpoint live only in the bounded table, never here); t lines are chain tokens; a w line names a held sweep whose tombstone an admitted transaction spent, which storage no longer hands a restore among its unspent rows. 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.

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 {
	// Halls are the hall identifiers the host carries.
	Halls   []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, at
	// least FloorDays (31 when zero); SpendTable the bound on spends of
	// outpoints no carrier used (MinSpendTable when zero; the floor is held
	// where an operator sets it, so a test may name a smaller one).
	RetentionDays int
	SpendTable    int
	// Now is the host's clock; time.Now when nil.
	Now func() time.Time
	// Trees is the chain view a replay reads a chain's first token's parent
	// from (Replay); nil when the host has none.
	Trees replay.TreeSource
	// Headers are the host's block headers, and MaxBEEF and MaxSweepInputs
	// the topic managers' bounds, which a replay holds a token it
	// assembles to; borgrec's defaults when zero.
	Headers                 chaintracker.ChainTracker
	MaxBEEF, MaxSweepInputs int
}

Options build a Service.

type OutputJSON

type OutputJSON struct {
	Beef        byteArray `json:"beef"`
	OutputIndex uint32    `json:"outputIndex"`
	Context     byteArray `json:"context,omitempty"`
}

OutputJSON is one output of the route's answer.

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_borg as the terms route asks its questions: a priced answer is hydrated as the engine hydrates one.

func (RouteAnswerer) Answer

Answer implements termsroute.Answerer.

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_borg. Its methods are safe for concurrent use; 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 NewService

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

NewService makes ls_borg over its journal, which it loads.

func (*Service) AdmissionMode

func (*Service) AdmissionMode() bmodule.AdmissionMode

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

func (*Service) Answer

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

Answer answers a classified question. 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 []byte) (*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 a hall the host does not carry is an error.

func (*Service) Counts

func (s *Service) Counts() Counts

Counts reads every gauge at once.

func (*Service) Dropped

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

Dropped reports 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, formulas []Formula) ([]bmodule.HydratedOutput, error)

Hydrate is an answer with each output's BEEF, as the engine hydrates one, read from the host's storage. A context rides along.

func (*Service) Lookup

Lookup implements module.LookupService: asked through the engine, a class the host prices is refused here. The answer is hydrated here and carries each output's context (bcommon module.HydratedOutput).

func (*Service) OutputAdmittedByTopic

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

OutputAdmittedByTopic implements module.LookupService: it indexes an admitted output, then reads back tokens whose predecessor is decided now and deletes what was dropped from storage.

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.

func (*Service) Prune

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

Prune applies retention at the host's time and deletes what was dropped from storage. Kept: tokens and matched sweeps for the host's life; a grant while the answered roll holds it, one never in a roll until its outpoint is swept, and otherwise for the retention period after it left the roll or was retracted; a policy record likewise with the answered policy set; the wraps of each group's current epoch, and those of an earlier epoch for the retention period after the host first saw the token that ended it. It returns how many carriers were dropped.

func (*Service) Replay

Replay implements bcommon module.Replayer for tm_borg_ topics.

func (*Service) Restore

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

Restore implements module.Restorer (spec section 11.4): 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 token, carrier and sweep the journal names that the unspent rows did not carry (a token its successor spent, say), and then each held token's predecessors, read through the input that spends them from the token as the engine stores it (the token alone, without its parent). A held sweep whose tombstone was spent is among those the journal names (its w line). Sweeps are taken in storage's order, so the bounded table keeps the newest. Statuses are functions of what is held, so the order storage returns rows in changes nothing else. A storage failure propagates: a restore that skipped a sweep would answer retracted carriers. An admission that arrives while it runs waits for it (the service's lock).

func (*Service) Restored

func (s *Service) Restored() bool

Restored reports whether the index has been restored.

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, bool)

Status is the status of the carrier with commitment c (hash byte order hex): retracted, superseded or held, and false when the host has no record of it.

func (*Service) TokenStatus

func (s *Service) TokenStatus(txid string) (string, bool)

TokenStatus is the status of the token with txid (display order), and false when the host does not hold it.

type TopicManager

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

TopicManager is tm_borg_<name>_<suffix>: the topic manager of one hall (spec section 11.1), one for each configured hall. The rules are borgrec.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. 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, and a token refused because the host's headers lagged would stay refused. So every refusal is raised, and the engine records nothing and marks nothing spent: a refused transaction offered again is decided again. No rule reads another topic or anything this topic holds: the previous coins decide only which spent outputs are retained.

func NewTopicManager

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

NewTopicManager makes the manager of one topic. The floors (262144 bytes, 1024 inputs) are held where an operator sets the bounds (ParseConfig); a test may name the vectors' smaller ones.

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