publish

package
v0.34.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 49 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 publish is bstore's publisher (spec sections 5, 9, 13 and 14): it builds an object's CHIRP closure and proof root while the content streams (Store.Stage), mints a hold output when a bounty is asked for, makes the piece carriers and the entry, and delivers them over the plane, by unicast to the hosts and providers configured, or by BRC-167 upload session; it judges each bounty's race (race.go), settles it by rank or reclaims it after its deadline (settle.go), challenges providers (challenge.go), publishes outcome records, and sweeps its funding trees (sweep.go). The S3 gateway and the command line both write through it.

Save before send. Every carrier spends one output of a mined funding tree, and a carrier rebuilt differently on the same output would be a second carrier the first's acknowledgement never names (spec section 13.2). So the outputs a put will spend are recorded used, and saved, before any carrier is signed; each carrier is written to the outbox, synced, before it is sent; and what a target did not take stays in the outbox and is sent again, the same bytes, by the background run and on the next start. Funding trees are recorded with their fee coin before they reach the settlement leg (bcommon producer Prepare) and settled on the next start (Recover), as the provider does. A settlement, a reclaim and a sweep are signed and recorded before they are sent, and a run that stops part way sends the same bytes again. An identity's directory is locked while a Publisher has it open.

Index

Constants

View Source
const (
	DefaultHoldAhead = 16384
	// DefaultEntryTree is the largest funding tree a host takes.
	DefaultEntryTree = 1023
	// DefaultTreesAhead is the entry and piece trees kept ready ahead.
	DefaultTreesAhead = 16
	// DefaultPieceWorkers is the piece carriers a put mints and sends at
	// once; providers admit 32 from one address by default.
	DefaultPieceWorkers = 16
)

ErrNoHold is a put that asked for a bounty when no mined hold output of that value was ready within HoldWait; minting more is under way. The funding a gateway keeps ready, by default. Every output is minted and mined before a put spends it, and what is minted to replace it is usable from the next block, so one identity's sustained puts per block interval are bounded by these. They are sized for a busy writer, not a trickle: 16,384 holds carry about 27 puts a second on a ten-minute chain and 270 on a one-minute one. A wallet too small for them fills what it can and says so; a hold locks its bounty until the race settles or lapses, so a gateway paying large bounties may want fewer.

View Source
const (
	RaceOpen     = "open"     // watching and judging
	RaceClosed   = "closed"   // the window ended with fewer than t passed: nothing is paid
	RaceSettling = "settling" // a settlement is signed and recorded, not yet seen mined
	RaceSettled  = "settled"  // the settlement mined
	RaceRemitted = "remitted" // the settlement taken by the network and remitted, not yet seen mined
	RaceLapsed   = "lapsed"   // the deadline came with nothing settled
	RaceSpent    = "spent"    // the hold output was spent by something this race did not make
	RaceReclaim  = "reclaiming"
	RaceReclaimd = "reclaimed"
)

Race states.

View Source
const (
	CandSeen      = "seen"      // eligible, not yet challenged
	CandWaiting   = "waiting"   // the hold output is not yet minAge deep for this provider
	CandPriced    = "priced"    // the provider would not answer free and the budget did not cover it
	CandPassed    = "passed"    // passed its settlement challenge
	CandFailed    = "failed"    // did not pass: skipped
	CandCancelled = "cancelled" // passed, then its advertisement was spent by something other than a renewal
)

Candidate statuses.

View Source
const DefaultOutboxMax = 8 << 30

DefaultOutboxMax is the bytes an identity's outbox may owe before a put is refused: what targets have not taken (a provider that is down), kept as files of the outbox's own or pinned in the store.

View Source
const DefaultPieceTree = 256

DefaultPieceTree is a piece funding tree's outputs when none is set: a put of up to 1 GiB (256 pieces of 4 MiB) spends one tree, and the tree adds about 12.5 KB to each piece carrier's BEEF.

View Source
const OutcomeNotADraw = "not a draw"

OutcomeNotADraw is a candidate's note that a challenge did not count as a draw (row C31).

View Source
const RemittedStale = time.Hour

RemittedStale is how long a settlement may stay remitted and unmined before it is reported: a block is expected within minutes, so an hour means the node does not serve its proof, or it will never mine.

View Source
const SeedBack = 2

SeedBack is how many blocks below the buyer's tip a request is seeded: an answerer whose headers are a block or two behind still holds the seed, and it stays within the answerer's six-block window for a while.

Variables

View Source
var (
	// ErrNotYet is a settlement or reclaim that cannot be decided now:
	// the race is open, a spend source gave no evidence, or a transaction
	// is on its way. It proves nothing either way.
	ErrNotYet = errors.New("publish: not decidable yet")
	// ErrPastDeadline is a settlement asked for at or after the deadline.
	ErrPastDeadline = errors.New("publish: the deadline has come; the bounty is reclaimed, not settled")
	// ErrBeforeDeadline is a reclaim asked for before the deadline.
	ErrBeforeDeadline = errors.New("publish: the deadline has not come; a bounty is reclaimed only after it")
)

Errors a caller maps to exit codes.

View Source
var CommitMode = ""

CommitMode chooses how synced writes reach the disk: "auto" (or empty) groups them on a filesystem where that measured faster (XFS on Linux) and syncs each alone elsewhere; "group" groups them everywhere; "direct" syncs each alone everywhere. bstore sets it from BSTORE_COMMIT.

View Source
var ErrCannotPay = errors.New("publish: this identity cannot pay now")

ErrCannotPay is a 402 this identity could not pay: its pool had no coin to spend (change waiting for its proof, or none at all). It is the buyer's own state, never the answerer's failure.

View Source
var ErrInUse = errors.New("publish: the identity is in use by another process")

ErrInUse is an identity directory another process has open: two processes writing one identity's state would each overwrite the other's record of what it spent.

View Source
var ErrKilled = errors.New("publish: the kill switch swept this identity's trees; it publishes nothing more")

ErrKilled is a write after the kill switch swept this identity's trees.

View Source
var ErrMixedSweep = errors.New("publish: a sweep or reclaim may not also create a hold output or an advertisement: it would retract nothing (spec section 12.4)")

ErrMixedSweep refuses a sweep or a reclaim that would also create a hold output or an advertisement. Such a transaction is a mined object (spec section 12.1), not a sweep, so it would retract nothing (spec section 12.4); the tooling never builds one.

View Source
var ErrNoHold = errors.New("publish: no mined hold output is ready for the bounty yet")
View Source
var ErrNoTip = errors.New("publish: the header source did not answer its tip")

ErrNoTip is a buyer with no tip to seed a request from.

View Source
var ErrNotSent = errors.New("publish: the entry was minted but no facade or host quorum took it yet")

ErrNotSent is an entry no facade or host quorum took on its first send; the outbox keeps sending it.

View Source
var ErrOutboxFull = errors.New("publish: the outbox is full")

ErrOutboxFull is a put refused because the outbox owes more than its bound: a target has not taken what was sent it. Nothing is spent.

View Source
var ErrOverBudget = errors.New("publish: the price is over the budget")

ErrOverBudget is a 402 whose price is over the bound the call was given.

View Source
var ErrTooLarge = errors.New("publish: the content is over the bound")

ErrTooLarge is a body over the bound Stage was given.

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

Profile is a publisher identity's embedded wallet: the fund key under [1, "bstore"] key id fund, counterparty self, and the registered basket.

View Source
var StageWorkers = 0

StageWorkers is how many blobs Stage hashes and stores at once (storerec.Parallel); 0 is chirp.DefaultWorkers.

Functions

func BEEFSubject

func BEEFSubject(b []byte, bound int) (tx *transaction.Transaction, err error)

BEEFSubject is the last transaction of a BEEF someone else sent, its shape held to bcommon guard's walk first (at most bound bytes), parsed under a recover: hostile bytes are an error, never a crash.

func CoinOf

func CoinOf(in mint.Input) bwallet.Output

CoinOf is a fee input as the pool keeps it.

func ForwardedNote added in v0.2.0

func ForwardedNote(front string) string

ForwardedNote says why a forwarded payee's remittance is not owed.

func HashBlob added in v0.12.0

func HashBlob(b []byte) (h, seg [32]byte, err error)

HashBlob is what Stage computes of each blob: its SHA-256, which names it, and its segment subtree root, which the proof root is composed of.

func Init

func Init(dir string) (string, error)

Init creates an identity's wallet under dir and returns its key.

func IsDrawOutcome added in v0.6.1

func IsDrawOutcome(o string) bool

IsDrawOutcome reports whether an attempt's outcome says what became of a draw (an answer, a spent or uncounted draw, the candidate failing), as against a progress note: "waiting", "priced" and "not asked" spend nothing.

func ObserveCommits added in v0.12.0

func ObserveCommits(f func(name string, seconds float64))

ObserveCommits has f told each commit's duration, in seconds, as `bstore_publish_commit_seconds`; nil stops it.

func OutcomeName

func OutcomeName(o int) string

OutcomeName is an outcome's word.

func PiecesFor added in v0.3.0

func PiecesFor(size uint64) int

PiecesFor is how many pieces a closure of size bytes has: its blobs, its branches and its root (CHIRP Profile 1, at most 256 children a node).

func Refused added in v0.24.0

func Refused(why string) error

Refused is how a local provider says it took nothing for a reason the same bytes will not change: the outbox neither counts the piece delivered there nor sends it again, as with a provider that answers a refusal over HTTP.

func SameEffect

func SameEffect(a, b *transaction.Transaction) bool

SameEffect reports whether b spends exactly a's outpoints, in a's order, and creates exactly a's outputs: a re-encoding of a.

func SetCommitMode added in v0.12.0

func SetCommitMode(mode string) error

SetCommitMode sets CommitMode, refusing a name it does not know.

func WalletDir

func WalletDir(dir string) string

WalletDir is an identity's wallet under its directory.

Types

type Attempt

type Attempt struct {
	At      int64  `json:"at"`
	C       uint64 `json:"c"`
	Front   string `json:"front"`
	Outcome string `json:"outcome"`
	Why     string `json:"why,omitempty"`
	Paid    uint64 `json:"paid,omitempty"`
}

Attempt is one settlement challenge of a candidate.

type Bounty

type Bounty struct {
	Satoshis       uint64
	T, K           uint64
	Retention      uint64 // seconds
	DeadlineBlocks uint64 // ahead of the tip when the entry is made
	CheckC         uint64
}

Bounty is the hold terms a put asks for (spec section 4.3), its hold output minted by the publisher before the entry.

type Call

type Call struct {
	Status int
	Body   []byte
	Paid   uint64
	// Payment is the BRC-105 payment made, when one was; Peer the
	// identity key (hex) the BRC-104 session authenticated the answer as.
	Payment *transaction.Transaction
	Peer    string
	// PaymentHeader is the x-bsv-payment header sent with Payment: a payee
	// that answers 202 holds the payment, and the same header sent again
	// once it is mined buys the answer.
	PaymentHeader string
	// contains filtered or unexported fields
}

Call is one authenticated request's answer: its status, its body (at most max bytes), and what was paid for it (0 when nothing was).

type Cand

type Cand struct {
	Advertiser string `json:"advertiser"` // 66 hex
	// First is the advertisement first seen (display txid and vout): the
	// rank keeps its first sight, and settlement checks it, or its renewal
	// successor, unspent.
	First       string `json:"first"`
	FirstVout   uint32 `json:"firstVout"`
	FirstExpiry uint64 `json:"firstExpiry"`
	FirstSeen   int64  `json:"firstSeen"` // Unix nanoseconds, the writer's clock
	// URL and Expiry are the live advertisement's with the latest expiry:
	// the tested URL (spec section 7.5).
	URL      string    `json:"url"`
	Expiry   uint64    `json:"expiry"`
	Status   string    `json:"status"`
	Attempts []Attempt `json:"attempts,omitempty"`
	// DrawLog is what became of each draw, apart from Attempts: progress
	// notes ("waiting" every step, "priced", "not asked") go to Attempts
	// only, so they never push out the reason a draw was spent.
	DrawLog []Attempt `json:"drawLog,omitempty"`
	// Draws are the settlement challenges spent; Pending is the one made
	// and not yet answered; BadFronts are fronts not asked again.
	Draws     int          `json:"draws,omitempty"`
	Pending   *PendingDraw `json:"pending,omitempty"`
	BadFronts []string     `json:"badFronts,omitempty"`
	// Front and Answerer are where it passed.
	Front    string `json:"front,omitempty"`
	Answerer string `json:"answerer,omitempty"`
	Paid     uint64 `json:"paid,omitempty"`
}

Cand is one advertiser in the race.

type Challenge

type Challenge struct {
	Bucket string
	// Root, ProofRoot and Size are the entry's.
	Root      [32]byte
	ProofRoot [32]byte
	Size      uint64
	// Entry is the entry's txid (display order), sent with the request:
	// the settlement challenge names the entry whose bounty it is for.
	Entry string
	// Provider is the advertiser's key; Answerer the key that signs (the
	// provider, or a front).
	Provider []byte
	Answerer []byte
	// Front is the answerer's base URL (ending /bstore/v1 when derived).
	Front string
	// URL is the tested URL: the provider's live advertisement's url for
	// the root, latest expiry.
	URL string
	// Blobs are the closure's blob references, by which a fetched blob is
	// checked.
	Blobs []chirp.Child
	C     uint64
	// Nonce, when set, is used instead of a fresh one.
	Nonce *[16]byte
	// Budget is the most paid for the answer; 0 pays nothing.
	Budget uint64
	// HeldWait is how long a payment the answerer holds for confirmation
	// (202, ERR_PAYMENT_HELD) is waited on before it is sent again with
	// the request, which then buys the answer; zero does not wait, and the
	// result says the payment is held.
	HeldWait time.Duration
	// Request, when set, is a request made before (its encoding), sent
	// again as it is: a draw is not redrawn because an answer was not
	// given.
	Request []byte
}

Challenge is what to challenge.

type ChallengeResult

type ChallengeResult struct {
	Request    []byte
	Req        *storerec.Request
	Status     int
	Refusal    string // a 422's label
	Code       string // a refusal's BRC-104 error code, as in ERR_ROUTE_NOT_FOUND
	Signed     []byte
	Verdict    storerec.Verdict
	Outcome    int // storerec.OutcomePass .. OutcomeUnretrievable
	Paid       uint64
	Why        string
	Fetches    int
	WholeBlobs int
	// Busy is a front that said try later (429, 503): no answer and no
	// failure, the same draw goes again on the next pass.
	Busy bool
	// NotTaken is set when the answerer refused the request after a
	// payment and signed that it did not take it (row C30): the payment's
	// coin is already back in the pool.
	NotTaken *storerec.NotTaken
}

ChallengeResult is a challenge's outcome.

func (*ChallengeResult) OutcomeRecord

func (r *ChallengeResult) OutcomeRecord(bucket string) *storerec.Outcome

OutcomeRecord is the outcome record of a result (spec section 8.1).

type Closure

type Closure interface {
	// Objects are the closure's distinct objects: the root first, then the
	// branches, then the blobs.
	Objects() [][32]byte
	// Object returns one of them, its bytes held to its hash.
	Object(ctx context.Context, h [32]byte) ([]byte, error)
}

Closure is a closure's objects, wherever they come from: the store for what the publisher built, a verified reader for a copy across buckets.

type CommitStats added in v0.12.0

type CommitStats struct {
	Commits, Files, Syncs int64
}

CommitStats are the committer's counts since the process started: the commits (a group, or one writer's own files when not grouped), the files and syncs they covered, and the device syncs (syncfs or fsync calls) they made.

func Commits added in v0.12.0

func Commits() CommitStats

Commits are the process's commit counts.

type Config

type Config struct {
	// Dir is the identity's directory: wallet/, publisher.json and txs/
	// (the state, state.go), outbox/, races/.
	Dir string
	// Chain is the chain view transactions, proofs and spends are asked
	// of (a node, or WhatsOnChain: chaincfg); Known says whether a
	// transaction sent is held, mined or not (nil: never, so one not
	// mined is sent again); Tip is the header source's height and its
	// header by height. Settler is the settlement leg transactions are
	// handed to.
	Chain   nodeapi.Chain
	Known   nodeapi.KnownSource
	Tip     chaincfg.Tip
	Settler bpub.Settler
	// Fees is the fee policy, or FeeSource, when set, answers it for each
	// build (a broadcaster's live policy).
	Fees      mint.Fees
	FeeSource feepolicy.Source
	// Accept is the payment acceptance rule a settlement is remitted by:
	// one whose largest payout is at or below its threshold is remitted on
	// Status's word that the network took it, before it mines. With no
	// Status (or the zero Accept) every settlement waits for its block.
	Accept  acceptance.Policy
	Status  acceptance.StatusSource
	Mainnet bool
	// PieceTree and EntryTree are the outputs of a new piece or entry
	// funding tree (spec section 19.2: small trees cost less per piece).
	// A put of up to PieceTree pieces never waits for a block: the next
	// tree of each kind is minted ahead, in the background, once the
	// current one has PieceAhead (EntryAhead) outputs or fewer left.
	// PieceAhead and EntryAhead zero are DefaultTreesAhead trees of each.
	PieceTree  int
	EntryTree  int
	PieceAhead int
	EntryAhead int
	// PieceWorkers is how many piece carriers are minted and sent at once;
	// zero is DefaultPieceWorkers.
	PieceWorkers int
	// Poll is how often a wait for a transaction to mine asks the node;
	// zero is a second.
	Poll time.Duration
	// LockWait is how long Open waits for an identity another process has
	// open; zero refuses at once (ErrInUse).
	LockWait time.Duration
	// HoldAhead is how many mined hold outputs of each bounty value are kept
	// ready, so a put never waits for a block; HoldWait is how long a put
	// waits for one when none is ready. HoldTree is how many hold outputs
	// one transaction carries (a hold tree): zero is storerec.MaxAdsPerTx,
	// the most, what a host admits of a mined transaction. A
	// hold output is named by the entry and never carried in a BEEF, so the
	// tree costs no carrier anything; a bigger tree means fewer
	// transactions, coins and records a block for the same holds ahead.
	HoldAhead int
	HoldTree  int
	HoldWait  time.Duration
	// Store is the local closure store, shared by every identity.
	Store *Store
	// Delivery reaches the plane, the hosts and the providers.
	Delivery *Delivery
	// Reader, when set, asks the hosts and verifies what they answer: the
	// race's advertisements and fronts, and closures the store lacks.
	Reader *reader.Reader
	// FrontHTTP reaches the fronts that advertisements and statements name
	// (challenges, terms, remittances): addresses a stranger chose, so it
	// should refuse private ones. Nil uses Delivery's client.
	FrontHTTP *http.Client
	Logf      func(format string, args ...any)
	// OutboxMax bounds the bytes the outbox may owe before a put is
	// refused (ErrOutboxFull); 0 is DefaultOutboxMax.
	OutboxMax int64
	Now       func() time.Time
}

Config is one publisher identity.

type Conflict

type Conflict struct {
	Input int
	By    *transaction.Transaction
	// Same is set when By is the recorded transaction re-encoded.
	Same bool
}

Conflict is an input of a recorded transaction spent elsewhere.

type Delivery

type Delivery struct {
	Facade    string
	Hosts     []string
	Providers []string
	// Uploads are providers' public URLs (the base their /chirp/v1 routes
	// hang from). Without a facade, when any is set, a closure goes to each
	// of them by BRC-167 upload session instead of as piece carriers.
	Uploads []string
	HTTP    *http.Client
	// Quorum is how many hosts must take an entry for a put without a
	// facade to count as sent; zero is one.
	Quorum int
	// Observe, when set, is told how long each step took, in seconds, as a
	// histogram name with labels: `bstore_publish_submit_seconds{target}`
	// for each send (plane, host or provider), and
	// `bstore_publish_piece_seconds{stage}` for each piece carrier's read,
	// mint, outbox and send.
	Observe func(name string, seconds float64)
	// Local, when set, is a provider in this process (a storage node): every
	// piece is also handed to it as a function call (LocalPiece), beside the
	// facade and the providers named, and is owed to it as to any target.
	Local func(ctx context.Context, lp LocalPiece) error
}

Delivery is how a publisher reaches the plane, the hosts and the providers (spec section 14). With a facade, pieces go to it once on the blob topic and records once on the records topic; mined objects also go to every host directly, because a host whose headers lagged refused them and the plane does not deliver them again. Without one (unicast), pieces go to each provider's submit route on the blob topic, and every record to each host and, for an entry, each provider. Either way an entry also goes to each provider named, so a provider that unicast pieces reached hears of the entry, and to the origin of each of Uploads.

type EntryLog

type EntryLog struct {
	Txid    string `json:"txid"`
	Bucket  string `json:"bucket"`
	Key     string `json:"key"`
	Kind    uint64 `json:"kind"`
	Created uint64 `json:"created"`
	Record  string `json:"record"` // hex
	// Named is the seq of the token that named it, once one has.
	Named *uint64 `json:"named,omitempty"`
}

EntryLog is one entry this identity made.

type Fields

type Fields struct {
	Bucket      string
	ID          [32]byte
	Key         string
	ContentType string
	ETag        *string
	Meta        []storerec.MetaPair
	Created     time.Time
}

Fields are what an entry says beyond the closure.

type HoldRecord

type HoldRecord struct {
	Txid    string `json:"txid"`
	Vout    uint32 `json:"vout"`
	Sats    uint64 `json:"sats"`
	RawHex  string `json:"rawHex,omitempty"`
	BumpHex string `json:"bumpHex,omitempty"`
	Height  uint32 `json:"height,omitempty"`
	// Used marks a hold output a put has taken, saved before its entry is
	// signed, so no two entries name one hold output.
	Used bool `json:"used,omitempty"`
	// Entry is the commitment of the entry that names it (display order),
	// once that entry is minted.
	Entry string `json:"entry,omitempty"`
	// Sent is when it was handed to the settlement leg (Unix seconds).
	Sent int64 `json:"sent,omitempty"`
	// Reclaim is its spend back to the fund key when no entry names it,
	// recorded before it is sent.
	Reclaim *ReclaimRecord `json:"reclaim,omitempty"`
}

HoldRecord is a hold output this identity minted (spec section 9.2): what a publisher client settles by rank or reclaims after the deadline.

type KillTree

type KillTree struct {
	Kind  string
	Txid  string
	Vouts []uint32
	// Unmined trees are named and left: a tree not yet mined funds no
	// carrier a host admitted.
	Unmined bool
}

KillTree is a tree the kill switch would sweep.

type LinkedBlob added in v0.12.0

type LinkedBlob struct {
	Path    string
	Hash    [32]byte
	SegRoot [32]byte
	Length  uint64
	// Fresh marks a blob this process hashed from the bytes it wrote at
	// Path: it is read back without hashing again while the stage holds
	// it, as Stage's own blobs are.
	Fresh bool
}

LinkedBlob is one blob of content already on disk outside the store, as a multipart part's blobs are kept: the file at Path holds exactly the blob, Hash and SegRoot are HashBlob of it.

type LocalPiece added in v0.24.0

type LocalPiece struct {
	Topic string
	BEEF  []byte

	Known      bool
	Bucket     string
	Root       [32]byte
	Writer     []byte
	Piece      []byte
	Hash       [32]byte
	Funding    transaction.Outpoint
	Commitment [32]byte
	Leaves     []byte
	Staged     bool
}

LocalPiece is a piece carrier a gateway hands to a provider in its own process (a storage node: s3d's local_provider) instead of sending it over HTTP. BEEF is the carrier as it would be sent, and Topic the blob topic it would be sent on.

When Known is set, the rest is the gateway's own account of what it minted: the bucket, root, writer and piece of the record, the piece's SHA-256, the funding output the carrier spends and the carrier's txid. A provider configured to trust its gateway takes those as given instead of deriving them from the BEEF again; one that verifies checks the BEEF as it checks any submission. Piece is a slice of BEEF. Known is unset for an item read back from the outbox after a restart, which kept only its bytes.

Leaves, with Known, are the piece's segment leaves (32 bytes a segment) from the pass that hashed it when it was staged, while the gateway still keeps them (a piece its stage wrote, still fresh), or nil: the provider takes them for its proofs instead of hashing the segments again.

Staged, with Known, says the gateway staged the piece's closure in this process: the root's content hash is the one its stage computed over the bytes it handed over, so a provider that trusts its gateway may check the closure on that account. A closure copied in from elsewhere (its content hash the source entry's) is not, and is walked.

type Manifest

type Manifest struct {
	Root     string   `json:"root"`
	Size     uint64   `json:"size"`
	Branches []string `json:"branches,omitempty"`
	Blobs    []string `json:"blobs,omitempty"`
}

Manifest is a stored closure: the root and branch nodes and every blob, by hash, in closure order (repeats included for blobs).

type Object

type Object struct {
	Root        [32]byte
	Size        uint64
	ContentHash [32]byte
	ProofRoot   [32]byte
	// Closure is where the pieces come from; nil publishes no pieces (a
	// copy within one bucket names a root its providers already hold).
	Closure Closure
}

Object is the closure a put names.

type Outbox

type Outbox struct {

	// Max bounds the bytes owed (0 is DefaultOutboxMax); owed is the
	// last count, and owedAt when it was taken.
	Max int64
	// contains filtered or unexported fields
}

Outbox is what an identity minted and has not delivered everywhere: each object's BEEF and the targets still owed it, written and synced before the first send. The same bytes are sent again until every target has taken them, or a week has passed.

A piece carrier is kept by reference: its BEEF less the stored object it carries (a head and a tail around it), the object's hash and a SHA-256 binding the head and the tail, so the 4 MiB of an object are neither written nor hashed a second time: the store holds the object to its hash. A put's pieces are written to one batch file, a line each, and the workers minting them share each sync (a group commit): every line is synced before its carrier is sent. An item a target still owes after its first send moves to a file of its own; one every target took is marked done in the batch, and a batch whose every line is done is removed. The objects referred to are pinned in the store while they are owed.

func (*Outbox) Drop

func (o *Outbox) Drop(kinds ...string) int

Drop removes every item of the given kinds ("piece", "entry", "outcome"): after a kill, what the sweeps retracted is not sent again.

func (*Outbox) Owed added in v0.5.0

func (o *Outbox) Owed() (int64, map[string]int64)

Owed is the bytes the outbox owes, in all and by target URL, counted at most a few seconds ago.

func (*Outbox) Pending

func (o *Outbox) Pending() int

Pending is the number of objects not yet delivered everywhere.

func (*Outbox) Retry

func (o *Outbox) Retry(ctx context.Context)

Retry sends every item that is due, oldest first; one a week old is given up, and said so.

func (*Outbox) RetryAll

func (o *Outbox) RetryAll(ctx context.Context)

RetryAll sends every item now, due or not.

type PayeeRecord

type PayeeRecord struct {
	Rank       int    `json:"rank"`
	Advertiser string `json:"advertiser"`
	Ad         string `json:"ad"`
	Satoshis   uint64 `json:"satoshis"`
	Vout       uint32 `json:"vout"`
	Front      string `json:"front"`
	Remitted   bool   `json:"remitted,omitempty"`
	Refused    string `json:"refused,omitempty"`
	Last       string `json:"last,omitempty"`
	// Spent is the transaction the node shows spending this payee's
	// output: only the payee's key can, so the payee has its share
	// whoever told it (a bridged incumbent learns of it from its front,
	// which forwards the settlement, spec C28).
	Spent string `json:"spent,omitempty"`
}

PayeeRecord is one rank of a settlement.

func (*PayeeRecord) Done added in v0.2.0

func (py *PayeeRecord) Done() bool

Done is a payee nothing more is owed: remitted, refused, or its output already spent by the payee.

type PaymentRecord

type PaymentRecord struct {
	Txid     string         `json:"txid"`
	Coin     bwallet.Output `json:"coin"`
	At       int64          `json:"at"`
	Answered bool           `json:"answered,omitempty"`
	// Small marks a fee coin taken from the payment coins, where it goes
	// back.
	Small bool `json:"small,omitempty"`
}

PaymentRecord is a BRC-105 payment this identity made: its fee coin left the pool and its change waits, unproven, until it mines. One whose call was not answered may never be broadcast by its payee.

type PendingDraw

type PendingDraw struct {
	Request  string `json:"request"` // hex
	Front    string `json:"front"`
	Answerer string `json:"answerer"`
	Tries    int    `json:"tries"`
}

PendingDraw is a request made and not yet answered.

type PublishedNote

type PublishedNote struct {
	Advertiser string `json:"advertiser"`
	Outcome    string `json:"outcome"`
	Txid       string `json:"txid"`
}

PublishedNote is an outcome record the race published.

type Publisher

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

Publisher is one identity's writer.

func Open

func Open(ctx context.Context, cfg Config) (*Publisher, error)

Open opens an identity, settles the funding trees a previous run left signed and unadopted, and resumes its outbox.

func (*Publisher) Background added in v0.3.0

func (p *Publisher) Background(ctx context.Context, o RaceOptions, tick time.Duration)

Background runs RaceTick every tick, and collects payments' change and settles payments not answered, until ctx ends. It is what a gateway runs for its own identities (spec section 9.4: the writer's own client judges the race).

func (*Publisher) Chain added in v0.9.0

func (p *Publisher) Chain() nodeapi.Chain

Chain is the chain view the identity asks.

func (*Publisher) Challenge

func (p *Publisher) Challenge(ctx context.Context, ch *Challenge, fetch *http.Client) (*ChallengeResult, error)

Challenge runs one challenge. An error is the buyer's own (no tip, a price over the budget, a request it cannot build); everything the answerer did or did not do is the result's outcome.

func (*Publisher) CheckHolds

func (p *Publisher) CheckHolds(ctx context.Context)

CheckHolds asks the node about every hold transaction handed to the leg and not seen mined: its proof once it has one, kept as the minimal path (a node's proof may flag the sibling leaf as a transaction id, which the hosts refuse); the same bytes sent again when the node does not know it.

func (*Publisher) CheckPayouts added in v0.2.0

func (p *Publisher) CheckPayouts(ctx context.Context, r *Race) error

CheckPayouts asks the node, for each payee of a mined settlement not yet done, whether its output is spent, and records a spend. It saves the race when anything changed. A spend source that cannot answer decides nothing.

func (*Publisher) Close

func (p *Publisher) Close()

Close stops what the identity runs in the background (a funding tree minted ahead is settled on the next start from its record) and releases the identity's directory for another process.

func (*Publisher) CollectChange

func (p *Publisher) CollectChange(ctx context.Context)

CollectChange asks the node for the proof of every transaction whose change the pool holds unproven (a payment this identity made), so that change becomes spendable once it has mined.

func (*Publisher) Delete

func (p *Publisher) Delete(ctx context.Context, bucket string, id [32]byte, key string, created time.Time) (*Receipt, error)

Delete publishes a delete entry for key (spec section 16.2). Once the entry is made (taken by a quorum now, or kept by the outbox until one takes it) the key's earlier races stop judging and its earlier entries leave entries/ on the next race pass (retire.go).

func (*Publisher) Delivery

func (p *Publisher) Delivery() *Delivery

Delivery is how the identity reaches hosts and providers.

func (*Publisher) Dir

func (p *Publisher) Dir() string

Dir is the identity's directory.

func (*Publisher) DoneRaces added in v0.26.0

func (p *Publisher) DoneRaces() int

DoneRaces counts the races moved to races/done/.

func (*Publisher) Entries

func (p *Publisher) Entries() []EntryLog

Entries are the entries this identity made, oldest claim first.

func (*Publisher) EntryBEEF

func (p *Publisher) EntryBEEF(txid string) ([]byte, error)

EntryBEEF is an entry's carrier as it was sent.

func (*Publisher) EntryRecord

func (p *Publisher) EntryRecord(txid string) (*storerec.Entry, *EntryLog, error)

EntryRecord is an entry this identity made, decoded.

func (*Publisher) Fees

func (p *Publisher) Fees() mint.Fees

Fees is the identity's fee policy.

func (*Publisher) FillHolds

func (p *Publisher) FillHolds(ctx context.Context, sats uint64)

FillHolds mints hold outputs of sats until HoldAhead are ready, in cycles: each cycle mints the deficit, at most 16 to a transaction and as many transactions as the pool has spendable coins for (one is always left), then waits for them to mine before it looks again. One fill runs at a time; a call while one runs returns at once, and the running fill sees the take that called it on its next cycle.

func (*Publisher) FillPayCoins added in v0.3.0

func (p *Publisher) FillPayCoins(ctx context.Context, maxPay uint64)

FillPayCoins splits one coin of the pool into small payment coins for calls that pay up to maxPay, until payCoins are held (proven or on their way). One runs at a time; a call while one runs returns at once.

func (*Publisher) Get

func (p *Publisher) Get(ctx context.Context, url string) (*Call, error)

Get sends a GET over BRC-104 and pays nothing.

func (*Publisher) HoldScriptOf

func (p *Publisher) HoldScriptOf() (*script.Script, error)

HoldScriptOf is the hold output's locking script for this identity.

func (*Publisher) Holds

func (p *Publisher) Holds() []HoldRecord

Holds are the hold outputs this identity minted.

func (*Publisher) Identity

func (p *Publisher) Identity() []byte

Identity is the identity key, 33 bytes.

func (*Publisher) IdentityHex

func (p *Publisher) IdentityHex() string

IdentityHex is the identity key, 66 hex digits.

func (*Publisher) Kill

func (p *Publisher) Kill(ctx context.Context) ([]SweepRecord, error)

Kill sweeps every tree of the plan, one mined transaction a tree, and publishes each sweep. The trees are retired first, so no carrier is made on them again. An output the chain already shows spent is left out: the transaction that spends it is another instance's sweep or a carrier that was mined, which a carrier never is. It returns the sweeps made and published.

func (*Publisher) KillPlan

func (p *Publisher) KillPlan() []KillTree

KillPlan is every tree output the kill switch would sweep: every output of every tree this identity holds that no sweep it recorded spends.

func (*Publisher) Killed

func (p *Publisher) Killed() bool

Killed reports whether a kill retired this identity's trees.

func (*Publisher) Logf

func (p *Publisher) Logf(format string, args ...any)

Logf writes to the identity's log.

func (*Publisher) MarkNamed

func (p *Publisher) MarkNamed(txid string, seq uint64) error

MarkNamed records that the token at seq named the entry.

func (*Publisher) MergeCoins added in v0.11.6

func (p *Publisher) MergeCoins(ctx context.Context) (int, error)

MergeCoins merges the identity's small coins, mergeBatch at most, when more than mergeAbove are held. It answers how many coins went into the merge: zero when there was nothing to do. The merged coin is in the pool unproven until its proof is collected (CollectChange).

func (*Publisher) NewPayer

func (p *Publisher) NewPayer(ctx context.Context) *producer.Payer

NewPayer is a Payer over the identity's pool and settlement leg.

func (*Publisher) NewRequest

func (p *Publisher) NewRequest(ctx context.Context, ch *Challenge) (*storerec.Request, []byte, error)

NewRequest builds a challenge request seeded SeedBack blocks below the header source's tip.

func (*Publisher) Now

func (p *Publisher) Now() time.Time

Now is the identity's clock.

func (*Publisher) Outbox

func (p *Publisher) Outbox() *Outbox

Outbox is what the identity has not delivered yet.

func (*Publisher) OwedUploads

func (p *Publisher) OwedUploads() int

OwedUploads is how many closures are owed to a provider.

func (*Publisher) PayCoins added in v0.3.0

func (p *Publisher) PayCoins() (int, uint64)

PayCoins is how many payment coins are held, and their value.

func (*Publisher) Post

func (p *Publisher) Post(ctx context.Context, url string, body []byte, maxPay uint64) (*Call, error)

Post sends a JSON body over BRC-104 to a front (a URL an advertisement or a statement named), paying a 402 up to maxPay.

func (*Publisher) PostPaid added in v0.10.2

func (p *Publisher) PostPaid(ctx context.Context, url string, body []byte, payment string) (*Call, error)

PostPaid sends a POST over BRC-104 carrying payment, an x-bsv-payment header sent before (a payment its payee held), and pays nothing more.

func (*Publisher) Prune added in v0.11.0

func (p *Publisher) Prune()

Prune drops what the state no longer needs and says so: the hold records whose story is over and the trees spent out. The state is saved under the same lock every take holds, so it is kept small.

func (*Publisher) PruneHolds added in v0.11.0

func (p *Publisher) PruneHolds() (int, error)

PruneHolds drops the hold records whose story is over: reclaimed and seen mined, spent by something else, or named by an entry whose race is settled, reclaimed or spent. It returns how many were dropped.

func (*Publisher) PublishOutcome

func (p *Publisher) PublishOutcome(ctx context.Context, o *storerec.Outcome) (string, error)

PublishOutcome publishes an outcome record (spec section 8.1) on the bucket's records topic: a carrier on an outcome funding tree output recorded used first, written to the outbox before it is sent. It returns the carrier's txid.

func (*Publisher) Put

func (p *Publisher) Put(ctx context.Context, f Fields, obj Object, b *Bounty) (*Receipt, error)

Put publishes obj under f: a hold output first when b asks for one, then the closure's pieces on the bucket's blob topic (unless obj.Closure is nil), then a put entry. It returns once the put is committed: the hold taken, a funding output reserved for every piece carrier and recorded used, a record to mint each from written to the outbox, the entry minted on an output recorded used and written to the outbox, all synced, and the entry logged with its race. The pieces are minted and sent in the background, PieceWorkers at a time, the entry sent after them, and what a target did not take is sent again from the outbox, after a restart too, each piece minted once on its reserved output; Wait reports the first send. A closure that goes by upload session is uploaded before Put returns, as the session answers for it.

func (*Publisher) Race

func (p *Publisher) Race(entry string) (*Race, error)

Race is the race of one entry, live or over.

func (*Publisher) RaceTick added in v0.3.0

func (p *Publisher) RaceTick(ctx context.Context, o RaceOptions) int

RaceTick is one pass of the writer's own race work over every race of this identity, as `bstore holds`, `settle` and `reclaim` do it by hand: an open race is judged (Step) and, once closed, settled by rank; a settlement on its way is followed to its block and its remittances sent again until taken; a race with nothing to settle is reclaimed once its deadline has come. Each race is saved as it goes; one that cannot be decided now is left for the next pass. It returns how many races are still open or owed something.

The pass first applies the deletes recorded since the last one (retire.go), works at one tip read a few times a pass rather than once a race, re-reads only the race files that changed, and ends by moving the races that are over to races/done/: its cost follows the live races, not every bounty this identity ever set.

func (*Publisher) Races

func (p *Publisher) Races() ([]*Race, error)

Races are this identity's live races, oldest first: those whose story is over are in races/done/ (archiveRace) and Race still finds them.

func (*Publisher) Reclaim

func (p *Publisher) Reclaim(ctx context.Context, r *Race) (*ReclaimRecord, error)

Reclaim spends a race's hold output back to the writer after its deadline (spec section 9.6), unless a settlement of it is recorded and not proven abandoned: a hold output settles or is reclaimed, never both.

func (*Publisher) ReclaimUnused

func (p *Publisher) ReclaimUnused(ctx context.Context) ([]string, error)

ReclaimUnused spends back to the fund key every mined hold output no entry names: one minted ahead and never taken, and one a put took and then failed before its entry was made. Each is marked taken, and its reclaim recorded, raw transaction and all, before it is sent; one a run left on its way is sent again; an error on one does not stop the rest. It returns the reclaims seen mined.

func (*Publisher) ReconcilePayments

func (p *Publisher) ReconcilePayments(ctx context.Context) int

ReconcilePayments settles every payment recorded: one mined has its change proven; one the node has not seen for paymentWait, whose coin the node shows unspent, gives its coin back to the pool and its change up; one whose coin something else spent is forgotten. It returns how many are still open.

func (*Publisher) RecordTargets

func (p *Publisher) RecordTargets(bucket string) []Target

RecordTargets are where a mined object or a record of bucket goes: the facade, when there is one, and every host.

func (*Publisher) ReleasePayment added in v0.3.0

func (p *Publisher) ReleasePayment(txid string) bool

ReleasePayment gives back the coin of a payment recorded as not answered, at once: its payee signed a note that it did not take it (row C30). The payment's change goes, and its fee coin returns to the pool. It reports whether a payment was released.

func (*Publisher) Resend

func (p *Publisher) Resend(ctx context.Context, id, what string, beef []byte, targets []Target) []Target

Resend offers a BEEF to the given targets through the outbox, as any object this identity minted: written before it is sent, sent again until every target took it. It returns the targets that took it.

func (*Publisher) ResendAll added in v0.2.0

func (p *Publisher) ResendAll(ctx context.Context, id, what string, beef []byte, targets []Target) (ok, refused []Target)

ResendAll is Resend, and also returns the targets that refused the BEEF. A refusal is final: the outbox never offers those bytes to them again.

func (*Publisher) RetryUploads

func (p *Publisher) RetryUploads(ctx context.Context) int

RetryUploads sends every closure still owed to a provider again, from the local store; one owed a week is given up, and said so.

func (*Publisher) ReturnCoin

func (p *Publisher) ReturnCoin(ctx context.Context, c bwallet.Output)

ReturnCoin puts a fee coin a recorded transaction never spent back in the pool, when the spend source shows it unspent.

func (*Publisher) Settle

func (p *Publisher) Settle(ctx context.Context, r *Race, force bool) (*SettleRecord, error)

Settle settles a race whose race has closed: or resumes a settlement a run recorded and did not see through. It returns the record of what it did (nil when nothing is paid).

func (*Publisher) Settler

func (p *Publisher) Settler() bpub.Settler

Settler is the identity's settlement leg.

func (*Publisher) SpentElsewhere

func (p *Publisher) SpentElsewhere(ctx context.Context, tx *transaction.Transaction) (*Conflict, error)

SpentElsewhere asks the node about each input of tx: the first one spent by another transaction, or nil when none is (as far as positive evidence goes). An input the node cannot say about is an error.

func (*Publisher) StaleRemitted added in v0.5.0

func (p *Publisher) StaleRemitted(age time.Duration) (n int, oldest time.Duration)

StaleRemitted counts this identity's races remitted before mining whose proof the node has not served for at least age, and the oldest's age. A race recorded before RemittedAt existed counts from its start.

func (*Publisher) Step

func (p *Publisher) Step(ctx context.Context, r *Race, o RaceOptions) error

Step is one step of a race: it watches the hosts for advertisements, challenges the candidates that have not passed or failed, and closes the race when K have passed, the window has ended or the deadline has come. It saves the race before it returns.

A step that cannot judge (the closure's blobs unreachable) counts a failure and sets the race's RetryAt: the background pass skips it until then, so a race that cannot be judged costs a step an hour, not one a pass. A retired race (its key deleted) is never stepped.

func (*Publisher) Store

func (p *Publisher) Store() *Store

Store is the local closure store.

func (*Publisher) Sweeps

func (p *Publisher) Sweeps() []SweepRecord

Sweeps are the kill switch's sweeps.

func (*Publisher) Unspent

func (p *Publisher) Unspent(ctx context.Context, txid string, vout uint32) (bool, string, error)

Unspent is a spend source's positive evidence about an output: true only for "" with no error; by names the spender; an error decides nothing (ErrNotYet).

func (*Publisher) Wallet

func (p *Publisher) Wallet() *bwallet.Embedded

Wallet is the identity's wallet.

type Race

type Race struct {
	Entry  string `json:"entry"` // txid, display order
	Bucket string `json:"bucket"`
	Record string `json:"record"` // the entry's encoding, hex
	// Hold is the hold output, "txid.vout"; HoldHeight the block it mined
	// in, when known.
	Hold       string `json:"hold"`
	HoldHeight uint32 `json:"holdHeight,omitempty"`
	Started    int64  `json:"started"`
	// RootLen is the root node's length, which an eligible advertisement's
	// fileSize must equal.
	RootLen uint64 `json:"rootLen,omitempty"`
	State   string `json:"state"`
	// Closing is set when the race has closed for settlement (the window
	// ended with at least t passed) and is waiting to be settled.
	Closing    bool          `json:"closing,omitempty"`
	Cands      []*Cand       `json:"candidates,omitempty"`
	Settlement *SettleRecord `json:"settlement,omitempty"`
	// Abandoned are settlements recorded that could never mine (a fee
	// input spent elsewhere), kept for the record.
	Abandoned []SettleRecord  `json:"abandoned,omitempty"`
	Reclaim   *ReclaimRecord  `json:"reclaim,omitempty"`
	Note      string          `json:"note,omitempty"`
	Outcomes  []PublishedNote `json:"outcomes,omitempty"`
	// Retired says why the race stopped judging before K passed or its
	// window ended: the key was deleted (retire.go). A retired race is
	// never stepped again; it settles or is reclaimed as a closed race.
	Retired string `json:"retired,omitempty"`
	// Fails counts the steps in a row that could not judge (the closure's
	// blobs unreachable); the next step waits until RetryAt, Unix seconds,
	// a minute doubling to an hour (retryDelay).
	Fails   int   `json:"fails,omitempty"`
	RetryAt int64 `json:"retryAt,omitempty"`
	// contains filtered or unexported fields
}

Race is one entry's hold race.

func (*Race) C

func (r *Race) C() [32]byte

C is the entry's commitment, hash byte order.

func (*Race) Closed

func (r *Race) Closed(now time.Time, window time.Duration) bool

Closed reports whether the race is ready to settle: K passed, or the window ended with at least t.

func (*Race) EntryOf

func (r *Race) EntryOf() *storerec.Entry

EntryOf is the race's entry.

func (*Race) Forwarder added in v0.2.0

func (r *Race) Forwarder(adv string) string

Forwarder is the front that answered for an advertiser in the race when that front is not the advertiser itself (a bridge in front of an incumbent UHRP host). Such a front forwards the settlement to the advertiser (C28); the advertiser's own front has no settle route.

func (*Race) Open

func (r *Race) Open() bool

Open reports whether the race still watches and judges.

func (*Race) Passed

func (r *Race) Passed() []*Cand

Passed are the candidates that passed, in rank order.

func (*Race) Ranked

func (r *Race) Ranked() []*Cand

Ranked are the candidates in the writer's ranking: by first sight, ties to the lower tie key of the advertisement first seen (spec section 9.4, storerec.TieKey).

func (*Race) Remitted added in v0.3.0

func (r *Race) Remitted() bool

Remitted reports whether every payee of the race's settlement has what it is owed: remitted to, refused, or seen spending its output; a payee a front answered for is told by that front.

func (*Race) RemittedAge added in v0.5.0

func (r *Race) RemittedAge(now time.Time) (time.Duration, bool)

RemittedAge is how long the race has been remitted and unmined.

func (*Race) RemittedBefore added in v0.5.0

func (r *Race) RemittedBefore() bool

RemittedBefore reports whether a settlement of this race was remitted before mining and then abandoned (it could never mine).

type RaceOptions

type RaceOptions struct {
	// Window is the writer's race window from the race's start; zero closes
	// the race only at K passes or the deadline.
	Window time.Duration
	// Budget is the most paid for one settlement challenge a provider does
	// not answer free; zero pays nothing.
	Budget uint64
	// Fetch reaches advertised URLs for by-reference samples.
	Fetch *http.Client
	// Publish publishes failed challenges as outcome records.
	Publish bool
	// Parallel is how many open races a pass steps at once. A step is
	// mostly waiting on providers, so one at a time held a gateway to
	// about five races a minute. Zero or one steps them one at a time.
	// Settlements and reclaims spend coins and stay one at a time either
	// way. Challenges to one front go one at a time whatever this says
	// (authPool); to different fronts at once.
	Parallel int
}

RaceOptions are the writer's policy for a race step.

type Receipt

type Receipt struct {
	Entry  *storerec.Entry
	Record []byte
	// C is the entry's commitment, hash byte order; Txid the same in
	// display order.
	C    [32]byte
	Txid string
	// Sent is whether the entry counts as sent (spec section 14): the
	// facade took it, or a quorum of the hosts. What a target did not take
	// is sent again from the outbox either way. A put's entry is sent in
	// the background: Sent is valid once Delivered is closed.
	Sent bool
	// Delivered is closed once the first send of the entry and, for a put,
	// of every piece carrier has been answered; the outbox keeps sending
	// what was not taken.
	Delivered <-chan struct{}

	// Pieces is how many piece carriers the put committed, each minted
	// in the background on the output reserved for it.
	Pieces int
	// Uploads are the providers' answers when the closure went by upload
	// sessions instead of piece carriers.
	Uploads []UploadResult
	// Hold is the hold output the entry names, when it asked for a bounty.
	Hold *HoldRecord
	// contains filtered or unexported fields
}

Receipt is an entry made.

func (*Receipt) Wait added in v0.14.0

func (r *Receipt) Wait(ctx context.Context) error

Wait returns once the receipt's first send is answered: nil when the entry counts as sent, ErrNotSent when no facade or host quorum took it yet, or ctx's error.

type ReclaimRecord

type ReclaimRecord struct {
	Txid   string         `json:"txid"`
	Raw    string         `json:"raw"`
	Fee    bwallet.Output `json:"fee"`
	Height uint32         `json:"height,omitempty"`
}

ReclaimRecord is a hold output spent back to the writer after its deadline.

type SettleRecord

type SettleRecord struct {
	Txid   string         `json:"txid"`
	Raw    string         `json:"raw"`
	Bump   string         `json:"bump,omitempty"`
	Height uint32         `json:"height,omitempty"`
	Fee    bwallet.Output `json:"fee"`
	Payees []PayeeRecord  `json:"payees"`
	// Dropped are advertisers that passed and whose advertisement was
	// then cancelled.
	Dropped []string `json:"dropped,omitempty"`
	// Abandoned is set when the network never took this settlement and
	// the hold output went elsewhere.
	Abandoned string `json:"abandoned,omitempty"`
	// RemittedAt is when it was remitted before mining (Unix seconds);
	// zero when it was remitted, if at all, only once mined.
	RemittedAt int64 `json:"remittedAt,omitempty"`
}

SettleRecord is a settlement made.

type Staged

type Staged struct {
	Root        [32]byte
	ContentHash [32]byte
	ProofRoot   [32]byte
	Size        uint64
	// Manifest is the closure as the store keeps it.
	Manifest *Manifest
	// contains filtered or unexported fields
}

Staged is content built into a CHIRP Profile 1 closure (no extension on the root) and its proof root, every object of it in the store. Nothing is published yet.

func (*Staged) Release

func (s *Staged) Release()

Release lets the store trim the closure again.

type Store

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

Store is the publisher's local copy of the closures it built: each CHIRP object under its SHA-256, and per root a manifest naming its objects. A gateway reads its own writes from it before any provider advertises them (spec section 4.4), a cross-bucket copy republishes from it, and a put retried after a crash finds its pieces here. It is a cache: Trim removes the least recently used closures beyond a bound, and nothing is lost when it does, because the closure's providers hold it.

Every path is made from a hash's hex digits alone.

func OpenStore

func OpenStore(dir string) (*Store, error)

OpenStore opens (creating) a store under dir.

func (*Store) Get

func (s *Store) Get(h [32]byte) ([]byte, error)

Get reads an object and holds it to its hash: bytes that went bad on disk are never returned.

func (*Store) Grown added in v0.27.1

func (s *Store) Grown() int64

Grown is the bytes written into the store since the last Trim began. A store is trimmed on a clock; under a heavy ingest it can take in many times its bound between two trims, and a caller that sees Grown pass a share of the bound trims then instead of waiting.

func (*Store) Has

func (s *Store) Has(h [32]byte) bool

Has reports whether an object is held.

func (*Store) Hold

func (s *Store) Hold(root [32]byte) func()

Hold marks root busy until the returned function is called.

func (*Store) Keep added in v0.31.0

func (s *Store) Keep(h [32]byte, b []byte) error

Keep stores an object whose SHA-256 the caller just computed as h: what a reader fetched from an advertiser and held to its hash (reader.Keeper). Until SaveManifest names it, it is an object no closure names.

func (*Store) Manifest

func (s *Store) Manifest(root [32]byte) (*Manifest, error)

Manifest reads a closure's manifest; it touches the closure as used.

func (*Store) Put

func (s *Store) Put(b []byte) ([32]byte, error)

Put stores an object under its hash, durably; an object already held is left alone.

func (*Store) SaveManifest

func (s *Store) SaveManifest(m *Manifest) error

SaveManifest records a closure, durably.

func (*Store) Stage

func (st *Store) Stage(ctx context.Context, r io.Reader, max uint64) (*Staged, error)

Stage reads content from r to its end, at most max bytes, building the closure and the proof root as it streams: each 4 MiB blob is hashed and goes to the store as soon as it is complete, on one of several cores (storerec.Parallel), while the content hash runs on another, so memory holds a few blobs whatever the content's size (spec section 16.2). An error from r, or content over max (ErrTooLarge), leaves nothing to publish.

func (*Store) StageLinked added in v0.12.0

func (st *Store) StageLinked(ctx context.Context, blobs []LinkedBlob, contentHash [32]byte) (*Staged, error)

StageLinked is Stage of content whose blobs are already on disk, hashed: blobs in content order (every one ChunkSize bytes but the last) and contentHash the SHA-256 of the whole content. Each blob file is linked into the store (copied where it cannot be), not read; the closure, the proof root and the manifest are what Stage returns for the same content, byte for byte.

func (*Store) StageTee added in v0.13.0

func (st *Store) StageTee(ctx context.Context, r io.Reader, max uint64, tee Tee) (*Staged, error)

StageTee is Stage with every buffer read also given to tee, before the closure takes it: the digests a request checks run over the same bytes, read once and copied by nothing but the chunker.

func (*Store) Trim

func (s *Store) Trim(max int64) (int64, error)

Trim removes objects no closure names that are older than orphanAge (what a put cut short left), then the least recently used closures until the objects held take at most max bytes; never a busy closure, a pinned object, or an object another remaining closure names. It returns the bytes held after.

type StoreClosure

type StoreClosure struct {
	Store    *Store
	Manifest *Manifest
	Staged   bool
}

StoreClosure is a stored closure as a Closure. Staged marks a closure this process staged in the same request, still pinned: its objects are read without hashing them a second time.

func (StoreClosure) Object

func (c StoreClosure) Object(_ context.Context, h [32]byte) ([]byte, error)

func (StoreClosure) Objects

func (c StoreClosure) Objects() [][32]byte

type SweepRecord

type SweepRecord struct {
	Kind   string         `json:"kind"`
	Tree   string         `json:"tree"`
	Vouts  []uint32       `json:"vouts"`
	Txid   string         `json:"txid"`
	Raw    string         `json:"raw"`
	Fee    bwallet.Output `json:"fee"`
	Height uint32         `json:"height,omitempty"`
	Bump   string         `json:"bump,omitempty"`
	// Published is set once every target took it.
	Published bool   `json:"published,omitempty"`
	Failed    string `json:"failed,omitempty"`
}

SweepRecord is one tree's sweep.

type Target

type Target struct {
	Base  string `json:"base"`
	Topic string `json:"topic"`
	// Plane marks the facade; Host a host (not a provider); Local the
	// provider in this process (Delivery.Local), whose Base is "local".
	Plane bool `json:"plane,omitempty"`
	Host  bool `json:"host,omitempty"`
	Local bool `json:"local,omitempty"`
}

Target is one place one object goes: a submit route and a topic.

func HostTarget

func HostTarget(host, bucket string) Target

HostTarget is one host's submit route for a bucket's records topic.

type Tee added in v0.13.0

type Tee func(p []byte, done func())

A Tee is given each buffer StageTee reads, in content order, and calls done once it is through with it; the buffer is not read into again before then.

type UploadRecord

type UploadRecord struct {
	Root     string `json:"root"`
	Provider string `json:"provider"`
	// Retention is the retention asked, seconds.
	Retention uint64 `json:"retention"`
	Created   int64  `json:"created"`
	Tries     int    `json:"tries,omitempty"`
	Last      string `json:"last,omitempty"`
}

UploadRecord is a closure owed to a provider's upload sessions.

type UploadResult

type UploadResult struct {
	Provider string
	// Status is 201 (advertised) or 202 (staged until an entry arrives).
	Status int
	Staged int
	Err    error
}

UploadResult is one provider's answer to a commit.

Jump to

Keyboard shortcuts

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