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
- Variables
- func ParseHalls(raw string) ([]string, error)
- type Classified
- type Config
- type Counts
- type Deleter
- type FileJournal
- type Formula
- type Front
- type Journal
- type Line
- type MemoryJournal
- type Mounted
- type Options
- type OutputJSON
- type OutputList
- type Refused
- type RouteAnswerer
- type Service
- func (*Service) AdmissionMode() bmodule.AdmissionMode
- func (s *Service) Answer(c *Classified, paid bool) ([]Formula, error)
- func (s *Service) Classify(service string, query []byte) (*Classified, error)
- func (s *Service) Counts() Counts
- func (s *Service) Dropped(c string) bool
- func (*Service) GetDocumentation() string
- func (*Service) GetMetaData() *overlay.MetaData
- func (s *Service) Hydrate(ctx context.Context, formulas []Formula) ([]bmodule.HydratedOutput, error)
- func (s *Service) Lookup(ctx context.Context, q *lookup.LookupQuestion) (*lookup.LookupAnswer, error)
- func (s *Service) OutputAdmittedByTopic(ctx context.Context, p *bmodule.OutputAdmittedByTopic) error
- func (s *Service) OutputEvicted(_ context.Context, op *transaction.Outpoint) error
- func (s *Service) OutputNoLongerRetainedInHistory(_ context.Context, op *transaction.Outpoint, topic string) error
- func (s *Service) Prune(ctx context.Context) int
- func (s *Service) Replay(ctx context.Context, r *bmodule.ReplayRequest) (*bmodule.ReplayAnswer, error)
- func (s *Service) Restore(ctx context.Context, outputs []bmodule.Output, storage bmodule.RestoreStorage) (int, error)
- func (s *Service) Restored() bool
- func (*Service) SpendNotificationMode() bmodule.SpendNotificationMode
- func (s *Service) Status(c string) (string, bool)
- func (s *Service) TokenStatus(txid string) (string, bool)
- type TopicManager
- func (t *TopicManager) Admit(ctx context.Context, raw []byte, held []int) (overlay.AdmittanceInstructions, error)
- func (t *TopicManager) GetDocumentation() string
- func (t *TopicManager) GetMetaData() *overlay.MetaData
- func (t *TopicManager) IdentifyAdmissibleOutputs(ctx context.Context, _ *transaction.Beef, _ *chainhash.Hash, ...) (overlay.AdmittanceInstructions, error)
Constants ¶
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).
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.
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).
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).
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.
const Name = "borg"
Name is the module's name, as a host's module list names it.
const PageSize = 64
PageSize is the most outputs a page of the roll, policy and wraps classes holds (spec section 10.2).
const RecentAdmissions = 4096
RecentAdmissions is how many admitted txids a manager remembers to count each once.
Variables ¶
var AdmitKinds = []string{"grant", "policy", "wrap", "org-token", "group-token", "sweep"}
AdmitKinds are what an admitted transaction was.
var Build = "unversioned"
Build is the version the host logs; a binary sets it.
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.
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.
var KindsReplayed = []string{replay.KindToken, "grant", "policy", "wrap", "sweep"}
KindsReplayed are the kinds a walk answers objects as.
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.
var TokenStatuses = []string{borgrec.StatusConsistent, borgrec.StatusPending, borgrec.StatusRollMismatch, borgrec.StatusMembersMismatch, borgrec.StatusCommitmentReuse, borgrec.StatusRejoinUnrotated}
TokenStatuses are the token statuses the index reports (spec section 11.2), each counted.
Functions ¶
func ParseHalls ¶
ParseHalls parses BORG_HALLS: hall identifiers, once each.
Types ¶
type Classified ¶
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.
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) 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 ¶
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 ¶
New is the factory a host calls: the configuration from getenv, checked against OVERLAY_TOPICS.
func (*Mounted) Close ¶
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.
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 ¶
Refused is raised for every refusal. The engine counts it as a failed topic for this submission and stores nothing.
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 ¶
func (r RouteAnswerer) Answer(ctx context.Context, q termsroute.Question) (any, error)
Answer implements termsroute.Answerer.
func (RouteAnswerer) Classify ¶
func (r RouteAnswerer) Classify(_ context.Context, q termsroute.Question) (string, error)
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 ¶
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) GetDocumentation ¶
GetDocumentation implements module.LookupService.
func (*Service) GetMetaData ¶
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 ¶
func (s *Service) Lookup(ctx context.Context, q *lookup.LookupQuestion) (*lookup.LookupAnswer, error)
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 ¶
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 ¶
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 ¶
func (s *Service) Replay(ctx context.Context, r *bmodule.ReplayRequest) (*bmodule.ReplayAnswer, error)
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) SpendNotificationMode ¶
func (*Service) SpendNotificationMode() bmodule.SpendNotificationMode
SpendNotificationMode implements module.LookupService: spends are read from admitted transactions, never from the engine's notices.
type TopicManager ¶
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.