sqlstore

package
v0.70.11 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Overview

Package sqlstore contains the shared database/sql metadata store.

Index

Constants

View Source
const (
	// DefaultCommitteeAuthRetentionSlots is the rollback window pruning keeps
	// history for, in slots. 129600 = 3k/f for k=2160, f=0.05: the Shelley-era
	// stability window on mainnet and preprod, and the same bound
	// internal/historyexpiry already uses to decide that block history is
	// immutable enough to expire locally. Networks with a smaller k (preview,
	// devnets) have a smaller true window, so this over-retains there, which
	// is the safe direction. Conway is the only era that has committee
	// certificates at all, so the smaller Byron 2k window never applies.
	DefaultCommitteeAuthRetentionSlots uint64 = 129600
)

auth_committee_hot records one row per AuthCommitteeHot certificate and never overwrites, so a committee member that re-authorizes a hot key on a schedule adds rows forever. On preprod at slot ~79.48M the table held 648,758 rows for 35 distinct cold credentials. Only the newest authorization per cold credential is ever read back (GetActiveCommitteeMembers and GetCommitteeMember both select the maximum by (added_slot, certificate_id)), so every older row is dead weight -- with one exception, which is what the retention window below exists for.

Retention rule, applied per (cold_credential_tag, cold_credential):

keep every row with added_slot > horizon,
plus the single newest row with added_slot <= horizon,
where horizon = tipSlot - retentionSlots.

Rollback safety. A chain rollback deletes committee certificate rows with "DELETE FROM auth_committee_hot WHERE added_slot > S" (see DeleteCertificatesAfterSlot), so after a rollback to S the newest surviving row is the answer the readers need. Ouroboros bounds S from below: a rollback cannot cross the immutable tip, so S >= tipSlot - stabilityWindow for every reachable rollback target. Choosing retentionSlots >= the stability window therefore gives horizon <= S always, and:

  • if any row exists in (horizon, S], it is retained (everything above the horizon is retained) and it dominates every row at or below the horizon, so the reader's answer is unchanged;
  • if no row exists in (horizon, S], the answer is the newest row at or below the horizon, which is exactly the one row the rule retains.

So the post-rollback query result is identical whether or not pruning ran. The rule also never removes a credential's last row, so a credential that has an authorization can never be turned into one that has none.

The partition is the tagged credential, matching the readers' PARTITION BY and the fact that a key-hash and a script-hash credential sharing 28 bytes are different identities. A script-hash row can never prune a key-hash row.

Only auth_committee_hot is pruned. committee_member (the seated-committee table that CommitteeStateAvailable reads include-deleted, to tell an authoritatively empty committee from an unpopulated one) is untouched.

View Source
const LatestPoolOpCertSequencesSQL = `
SELECT pool_key_hash, MAX(sequence)
FROM pool_opcert_sequence
GROUP BY pool_key_hash`

LatestPoolOpCertSequencesSQL is the statement LatestPoolOpCertSequences issues.

Exported so a test can pin its query plan against the statement the store actually runs. The index this reads is only worth its write cost while the planner chooses it, and a test EXPLAINing a hand-copied statement would keep passing against the copy after the store's own SQL moved off the index.

Variables

This section is empty.

Functions

func CreateDirDurable added in v0.70.0

func CreateDirDurable(dir string) error

CreateDirDurable is os.MkdirAll(dir, 0o755), but additionally fsyncs the parent of every directory component it actually had to create, so each new directory's own entry is durable -- not just, per a subsequent file write's own directory-sync, the eventual contents placed inside it. A directory's fsync only guarantees ITS children's directory entries are persisted; a power loss right after mkdir could otherwise leave the newly created directory itself unreachable (or entirely absent) from its parent after a crash, even though a file was safely and durably written inside it a moment later.

func OpenDB

func OpenDB(
	driverName, dataSourceName, systemName string,
	tracingEnabled bool,
) (*sql.DB, error)

OpenDB opens a database/sql pool, instrumented with OpenTelemetry tracing only when tracingEnabled is true. Keeping driver wrapping in the shared package gives every provider the same query and transaction tracing behavior when tracing is on.

otelsql.Open's wrapping is not free even when no TracerProvider is registered: with tracing off (the default), every ExecContext/QueryContext/ QueryRowContext call still starts a span against the no-op provider, computes its attributes, and allocates a wrapping *sql.Rows -- pure overhead for zero observability benefit. Measured on a from-genesis sync with tracing disabled, otelsql/otel accounted for roughly 9% of all allocated bytes over the run. Skipping the wrap entirely when tracing is off removes that cost without changing any query's behavior or result.

func PublishBackupFile added in v0.70.0

func PublishBackupFile(
	dstPath string,
	write func(stagedPath string) error,
) (err error)

PublishBackupFile runs write against a path inside a private, uniquely named staging directory next to dstPath, then publishes the result to dstPath (which must not already exist) with an os.Link and fsyncs dstDir so the link is durable, not just atomic.

Every dump-producing metadata backend (sqlite's VACUUM INTO, postgres's pg_dump, mysql's mysqldump) needs the exact same crash-safety shape: the dump tool must never write dstPath directly, because a failed or cancelled dump would then require deleting dstPath to clean up, and an unconditional os.Remove(dstPath) on failure is a TOCTOU race against a concurrent creator that populated dstPath in the window between the existence check and the failure. Staging into a private os.MkdirTemp directory sidesteps that: nothing else can be using that path, and publishing via os.Link (not os.Rename) is itself no-clobber -- it fails if a concurrent creator populated dstPath after the initial check, rather than silently overwriting it.

func TransactionWitnessCleanupSQL added in v0.70.1

func TransactionWitnessCleanupSQL(table string) string

TransactionWitnessCleanupSQL is the idempotency delete storeTransactionWitnesses runs against one witness table on every API-mode SetTransaction.

Exported so a test can pin its query plan against the statement the store actually runs. The predicate column must stay indexed through bulk load: unindexed, each of these deletes degrades into a full scan of a table that grows with every transaction written, which makes historical backfill quadratic (issue #3253).

func TransactionWitnessTables added in v0.70.1

func TransactionWitnessTables() []string

TransactionWitnessTables lists the tables TransactionWitnessCleanupSQL is issued against, in the order storeTransactionWitnesses clears them.

Types

type Config

type Config struct {
	WriteDB *sql.DB
	ReadDB  *sql.DB
	Dialect Dialect
	Logger  *slog.Logger
	// StorageMode controls retention of API-only transaction detail. Empty
	// selects the consensus-focused core mode.
	StorageMode string
	// CommitteeAuthRetentionSlots overrides how far back superseded
	// auth_committee_hot rows are retained for rollback, in slots. Zero
	// selects DefaultCommitteeAuthRetentionSlots; see committee_prune.go for
	// the retention rule and why the window has to cover the rollback bound.
	CommitteeAuthRetentionSlots uint64

	Migrations      []migrations.Migration
	MigrationLocker migrations.Locker
	DiskSize        func() (int64, error)
	// Maintenance is optional backend maintenance started only after the
	// migration readiness gate succeeds. SQLite uses it for periodic VACUUM.
	Maintenance         func(context.Context) error
	MaintenanceInterval time.Duration
	// BackupTo and RestoreFrom are optional provider-owned lifecycle hooks.
	// SQLite supplies them for its file-backed store; other dialects may leave
	// them unset until a native snapshot mechanism is available.
	BackupTo    func(context.Context, string) error
	RestoreFrom func(context.Context, string) error
	// Prepare is an optional provider-owned hook run once at the start of
	// Start, before anything touches the pools. It is where a provider does
	// setup that has to happen on a connection of its own and must not
	// happen at construction time: SQLite uses it to put a new database into
	// WAL mode, which materialises the file, and constructing a store is not
	// allowed to do that -- RestoreFrom runs against a constructed but
	// unstarted store and requires the destination not to exist.
	Prepare func(context.Context) error
	// Reset is an optional provider-owned hook clearing all data this store
	// owns, using the still-open pool (it must run before the store is
	// closed). See metadata.Resettable's doc comment for why this exists:
	// a live client/server backend's restore orchestration needs a way to
	// undo a brief resolve-and-start's real migrations against the actual
	// remote database, which a directory wipe (sqlite/badger's mechanism)
	// cannot touch. Left unset, Reset is a harmless no-op.
	Reset func(context.Context) error
	// ValidateBackup is an optional provider-owned hook checking a backup
	// file's structural integrity without touching any database -- see
	// metadata.BackupValidator's doc comment for why this exists
	// specifically for Resettable providers: their restore orchestration
	// resets a live remote target before RestoreFrom ever parses the
	// backup, so an invalid backup needs to be caught before that reset,
	// not after it. Left unset, ValidateBackup is a harmless no-op.
	ValidateBackup func(context.Context, string) error
}

Config contains backend-neutral dependencies for a Store.

type Dialect

type Dialect interface {
	Name() string
	Rebind(string) string
	QuoteIdentifier(string) string
	ParameterLimit() int
	BeginOptions(readOnly bool) *sql.TxOptions
	SetBulkMode(context.Context, Execer) error
	RestoreNormalMode(context.Context, Execer) error
	UpdatePlannerStats(context.Context, Execer) error
	DropIndexSQL(name, table string) string
	CreateIndexSQL(name, table string, columns []string) string
	CanDropIndex(name, table string) bool
}

Dialect is the deliberately small backend capability boundary. Metadata orchestration belongs in Store; only SQL mechanics and backend tuning belong behind this interface.

func MySQLDialect

func MySQLDialect() Dialect

MySQLDialect returns MySQL database/sql capabilities.

func PostgresDialect

func PostgresDialect() Dialect

PostgresDialect returns PostgreSQL database/sql capabilities.

func SQLiteDialect

func SQLiteDialect() Dialect

SQLiteDialect returns the capabilities used by the pure-Go SQLite driver.

type Execer

type Execer interface {
	ExecContext(context.Context, string, ...any) (sql.Result, error)
}

Execer is implemented by *sql.DB, *sql.Conn, and *sql.Tx.

type Store

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

Store owns the shared database/sql pools. Provider packages own DSN and driver selection; metadata behavior belongs here.

func New

func New(config Config) (*Store, error)

New constructs a shared store around already-opened connection pools.

func (*Store) AccountInactivityActivationMembership

func (s *Store) AccountInactivityActivationMembership(
	refs []models.StakeCredentialRef,
	txn types.Txn,
) (map[string]struct{}, error)

func (*Store) AccountLastWitnessSlots

func (s *Store) AccountLastWitnessSlots(
	refs []models.StakeCredentialRef,
	maxSlot uint64,
	txn types.Txn,
) (map[string]uint64, error)

func (*Store) AccountsWitnessedAfterSlot

func (s *Store) AccountsWitnessedAfterSlot(
	slot uint64,
	txn types.Txn,
) ([]models.StakeCredentialRef, error)

func (*Store) AddAccountRewardByCredential

func (s *Store) AddAccountRewardByCredential(
	credentialTag uint8,
	stakeKey []byte,
	amount uint64,
	slot uint64,
	sourceHash []byte,
	txn types.Txn,
) error

func (*Store) AddNetworkDonation

func (s *Store) AddNetworkDonation(
	slot, epoch, amount uint64,
	txn types.Txn,
) error

func (*Store) AddPostSnapshotAccountRewardByCredential

func (s *Store) AddPostSnapshotAccountRewardByCredential(
	credentialTag uint8,
	stakeKey []byte,
	amount uint64,
	slot uint64,
	sourceHash []byte,
	txn types.Txn,
) error

func (*Store) AddUtxos

func (s *Store) AddUtxos(
	utxos []models.UtxoSlot,
	txn types.Txn,
) error

func (*Store) ApplyAccountRewardWithdrawal

func (s *Store) ApplyAccountRewardWithdrawal(
	credentialTag uint8,
	stakeKey []byte,
	amount uint64,
	slot uint64,
	txHash []byte,
	txn types.Txn,
) error

func (*Store) BackupTo

func (s *Store) BackupTo(ctx context.Context, dstPath string) error

func (*Store) BuildCriticalDeferredIndexes

func (s *Store) BuildCriticalDeferredIndexes() error

BuildCriticalDeferredIndexes restores the indexes needed before API and rollback traffic begins. The recovery marker stays set until the full manifest is restored.

func (*Store) BuildDeferredIndexes

func (s *Store) BuildDeferredIndexes() error

BuildDeferredIndexes restores the full manifest and clears the durable recovery marker in the same transaction.

func (*Store) ClaimFallbackRewardSnapshot

func (s *Store) ClaimFallbackRewardSnapshot(
	snapshot *models.RewardSnapshot,
	txn types.Txn,
) (bool, error)

func (*Store) ClaimFallbackRewardSnapshotGuard

func (s *Store) ClaimFallbackRewardSnapshotGuard(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) (bool, uint, error)

func (*Store) ClearCommitteeQuorum

func (s *Store) ClearCommitteeQuorum(
	slot uint64,
	txn types.Txn,
) error

func (*Store) ClearDanglingDRepDelegations

func (s *Store) ClearDanglingDRepDelegations(
	atSlot uint64,
	txn types.Txn,
) (int, error)

func (*Store) ClearDelegationsToRetiredPool added in v0.70.5

func (s *Store) ClearDelegationsToRetiredPool(
	poolKeyHash []byte,
	boundarySlot uint64,
	txn types.Txn,
) error

ClearDelegationsToRetiredPool removes every account delegation pointing at a pool reaped at an epoch boundary, the delegation half of the Shelley POOLREAP transition (domain-restrict the delegation map by the retired pools, Shelley spec Fig. 41).

Called from ledger.applyPoolRetirements with the same boundary slot the deposit refund is written at. Stamping added_slot with that slot is what makes the clear rollback-safe: RestoreAccountStateAtSlot only revisits accounts whose added_slot is past the rollback target, and re-derives the delegation from the certificates surviving there — so a rollback to before the reap restores the delegation, and one to after it leaves the account cleared. Without the stamp the account is never revisited and stays un-delegated with no certificate saying so.

The reward_live_stake aggregate carries the same attribution and is cleared with it: it mirrors account.pool only when refreshRewardLiveStakeAggregate runs for the credential, which a reap does not trigger, and it is what the boundary snapshot actually reads.

The import baseline is deliberately left alone. It records the delegation a Mithril snapshot observed at its anchor, which is a statement about a slot before this boundary; a rollback past the reap must restore exactly that.

func (*Store) ClearGovernanceProposalRatification added in v0.70.3

func (s *Store) ClearGovernanceProposalRatification(
	txHash []byte,
	actionIndex uint32,
	transitionSlot uint64,
	txn types.Txn,
) error

func (*Store) ClearSyncState

func (s *Store) ClearSyncState(txn types.Txn) error

func (*Store) Close

func (s *Store) Close() error

Close closes each owned pool exactly once.

func (*Store) CloseContext

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

CloseContext cancels maintenance and closes each owned pool. The lifecycle context is also passed to the maintenance wait so cancellation can interrupt a long-running VACUUM before the provider shutdown deadline expires.

func (*Store) CountAccountDelegationHistoryByCredential

func (s *Store) CountAccountDelegationHistoryByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (int, error)

func (*Store) CountAccountRegistrationHistoryByCredential

func (s *Store) CountAccountRegistrationHistoryByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (int, error)

func (*Store) CountAccountWithdrawalHistoryByCredential

func (s *Store) CountAccountWithdrawalHistoryByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (int, error)

func (*Store) CountAddressTransactionsByCredential

func (s *Store) CountAddressTransactionsByCredential(
	credentialTag uint8,
	stakingKey []byte,
	from *models.AddressTransactionPosition,
	to *models.AddressTransactionPosition,
	txn types.Txn,
) (int, error)

func (*Store) CountAddressesByCredential

func (s *Store) CountAddressesByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (int, error)

func (*Store) CountPoolBlocksInSlotRange

func (s *Store) CountPoolBlocksInSlotRange(
	poolKeyHashes []lcommon.PoolKeyHash,
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) (map[string]uint64, uint64, error)

func (*Store) CountRewardAccountOutputsByCredential

func (s *Store) CountRewardAccountOutputsByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (int, error)

func (*Store) CountTransactionsByAddress

func (s *Store) CountTransactionsByAddress(
	paymentKey []byte,
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (int, error)

func (*Store) CountTransactionsByMetadataLabel

func (s *Store) CountTransactionsByMetadataLabel(
	label uint64,
	txn types.Txn,
) (int, error)

func (*Store) CountTransactionsByPaymentCred

func (s *Store) CountTransactionsByPaymentCred(
	paymentKey []byte,
	txn types.Txn,
) (int, error)

func (*Store) CountTransactionsInSlotRange

func (s *Store) CountTransactionsInSlotRange(
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) (int, error)

func (*Store) CountUtxosByAddressWithOrdering added in v0.70.3

func (s *Store) CountUtxosByAddressWithOrdering(
	query *models.UtxoWithOrderingQuery,
	txn types.Txn,
) (int, error)

CountUtxosByAddressWithOrdering returns the number of live UTxOs matching query's coarse SQL predicate (address patterns and asset filter), without materializing rows. It rejects a query whose address patterns require CBOR-based exact-address filtering (see RequiresExactAddressFilter): the coarse predicate alone over-matches address forms that share a payment/delegation credential (for example pointer addresses), so a count against it would not equal the exact-match total.

func (*Store) CreateAccount

func (s *Store) CreateAccount(
	txn types.Txn,
	account *models.Account,
) error

func (*Store) CreateDrep

func (s *Store) CreateDrep(txn types.Txn, drep *models.Drep) error

func (*Store) CreateMidnightAriadneRollback

func (s *Store) CreateMidnightAriadneRollback(
	txn types.Txn,
	rollback *models.MidnightAriadneRollback,
) error

func (*Store) CreateMidnightAssetCreate

func (s *Store) CreateMidnightAssetCreate(
	txn types.Txn,
	row *models.MidnightAssetCreate,
) error

func (*Store) CreateMidnightAssetSpend

func (s *Store) CreateMidnightAssetSpend(
	txn types.Txn,
	row *models.MidnightAssetSpend,
) error

func (*Store) CreateMidnightDeregistration

func (s *Store) CreateMidnightDeregistration(
	txn types.Txn,
	row *models.MidnightDeregistration,
) error

func (*Store) CreateMidnightRegistration

func (s *Store) CreateMidnightRegistration(
	txn types.Txn,
	row *models.MidnightRegistration,
) error

func (*Store) CreateUtxo

func (s *Store) CreateUtxo(txn types.Txn, utxo *models.Utxo) error

func (*Store) DeactivateAccounts

func (s *Store) DeactivateAccounts(
	txn types.Txn,
	refs []models.StakeCredentialRef,
) error

DeactivateAccounts tombstones the given credentials and their import baselines. The two writes and every chunk of them share one transaction: an account tombstoned while its baseline stays active is contradictory state that lets a later rollback restore exactly the account this call removed.

func (*Store) DeactivateDreps

func (s *Store) DeactivateDreps(
	txn types.Txn,
	credentials []models.StakeCredentialRef,
) error

func (*Store) DeleteAccountRewardsAfterSlot

func (s *Store) DeleteAccountRewardsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteAddressTransactionsAfterSlot

func (s *Store) DeleteAddressTransactionsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteBlockNoncesAfterPoint

func (s *Store) DeleteBlockNoncesAfterPoint(
	point ocommon.Point,
	txn types.Txn,
) error

func (*Store) DeleteBlockNoncesBeforeSlot

func (s *Store) DeleteBlockNoncesBeforeSlot(
	slotNumber uint64,
	txn types.Txn,
) error

func (*Store) DeleteBlockNoncesBeforeSlotWithoutCheckpoints

func (s *Store) DeleteBlockNoncesBeforeSlotWithoutCheckpoints(
	slotNumber uint64,
	txn types.Txn,
) error

func (*Store) DeleteCertificatesAfterSlot

func (s *Store) DeleteCertificatesAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteCommitteeMembersAfterSlot

func (s *Store) DeleteCommitteeMembersAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteConstitutionsAfterSlot

func (s *Store) DeleteConstitutionsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteEpochSummariesAfterEpoch

func (s *Store) DeleteEpochSummariesAfterEpoch(
	epoch uint64,
	txn types.Txn,
) error

func (*Store) DeleteEpochsAfterSlot

func (s *Store) DeleteEpochsAfterSlot(slot uint64, txn types.Txn) error

func (*Store) DeleteGovernanceProposalsAfterSlot

func (s *Store) DeleteGovernanceProposalsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteGovernanceVotesAfterSlot

func (s *Store) DeleteGovernanceVotesAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteImportedPoolBlockCountsForEpoch added in v0.70.7

func (s *Store) DeleteImportedPoolBlockCountsForEpoch(
	epoch uint64,
	txn types.Txn,
) error

DeleteImportedPoolBlockCountsForEpoch removes an epoch's imported counts, so a re-import replaces them rather than merging into a stale set.

func (*Store) DeleteMidnightAriadneParamsByEpoch

func (s *Store) DeleteMidnightAriadneParamsByEpoch(
	txn types.Txn,
	epoch uint64,
) error

func (*Store) DeleteMidnightAriadneRollbacksBeforeBlock

func (s *Store) DeleteMidnightAriadneRollbacksBeforeBlock(
	txn types.Txn,
	blockNumber uint64,
) error

func (*Store) DeleteMidnightAriadneRollbacksByBlock

func (s *Store) DeleteMidnightAriadneRollbacksByBlock(
	txn types.Txn,
	blockNumber uint64,
) error

func (*Store) DeleteMidnightAssetCreatesByBlock

func (s *Store) DeleteMidnightAssetCreatesByBlock(
	txn types.Txn,
	blockNumber uint64,
) ([]models.MidnightAssetCreate, error)

func (*Store) DeleteMidnightAssetSpendsByBlock

func (s *Store) DeleteMidnightAssetSpendsByBlock(
	txn types.Txn,
	blockNumber uint64,
) ([]models.MidnightAssetSpend, error)

func (*Store) DeleteMidnightCommitteeCandidateRegistrationsByBlock

func (s *Store) DeleteMidnightCommitteeCandidateRegistrationsByBlock(
	txn types.Txn,
	blockNumber uint64,
) error

func (*Store) DeleteMidnightDeregistrationsByBlock

func (s *Store) DeleteMidnightDeregistrationsByBlock(
	txn types.Txn,
	blockNumber uint64,
) ([]models.MidnightDeregistration, error)

func (*Store) DeleteMidnightEpochCandidatesByBlock

func (s *Store) DeleteMidnightEpochCandidatesByBlock(
	txn types.Txn,
	blockNumber uint64,
) error

func (*Store) DeleteMidnightGovernanceDatumsByBlock

func (s *Store) DeleteMidnightGovernanceDatumsByBlock(
	txn types.Txn,
	blockNumber uint64,
) error

func (*Store) DeleteMidnightRegistrationsByBlock

func (s *Store) DeleteMidnightRegistrationsByBlock(
	txn types.Txn,
	blockNumber uint64,
) ([]models.MidnightRegistration, error)

func (*Store) DeleteNetworkDonationsAfterSlot

func (s *Store) DeleteNetworkDonationsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteNetworkStateAfterSlot

func (s *Store) DeleteNetworkStateAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeletePParamUpdatesAfterSlot

func (s *Store) DeletePParamUpdatesAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeletePParamsAfterSlot

func (s *Store) DeletePParamsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeletePoolStakeSnapshotsAfterEpoch

func (s *Store) DeletePoolStakeSnapshotsAfterEpoch(
	epoch uint64,
	txn types.Txn,
) error

func (*Store) DeletePoolStakeSnapshotsBeforeEpoch

func (s *Store) DeletePoolStakeSnapshotsBeforeEpoch(
	epoch uint64,
	txn types.Txn,
) error

func (*Store) DeletePoolStakeSnapshotsForEpoch

func (s *Store) DeletePoolStakeSnapshotsForEpoch(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) error

func (*Store) DeleteProvisionalRewardSnapshot added in v0.70.1

func (s *Store) DeleteProvisionalRewardSnapshot(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) error

func (*Store) DeleteRewardInputsForEpoch

func (s *Store) DeleteRewardInputsForEpoch(
	epoch uint64,
	txn types.Txn,
) error

func (*Store) DeleteRewardOutputsForEpoch

func (s *Store) DeleteRewardOutputsForEpoch(
	epoch uint64,
	txn types.Txn,
) error

func (*Store) DeleteRewardSeedFailure added in v0.70.7

func (s *Store) DeleteRewardSeedFailure(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) error

func (*Store) DeleteRewardStakeInputBeforeEpoch

func (s *Store) DeleteRewardStakeInputBeforeEpoch(
	epoch uint64,
	txn types.Txn,
) error

func (*Store) DeleteRewardStateAfterSlot

func (s *Store) DeleteRewardStateAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteRewardStateBeforeEpoch

func (s *Store) DeleteRewardStateBeforeEpoch(
	epoch uint64,
	txn types.Txn,
) error

func (*Store) DeleteSyncState

func (s *Store) DeleteSyncState(key string, txn types.Txn) error

func (*Store) DeleteTransactionMetadataLabelsAfterSlot

func (s *Store) DeleteTransactionMetadataLabelsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteTransactionsAfterSlot

func (s *Store) DeleteTransactionsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DeleteUtxo

func (s *Store) DeleteUtxo(
	utxoID models.UtxoId,
	txn types.Txn,
) error

func (*Store) DeleteUtxos

func (s *Store) DeleteUtxos(
	utxoIDs []models.UtxoId,
	txn types.Txn,
) error

func (*Store) DeleteUtxosAfterSlot

func (s *Store) DeleteUtxosAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) DiskSize

func (s *Store) DiskSize() (int64, error)

DiskSize returns backend storage usage when the provider supplies it.

func (*Store) DropDeferredIndexes

func (s *Store) DropDeferredIndexes() error

DropDeferredIndexes records the durable recovery marker and drops the manifest in one SQLite transaction.

func (*Store) EnsureOffchainMetadataPointers

func (s *Store) EnsureOffchainMetadataPointers(
	ctx context.Context,
	now time.Time,
	txn types.Txn,
) (int, error)

func (*Store) FindMidnightAriadneRollbacksByBlock

func (s *Store) FindMidnightAriadneRollbacksByBlock(
	txn types.Txn,
	blockNumber uint64,
) ([]models.MidnightAriadneRollback, error)

func (*Store) FindMidnightAssetCreatesFrom

func (s *Store) FindMidnightAssetCreatesFrom(
	startBlock uint64,
	startTxIndex uint32,
	limit int,
	txn types.Txn,
) ([]models.MidnightAssetCreate, error)

func (*Store) FindMidnightAssetSpendsFrom

func (s *Store) FindMidnightAssetSpendsFrom(
	startBlock uint64,
	startTxIndex uint32,
	limit int,
	txn types.Txn,
) ([]models.MidnightAssetSpend, error)

func (*Store) FindMidnightDeregistrationsFrom

func (s *Store) FindMidnightDeregistrationsFrom(
	startBlock uint64,
	startTxIndex uint32,
	limit int,
	txn types.Txn,
) ([]models.MidnightDeregistration, error)

func (*Store) FindMidnightRegistrationsFrom

func (s *Store) FindMidnightRegistrationsFrom(
	startBlock uint64,
	startTxIndex uint32,
	limit int,
	txn types.Txn,
) ([]models.MidnightRegistration, error)

func (*Store) FindUnspentMidnightAssetCreates

func (s *Store) FindUnspentMidnightAssetCreates() (
	[]models.MidnightAssetCreate,
	error,
)

func (*Store) FindUnspentMidnightRegistrations

func (s *Store) FindUnspentMidnightRegistrations() (
	[]models.MidnightRegistration,
	error,
)

func (*Store) FlushBatch

func (s *Store) FlushBatch(
	accumulator types.MetadataBatchAccumulator,
	_ types.Txn,
) error

func (*Store) GetAccountByCredential

func (s *Store) GetAccountByCredential(
	credentialTag uint8,
	stakeKey []byte,
	includeInactive bool,
	txn types.Txn,
) (*models.Account, error)

func (*Store) GetAccountDelegationHistoryByCredential

func (s *Store) GetAccountDelegationHistoryByCredential(
	credentialTag uint8,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	txn types.Txn,
) ([]models.AccountDelegationHistoryRow, error)

func (*Store) GetAccountImportRegistrationByCredential added in v0.70.4

func (s *Store) GetAccountImportRegistrationByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (*models.AccountImportRegistration, error)

GetAccountImportRegistrationByCredential returns the virtual registration established by an import or genesis baseline. A nil Deposit means the baseline predates deposit preservation; callers must not substitute the current protocol-parameter value for an unknown historical deposit.

func (*Store) GetAccountRegistrationHistoryByCredential

func (s *Store) GetAccountRegistrationHistoryByCredential(
	credentialTag uint8,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	txn types.Txn,
) ([]models.AccountRegistrationHistoryRow, error)

func (*Store) GetAccountSumsByCredential

func (s *Store) GetAccountSumsByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (models.AccountSums, error)

func (*Store) GetAccountWithdrawalHistoryByCredential

func (s *Store) GetAccountWithdrawalHistoryByCredential(
	credentialTag uint8,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	txn types.Txn,
) ([]models.AccountWithdrawalHistoryRow, error)

func (*Store) GetAccountsActiveAtSlot

func (s *Store) GetAccountsActiveAtSlot(
	refs []models.StakeCredentialRef,
	slot uint64,
	txn types.Txn,
) (map[string]struct{}, error)

func (*Store) GetAccountsByCredential

func (s *Store) GetAccountsByCredential(
	refs []models.StakeCredentialRef,
	includeInactive bool,
	txn types.Txn,
) (map[string]*models.Account, error)

func (*Store) GetActiveAccountCredentials

func (s *Store) GetActiveAccountCredentials(
	txn types.Txn,
) ([]models.StakeCredentialRef, error)

func (*Store) GetActiveCommitteeMembers

func (s *Store) GetActiveCommitteeMembers(
	txn types.Txn,
) ([]*models.AuthCommitteeHot, error)

func (*Store) GetActiveDreps

func (s *Store) GetActiveDreps(
	txn types.Txn,
) ([]*models.Drep, error)

func (*Store) GetActiveGovernanceProposals

func (s *Store) GetActiveGovernanceProposals(
	epoch uint64,
	txn types.Txn,
) ([]*models.GovernanceProposal, error)

func (*Store) GetActivePoolKeyHashes

func (s *Store) GetActivePoolKeyHashes(
	txn types.Txn,
) ([][]byte, error)

func (*Store) GetActivePoolKeyHashesAtSlot

func (s *Store) GetActivePoolKeyHashesAtSlot(
	slot uint64,
	txn types.Txn,
) ([][]byte, error)

func (*Store) GetActivePoolKeyHashesOrdered

func (s *Store) GetActivePoolKeyHashesOrdered(
	txn types.Txn,
) ([][]byte, error)

func (*Store) GetActivePoolRelays

func (s *Store) GetActivePoolRelays(
	txn types.Txn,
) ([]models.PoolRegistrationRelay, error)

GetActivePoolRelays returns relays from each active pool's latest registration. The query uses the same chain-position ordering as active-pool selection and avoids loading historical registrations into memory.

func (*Store) GetAddressTransactionsByCredential

func (s *Store) GetAddressTransactionsByCredential(
	credentialTag uint8,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	from *models.AddressTransactionPosition,
	to *models.AddressTransactionPosition,
	txn types.Txn,
) ([]models.AccountTransactionAssociationRow, error)

func (*Store) GetAddressesByCredential

func (s *Store) GetAddressesByCredential(
	credentialTag uint8,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	txn types.Txn,
) ([]models.AddressTransaction, error)

func (*Store) GetAssetByPolicyAndName

func (s *Store) GetAssetByPolicyAndName(
	policyID lcommon.Blake2b224,
	assetName []byte,
	txn types.Txn,
) (models.Asset, error)

func (*Store) GetAssetMintBurnInfo

func (s *Store) GetAssetMintBurnInfo(
	policyID lcommon.Blake2b224,
	assetName []byte,
	txn types.Txn,
) ([]byte, int, error)

func (*Store) GetAssetQuantityByPolicyAndName

func (s *Store) GetAssetQuantityByPolicyAndName(
	policyID lcommon.Blake2b224,
	assetName []byte,
	txn types.Txn,
) (uint64, error)

func (*Store) GetBackfillCheckpoint

func (s *Store) GetBackfillCheckpoint(
	phase string,
	txn types.Txn,
) (*models.BackfillCheckpoint, error)

func (*Store) GetBlockNonce

func (s *Store) GetBlockNonce(
	point ocommon.Point,
	txn types.Txn,
) ([]byte, error)

func (*Store) GetBlockNoncesInSlotRange

func (s *Store) GetBlockNoncesInSlotRange(
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) ([]models.BlockNonce, error)

func (*Store) GetBlockSlotRangeStats

func (s *Store) GetBlockSlotRangeStats(
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) (metadata.SlotRangeStats, error)

func (*Store) GetChildGovernanceProposals

func (s *Store) GetChildGovernanceProposals(
	parentTxHash []byte,
	parentActionIndex uint32,
	txn types.Txn,
) ([]*models.GovernanceProposal, error)

func (*Store) GetCommitTimestamp

func (s *Store) GetCommitTimestamp() (int64, error)

func (*Store) GetCommitteeActiveCount

func (s *Store) GetCommitteeActiveCount(
	txn types.Txn,
) (int, error)

func (*Store) GetCommitteeMember

func (s *Store) GetCommitteeMember(
	coldCredentialTag uint8,
	coldKey []byte,
	termStartSlot uint64,
	txn types.Txn,
) (*models.AuthCommitteeHot, error)

func (*Store) GetCommitteeMembers

func (s *Store) GetCommitteeMembers(
	txn types.Txn,
) ([]*models.CommitteeMember, error)

func (*Store) GetCommitteeMembersIncludeDeleted

func (s *Store) GetCommitteeMembersIncludeDeleted(
	txn types.Txn,
) ([]*models.CommitteeMember, error)

func (*Store) GetCommitteeQuorum

func (s *Store) GetCommitteeQuorum(
	txn types.Txn,
) (*types.Rat, error)

func (*Store) GetConstitution

func (s *Store) GetConstitution(
	txn types.Txn,
) (*models.Constitution, error)

func (*Store) GetControlledAmountByCredential

func (s *Store) GetControlledAmountByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) (uint64, error)

func (*Store) GetDRepDelegators

func (s *Store) GetDRepDelegators(
	credentialTag uint8,
	credential []byte,
	txn types.Txn,
) ([]models.StakeCredentialRef, error)

func (*Store) GetDRepVotingPower

func (s *Store) GetDRepVotingPower(
	credentialTag uint8,
	credential []byte,
	expiryEpoch uint64,
	txn types.Txn,
) (uint64, error)

func (*Store) GetDRepVotingPowerBatch

func (s *Store) GetDRepVotingPowerBatch(
	credentials []models.StakeCredentialRef,
	expiryEpoch uint64,
	txn types.Txn,
) (map[string]uint64, error)

func (*Store) GetDRepVotingPowerByType

func (s *Store) GetDRepVotingPowerByType(
	drepTypes []uint64,
	expiryEpoch uint64,
	txn types.Txn,
) (map[uint64]uint64, error)

func (*Store) GetDatum

func (s *Store) GetDatum(
	hash lcommon.Blake2b256,
	txn types.Txn,
) (*models.Datum, error)

func (*Store) GetDrep

func (s *Store) GetDrep(
	credential []byte,
	includeInactive bool,
	txn types.Txn,
) (*models.Drep, error)

func (*Store) GetDrepByCredential

func (s *Store) GetDrepByCredential(
	credentialTag uint8,
	credential []byte,
	includeInactive bool,
	txn types.Txn,
) (*models.Drep, error)

func (*Store) GetDrepLastRegistrationDeposit added in v0.70.7

func (s *Store) GetDrepLastRegistrationDeposit(
	credentialTag uint8,
	credential []byte,
	txn types.Txn,
) (*uint64, error)

func (*Store) GetDrepLastRegistrationDeposits added in v0.70.7

func (s *Store) GetDrepLastRegistrationDeposits(
	txn types.Txn,
) (map[string]uint64, error)

GetDrepLastRegistrationDeposits returns the most recent registration deposit of every active DRep in one query, keyed by models.DrepDepositKey. Credentials with no registration_drep row are absent from the map. See GetDrepLastRegistrationDeposit for why bootstrap-slot import rows are not filtered out.

func (*Store) GetDrepLastRegistrationSlot

func (s *Store) GetDrepLastRegistrationSlot(
	credentialTag uint8,
	credential []byte,
	txn types.Txn,
) (uint64, error)

func (*Store) GetDreps

func (s *Store) GetDreps(
	txn types.Txn,
) ([]models.DrepListRow, error)

func (*Store) GetEnactedGovernanceProposalsAt

func (s *Store) GetEnactedGovernanceProposalsAt(
	epoch uint64,
	slot uint64,
	txn types.Txn,
) ([]*models.GovernanceProposal, error)

func (*Store) GetEpoch

func (s *Store) GetEpoch(
	epochID uint64,
	txn types.Txn,
) (*models.Epoch, error)

func (*Store) GetEpochBoundaryRewardStakeInputsForPools

func (s *Store) GetEpochBoundaryRewardStakeInputsForPools(
	poolKeyHashes [][]byte,
	snapshotSlot uint64,
	boundarySlot uint64,
	expiryEpoch uint64,
	inactivityPeriod uint64,
	txn types.Txn,
) ([]*models.RewardStakeInput, error)

func (*Store) GetEpochBoundaryStakeByPools

func (s *Store) GetEpochBoundaryStakeByPools(
	poolKeyHashes [][]byte,
	snapshotSlot uint64,
	boundarySlot uint64,
	expiryEpoch uint64,
	inactivityPeriod uint64,
	txn types.Txn,
) (map[string]uint64, map[string]uint64, error)

func (*Store) GetEpochBySlot

func (s *Store) GetEpochBySlot(
	slot uint64,
	txn types.Txn,
) (*models.Epoch, error)

func (*Store) GetEpochSummary

func (s *Store) GetEpochSummary(
	epoch uint64,
	txn types.Txn,
) (*models.EpochSummary, error)

func (*Store) GetEpochs

func (s *Store) GetEpochs(txn types.Txn) ([]models.Epoch, error)

func (*Store) GetEpochsByEra

func (s *Store) GetEpochsByEra(
	eraID uint,
	txn types.Txn,
) ([]models.Epoch, error)

func (*Store) GetExpiredDReps

func (s *Store) GetExpiredDReps(
	epoch uint64,
	txn types.Txn,
) ([]*models.Drep, error)

func (*Store) GetExpiredGovernanceProposalsAt

func (s *Store) GetExpiredGovernanceProposalsAt(
	epoch uint64,
	slot uint64,
	txn types.Txn,
) ([]*models.GovernanceProposal, error)

func (*Store) GetExpiringGovernanceProposals

func (s *Store) GetExpiringGovernanceProposals(
	epoch uint64,
	txn types.Txn,
) ([]*models.GovernanceProposal, error)

func (*Store) GetGenesisDelegationForSlot

func (s *Store) GetGenesisDelegationForSlot(
	genesisHash []byte,
	blockSlot uint64,
	txn types.Txn,
) (*models.GenesisDelegation, error)

func (*Store) GetGovernanceProposal

func (s *Store) GetGovernanceProposal(
	txHash []byte,
	actionIndex uint32,
	txn types.Txn,
) (*models.GovernanceProposal, error)

func (*Store) GetGovernanceVotes

func (s *Store) GetGovernanceVotes(
	proposalID uint,
	txn types.Txn,
) ([]*models.GovernanceVote, error)

func (*Store) GetImportCheckpoint

func (s *Store) GetImportCheckpoint(
	importKey string,
	txn types.Txn,
) (*models.ImportCheckpoint, error)

func (*Store) GetImportedPoolBlockCounts added in v0.70.7

func (s *Store) GetImportedPoolBlockCounts(
	epoch uint64,
	txn types.Txn,
) (map[string]uint64, uint64, bool, error)

GetImportedPoolBlockCounts returns an epoch's imported per-pool block counts keyed by pool key hash, and the epoch total they sum to. The bool reports whether block counts were imported for the epoch at all; false means the counts are unknown, which is not the same answer as a zero-block epoch.

The stored total is compared against the rows rather than derived from them. A per-pool set truncated by a partial write would otherwise present as a smaller but self-consistent epoch, which raises every surviving pool's share of the blocks and over-credits its rewards.

func (*Store) GetLastBlockNonceInRange

func (s *Store) GetLastBlockNonceInRange(
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) ([]byte, error)

func (*Store) GetLastEnactedGovernanceProposal

func (s *Store) GetLastEnactedGovernanceProposal(
	actionTypes []uint8,
	txn types.Txn,
) (*models.GovernanceProposal, error)

func (*Store) GetLatestBlockNonce

func (s *Store) GetLatestBlockNonce(
	txn types.Txn,
) (models.BlockNonce, bool, error)

GetLatestBlockNonce returns the highest-slot nonce row, using its ID to preserve application order when multiple blocks share a slot. The nonce is written in the same metadata transaction as the corresponding ledger effects, so this row is the durable ledger-state high-water mark.

func (*Store) GetLatestEpochSummary

func (s *Store) GetLatestEpochSummary(
	txn types.Txn,
) (*models.EpochSummary, error)

func (*Store) GetLatestMidnightAriadneParams

func (s *Store) GetLatestMidnightAriadneParams(
	txn types.Txn,
) (*models.MidnightAriadneParams, error)

func (*Store) GetLatestMidnightGovernanceDatum

func (s *Store) GetLatestMidnightGovernanceDatum(
	datumType string,
	blockNumber uint64,
	txn types.Txn,
) (*models.MidnightGovernanceDatum, error)

func (*Store) GetLiveStakeInputsForPools

func (s *Store) GetLiveStakeInputsForPools(
	poolKeyHashes [][]byte,
	expiryEpoch uint64,
	txn types.Txn,
) ([]*models.RewardStakeInput, error)

func (*Store) GetLiveUtxosBySlot

func (s *Store) GetLiveUtxosBySlot(
	slot uint64,
	txn types.Txn,
) ([]models.UtxoId, error)

func (*Store) GetMIRCertsInSlotRange

func (s *Store) GetMIRCertsInSlotRange(
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) ([]models.MIREffect, error)

func (*Store) GetMidnightAriadneParamsAtOrBeforeEpoch

func (s *Store) GetMidnightAriadneParamsAtOrBeforeEpoch(
	epoch uint64,
	txn types.Txn,
) (*models.MidnightAriadneParams, error)

func (*Store) GetMidnightAriadneParamsByEpoch

func (s *Store) GetMidnightAriadneParamsByEpoch(
	epoch uint64,
	txn types.Txn,
) (*models.MidnightAriadneParams, error)

func (*Store) GetMidnightCandidates

func (s *Store) GetMidnightCandidates(
	address ledger.Address,
	txn types.Txn,
) ([]models.Utxo, error)

func (*Store) GetMidnightCommitteeCandidateRegistrationsByTxHashes

func (s *Store) GetMidnightCommitteeCandidateRegistrationsByTxHashes(
	txHashes [][]byte,
	txn types.Txn,
) ([]models.MidnightCommitteeCandidateRegistration, error)

func (*Store) GetMidnightEpochCandidatesByEpoch

func (s *Store) GetMidnightEpochCandidatesByEpoch(
	epoch uint64,
	txn types.Txn,
) (*models.MidnightEpochCandidates, error)

func (*Store) GetNetworkState

func (s *Store) GetNetworkState(
	txn types.Txn,
) (*models.NetworkState, error)

func (*Store) GetNetworkStateAsOfSlot added in v0.70.9

func (s *Store) GetNetworkStateAsOfSlot(
	slot uint64,
	txn types.Txn,
) (*models.NetworkState, error)

GetNetworkStateAsOfSlot resolves the most recent network-state row with Slot <= the supplied slot, rather than GetNetworkState's always-latest row -- see ledger's totalCirculatingSupply for why a historical GetStakeDistribution answer needs this instead (blinklabs-io/dingo#382). A slot older than every row ever written (e.g. before the first recorded treasury/reserves change) returns (nil, nil), the same "not found" shape GetNetworkState already uses.

func (*Store) GetNodeSettings

func (s *Store) GetNodeSettings() (*types.NodeSettings, error)

func (*Store) GetNodeSettingsGates

func (s *Store) GetNodeSettingsGates() (nodesettings.Values, error)

GetNodeSettingsGates returns the persisted node settings gate values, keyed by gate name. An empty result means no gates have been recorded yet.

func (*Store) GetOffchainMetadata

func (s *Store) GetOffchainMetadata(
	sourceType string,
	url string,
	hash []byte,
	txn types.Txn,
) (*models.OffchainMetadata, error)

func (*Store) GetOffchainMetadataBatch

func (s *Store) GetOffchainMetadataBatch(
	sourceType string,
	urls []string,
	txn types.Txn,
) ([]models.OffchainMetadata, error)

func (*Store) GetOffchainMetadataFetchBatch

func (s *Store) GetOffchainMetadataFetchBatch(
	ctx context.Context,
	limit int,
	now time.Time,
	txn types.Txn,
) ([]models.OffchainMetadata, error)

func (*Store) GetPParamUpdates

func (s *Store) GetPParamUpdates(
	epoch uint64,
	txn types.Txn,
) ([]models.PParamUpdate, error)

func (*Store) GetPParams

func (s *Store) GetPParams(
	epoch uint64,
	eraID uint,
	txn types.Txn,
) ([]models.PParams, error)

func (*Store) GetPointerStakeInputsForPools added in v0.70.9

func (s *Store) GetPointerStakeInputsForPools(
	poolKeyHashes [][]byte,
	slot uint64,
	boundarySlot uint64,
	expiryEpoch uint64,
	txn types.Txn,
) ([]*models.RewardStakeInput, error)

GetPointerStakeInputsForPools returns the additional per-credential stake held at a pointer address, for pools in poolKeyHashes and credentials resolved and delegated as of slot.

It exists for the live snapshot path (calculateLiveStakeDistributionInTxn), which otherwise reads only reward_live_stake. reward_live_stake never carries pointer-derived UTxO stake: attribution is a function of certificate history at the slot being evaluated -- a registration or de-registration anywhere can change which credential an existing pointer output belongs to -- and reward_live_stake is an incrementally maintained aggregate keyed on (credential_tag, staking_key) with its own consistency verifier (RewardLiveStakeNeedsBackfill) that has no notion of "as of slot". Rather than teach that aggregate to react to registration/de-registration/ era-translation events out of band, this recomputes the same activeDelegationSQL/pointerResolutionSQL join the historical fallback already uses, restricted to what the live aggregate is missing, and the caller adds the result to what GetLiveStakeInputsForPools returned.

boundarySlot is threaded through to the era gate exactly as in historicalStakeCTE; see pointerStakeCounted. When the era at slot (or the boundary it belongs to) does not count pointer stake, this returns nil without issuing a query -- the live path's SQL and result stay exactly what they were before pointer resolution existed.

func (*Store) GetPool

func (s *Store) GetPool(
	poolKeyHash lcommon.PoolKeyHash,
	includeInactive bool,
	txn types.Txn,
) (*models.Pool, error)

func (*Store) GetPoolBlockIssuersInSlotRange

func (s *Store) GetPoolBlockIssuersInSlotRange(
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) ([]models.PoolOpCertSequence, error)

func (*Store) GetPoolByVrfKeyHash

func (s *Store) GetPoolByVrfKeyHash(
	vrfKeyHash []byte,
	txn types.Txn,
) (*models.Pool, error)

func (*Store) GetPoolCertificateHistory

func (s *Store) GetPoolCertificateHistory(
	pkh lcommon.PoolKeyHash,
	txn types.Txn,
) ([][]byte, [][]byte, error)

func (*Store) GetPoolEarliestVrfKeyHashAtSlot added in v0.70.7

func (s *Store) GetPoolEarliestVrfKeyHashAtSlot(
	poolKeyHash []byte,
	slot uint64,
	txn types.Txn,
) ([]byte, bool, error)

GetPoolEarliestVrfKeyHashAtSlot returns the VRF key hash from the pool's earliest registration at or before the given slot.

This is the key cardano-ledger's psStakePools holds for a pool that first registered inside the captured epoch. The POOL rule inserts a first registration into psStakePools directly and defers only a re-registration through psFutureStakePoolParams, so when both land in that epoch the snapshot carries the first one's key. GetPoolVrfKeyHashAtSlot answers the opposite question and would resolve the deferred key.

func (*Store) GetPoolKeyHashesRetiredByEpoch added in v0.70.7

func (s *Store) GetPoolKeyHashesRetiredByEpoch(
	epoch uint64,
	boundarySlot uint64,
	txn types.Txn,
) ([][]byte, error)

GetPoolKeyHashesRetiredByEpoch is GetPoolsRetiringAtEpoch's "at or before" sibling: same latest-certificate resolution and same cancellation rule, but it matches every retirement effective up to and including epoch rather than only the one landing on it, and returns bare key hashes because no deposit refund is being applied. See MetadataStore's doc comment for why the parity checker needs the wider comparison (dingo #3925).

"Same resolution" includes the synthetic-retirement key every latest-retirement query in the tree shares. A reconcile retirement (certificate_id = 0) has no certs/transaction join, so its COALESCE'd block_index/cert_index are both zero: without ranking it first and exempting it from the same-slot cancellation clauses it would lose the tie-break to any certificate-backed registration in its own slot, and the pool would be reported as still active. ledgerstate's snapshot import writes exactly that shape — ImportPool followed by RetirePools at one slot — so this is the ordinary bootstrap case, not an edge case. DingoDB.GetPoolsRetiredByEpoch carries the same three elements, and koiosparity's implementations-agree test runs both against one database to pin them against drift.

func (*Store) GetPoolOwnerStakeAtSlot

func (s *Store) GetPoolOwnerStakeAtSlot(
	ownerKeys [][]byte,
	slot uint64,
	expiryEpoch uint64,
	inactivityPeriod uint64,
	txn types.Txn,
) (map[string]uint64, error)

func (*Store) GetPoolRegistrations

func (s *Store) GetPoolRegistrations(
	poolKeyHash lcommon.PoolKeyHash,
	txn types.Txn,
) ([]lcommon.PoolRegistrationCertificate, error)

GetPoolRegistrations reconstructs the ledger certificates for a pool.

func (*Store) GetPoolRegistrationsAtSlot

func (s *Store) GetPoolRegistrationsAtSlot(
	poolKeyHashes []lcommon.PoolKeyHash,
	slot uint64,
	txn types.Txn,
) ([]models.PoolRegistration, error)

GetPoolRegistrationsAtSlot returns the latest registration for every requested pool at or before slot. Certificate position breaks same-slot ties, with the row ID as a deterministic final fallback.

func (*Store) GetPoolRegistrationsEffectiveForEpoch

func (s *Store) GetPoolRegistrationsEffectiveForEpoch(
	poolKeyHashes []lcommon.PoolKeyHash,
	epochStartSlot uint64,
	endedEpoch uint64,
	snapshotSlot uint64,
	txn types.Txn,
) ([]models.PoolRegistration, error)

func (*Store) GetPoolStakeSnapshot

func (s *Store) GetPoolStakeSnapshot(
	epoch uint64,
	snapshotType string,
	poolKeyHash []byte,
	txn types.Txn,
) (*models.PoolStakeSnapshot, error)

func (*Store) GetPoolStakeSnapshotsByEpoch

func (s *Store) GetPoolStakeSnapshotsByEpoch(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) ([]*models.PoolStakeSnapshot, error)

func (*Store) GetPoolStakeSnapshotsForPools

func (s *Store) GetPoolStakeSnapshotsForPools(
	epoch uint64,
	snapshotType string,
	poolKeyHashes [][]byte,
	txn types.Txn,
) ([]*models.PoolStakeSnapshot, error)

GetPoolStakeSnapshotsForPools returns the snapshot rows for just the pools named, for a caller that wants a bounded subset rather than a whole epoch.

A named pool with no row is simply absent from the result: the snapshot holds a row per pool with stake, so a pool it does not hold has no stake in that snapshot rather than a stake of zero.

The read is chunked over the dialect's parameter limit rather than issued per pool, so a large filter costs a bounded number of round trips instead of one per pool named.

func (*Store) GetPoolVrfKeyHashAtSlot added in v0.70.7

func (s *Store) GetPoolVrfKeyHashAtSlot(
	poolKeyHash []byte,
	slot uint64,
	txn types.Txn,
) ([]byte, bool, error)

GetPoolVrfKeyHashAtSlot returns the VRF key hash the pool had registered as of slot, which is not necessarily the one it has registered now.

A pool may rotate its VRF key, and a re-registration does not retroactively change the key it was elected under: the leader schedule for an epoch is built from a stake snapshot captured at an earlier boundary, and a block's header carries the key registered at that capture. Validating a header against the current registration rejects every block the pool makes for the rest of the epoch it rotated in (issue #3842).

The selection is the same latest-certificate-wins ordering GetActivePoolKeyHashesAtSlot uses -- later added_slot, then later block index, then later certificate index -- so the two agree on which registration was in force.

The bool reports whether any registration exists at or before slot. False means the pool had not registered yet, which is a different answer from a pool with no VRF key recorded.

func (*Store) GetPools

func (s *Store) GetPools(
	poolKeyHashes []lcommon.PoolKeyHash,
	txn types.Txn,
) ([]models.Pool, error)

func (*Store) GetPoolsRetiringAtEpoch

func (s *Store) GetPoolsRetiringAtEpoch(
	epoch uint64,
	boundarySlot uint64,
	txn types.Txn,
) ([]models.PoolRetirementRefund, error)

func (*Store) GetPredefinedDrepFirstSeenSlots

func (s *Store) GetPredefinedDrepFirstSeenSlots(
	txn types.Txn,
) (map[uint64]uint64, error)

func (*Store) GetRatifiedGovernanceProposals

func (s *Store) GetRatifiedGovernanceProposals(
	txn types.Txn,
) ([]*models.GovernanceProposal, error)

func (*Store) GetResignedCommitteeMembers

func (s *Store) GetResignedCommitteeMembers(
	coldCredentials []models.CommitteeCredential,
	txn types.Txn,
) (map[string]bool, error)

func (*Store) GetRetiringPools

func (s *Store) GetRetiringPools(
	currentEpoch uint64,
	txn types.Txn,
) ([]models.PoolRetiringRow, error)

func (*Store) GetRewardAccountOutputs

func (s *Store) GetRewardAccountOutputs(
	epoch uint64,
	txn types.Txn,
) ([]*models.RewardAccountOutput, error)

func (*Store) GetRewardAccountOutputsByCredential

func (s *Store) GetRewardAccountOutputsByCredential(
	credentialTag uint8,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	txn types.Txn,
) ([]*models.RewardAccountOutput, error)

func (*Store) GetRewardAdaPots

func (s *Store) GetRewardAdaPots(
	epoch uint64,
	txn types.Txn,
) (*models.RewardAdaPots, error)

func (*Store) GetRewardPoolInputs

func (s *Store) GetRewardPoolInputs(
	epoch uint64,
	txn types.Txn,
) ([]*models.RewardPoolInput, error)

func (*Store) GetRewardPoolOutputs

func (s *Store) GetRewardPoolOutputs(
	epoch uint64,
	txn types.Txn,
) ([]*models.RewardPoolOutput, error)

func (*Store) GetRewardSeedFailure added in v0.70.7

func (s *Store) GetRewardSeedFailure(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) (string, error)

func (*Store) GetRewardSnapshot

func (s *Store) GetRewardSnapshot(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) (*models.RewardSnapshot, error)

func (*Store) GetRewardStakeInputs

func (s *Store) GetRewardStakeInputs(
	epoch uint64,
	txn types.Txn,
) ([]*models.RewardStakeInput, error)

func (*Store) GetRewardStakeInputsForPools

func (s *Store) GetRewardStakeInputsForPools(
	poolKeyHashes [][]byte,
	slot uint64,
	expiryEpoch uint64,
	inactivityPeriod uint64,
	txn types.Txn,
) ([]*models.RewardStakeInput, error)

func (*Store) GetScript

func (s *Store) GetScript(
	hash lcommon.ScriptHash,
	txn types.Txn,
) (*models.Script, error)

func (*Store) GetScriptLockedSupply

func (s *Store) GetScriptLockedSupply(txn types.Txn) (uint64, error)

func (*Store) GetStakeByPool

func (s *Store) GetStakeByPool(
	poolKeyHash []byte,
	txn types.Txn,
) (uint64, uint64, error)

func (*Store) GetStakeByPools

func (s *Store) GetStakeByPools(
	poolKeyHashes [][]byte,
	txn types.Txn,
) (map[string]uint64, map[string]uint64, error)

func (*Store) GetStakeByPoolsAtSlot

func (s *Store) GetStakeByPoolsAtSlot(
	poolKeyHashes [][]byte,
	slot uint64,
	expiryEpoch uint64,
	inactivityPeriod uint64,
	txn types.Txn,
) (map[string]uint64, map[string]uint64, error)

func (*Store) GetStakeRegistrationsByCredential

func (s *Store) GetStakeRegistrationsByCredential(
	credentialTag uint8,
	stakingKey []byte,
	txn types.Txn,
) ([]lcommon.StakeRegistrationCertificate, error)

func (*Store) GetSyncState

func (s *Store) GetSyncState(key string, txn types.Txn) (string, error)

func (*Store) GetTip

func (s *Store) GetTip(txn types.Txn) (ochainsync.Tip, error)

func (*Store) GetTokenRegistryEntry added in v0.70.1

func (s *Store) GetTokenRegistryEntry(
	subject string,
	txn types.Txn,
) (*models.TokenRegistryEntry, error)

GetTokenRegistryEntry returns the registry properties for a subject, or nil when the registry has nothing for it. An unknown subject is absence rather than an error: the API serves a null `metadata` field for it.

func (*Store) GetTotalActiveStake

func (s *Store) GetTotalActiveStake(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) (uint64, error)

func (*Store) GetTransactionByHash

func (s *Store) GetTransactionByHash(
	hash []byte,
	txn types.Txn,
) (*models.Transaction, error)

func (*Store) GetTransactionHashesAfterSlot

func (s *Store) GetTransactionHashesAfterSlot(
	slot uint64,
	txn types.Txn,
) ([][]byte, error)

func (*Store) GetTransactionIDByHash

func (s *Store) GetTransactionIDByHash(
	hash []byte,
	txn types.Txn,
) (uint, bool, error)

func (*Store) GetTransactionMetadataByHash

func (s *Store) GetTransactionMetadataByHash(
	hash []byte,
	txn types.Txn,
) ([]byte, error)

func (*Store) GetTransactionSlotByHash

func (s *Store) GetTransactionSlotByHash(
	hash []byte,
	txn types.Txn,
) (uint64, bool, error)

func (*Store) GetTransactionsByAddress

func (s *Store) GetTransactionsByAddress(
	paymentKey []byte,
	credentialTag uint8,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	txn types.Txn,
) ([]models.Transaction, error)

func (*Store) GetTransactionsByBlockHash

func (s *Store) GetTransactionsByBlockHash(
	blockHash []byte,
	txn types.Txn,
) ([]models.Transaction, error)

func (*Store) GetTransactionsByHashes

func (s *Store) GetTransactionsByHashes(
	hashes [][]byte,
	txn types.Txn,
) ([]models.Transaction, error)

func (*Store) GetTransactionsByMetadataLabel

func (s *Store) GetTransactionsByMetadataLabel(
	label uint64,
	limit int,
	offset int,
	descending bool,
	txn types.Txn,
) ([]models.Transaction, error)

func (*Store) GetUtxo

func (s *Store) GetUtxo(
	txID []byte,
	index uint32,
	txn types.Txn,
) (*models.Utxo, error)

func (*Store) GetUtxoBalanceByAddress

func (s *Store) GetUtxoBalanceByAddress(
	address lcommon.Address,
	mode models.UtxoAddressMatchMode,
	txn types.Txn,
) (models.AddressBalance, error)

func (*Store) GetUtxoIncludingSpent

func (s *Store) GetUtxoIncludingSpent(
	txID []byte,
	index uint32,
	txn types.Txn,
) (*models.Utxo, error)

func (*Store) GetUtxoPaymentScriptByCredential

func (s *Store) GetUtxoPaymentScriptByCredential(
	credentialTag uint8,
	stakingKey []byte,
	paymentKeys [][]byte,
	txn types.Txn,
) (map[string]bool, error)

func (*Store) GetUtxosAddedAfterSlot

func (s *Store) GetUtxosAddedAfterSlot(
	slot uint64,
	txn types.Txn,
) ([]models.Utxo, error)

GetUtxosAddedAfterSlot returns every UTxO added after slot, newest first.

The rollback sweep calls this (through UtxosDeleteRolledback) immediately before DeleteUtxosAfterSlot, to hand the blob store the objects it has to drop. The statement used to end in "ORDER BY id DESC". id is the rowid, so SQLite satisfied that by walking the table backwards -- a full SCAN, with readahead defeated by the descending direction -- rather than range-searching idx_utxo_added_slot, and the sweep read the entire utxo table to return the handful of rows a rollback actually touches.

Ordering by added_slot first fixes it without giving up a deterministic order: idx_utxo_added_slot is (added_slot, rowid) and id is the rowid, so "ORDER BY added_slot DESC, id DESC" is exactly that index's reverse order. SQLite walks the matching range backwards and needs no sorter, at every table size and whether or not ANALYZE has run. TestGetUtxosAddedAfterSlotUsesSlotIndex pins the plan.

func (*Store) GetUtxosByAddress

func (s *Store) GetUtxosByAddress(
	patterns []models.UtxoAddressPattern,
	maxResults int,
	txn types.Txn,
) ([]models.Utxo, error)

GetUtxosByAddress runs one OR-joined query per chunk of patterns -- a single statement covering every pattern can exceed the dialect's bound-parameter limit (e.g. SQLite's 999) or its OR-expression tree depth limit once enough addresses are requested. Chunking is bounded by both accumulated bind-argument count and branch count: a pattern whose exact-address hash decodes as the zero hash for both payment and staking (e.g. a Byron address with an all-zero payment hash) falls back to a zero-argument branch in AppendUtxoAddressPatternOrBranch, so argument-count alone would never chunk a run of such patterns before the expression tree overflowed. Candidates are deduplicated by (tx id, output index) across chunks -- a coarse, non-selective branch (e.g. the zero-argument fallback above) can return the same candidate rows from every chunk it appears in -- before assets are loaded once on the final deduplicated set, so asset-loading cost is bounded by the result size rather than chunk count times candidate-set size.

maxResults must be positive: it is an explicit, caller-supplied bound on the number of candidate rows this call may materialize, since a broad pattern set (or an address with an unusually large UTxO set) would otherwise force an unbounded result. Exceeding it returns models.ErrTooManyUtxoResults rather than silently truncating the answer.

func (*Store) GetUtxosByAddressAtSlot

func (s *Store) GetUtxosByAddressAtSlot(
	pattern models.UtxoAddressPattern,
	slot uint64,
	txn types.Txn,
) ([]models.Utxo, error)

func (*Store) GetUtxosByAddressWithOrdering

func (s *Store) GetUtxosByAddressWithOrdering(
	query *models.UtxoWithOrderingQuery,
	txn types.Txn,
) ([]models.UtxoWithOrdering, error)

func (*Store) GetUtxosByAssets

func (s *Store) GetUtxosByAssets(
	policyID []byte,
	assetName []byte,
	txn types.Txn,
) ([]models.Utxo, error)

func (*Store) GetUtxosByRefs added in v0.70.0

func (s *Store) GetUtxosByRefs(
	refs []models.UtxoId,
	txn types.Txn,
) ([]models.Utxo, error)

GetUtxosByRefs retrieves multiple live UTxOs by their (tx_id, output_idx) references in a single batch. Refs with no matching live UTxO are simply absent from the result. A ref repeated in the input yields at most one row, keeping one-row-per-requested-ref semantics for callers.

func (*Store) GetUtxosByRefsAsOf added in v0.70.9

func (s *Store) GetUtxosByRefsAsOf(
	refs []models.UtxoId,
	atSlot uint64,
	txn types.Txn,
) ([]models.Utxo, error)

GetUtxosByRefsAsOf retrieves the UTxOs matching refs as they stood at atSlot: created at-or-before atSlot and either still live (deleted_slot = 0) or spent strictly after it (deleted_slot > atSlot). See the UtxoStore interface doc comment for the retention caveat callers must enforce themselves -- a row spent long enough ago can already be hard-deleted by the periodic stability-window cleanup regardless of atSlot.

func (*Store) GetUtxosBySlot

func (s *Store) GetUtxosBySlot(
	slot uint64,
	txn types.Txn,
) ([]models.UtxoId, error)

func (*Store) GetUtxosDeletedBeforeSlot

func (s *Store) GetUtxosDeletedBeforeSlot(
	slot uint64,
	limit int,
	txn types.Txn,
) ([]models.Utxo, error)

func (*Store) HasDeferredIndexesPending

func (s *Store) HasDeferredIndexesPending() (bool, error)

HasDeferredIndexesPending reports whether a prior drop/rebuild cycle still owns the durable recovery marker.

func (*Store) HasDestructiveReset added in v0.70.0

func (s *Store) HasDestructiveReset() bool

HasDestructiveReset reports whether Reset actually mutates a live target (postgres/mysql, which wire a real Config.Reset callback) rather than being a harmless no-op (sqlite, which never sets one). Every backend's concrete *Store satisfies metadata.Resettable's Reset(ctx) error method regardless, so a plain type assertion against that interface alone cannot distinguish "genuinely destructive" from "no-op" -- callers that need to know whether Reset already happening (or having failed partway) means there is no safe pre-restore state left to resume on (see node_lifecycle.go's Restore) must check this instead.

func (*Store) ImportAccount

func (s *Store) ImportAccount(
	account *models.Account,
	txn types.Txn,
) error

ImportAccount writes a snapshot-imported or genesis-delegated account row together with the baseline a later rollback restores it to. Both writes share one transaction: an account row committed without its baseline leaves RestoreAccountStateAtSlot deriving the pre-fix state for that credential, and nothing rewrites the baseline afterwards unless the account is imported again.

func (*Store) ImportDrep

func (s *Store) ImportDrep(
	drep *models.Drep,
	registration *models.RegistrationDrep,
	txn types.Txn,
) error

func (*Store) ImportPool

func (s *Store) ImportPool(
	pool *models.Pool,
	registration *models.PoolRegistration,
	txn types.Txn,
) error

func (*Store) ImportUtxos

func (s *Store) ImportUtxos(
	utxos []models.Utxo,
	txn types.Txn,
) error

func (*Store) InsertDrepIfAbsent

func (s *Store) InsertDrepIfAbsent(
	credentialTag uint8,
	credential []byte,
	slot uint64,
	url string,
	hash []byte,
	active bool,
	txn types.Txn,
) error

func (*Store) InsertMidnightCommitteeCandidateRegistration

func (s *Store) InsertMidnightCommitteeCandidateRegistration(
	txn types.Txn,
	row *models.MidnightCommitteeCandidateRegistration,
) error

func (*Store) InsertMidnightGovernanceDatum

func (s *Store) InsertMidnightGovernanceDatum(
	txn types.Txn,
	datum *models.MidnightGovernanceDatum,
) error

func (*Store) InsertNodeSettingsGateIfAbsent

func (s *Store) InsertNodeSettingsGateIfAbsent(
	name string,
	value string,
	recordedEpoch uint64,
	recordedSlot uint64,
) (bool, error)

InsertNodeSettingsGateIfAbsent persists a single gate only if no row for name exists yet, reporting whether this call is what created it. Unlike SetNodeSettingsGates's unconditional upsert, this lets a caller detect a concurrent opener's first-ever write to the same gate (see commit_timestamp.go's evaluateAndPersistGates) instead of silently overwriting it -- the loser learns it lost and can re-evaluate against what is now actually persisted rather than assuming its own write landed.

func (*Store) InsertNodeSettingsGatesIfAbsent

func (s *Store) InsertNodeSettingsGatesIfAbsent(
	gates nodesettings.Values,
	recordedEpoch uint64,
	recordedSlot uint64,
) (bool, error)

InsertNodeSettingsGatesIfAbsent inserts a complete first-fill set in one transaction. A concurrent initializer may win the conditional insert for one or more names; in that case the transaction is rolled back so this method never leaves a partially initialized gate set behind.

func (*Store) IsCommitteeMemberResigned

func (s *Store) IsCommitteeMemberResigned(
	coldCredentialTag uint8,
	coldKey []byte,
	termStartSlot uint64,
	txn types.Txn,
) (bool, error)

func (*Store) IterateLiveUtxos

func (s *Store) IterateLiveUtxos(
	txn types.Txn,
	fn func(*models.Utxo) error,
) error

func (*Store) LatestPoolOpCertSequence

func (s *Store) LatestPoolOpCertSequence(
	poolKeyHash lcommon.PoolKeyHash,
	txn types.Txn,
) (uint64, bool, error)

func (*Store) LatestPoolOpCertSequenceAfter added in v0.70.2

func (s *Store) LatestPoolOpCertSequenceAfter(
	poolKeyHash lcommon.PoolKeyHash,
	afterSlot uint64,
	txn types.Txn,
) (uint64, bool, error)

LatestPoolOpCertSequenceAfter returns the highest sequence recorded for a pool after afterSlot. A Mithril-restored ledger uses this to distinguish replayed counter history from rows imported at its trust boundary.

func (*Store) LatestPoolOpCertSequenceAtOrBefore added in v0.70.2

func (s *Store) LatestPoolOpCertSequenceAtOrBefore(
	poolKeyHash lcommon.PoolKeyHash,
	slot uint64,
	txn types.Txn,
) (uint64, bool, error)

func (*Store) LatestPoolOpCertSequences

func (s *Store) LatestPoolOpCertSequences(
	txn types.Txn,
) (map[string]uint64, error)

LatestPoolOpCertSequences returns the highest observed op-cert sequence for every pool that has issued a block, keyed by pool key hash.

The issuer table records one row per (pool, slot), so the highest sequence is an aggregate rather than the newest row: a pool that rotated to a lower issue number after a higher one has still had the higher number accepted, and that is the number the chain enforces.

func (*Store) ListSyncStateKeysByPrefix added in v0.70.6

func (s *Store) ListSyncStateKeysByPrefix(
	prefix string,
	txn types.Txn,
) ([]string, error)

ListSyncStateKeysByPrefix returns every sync_state key that has the given byte prefix, sorted ascending. It enumerates the (small) sync_state keyspace and filters the exact prefix in Go with strings.HasPrefix, so the match is byte-exact and identical on every backend. A SQL range scan or LIKE would be wrong here: on MySQL/Postgres the >=/< and LIKE operators honor the column's COLLATION, not byte order, so a case- or locale-insensitive collation could include keys that lack the byte prefix (or exclude keys that have it), and a synthesized range upper bound over a non-ASCII prefix can be invalid UTF-8. The deferred-header retention markers this enumerates (issue #3727) must be matched exactly or a restart could miss a marker and fail to pin a snapshot.

func (*Store) MarkUtxosDeletedAtSlot

func (s *Store) MarkUtxosDeletedAtSlot(
	txn types.Txn,
	refs []types.UtxoKey,
	atSlot uint64,
) error

func (*Store) MissingCriticalDeferredIndexes added in v0.70.11

func (s *Store) MissingCriticalDeferredIndexes() ([]string, error)

MissingCriticalDeferredIndexes reports the Critical=true manifest entries absent from the schema, in manifest order, using the read connection and no DDL. Callers use it to name the indexes a rebuild is about to build before the rebuild starts.

func (*Store) NewBatchAccumulator

func (s *Store) NewBatchAccumulator() types.MetadataBatchAccumulator

func (*Store) PruneTokenRegistryEntriesBefore added in v0.70.1

func (s *Store) PruneTokenRegistryEntriesBefore(
	ctx context.Context,
	cutoff time.Time,
	txn types.Txn,
) (int, error)

PruneTokenRegistryEntriesBefore deletes registry rows last confirmed by a snapshot older than cutoff, returning the number removed. Callers pass the timestamp they gave UpsertTokenRegistryEntries for the snapshot just applied, which leaves that snapshot's own rows (stamped exactly at the cutoff) in place and removes everything it did not carry.

This is what stops a subject the upstream registry has dropped, or one that lost every property, from being served forever by an upsert-only sync. It must run only after a snapshot has fully applied: pruning against a partial snapshot would delete live subjects the failed run never reached.

func (*Store) ReadPoolStats

func (s *Store) ReadPoolStats() sql.DBStats

ReadPoolStats exposes read-pool telemetry. SQLite file stores use this to report their independently-sized WAL reader pool.

func (*Store) ReadTransaction

func (s *Store) ReadTransaction(ctx context.Context) types.Txn

ReadTransaction begins a repeatable, read-only transaction on the read pool, bound to ctx the same way Transaction is.

func (*Store) Ready

func (s *Store) Ready() bool

Ready reports whether startup migrations completed successfully.

func (*Store) RebuildRewardLiveStake

func (s *Store) RebuildRewardLiveStake(
	slot uint64,
	txn types.Txn,
) error

func (*Store) RecomputeGapCollateralFee

func (s *Store) RecomputeGapCollateralFee(
	transaction lcommon.Transaction,
	_ ocommon.Point,
	txn types.Txn,
) error

func (*Store) ReleaseFallbackRewardSnapshotGuard

func (s *Store) ReleaseFallbackRewardSnapshotGuard(
	guardID uint,
	txn types.Txn,
) error

func (*Store) RenewAccountExpirations

func (s *Store) RenewAccountExpirations(
	refs []models.StakeCredentialRef,
	expirationEpoch uint64,
	txn types.Txn,
) error

func (*Store) Reset added in v0.70.0

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

Reset clears all data this store owns, for providers that supply the hook (see metadata.Resettable). A no-op for providers that don't -- unlike BackupTo/RestoreFrom, silently doing nothing here is correct, not a lost user request: sqlite (the only file-based provider built on this shared Store) has nothing for this to do, since restoreMetadataStore's directory wipe already fully undoes its brief resolve-and-start. Every backend built on this shared Store -- sqlite included -- therefore satisfies metadata.Resettable's interface, but only postgres/mysql wire a non-nil Config.Reset into it; sqlite's Reset is a documented no-op, not evidence that it "needs more than a directory wipe" the way metadata.Resettable's own doc comment describes for the backends that do.

func (*Store) ResetAccountExpirationActivation

func (s *Store) ResetAccountExpirationActivation(
	txn types.Txn,
) ([]models.StakeCredentialRef, error)

func (*Store) RestoreAccountStateAtSlot

func (s *Store) RestoreAccountStateAtSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) RestoreDrepStateAtSlot

func (s *Store) RestoreDrepStateAtSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) RestoreFrom

func (s *Store) RestoreFrom(ctx context.Context, srcPath string) error

func (*Store) RestoreNormalPragmas

func (s *Store) RestoreNormalPragmas() error

RestoreNormalPragmas restores safe backend defaults.

func (*Store) RestorePoolStateAtSlot

func (s *Store) RestorePoolStateAtSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) RetirePools

func (s *Store) RetirePools(
	txn types.Txn,
	poolKeyHashes [][]byte,
	epoch uint64,
	addedSlot uint64,
) error

func (*Store) RewardLiveStakeNeedsBackfill

func (s *Store) RewardLiveStakeNeedsBackfill(
	txn types.Txn,
) (bool, error)

func (*Store) SaveEpochSummary

func (s *Store) SaveEpochSummary(
	summary *models.EpochSummary,
	txn types.Txn,
) error

func (*Store) SaveImportedEpochBlockTotal added in v0.70.7

func (s *Store) SaveImportedEpochBlockTotal(
	epoch uint64,
	totalBlocks uint64,
	capturedSlot uint64,
	txn types.Txn,
) error

SaveImportedEpochBlockTotal records that an epoch's block counts came from a bootstrap snapshot, and the total the per-pool rows sum to. The row is what distinguishes a certified zero-block epoch from an epoch nothing was imported for; the per-pool rows alone cannot, because a BlocksMade map with no entries writes none.

func (*Store) SaveImportedPoolBlockCounts added in v0.70.7

func (s *Store) SaveImportedPoolBlockCounts(
	counts []models.ImportedPoolBlockCount,
	txn types.Txn,
) error

SaveImportedPoolBlockCounts records the per-pool block counts a bootstrap snapshot carries for one epoch. The rows are the node's only source of pool performance for an epoch that ended below its trust anchor.

func (*Store) SavePoolStakeSnapshot

func (s *Store) SavePoolStakeSnapshot(
	snapshot *models.PoolStakeSnapshot,
	txn types.Txn,
) error

func (*Store) SavePoolStakeSnapshots

func (s *Store) SavePoolStakeSnapshots(
	snapshots []*models.PoolStakeSnapshot,
	txn types.Txn,
) error

func (*Store) SaveRewardAccountOutputs

func (s *Store) SaveRewardAccountOutputs(
	outputs []*models.RewardAccountOutput,
	txn types.Txn,
) error

func (*Store) SaveRewardAdaPots

func (s *Store) SaveRewardAdaPots(
	pots *models.RewardAdaPots,
	txn types.Txn,
) error

func (*Store) SaveRewardPoolInputs

func (s *Store) SaveRewardPoolInputs(
	inputs []*models.RewardPoolInput,
	txn types.Txn,
) error

func (*Store) SaveRewardPoolOutputs

func (s *Store) SaveRewardPoolOutputs(
	outputs []*models.RewardPoolOutput,
	txn types.Txn,
) error

func (*Store) SaveRewardSeedFailure added in v0.70.7

func (s *Store) SaveRewardSeedFailure(
	epoch uint64,
	snapshotType string,
	reason string,
	capturedSlot uint64,
	txn types.Txn,
) error

func (*Store) SaveRewardSnapshot

func (s *Store) SaveRewardSnapshot(
	snapshot *models.RewardSnapshot,
	txn types.Txn,
) error

func (*Store) SaveRewardStakeInputs

func (s *Store) SaveRewardStakeInputs(
	inputs []*models.RewardStakeInput,
	txn types.Txn,
) error

func (*Store) SetBackfillCheckpoint

func (s *Store) SetBackfillCheckpoint(
	checkpoint *models.BackfillCheckpoint,
	txn types.Txn,
) error

func (*Store) SetBlockNonce

func (s *Store) SetBlockNonce(
	blockHash []byte,
	slotNumber uint64,
	nonce []byte,
	isCheckpoint bool,
	txn types.Txn,
) error

func (*Store) SetBulkLoadPragmas

func (s *Store) SetBulkLoadPragmas() error

SetBulkLoadPragmas enables backend-specific session tuning.

func (*Store) SetCommitTimestamp

func (s *Store) SetCommitTimestamp(
	timestamp int64,
	txn types.Txn,
) error

func (*Store) SetCommitteeMembers

func (s *Store) SetCommitteeMembers(
	members []*models.CommitteeMember,
	txn types.Txn,
) error

func (*Store) SetCommitteeQuorum

func (s *Store) SetCommitteeQuorum(
	quorum *types.Rat,
	slot uint64,
	txn types.Txn,
) error

func (*Store) SetConstitution

func (s *Store) SetConstitution(
	constitution *models.Constitution,
	txn types.Txn,
) error

func (*Store) SetDatum

func (s *Store) SetDatum(
	hash lcommon.Blake2b256,
	rawDatum []byte,
	addedSlot uint64,
	txn types.Txn,
) error

func (*Store) SetDrep

func (s *Store) SetDrep(
	credentialTag uint8,
	credential []byte,
	slot uint64,
	url string,
	hash []byte,
	active bool,
	txn types.Txn,
) error

SetDrep updates all mutable registration state. It remains a concrete store helper because existing callers use it even though it is not part of the public MetadataStore interface.

func (*Store) SetEpoch

func (s *Store) SetEpoch(
	slot, epoch uint64,
	nonce, evolvingNonce, candidateNonce, lastEpochBlockNonce []byte,
	era, slotLength, lengthInSlots uint,
	txn types.Txn,
) error

func (*Store) SetGapBlockTransaction

func (s *Store) SetGapBlockTransaction(
	transaction lcommon.Transaction,
	point ocommon.Point,
	index uint32,
	certDeposits map[int]uint64,
	txn types.Txn,
) error

func (*Store) SetGenesisGovernance

func (s *Store) SetGenesisGovernance(
	initialDReps conway.ConwayGenesisInitialDReps,
	delegations conway.ConwayGenesisDelegs,
	_ []byte,
	txn types.Txn,
) error

func (*Store) SetGenesisStaking

func (s *Store) SetGenesisStaking(
	pools map[string]lcommon.PoolRegistrationCertificate,
	stakeDelegations map[string]string,
	keyDeposit uint64,
	_ []byte,
	txn types.Txn,
) error

func (*Store) SetGenesisTransaction

func (s *Store) SetGenesisTransaction(
	hash []byte,
	blockHash []byte,
	outputs []models.Utxo,
	txn types.Txn,
) error

func (*Store) SetGovernanceProposal

func (s *Store) SetGovernanceProposal(
	proposal *models.GovernanceProposal,
	txn types.Txn,
) error

func (*Store) SetGovernanceVote

func (s *Store) SetGovernanceVote(
	vote *models.GovernanceVote,
	txn types.Txn,
) error

func (*Store) SetImportCheckpoint

func (s *Store) SetImportCheckpoint(
	checkpoint *models.ImportCheckpoint,
	txn types.Txn,
) error

func (*Store) SetNetworkState

func (s *Store) SetNetworkState(
	treasury, reserves uint64,
	slot uint64,
	txn types.Txn,
) error

func (*Store) SetNodeSettings

func (s *Store) SetNodeSettings(settings *types.NodeSettings) error

func (*Store) SetNodeSettingsGates

func (s *Store) SetNodeSettingsGates(
	gates nodesettings.Values,
	recordedEpoch uint64,
	recordedSlot uint64,
) error

SetNodeSettingsGates persists gates, upserting one row per entry so a later call can overwrite an earlier one. recordedEpoch and recordedSlot are stamped on every row in this call; callers pass zero for both when the write happens before the first block. A nil or empty gates is a no-op.

func (*Store) SetOffchainMetadataFetchResult

func (s *Store) SetOffchainMetadataFetchResult(
	ctx context.Context,
	doc *models.OffchainMetadata,
	txn types.Txn,
) error

func (*Store) SetPParamUpdate

func (s *Store) SetPParamUpdate(
	genesis, update []byte,
	slot, epoch uint64,
	txn types.Txn,
) error

func (*Store) SetPParams

func (s *Store) SetPParams(
	params []byte,
	slot, epoch uint64,
	eraID uint,
	txn types.Txn,
) error

func (*Store) SetSyncState

func (s *Store) SetSyncState(
	key, value string,
	txn types.Txn,
) error

func (*Store) SetTip

func (s *Store) SetTip(tip ochainsync.Tip, txn types.Txn) error

func (*Store) SetTransaction

func (s *Store) SetTransaction(
	transaction lcommon.Transaction,
	point ocommon.Point,
	index uint32,
	certDeposits map[int]uint64,
	skipWithdrawalWitness bool,
	txn types.Txn,
) error

func (*Store) SetTransactionBatched

func (s *Store) SetTransactionBatched(
	transaction lcommon.Transaction,
	point ocommon.Point,
	index uint32,
	certDeposits map[int]uint64,
	skipWithdrawalWitness bool,
	accumulator types.MetadataBatchAccumulator,
	txn types.Txn,
) error

func (*Store) SetTransactionBatchedHistorical added in v0.70.3

func (s *Store) SetTransactionBatchedHistorical(
	transaction lcommon.Transaction,
	point ocommon.Point,
	index uint32,
	certDeposits map[int]uint64,
	skipWithdrawalWitness bool,
	historicalBackfill bool,
	accumulator types.MetadataBatchAccumulator,
	txn types.Txn,
) error

SetTransactionBatchedHistorical is the historical-replay variant. It keeps the public MetadataStore contract stable while allowing API backfill to preserve snapshot-boundary reward balances instead of applying live-slot withdrawal sufficiency checks.

func (*Store) SetTransactionLeiosClosure added in v0.70.3

func (s *Store) SetTransactionLeiosClosure(
	transaction lcommon.Transaction,
	point ocommon.Point,
	index uint32,
	certDeposits map[int]uint64,
	skipWithdrawalWitness bool,
	txn types.Txn,
) error

SetTransactionLeiosClosure records a transaction on the Leios endorser-block closure path (the Musashi/Haskell-conformant ValidateNone apply). It behaves like SetTransaction except that a consumed input already spent by a *different* transaction is treated as a no-op instead of ErrUtxoConflict, matching the reference ledger's applyLeiosClosure: two certified endorser blocks may legitimately name the same input across blocks, and the canonical chain folds the closure without re-validation rather than rejecting it. Do not use this for ranking-block application, where a real double-spend must still fail.

func (*Store) SetUtxoDeletedAtSlot

func (s *Store) SetUtxoDeletedAtSlot(
	input ledger.TransactionInput,
	slot uint64,
	spenderTxHash []byte,
	txn types.Txn,
) error

func (*Store) SetUtxosNotDeletedAfterSlot

func (s *Store) SetUtxosNotDeletedAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*Store) SoftDeleteAllCommitteeMembers

func (s *Store) SoftDeleteAllCommitteeMembers(
	slot uint64,
	txn types.Txn,
) error

func (*Store) SoftDeleteCommitteeMembers

func (s *Store) SoftDeleteCommitteeMembers(
	coldCredentials []models.CommitteeCredential,
	slot uint64,
	txn types.Txn,
) error

func (*Store) StaleConsensusStakeSnapshotsExist

func (s *Store) StaleConsensusStakeSnapshotsExist(
	txn types.Txn,
) (bool, error)

func (*Store) StampAllActiveAccountExpirations

func (s *Store) StampAllActiveAccountExpirations(
	expirationEpoch uint64,
	txn types.Txn,
) (int64, error)

func (*Store) Start

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

Start verifies connectivity and completes every offline migration before making the store available to normal readers or writers.

func (*Store) SumNetworkDonationsForEpoch

func (s *Store) SumNetworkDonationsForEpoch(
	epoch uint64,
	txn types.Txn,
) (uint64, error)

func (*Store) SumTransactionFeesInSlotRange

func (s *Store) SumTransactionFeesInSlotRange(
	startSlot uint64,
	endSlot uint64,
	txn types.Txn,
) (uint64, error)

func (*Store) Transaction

func (s *Store) Transaction(ctx context.Context) types.Txn

Transaction begins a write transaction bound to ctx: every statement a caller issues against the returned Txn (via a domain method's txn parameter) runs with this ctx, and per database/sql's own BeginTx contract, canceling it rolls the transaction back rather than leaving it to time out on its own. Begin failures are retained on the returned transaction because the historical MetadataStore contract cannot return an error from this method. A nil ctx is treated as context.Background(), matching prior behavior for any caller that does not supply one.

func (*Store) UpdateDRepActivity

func (s *Store) UpdateDRepActivity(
	credentialTag uint8,
	credential []byte,
	activityEpoch uint64,
	inactivityPeriod uint64,
	txn types.Txn,
) error

func (*Store) UpdatePlannerStats

func (s *Store) UpdatePlannerStats() error

UpdatePlannerStats refreshes backend planner statistics.

func (*Store) UpdatePoolOpCertSequence

func (s *Store) UpdatePoolOpCertSequence(
	poolKeyHash lcommon.PoolKeyHash,
	sequence uint64,
	slot uint64,
	txn types.Txn,
) error

func (*Store) UpsertMidnightAriadneParams

func (s *Store) UpsertMidnightAriadneParams(
	txn types.Txn,
	params *models.MidnightAriadneParams,
) error

func (*Store) UpsertMidnightEpochCandidates

func (s *Store) UpsertMidnightEpochCandidates(
	txn types.Txn,
	epochCandidates *models.MidnightEpochCandidates,
) error

func (*Store) UpsertTokenRegistryEntries added in v0.70.1

func (s *Store) UpsertTokenRegistryEntries(
	ctx context.Context,
	entries []models.TokenRegistryEntry,
	syncedAt time.Time,
	txn types.Txn,
) (int, error)

UpsertTokenRegistryEntries writes CIP-26 token registry properties, keyed by subject, and returns the number of rows written. Each entry replaces every property of an existing row for the same subject, so a property the upstream registry has dropped stops being served rather than surviving from an earlier sync.

syncedAt stamps every written row with the timestamp of the snapshot being applied, so that PruneTokenRegistryEntriesBefore can afterwards identify rows the snapshot did not carry. All batches of one snapshot must pass the same value, or a later batch would make earlier ones look stale.

Entries are written one statement at a time rather than as a single multi-row INSERT: a registry sync is an infrequent background pass whose latency nobody waits on, and a per-row statement keeps one malformed subject from failing the batch around it.

func (*Store) ValidateBackup added in v0.70.0

func (s *Store) ValidateBackup(ctx context.Context, srcPath string) error

ValidateBackup checks a backup file's structural integrity, for providers that supply the hook (see metadata.BackupValidator). A no-op for providers that don't -- every backend built on this shared Store therefore satisfies metadata.BackupValidator's interface, but only providers whose restore orchestration needs it wire a non-nil Config.ValidateBackup in.

func (*Store) WritePoolStats

func (s *Store) WritePoolStats() sql.DBStats

WritePoolStats exposes database/sql pool telemetry without exposing the underlying database handle.

Directories

Path Synopsis
internal
Package migrations implements offline, forward-only metadata upgrades.
Package migrations implements offline, forward-only metadata upgrades.

Jump to

Keyboard shortcuts

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