store

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 26 Imported by: 1 module, 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 store is the Go overlay engine's own storage: an INDEX store (the outpoint index, small, hot, updated on spend) and a BEEF BLOB store (large, written once per transaction, read on lookup and GASP, unlinked by retention), behind one URL-scheme factory, Teranode-style. Ruling R-h (1bsv-ops decisions.md §7, storage-options.md §7).

Backends:

pebble:///path/to/index     Pebble v2 (default; WAL synced on a timer)
sqlite:///path/to/index.db  modernc.org/sqlite, WAL, synchronous=NORMAL, rowid tables
file:///path/to/blobs       one file per txid, sharded by txid prefix, temp + rename

Store composes the two into the plain engine.Storage interface. It does NOT advertise overlay-admission-v1, so the engine takes its ordinary path (a duplicate answers empty arrays, exactly as the TypeScript host does).

Write order: the BEEF blob is written BEFORE the index rows, so a crash never leaves an output without its bytes. Durability is a policy: the WAL is synced on a timer (bounded loss, recovered from the plane by re-delivery and GASP, ruling R-j), or on every batch when the timer is 0.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrScope is a store created for another chain (genesis) being opened.
	ErrScope = errors.New("store: index was created for another chain")
	// ErrLocked is an index another process holds open.
	ErrLocked = errors.New("store: index is open in another process")
)

Errors.

Functions

func Backend

func Backend(raw string) string

Backend names the backend of a URL, for the build info gauge.

Types

type Blobs

type Blobs interface {
	Put(ctx context.Context, txid chainhash.Hash, data []byte) error
	// Get returns nil, nil when absent.
	Get(ctx context.Context, txid chainhash.Hash) ([]byte, error)
	Has(ctx context.Context, txid chainhash.Hash) (bool, error)
	// Delete of an absent blob is not an error.
	Delete(ctx context.Context, txid chainhash.Hash) error
	// Walk visits every blob.
	Walk(ctx context.Context, fn func(txid chainhash.Hash, size int64) error) error
	// Snapshot links or copies every blob into dir (which must not exist).
	Snapshot(ctx context.Context, dir string) error
	Close() error
}

Blobs is the BEEF blob store, keyed by txid.

func OpenBlobs

func OpenBlobs(rawURL string, cfg Config) (Blobs, error)

OpenBlobs opens the blob store named by a URL.

type CheckReport

type CheckReport struct {
	Transactions uint64
	Outputs      uint64
	Blobs        uint64
	// MissingBlobs are transactions the index says hold a blob whose file is
	// absent: an output without its bytes. The one inconsistency the write
	// order is designed to prevent.
	MissingBlobs []chainhash.Hash
	// OrphanRows are output rows whose transaction row is absent.
	OrphanRows []string
	// Unreferenced are blobs no transaction row claims: a blob written for
	// an admission whose index batch never committed (a crash between the
	// two). Harmless; the next retention or a re-delivery resolves it.
	Unreferenced []chainhash.Hash
}

CheckReport is what Check found.

func (CheckReport) OK

func (r CheckReport) OK() bool

OK is true when nothing is missing (unreferenced blobs do not count).

func (CheckReport) String

func (r CheckReport) String() string

type Config

type Config struct {
	// IndexURL: pebble:///dir or sqlite:///file.db.
	IndexURL string
	// BlobsURL: file:///dir.
	BlobsURL string
	// WALSync is how often Pebble's WAL is synced; 0 syncs every batch.
	WALSync time.Duration
	// BlobFsync fsyncs each blob file before its rename.
	BlobFsync bool
	// CacheMB is the index block cache (Pebble) or page cache (SQLite).
	CacheMB int
	// Network and Genesis scope the store: an index created for another
	// genesis refuses to open (a lab genesis reset means a wipe, not a mix).
	Network string
	Genesis string
	// Metrics may be nil (the CLI).
	Metrics *metrics.Metrics
}

Config is what Open needs.

type Index

type Index interface {
	// Meta reads the scope record; nil when the index is new.
	Meta(ctx context.Context) (*Meta, error)
	SetMeta(ctx context.Context, m Meta) error

	// Get returns the rows of one outpoint, in every topic when topic is nil.
	Get(ctx context.Context, op transaction.Outpoint, topic *string) ([]*Record, error)
	ByTxid(ctx context.Context, txid chainhash.Hash) ([]*Record, error)
	// Scan lists a topic's rows with score >= since in score order, at most
	// limit (0 = no limit), filtered by spent when non-nil. With spent nil
	// the order is the backend's primary key order and since is ignored.
	Scan(ctx context.Context, topic string, since uint64, limit uint32, spent *bool) ([]*Record, error)

	// Insert writes rows that do not exist yet (an existing row is left as
	// is) and the transaction's meta, in one atomic batch.
	Insert(ctx context.Context, recs []*Record, tx *TxMeta) error
	// Delete removes a row; when it was the transaction's last, the
	// transaction's meta records that (tip is the best known height).
	Delete(ctx context.Context, topic string, op transaction.Outpoint, tip uint32) error
	// MarkSpent marks rows spent by spendTxid and flags transactions whose
	// rows are now all spent.
	MarkSpent(ctx context.Context, topic string, ops []transaction.Outpoint, spendTxid chainhash.Hash) error
	SetConsumedBy(ctx context.Context, topic string, op transaction.Outpoint, consumedBy []transaction.Outpoint) error
	SetBlock(ctx context.Context, topic string, op transaction.Outpoint, height uint32, idx uint64) error
	// SetMerkleRoot records the root a transaction's proof computes to, on
	// every row of the transaction; a nil root clears it (unmined).
	SetMerkleRoot(ctx context.Context, txid chainhash.Hash, root *chainhash.Hash, height uint32, idx uint64) error
	ByMerkleState(ctx context.Context, topic string, state uint8, limit uint32) ([]transaction.Outpoint, error)
	AtHeight(ctx context.Context, topic string, height uint32) ([]*Record, error)
	SetMerkleStates(ctx context.Context, updates []StateUpdate) error

	PutApplied(ctx context.Context, txid chainhash.Hash, topic string) error
	HasApplied(ctx context.Context, txid chainhash.Hash, topic string) (bool, error)
	// DeleteApplied forgets that topic applied txid, so the transaction
	// offered again is decided afresh; absent is no error.
	DeleteApplied(ctx context.Context, txid chainhash.Hash, topic string) error
	// Applied lists the transactions topic applied (a full walk of the
	// applied records: an operator's tool, never the admission path).
	Applied(ctx context.Context, topic string) ([]chainhash.Hash, error)
	SetInteraction(ctx context.Context, host, topic string, since float64) error
	Interaction(ctx context.Context, host, topic string) (float64, error)

	// Tx reads a transaction's meta; nil when absent.
	Tx(ctx context.Context, txid chainhash.Hash) (*TxMeta, error)
	// SetTxBlob records whether the blob is held (retention clears it).
	SetTxBlob(ctx context.Context, txid chainhash.Hash, present bool, size uint64) error
	// RetentionCandidates lists transactions whose blob is held and whose
	// rows are all spent and all proven (merkle state validated or
	// immutable) at heights no greater than maxHeight, or whose rows the
	// engine removed and that were proven, or removed, at such a height.
	RetentionCandidates(ctx context.Context, maxHeight uint32, limit int) ([]chainhash.Hash, error)
	// Tip and SetTip keep the best chain height the store has seen (SetTip
	// never lowers it).
	Tip(ctx context.Context) (uint32, error)
	SetTip(ctx context.Context, height uint32) error
	// Txs walks every transaction row (consistency checks).
	Txs(ctx context.Context, fn func(TxMeta) error) error
	// Topics lists the topics that have rows.
	Topics(ctx context.Context) ([]string, error)

	Stats(ctx context.Context) (Stats, error)
	// Checkpoint writes a consistent copy of the index into dir (which must
	// not exist).
	Checkpoint(ctx context.Context, dir string) error
	// Sync forces the write-ahead log to disk.
	Sync() error
	Close() error
}

Index is the outpoint index. Every method is safe for concurrent use. Secondary orderings a backend must serve: (topic, spent, score) for Scan, txid for ByTxid, (topic, merkle state) for ByMerkleState and (topic, block height) for AtHeight.

func OpenIndex

func OpenIndex(ctx context.Context, rawURL string, cfg Config) (Index, error)

OpenIndex opens the index named by a URL.

type Meta

type Meta struct {
	Network string
	Genesis string
	// Created is when the index was created, RFC 3339.
	Created string
}

Meta is what the index remembers about the store it belongs to.

type Record

type Record struct {
	Topic    string
	Outpoint transaction.Outpoint
	Spent    bool
	// SpendTxid is set once Spent.
	SpendTxid *chainhash.Hash
	// Score orders a topic's outputs for GASP paging: microseconds since the
	// epoch, monotonic within one store process.
	Score       uint64
	BlockHeight uint32
	BlockIdx    uint64
	MerkleRoot  *chainhash.Hash
	MerkleState uint8
	// OutputsConsumed are the outpoints this output's transaction consumed in
	// its topic; ConsumedBy the outputs that later consumed this one.
	OutputsConsumed []transaction.Outpoint
	ConsumedBy      []transaction.Outpoint
	AncillaryTxids  []chainhash.Hash
}

Record is one output row of the index.

type RetentionResult

type RetentionResult struct {
	// MaxHeight is the newest height whose spent-and-proven transactions
	// were eligible (tip - blocks).
	MaxHeight uint32
	// Candidates is how many transactions were all-spent with a blob held
	// before the pass.
	Candidates int
	Unlinked   int
	Bytes      uint64
}

RetentionResult is what one retention pass did.

type StateUpdate

type StateUpdate struct {
	Topic    string
	Outpoint transaction.Outpoint
	State    uint8
}

StateUpdate is one merkle-state change for SetMerkleStates.

type Stats

type Stats struct {
	Backend string
	Topics  map[string]TopicStats
	// Transactions is the number of transaction rows; WithBlob those whose
	// BEEF blob is held; Candidates those whose outputs are all spent and
	// whose blob is held (retention looks only at these).
	Transactions uint64
	WithBlob     uint64
	BlobBytes    uint64
	Candidates   uint64
	Applied      uint64
}

Stats is what Index.Stats reports.

type Store

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

Store is the engine's storage: an Index and a Blobs composed into the plain engine.Storage interface. It deliberately does not implement the admission capability (engine.AdmissionStorage).

func Open

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

Open opens both halves, writes or checks the scope record and returns the composed store.

func (*Store) Check

func (s *Store) Check(ctx context.Context) (CheckReport, error)

Check walks the index and the blobs and reports what disagrees.

func (*Store) Checkpoint

func (s *Store) Checkpoint(ctx context.Context, dir string, withBlobs bool) error

Checkpoint writes a consistent copy of the index into dir/index and a hard-linked snapshot of the blobs into dir/blobs.

func (*Store) Close

func (s *Store) Close() (err error)

Close closes both halves; a second call does nothing.

func (*Store) DeleteAppliedTransaction added in v0.4.0

func (s *Store) DeleteAppliedTransaction(ctx context.Context, txid *chainhash.Hash, topic string) error

DeleteAppliedTransaction forgets that topic applied txid, so the same transaction offered again is shown to the topic's manager afresh: what a lookup service that drops an object it indexed (bstore's retention and retractions) asks for beside DeleteOutput. Not part of engine.Storage; the module seam asserts for it.

func (*Store) DeleteOutput

func (s *Store) DeleteOutput(ctx context.Context, outpoint *transaction.Outpoint, topic string) error

func (*Store) DoesAppliedTransactionExist

func (s *Store) DoesAppliedTransactionExist(ctx context.Context, tx *overlay.AppliedTransaction) (bool, error)

func (*Store) DropTopic added in v0.5.0

func (s *Store) DropTopic(ctx context.Context, topic string) (rows, applied int, err error)

DropTopic forgets a topic: every row of it, spent or not, and every applied record, so that the same objects offered again are decided afresh by whatever manages the topic now. Blobs and transaction meta stay (another topic may hold the transaction; retention reclaims the rest). The operator's tool for handing a topic from one module to another (store drop-topic); never called by the engine.

func (*Store) FindOutpointsByMerkleState

func (s *Store) FindOutpointsByMerkleState(ctx context.Context, topic string, state engine.MerkleState, limit uint32) ([]*transaction.Outpoint, error)

func (*Store) FindOutput

func (s *Store) FindOutput(ctx context.Context, outpoint *transaction.Outpoint, topic *string, spent *bool, includeBEEF bool) (*engine.Output, error)

FindOutput returns one output, or nil, nil when absent.

func (*Store) FindOutputs

func (s *Store) FindOutputs(ctx context.Context, outpoints []*transaction.Outpoint, topic string, spent *bool, includeBEEF bool) ([]*engine.Output, error)

FindOutputs is slot-aligned with outpoints: a nil for each one absent.

func (*Store) FindOutputsForTransaction

func (s *Store) FindOutputsForTransaction(ctx context.Context, txid *chainhash.Hash, includeBEEF bool) ([]*engine.Output, error)

func (*Store) FindUTXOsForTopic

func (s *Store) FindUTXOsForTopic(ctx context.Context, topic string, since float64, limit uint32, includeBEEF bool) ([]*engine.Output, error)

FindUTXOsForTopic lists unspent outputs with score >= since in score order (the TypeScript reference's comparison), at most limit.

func (*Store) GetLastInteraction

func (s *Store) GetLastInteraction(ctx context.Context, host, topic string) (float64, error)

func (*Store) InsertAppliedTransaction

func (s *Store) InsertAppliedTransaction(ctx context.Context, tx *overlay.AppliedTransaction) error

func (*Store) InsertOutputs

func (s *Store) InsertOutputs(ctx context.Context, topic string, txid *chainhash.Hash, outputs []uint32, outpointsConsumed []*transaction.Outpoint, beef *transaction.Beef, ancillaryTxids []*chainhash.Hash) error

InsertOutputs writes the BEEF once per txid (before any row), then the output rows, the transaction's meta and, when the BEEF carries the subject's proof, its block coordinates and root.

func (*Store) LoadAncillaryBeef

func (s *Store) LoadAncillaryBeef(ctx context.Context, output *engine.Output) error

LoadAncillaryBeef merges the blobs of the output's ancillary transactions into its Beef. A blob retention removed is skipped, as upstream skips an absent one.

func (*Store) MarkUTXOsAsSpent

func (s *Store) MarkUTXOsAsSpent(ctx context.Context, outpoints []*transaction.Outpoint, topic string, spendTxid *chainhash.Hash) error

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping is the readiness check: the index answers.

func (*Store) ReconcileMerkleRoot

func (s *Store) ReconcileMerkleRoot(ctx context.Context, topic string, blockHeight uint32, merkleRoot *chainhash.Hash) error

ReconcileMerkleRoot applies upstream's rule to every row of the topic at the height: no stored root stays Unmined, a matching root becomes Validated, a differing one Invalidated. (Immutable is never set here: the engine's "old enough" promotion is a lookup-side policy this host does not run.)

func (*Store) Retention

func (s *Store) Retention(ctx context.Context, tip, blocks uint32) (RetentionResult, error)

Retention unlinks the BEEF blobs of transactions whose outputs are all spent and all proven at heights at least blocks below tip. Index rows stay: the outpoint, its spend and its proof state remain answerable; only the bytes go. A transaction consumed later by LoadAncillaryBeef or a lookup with BEEF then answers without them, as upstream does for an absent blob.

func (*Store) RunRetention

func (s *Store) RunRetention(ctx context.Context, tip Tip, blocks uint32, every time.Duration, log *slog.Logger)

RunRetention runs Retention every interval until ctx ends. blocks 0 disables it.

func (*Store) SeenHeight

func (s *Store) SeenHeight(ctx context.Context, height uint32)

SeenHeight tells the store the chain reached height (reconciliation and retention do); it is remembered across restarts and never lowered.

func (*Store) Transaction added in v0.7.0

func (s *Store) Transaction(ctx context.Context, txid chainhash.Hash) (*transaction.Transaction, error)

Transaction returns a held transaction with the ancestry and proofs its blob carries, or nil, nil when no blob is held (never admitted, or unlinked by retention). One blob serves every topic. GASP catch-up reads it so that an ancestor this host already holds is never fetched from a peer.

func (*Store) UpdateConsumedBy

func (s *Store) UpdateConsumedBy(ctx context.Context, outpoint *transaction.Outpoint, topic string, consumedBy []*transaction.Outpoint) error

func (*Store) UpdateLastInteraction

func (s *Store) UpdateLastInteraction(ctx context.Context, host, topic string, since float64) error

func (*Store) UpdateOutputBlockHeight

func (s *Store) UpdateOutputBlockHeight(ctx context.Context, outpoint *transaction.Outpoint, topic string, blockHeight uint32, blockIndex uint64) error

func (*Store) UpdateTransactionBEEF

func (s *Store) UpdateTransactionBEEF(ctx context.Context, txid *chainhash.Hash, beef *transaction.Beef) error

UpdateTransactionBEEF replaces the blob (a proof arrived) and records the root and block coordinates the new proof computes to on every row of the transaction, so ReconcileMerkleRoot has something to compare.

type Tip

type Tip interface {
	FreshHeight(ctx context.Context) (uint32, error)
}

Tip is where the retention job asks for the chain height.

type TopicStats

type TopicStats struct {
	Outputs uint64
	Unspent uint64
}

TopicStats are per-topic counts.

type TxMeta

type TxMeta struct {
	Txid      chainhash.Hash
	Blob      bool
	BlobBytes uint64
	AllSpent  bool
	// ProvenHeight is the height its rows were proven at when the engine
	// removed them (spent, not retained), 0 if they were unproven then.
	ProvenHeight uint32
	// DeletedHeight is the store's best known chain height when its last
	// row was removed, 0 if unknown.
	DeletedHeight uint32
}

TxMeta is the index's row per transaction: whether its BEEF blob is held and whether every output row of it is spent (a retention candidate).

Jump to

Keyboard shortcuts

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