engine

package
v0.7.3 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 32 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 engine is a borg publisher: the organization's tooling (docs/spec.md sections 7, 9 and 12), run from one identity's home. It issues grants, mints the organization's and its groups' chain tokens, samples and wraps epoch keys, revokes by roll and by sweep, and publishes every object on the plane or to each host.

It is built on bcommon's producer package. A Payer pays for funding trees and chain tokens from the home's coin pool, and Trees mints the three kinds of funding tree the contract keeps apart (spec section 9.4): grant trees, record trees (which fund wraps) and chain trees (which pay for a chain's first token), each under its own derived key. Grant and record trees are minted ahead, so the next is on its way before the current runs out. A tree is recorded with its fee coin before it reaches the settlement leg (Trees.Prepare), and a command that finds the record of a tree never adopted settles it before it spends (RecoverTrees). A funding tree is never published to a hall: every carrier carries its own, and a chain's first token carries its chain tree.

Every object is persisted in the home's state before it is sent: a carrier with the funding output it spends marked used, a transition with the epoch key it commits to. A run that stops part way sends the same bytes again (Resume), and never a second carrier on one funding output or a second key for one epoch. A transition takes effect only when a transaction spending its predecessor is mined in the publisher's own headers and carries byte for byte the record built (spec section 7.3).

Index

Constants

View Source
const SignerRole = "signer"

SignerRole is the role of the signer key's grant: a label.

Variables

View Source
var ErrNoOrg = errors.New("this home runs no organization (borg org create)")

ErrNoOrg is a home that runs no organization yet.

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

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

View Source
var Retries = limits.Retries

Retries are the waits between the tries of a submission to the facade.

Functions

func CollectChange

func CollectChange(ctx context.Context, pool *bwallet.Pool, asset nodeapi.ProofSource) int

CollectChange gives every unproven coin in the pool its proof, once its transaction has mined.

func FeeError

func FeeError(err error) error

FeeError words the library's refusals to find a fee input.

func Flagged

func Flagged(g *state.Group) (string, uint64, error)

Flagged reports whether the group's current epoch holds a token the index reports commitment-reuse or rejoin-unrotated (spec section 11.2): its status and seq, or "" when the epoch is clean. Such an epoch's key is not one to release: a key re-added without a rotation would read what was written while it was away, and a repeated commitment is an old key. A rotation begins a clean epoch.

func GroupRecords

func GroupRecords(g *state.Group) ([]*borgrec.Group, error)

GroupRecords are a group's own chain, decoded.

func Journal added in v0.1.1

func Journal(st *state.State, pool *bwallet.Pool, carried []bwallet.Output)

Journal makes every save of st record the pool, with the coins carried over from a reconciliation that could not settle them.

func Members

func Members(g *state.Group) ([][]byte, map[string]bool, error)

Members folds a group's own chain: the members after its latest token and every key any token removed. Only a fold that breaks (members-mismatch) is an error: a token the index reports commitment-reuse or rejoin-unrotated leaves the members well defined, and the group must stay operable so that it can be rotated (Flagged).

func Minimal

Minimal is mp cut to the proof of txid alone (borgrec.MinimalPath).

func Params

func Params(kind string) carrier.Params

Params are the carrier parameters of a tree kind: its derivation and the funding tag. A payload is checked by the host's rules before anything is persisted, so it is not checked again here.

func Reconcile added in v0.1.1

func Reconcile(ctx context.Context, st *state.State, pool *bwallet.Pool, asset nodeapi.SpendSource, note func(string, ...any)) []bwallet.Output

Reconcile settles what a run that stopped left in the journal. A coin the journal holds that the pool no longer does was taken; when no transaction the home records spends it, the run stopped before it recorded one. The node is asked: a coin it shows unspent goes back in the pool; one it shows spent is spent by a transaction this home did not record, and is reported; one it cannot answer for is carried over to the next command.

func Records added in v0.6.0

func Records(set []*state.Policy) ([]*borgrec.Policy, error)

Records decodes this home's policy set, for the effective-permission fold.

func Short

func Short(txid string) string

Short is a txid's first 12 digits.

func Txid

func Txid(h [32]byte) string

Txid is a hash in display order.

func Unjournal added in v0.1.1

func Unjournal(st *state.State)

Unjournal ends the journal: the command ended, so the pool's file and the state agree, and nothing is recorded as being taken.

Types

type Change

type Change struct {
	Add    [][]byte
	Remove [][]byte
	// Rotate begins a new epoch whatever else the change does.
	Rotate bool
	What   string
}

Change is a group transition asked for.

type ChangeResult

type ChangeResult struct {
	Seq     uint64
	Epoch   uint32
	Rotated bool
	// Debt are the keys removed because they held no current grant.
	Debt [][]byte
	// Rejoin are the keys added back that an earlier token removed.
	Rejoin [][]byte
}

ChangeResult is what a group transition did.

type Engine

type Engine struct {
	St     *state.State
	Signer *bwallet.Signer
	// Key is the organization's identity private key. It derives the
	// signer key (signer.go), which only Sync opens wraps with.
	Key  *ec.PrivateKey
	Pool *bwallet.Pool
	Legs Legs
	Opts Options
	// Now is the clock records are stamped with; Sleep waits.
	Now   func() time.Time
	Sleep func(ctx context.Context, d time.Duration) error
	// Note receives progress lines.
	Note    func(format string, args ...any)
	Verbose bool
	// contains filtered or unexported fields
}

Engine is one publisher run over one home.

func New

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

New builds an engine over a home's state.

func (*Engine) Close

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

Close collects a tree still being minted ahead, so its change reaches the pool, and records every tree the library holds and never adopted in its kind's Ahead list, so a sweep finds it.

func (*Engine) ConfirmGrants

func (e *Engine) ConfirmGrants(ctx context.Context, commitments []string) error

ConfirmGrants asks every host named whether it answers each grant now that the roll admits it, and offers the grant again to a host that lacks it (spec section 12: anyone who holds an object may submit it to a host that lacks it). A grant fewer hosts than the quorum answer is not published: it goes back to the outbox, and the next command publishes it.

func (*Engine) ConfirmPolicies added in v0.6.0

func (e *Engine) ConfirmPolicies(ctx context.Context, commitments []string) error

ConfirmPolicies is ConfirmGrants for the policy records a token defines. It matters more than it does for a grant: a reader holds the whole set to the root the latest token commits to, so one record a host lacks makes every decision at that host fail closed, not just one subject's.

func (*Engine) CreateGroup

func (e *Engine) CreateGroup(ctx context.Context, name string, members [][]byte, rotateOnJoin bool, rotateEvery uint64) (*state.Group, error)

CreateGroup creates a group (spec section 7.1): a fresh group id and epoch key, token seq 0 adding members, spending a chain-tree output; once mined, the token and the wraps of epoch 0 to every member. Every member must hold a current grant.

func (*Engine) CreateOrg

func (e *Engine) CreateOrg(ctx context.Context, orgKey *ec.PrivateKey, hall, name string, opaque bool, members []GrantReq) error

CreateOrg begins the organization (spec section 7.1): a chain tree and a grant tree, mined; the first grants, published; organization token seq 0 admitting them, mined and then published with the chain tree. A run that stopped part way is finished: grants issued and not admitted are reused.

func (*Engine) CurrentGrant

func (e *Engine) CurrentGrant(subject string) *state.Grant

CurrentGrant is the subject's current grant, or nil.

func (*Engine) Debt

func (e *Engine) Debt(g *state.Group) ([][]byte, error)

Debt is a group's rotation debt by the organization's own record: the members with no current grant now (spec section 7.1).

func (*Engine) EnsureSigner

func (e *Engine) EnsureSigner(ctx context.Context) ([]byte, error)

EnsureSigner gives the signer key a current grant when it holds none (an organization token admits it), and returns the key. A grant that expired is replaced before any group transition, so the signer key is never rotation debt.

func (*Engine) FinishSweep

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

FinishSweep takes the sweep in flight, if any, through settlement, its proof and its publication. A sweep the network definitively refuses is marked failed, its fee coin given back when the node shows it unspent, and a *SweepRefusedError returned. Any other failure leaves it in flight.

func (*Engine) FinishTransition

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

FinishTransition takes the persisted transition, if any, to the chain: it is sent (again, the same bytes, when a previous run stopped), its proof awaited, and once mined in the publisher's own headers it joins the chain and is published. One that loses its predecessor to another transaction is discarded with its epoch key (spec section 7.3), unless the transaction that won carries byte for byte the same record: then it is the same transition, re-encoded, and is taken as it is.

func (*Engine) GroupChange

func (e *Engine) GroupChange(ctx context.Context, gid string, c Change) (*ChangeResult, error)

GroupChange mints a group's next token (spec sections 4.2 and 7.1). Every transition first removes the group's rotation debt. A removal, a predecessor's rotateOnJoin with an addition, a key an earlier token removed coming back, or Rotate begins a new epoch with a freshly sampled key; the transition is checked against the host's rules and the index's fold before it is built, and refused if it would trip either.

func (*Engine) IssueGrant

func (e *Engine) IssueGrant(ctx context.Context, orgKey *ec.PrivateKey, req GrantReq) (*state.Grant, error)

IssueGrant issues a grant to req.Subject (spec sections 5 and 7.1): a BRC-52 certificate signed by orgKey, its revocation outpoint the grant- tree output its carrier spends. The carrier is persisted and published before any organization token admits it.

func (*Engine) NewPayer

func (e *Engine) NewPayer() *producer.Payer

NewPayer is a Payer over the engine's pool and legs.

func (*Engine) OrgKey

func (e *Engine) OrgKey() []byte

OrgKey is the organization's identity key, compressed.

func (*Engine) OrgTransition

func (e *Engine) OrgTransition(ctx context.Context, admit, revoke []*state.Grant, what string) error

OrgTransition mints the organization's next token: admit and revoke grants (spec sections 3 and 5.6). The tooling refuses to build a transition the index would report: its fold over the organization's own chain must stay consistent.

func (*Engine) OrgTransitionWith added in v0.6.0

func (e *Engine) OrgTransitionWith(ctx context.Context, admit, revoke []*state.Grant, define, retire []*state.Policy, what string) error

OrgTransitionWith is OrgTransition with a change of the policy set beside the change of the roll (spec section 3.3). One chain carries both, so a service never holds a new role against an old roll.

func (*Engine) Owed

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

Owed publishes what the home owes the hall: a token of its own chains mined and not yet published, and the wraps of each group's current epoch not yet made for some member.

func (*Engine) PublishPolicy added in v0.6.0

func (e *Engine) PublishPolicy(ctx context.Context, req PolicyReq) (*state.Policy, error)

PublishPolicy writes one policy record on a policy-tree output and queues its carrier. The organization's next token defines it (spec section 3.3): until then the record is published and in no set, which is what a host answers nothing for.

func (*Engine) RecoverTrees added in v0.1.2

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

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

  • a tree the chain holds is adopted, or held while the current tree of its kind has outputs left, and its change is taken. Any number are held, in the order of their records, and the switch takes them in that order. 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 decides nothing: the record stays, the next command asks again, and this one goes on. So does a node that serves an unproven tree and cannot say who spent its coin: trees are settled without waiting for a block, and none is adopted on that alone.

A coin the pool holds although the chain shows it spent (it was put back before the tree landed) is taken out of the pool by the library, which says so. Only a failure to save the state is returned.

func (*Engine) Resume

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

Resume publishes every object a previous run persisted: the same bytes, so a host that already holds one answers a duplicate. Every object is tried; one that cannot be published stays in the outbox, and the first failure is returned.

func (*Engine) Retire

func (e *Engine) Retire() error

Retire stops the home spending every grant, policy and record tree it holds: after the kill switch no output of them funds anything again.

func (*Engine) Retract

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

Retract builds and persists one sweep of vouts of the funding tree txid, with its fee from the pool, then settles and publishes it in hall.

func (*Engine) SignerKey

func (e *Engine) SignerKey() ([]byte, error)

SignerKey is the organization's signer key, compressed.

func (*Engine) Stale

func (e *Engine) Stale(ctx context.Context) bool

Stale reports whether another instance changed the organization since this home last wrote: the node shows the latest token of one of its chains spent, or a host answers a group this home does not hold. It asks the node once per chain and each host once.

func (*Engine) Start

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

Start reads the chain tip for coinbase maturity, collects the proofs of change the pool holds back, and finishes whatever a previous run persisted and did not finish: a sweep, every object not confirmed published, a transition, and the tokens and wraps it owed. Each piece of work is tried whatever became of the one before it: one that cannot finish (a host that is down, a transition another beat to the chain) does not keep the rest from the chain or the hosts. The first failure is returned, a *LostError only when nothing else failed; the others are noted.

func (*Engine) SweptBy

func (e *Engine) SweptBy(txid string, vout uint32) *state.Sweep

SweptBy is the sweep that spends output vout of the funding tree txid, or nil. A failed sweep spends nothing.

func (*Engine) Sync

func (e *Engine) Sync(ctx context.Context, hall string, opt SyncOptions) (*SyncReport, error)

Sync catches the home up with the organization as the hosts in hall answer it.

func (*Engine) Tx

func (e *Engine) Tx(txid string) (*transaction.Transaction, error)

Tx is a funding tree the home keeps, rebuilt.

type GrantReq

type GrantReq struct {
	Subject *ec.PublicKey
	Role    string
	Scope   string
	Expiry  time.Time
}

GrantReq is a grant to issue.

type Legs

type Legs struct {
	Settler publish.Settler
	// Chain is the chain view: transactions, proofs and spends
	// (nodeapi.ParseChain over a node or WhatsOnChain).
	Chain   nodeapi.Chain
	Arcade  *publish.Arcade
	Facade  *publish.Facade
	Hosts   *unicast.Set
	Direct  *unicast.Set
	Reader  *reader.Client
	Headers chaintracker.ChainTracker
}

Legs are the endpoints a publisher talks to. Objects go to exactly one of Facade (mode plane) and Hosts (mode unicast). In mode plane, Direct are the other hosts every mined object is also submitted to. Reader confirms, by lookup, a host that admitted nothing. Headers are the publisher's own block headers: a mined object is published only once its block is in them.

type LostError

type LostError struct {
	What string
	Txid string
	By   string
	// Fee is set when it was the fee coin, not the predecessor, that
	// another transaction spent: no transition beat this one.
	Fee bool
}

LostError is a transition another transaction spending the same predecessor beat to the chain (spec section 7.3): the epoch key it sampled is discarded and nothing it built was released.

func (*LostError) Error

func (e *LostError) Error() string

type MissingKey

type MissingKey struct {
	Group string
	Epoch uint32
	// Current is set when it is the group's epoch in force.
	Current bool
	Why     string
}

MissingKey is an epoch whose key Sync could not open.

type Options

type Options struct {
	// TreeCount sizes grant and record trees, ChainTreeCount chain trees;
	// TreeSats is each output's value; Ahead is how few outputs a tree has
	// left when the next is minted ahead.
	TreeCount      int
	ChainTreeCount int
	TreeSats       uint64
	Ahead          uint32
	// Fees is the fee policy of trees, tokens, sweeps and payments.
	Fees mint.Fees
	// ObjectBound is the plane's object bound, in bytes.
	ObjectBound int
	// Poll paces proof waits and Wait bounds one.
	Poll time.Duration
	Wait time.Duration
	// Delay is the propagation delay before a mined object is published.
	Delay time.Duration
	// Signers is how many tooling instances can sign transitions: above
	// one, wraps wait one further block.
	Signers int
	// Entries is the most wrap entries one wrap record carries.
	Entries int
	// PlaneNeed is, in mode plane, how many of the hosts named must answer
	// a carrier by lookup for it to count as published; zero is all of
	// them. A mined object always needs every host.
	PlaneNeed int
}

Options are a publisher's choices. None of them is frozen.

type PolicyReq added in v0.6.0

type PolicyReq struct {
	Role        string
	Permissions []string
	// To is a binding's subject: a group identifier (16 bytes) or an
	// identity key (33). Empty makes the record a role definition.
	To []byte
	// Expiry is a binding's expiry in the one spelling, or empty.
	Expiry string
}

PolicyReq is one policy record to publish: a role definition when To is empty, a binding otherwise.

type SweepRefusedError

type SweepRefusedError struct {
	Txid 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 home, its fee coin is back in the pool when the node shows it unspent, and the outputs it named may be swept again.

func (*SweepRefusedError) Error

func (e *SweepRefusedError) Error() string

type SyncError

type SyncError struct {
	Incomplete bool
	Msg        string
}

SyncError is a catch-up that could not be made from what the hosts answered. Incomplete is set when asking again, or other hosts, may help; otherwise the evidence contradicts the home.

func (*SyncError) Error

func (e *SyncError) Error() string

type SyncOptions

type SyncOptions struct {
	// RetireTrees stops this home spending its current grant and record
	// trees whatever the hosts show: for a home that is a copy of another,
	// which holds the same trees.
	RetireTrees bool
}

SyncOptions are Sync's choices.

type SyncReport

type SyncReport struct {
	// OrgTokens and GroupTokens are the tokens adopted, Displaced those of
	// this home's that are no longer in the chain (a reorganization).
	OrgTokens, GroupTokens, Displaced int
	// Groups are the groups this home did not hold; Grants the grants;
	// Policies the policy records.
	Groups, Grants, Policies int
	// Keys are the epoch keys opened from wraps to the signer key.
	Keys    int
	Missing []MissingKey
	// Coins are the outputs added to the pool; Spent those removed because
	// another instance spent them.
	Coins, Spent int
	// Retired are the funding trees this home stopped spending.
	Retired []string
	// Unasked are the hosts that could not be asked.
	Unasked []string
	// Refused are the answers a host gave that did not verify: tokens,
	// grants and wraps, each naming its host. None is used.
	Refused []reader.Refusal
}

SyncReport is what Sync did.

func (*SyncReport) Changed

func (r *SyncReport) Changed() bool

Changed reports whether Sync changed the home.

Jump to

Keyboard shortcuts

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