sqlite

package
v0.43.0 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultMaxConnections = 5

DefaultMaxConnections is the default connection pool size for SQLite. This should match the DatabaseWorkers configuration (default 5).

Variables

This section is empty.

Functions

func NewFromCmdlineOptions added in v0.18.0

func NewFromCmdlineOptions() plugin.Plugin

Types

type BatchAccumulator added in v0.35.0

type BatchAccumulator struct {
	KeyWitnesses   []models.KeyWitness
	WitnessScripts []models.WitnessScripts
	Scripts        []models.Script
	PlutusData     []models.PlutusData
	Redeemers      []models.Redeemer
	AddressTxs     []models.AddressTransaction
	UtxoOutputs    []models.Utxo
	UtxoSpends     []utxoSpend
	CollateralRets []models.Utxo
	DeleteTxIDs    []uint
}

BatchAccumulator collects metadata rows across multiple transactions for bulk database insertion. It is the foundational data structure for the backfill batching optimization that reduces per-block SQL statements from 30-150 down to 2-5 by batching writes across 50-100 blocks.

func NewBatchAccumulator added in v0.35.0

func NewBatchAccumulator() *BatchAccumulator

NewBatchAccumulator returns an empty BatchAccumulator ready for use.

func (*BatchAccumulator) AddAddressTx added in v0.35.0

func (b *BatchAccumulator) AddAddressTx(at models.AddressTransaction)

AddAddressTx appends an address-transaction record to the batch.

func (*BatchAccumulator) AddCollateralReturn added in v0.35.0

func (b *BatchAccumulator) AddCollateralReturn(u models.Utxo)

AddCollateralReturn appends a collateral return UTxO to the batch.

func (*BatchAccumulator) AddDeleteTxID added in v0.35.0

func (b *BatchAccumulator) AddDeleteTxID(id uint)

AddDeleteTxID appends a transaction ID scheduled for idempotent retry deletion.

func (*BatchAccumulator) AddKeyWitness added in v0.35.0

func (b *BatchAccumulator) AddKeyWitness(kw models.KeyWitness)

AddKeyWitness appends a key witness record to the batch.

func (*BatchAccumulator) AddPlutusData added in v0.35.0

func (b *BatchAccumulator) AddPlutusData(pd models.PlutusData)

AddPlutusData appends a plutus data record to the batch.

func (*BatchAccumulator) AddRedeemer added in v0.35.0

func (b *BatchAccumulator) AddRedeemer(r models.Redeemer)

AddRedeemer appends a redeemer record to the batch.

func (*BatchAccumulator) AddScript added in v0.35.0

func (b *BatchAccumulator) AddScript(s models.Script)

AddScript appends a script record to the batch.

func (*BatchAccumulator) AddUtxoOutput added in v0.35.0

func (b *BatchAccumulator) AddUtxoOutput(u models.Utxo)

AddUtxoOutput appends a produced UTxO record to the batch.

func (*BatchAccumulator) AddUtxoSpend added in v0.35.0

func (b *BatchAccumulator) AddUtxoSpend(s utxoSpend)

AddUtxoSpend appends a consumed UTxO record to the batch.

func (*BatchAccumulator) AddWitnessScript added in v0.35.0

func (b *BatchAccumulator) AddWitnessScript(ws models.WitnessScripts)

AddWitnessScript appends a witness script record to the batch.

func (*BatchAccumulator) MergeFrom added in v0.41.0

func (b *BatchAccumulator) MergeFrom(other *BatchAccumulator)

MergeFrom appends all records from other into b. It is a no-op when other is nil or other == b.

func (*BatchAccumulator) Reset added in v0.35.0

func (b *BatchAccumulator) Reset()

Reset clears all accumulated slices, reusing backing arrays to reduce GC pressure across flush cycles.

type CommitTimestamp added in v0.4.0

type CommitTimestamp struct {
	ID        uint `gorm:"primarykey"`
	Timestamp int64
}

CommitTimestamp represents the sqlite table used to track the current commit timestamp

func (CommitTimestamp) TableName added in v0.4.0

func (CommitTimestamp) TableName() string

type MetadataStoreSqlite added in v0.4.0

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

MetadataStoreSqlite stores all data in sqlite. Data may not be persisted

func New

func New(
	dataDir string,
	logger *slog.Logger,
	promRegistry prometheus.Registerer,
) (*MetadataStoreSqlite, error)

New creates a new database

func NewWithOptions added in v0.18.0

func NewWithOptions(opts ...SqliteOptionFunc) (*MetadataStoreSqlite, error)

NewWithOptions creates a new database with options

func (*MetadataStoreSqlite) AddAccountReward added in v0.37.0

func (d *MetadataStoreSqlite) AddAccountReward(
	stakeKey []byte,
	amount uint64,
	slot uint64,
	txn types.Txn,
) error

AddAccountReward credits a registered reward account.

func (*MetadataStoreSqlite) AddUtxos added in v0.8.0

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

AddUtxos saves a batch of UTxOs directly

func (*MetadataStoreSqlite) AutoMigrate added in v0.4.0

func (d *MetadataStoreSqlite) AutoMigrate(dst ...any) error

AutoMigrate wraps the gorm AutoMigrate

func (*MetadataStoreSqlite) BeginTxn added in v0.19.0

func (d *MetadataStoreSqlite) BeginTxn() (types.Txn, error)

BeginTxn starts a transaction and returns the handle with an error. Callers that prefer explicit error handling can use this instead of Transaction().

func (*MetadataStoreSqlite) ClearCommitteeQuorum added in v0.37.0

func (d *MetadataStoreSqlite) ClearCommitteeQuorum(
	slot uint64,
	txn types.Txn,
) error

ClearCommitteeQuorum records that no quorum is in effect from the given slot onward. It inserts a zero-valued marker row so a later GetCommitteeQuorum returns nil (and callers fall back to Conway genesis) until a subsequent UpdateCommittee sets a new positive quorum. Shares the one-mutation-per-slot invariant documented on SetCommitteeQuorum.

func (*MetadataStoreSqlite) ClearDanglingDRepDelegations added in v0.37.0

func (d *MetadataStoreSqlite) ClearDanglingDRepDelegations(
	atSlot uint64,
	txn types.Txn,
) (int, error)

ClearDanglingDRepDelegations implements the Conway HARDFORK rule for protocol major version 10 (Plomin). See the MetadataStore interface documentation for semantics.

func (*MetadataStoreSqlite) ClearSyncState added in v0.22.0

func (d *MetadataStoreSqlite) ClearSyncState(
	txn types.Txn,
) error

ClearSyncState removes all sync state entries.

func (*MetadataStoreSqlite) Close added in v0.4.0

func (d *MetadataStoreSqlite) Close() error

Close gets the database handle from our MetadataStore and closes it

func (*MetadataStoreSqlite) CountTransactionsByAddress added in v0.33.0

func (d *MetadataStoreSqlite) CountTransactionsByAddress(
	paymentKey []byte,
	stakingKey []byte,
	txn types.Txn,
) (int, error)

CountTransactionsByAddress returns the total number of distinct transactions involving the given payment/staking key.

func (*MetadataStoreSqlite) CountTransactionsByMetadataLabel added in v0.34.0

func (d *MetadataStoreSqlite) CountTransactionsByMetadataLabel(
	label uint64,
	txn types.Txn,
) (int, error)

CountTransactionsByMetadataLabel returns the total number of transactions that include metadata for the requested label.

func (*MetadataStoreSqlite) Create added in v0.4.0

func (d *MetadataStoreSqlite) Create(value any) *gorm.DB

Create creates a record

func (*MetadataStoreSqlite) CreateAccount added in v0.37.0

func (d *MetadataStoreSqlite) CreateAccount(
	txn types.Txn,
	account *models.Account,
) error

CreateAccount inserts an Account row directly. See the MetadataStore interface for semantics.

func (*MetadataStoreSqlite) CreateDrep added in v0.37.0

func (d *MetadataStoreSqlite) CreateDrep(
	txn types.Txn,
	drep *models.Drep,
) error

CreateDrep inserts a Drep row directly. See the MetadataStore interface for semantics.

func (*MetadataStoreSqlite) CreateUtxo added in v0.37.0

func (d *MetadataStoreSqlite) CreateUtxo(
	txn types.Txn,
	utxo *models.Utxo,
) error

CreateUtxo inserts a Utxo row directly. See the MetadataStore interface for semantics.

func (*MetadataStoreSqlite) DB added in v0.4.0

func (d *MetadataStoreSqlite) DB() *gorm.DB

DB returns the write database handle

func (*MetadataStoreSqlite) DeleteAccountRewardsAfterSlot added in v0.37.0

func (d *MetadataStoreSqlite) DeleteAccountRewardsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteAccountRewardsAfterSlot reverts account reward credits recorded after the given slot and deletes their journal rows.

func (*MetadataStoreSqlite) DeleteAddressTransactionsAfterSlot added in v0.22.0

func (d *MetadataStoreSqlite) DeleteAddressTransactionsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteAddressTransactionsAfterSlot removes address-transaction mapping records added after the given slot.

func (*MetadataStoreSqlite) DeleteBlockNoncesAfterPoint added in v0.38.0

func (d *MetadataStoreSqlite) DeleteBlockNoncesAfterPoint(
	point ocommon.Point,
	txn types.Txn,
) error

DeleteBlockNoncesAfterPoint deletes block_nonce rows that are no longer on the active chain after a rollback. The rollback point's exact row is kept; same-slot rows with a different hash are removed.

func (*MetadataStoreSqlite) DeleteBlockNoncesBeforeSlot added in v0.11.0

func (d *MetadataStoreSqlite) DeleteBlockNoncesBeforeSlot(
	slotNumber uint64,
	txn types.Txn,
) error

DeleteBlockNoncesBeforeSlot deletes block_nonce records with slot less than the specified value

func (*MetadataStoreSqlite) DeleteBlockNoncesBeforeSlotWithoutCheckpoints added in v0.11.0

func (d *MetadataStoreSqlite) DeleteBlockNoncesBeforeSlotWithoutCheckpoints(
	slotNumber uint64,
	txn types.Txn,
) error

DeleteBlockNoncesBeforeSlotWithoutCheckpoints deletes block_nonce records with slot < given value AND is_checkpoint = false

func (*MetadataStoreSqlite) DeleteCertificatesAfterSlot added in v0.21.0

func (d *MetadataStoreSqlite) DeleteCertificatesAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteCertificatesAfterSlot removes all certificate records added after the given slot. This is used during chain rollbacks to undo certificate state changes. All deletions are performed atomically within a transaction to ensure consistency.

func (*MetadataStoreSqlite) DeleteCommitteeMembersAfterSlot added in v0.22.0

func (d *MetadataStoreSqlite) DeleteCommitteeMembersAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteCommitteeMembersAfterSlot removes committee state added after the given slot and clears deleted_slot for any members soft-deleted after that slot. This is used during chain rollbacks.

func (*MetadataStoreSqlite) DeleteConstitutionsAfterSlot added in v0.22.0

func (d *MetadataStoreSqlite) DeleteConstitutionsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteConstitutionsAfterSlot removes constitutions added after the given slot and clears deleted_slot for any that were soft-deleted after that slot. This is used during chain rollbacks.

func (*MetadataStoreSqlite) DeleteEpochSummariesAfterEpoch added in v0.22.0

func (d *MetadataStoreSqlite) DeleteEpochSummariesAfterEpoch(
	epoch uint64,
	txn types.Txn,
) error

DeleteEpochSummariesAfterEpoch deletes all epoch summaries after a given epoch. This is used during chain rollbacks.

func (*MetadataStoreSqlite) DeleteEpochSummariesBeforeEpoch added in v0.22.0

func (d *MetadataStoreSqlite) DeleteEpochSummariesBeforeEpoch(
	epoch uint64,
	txn types.Txn,
) error

DeleteEpochSummariesBeforeEpoch deletes all epoch summaries before a given epoch.

func (*MetadataStoreSqlite) DeleteEpochsAfterSlot added in v0.22.0

func (d *MetadataStoreSqlite) DeleteEpochsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteEpochsAfterSlot removes all epoch entries whose start slot is after the given slot.

func (*MetadataStoreSqlite) DeleteGovernanceProposalsAfterSlot added in v0.22.0

func (d *MetadataStoreSqlite) DeleteGovernanceProposalsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteGovernanceProposalsAfterSlot removes proposals added after the given slot, clears deleted_slot for any that were soft-deleted after that slot, and reverts status changes (ratified/enacted) that occurred after the rollback slot. This is used during chain rollbacks.

Transactional contract: when txn is nil this function wraps the rollback in its own transaction so partial failures cannot leave the table half-rolled. When txn is non-nil the operations execute directly against the caller's transaction. On error the caller MUST abort/rollback that outer transaction itself; this function will not undo updates that already succeeded within the caller-supplied txn.

func (*MetadataStoreSqlite) DeleteGovernanceVotesAfterSlot added in v0.22.0

func (d *MetadataStoreSqlite) DeleteGovernanceVotesAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteGovernanceVotesAfterSlot removes votes added after the given slot and clears deleted_slot for any that were soft-deleted after that slot. This is used during chain rollbacks.

NOTE: Vote changes (when a voter changes their vote) are tracked via vote_updated_slot. If a vote was changed after the rollback slot but originally cast before it, we cannot restore the previous vote value with the current upsert model. For full rollback support of vote changes, votes should be append-only. Currently, we delete any vote whose update occurred after the rollback slot to avoid having stale vote values persist.

func (*MetadataStoreSqlite) DeleteNetworkStateAfterSlot added in v0.22.0

func (d *MetadataStoreSqlite) DeleteNetworkStateAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteNetworkStateAfterSlot removes network state records added after the given slot.

func (*MetadataStoreSqlite) DeletePParamUpdatesAfterSlot added in v0.21.0

func (d *MetadataStoreSqlite) DeletePParamUpdatesAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeletePParamUpdatesAfterSlot removes protocol parameter update records added after the given slot.

func (*MetadataStoreSqlite) DeletePParamsAfterSlot added in v0.21.0

func (d *MetadataStoreSqlite) DeletePParamsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeletePParamsAfterSlot removes protocol parameter records added after the given slot.

func (*MetadataStoreSqlite) DeletePoolStakeSnapshotsAfterEpoch added in v0.22.0

func (d *MetadataStoreSqlite) DeletePoolStakeSnapshotsAfterEpoch(
	epoch uint64,
	txn types.Txn,
) error

DeletePoolStakeSnapshotsAfterEpoch deletes all pool stake snapshots after a given epoch. This is used during chain rollbacks.

func (*MetadataStoreSqlite) DeletePoolStakeSnapshotsBeforeEpoch added in v0.22.0

func (d *MetadataStoreSqlite) DeletePoolStakeSnapshotsBeforeEpoch(
	epoch uint64,
	txn types.Txn,
) error

DeletePoolStakeSnapshotsBeforeEpoch deletes all pool stake snapshots before a given epoch.

func (*MetadataStoreSqlite) DeletePoolStakeSnapshotsForEpoch added in v0.22.0

func (d *MetadataStoreSqlite) DeletePoolStakeSnapshotsForEpoch(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) error

DeletePoolStakeSnapshotsForEpoch deletes all pool stake snapshots for a specific epoch

func (*MetadataStoreSqlite) DeleteSyncState added in v0.22.0

func (d *MetadataStoreSqlite) DeleteSyncState(
	key string,
	txn types.Txn,
) error

DeleteSyncState removes a sync state key.

func (*MetadataStoreSqlite) DeleteTransactionMetadataLabelsAfterSlot added in v0.28.0

func (d *MetadataStoreSqlite) DeleteTransactionMetadataLabelsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteTransactionMetadataLabelsAfterSlot removes transaction metadata label index records added after the given slot.

func (*MetadataStoreSqlite) DeleteTransactionsAfterSlot added in v0.21.0

func (d *MetadataStoreSqlite) DeleteTransactionsAfterSlot(
	slot uint64,
	txn types.Txn,
) error

DeleteTransactionsAfterSlot removes transaction records added after the given slot. Child records are automatically removed via CASCADE constraints. UTXO hash-based foreign keys (spent_at_tx_id, collateral_by_tx_id, referenced_by_tx_id) are NULLed out before deleting transactions to prevent orphaned references.

func (*MetadataStoreSqlite) DeleteUtxo added in v0.4.2

func (d *MetadataStoreSqlite) DeleteUtxo(
	utxoId models.UtxoId,
	txn types.Txn,
) error

func (*MetadataStoreSqlite) DeleteUtxos added in v0.4.2

func (d *MetadataStoreSqlite) DeleteUtxos(
	utxos []models.UtxoId,
	txn types.Txn,
) error

func (*MetadataStoreSqlite) DeleteUtxosAfterSlot added in v0.4.4

func (d *MetadataStoreSqlite) DeleteUtxosAfterSlot(
	slot uint64,
	txn types.Txn,
) error

func (*MetadataStoreSqlite) DiskSize added in v0.29.0

func (d *MetadataStoreSqlite) DiskSize() (int64, error)

DiskSize returns the on-disk size of the SQLite database in bytes. Returns 0 for in-memory databases (empty dataDir).

func (*MetadataStoreSqlite) First added in v0.4.0

func (d *MetadataStoreSqlite) First(args any) *gorm.DB

First returns the first DB entry

func (*MetadataStoreSqlite) FlushBatch added in v0.37.0

func (d *MetadataStoreSqlite) FlushBatch(
	batch *BatchAccumulator,
	txn types.Txn,
) error

FlushBatch writes all accumulated records in a deterministic order.

func (*MetadataStoreSqlite) GetAccount added in v0.6.0

func (d *MetadataStoreSqlite) GetAccount(
	stakeKey []byte,
	includeInactive bool,
	txn types.Txn,
) (*models.Account, error)

GetAccount gets an account

func (*MetadataStoreSqlite) GetAccounts added in v0.42.0

func (d *MetadataStoreSqlite) GetAccounts(
	stakeKeys [][]byte,
	includeInactive bool,
	txn types.Txn,
) (map[string]*models.Account, error)

GetAccounts fetches multiple accounts in one IN-list query, keyed by string(StakingKey). Stake keys with no matching row are omitted.

func (*MetadataStoreSqlite) GetActiveCommitteeMembers added in v0.22.0

func (d *MetadataStoreSqlite) GetActiveCommitteeMembers(
	txn types.Txn,
) ([]*models.AuthCommitteeHot, error)

GetActiveCommitteeMembers retrieves all active committee members. Returns only the latest authorization per cold key, and excludes members whose latest resignation is after their latest authorization.

func (*MetadataStoreSqlite) GetActiveDreps added in v0.22.0

func (d *MetadataStoreSqlite) GetActiveDreps(
	txn types.Txn,
) ([]*models.Drep, error)

GetActiveDreps retrieves all active DReps.

func (*MetadataStoreSqlite) GetActiveGovernanceProposals added in v0.22.0

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

GetActiveGovernanceProposals retrieves all governance proposals that are still in the active pool: not expired past the given epoch, not enacted, not marked expired, not soft-deleted.

func (*MetadataStoreSqlite) GetActivePoolKeyHashes added in v0.22.0

func (d *MetadataStoreSqlite) GetActivePoolKeyHashes(
	txn types.Txn,
) ([][]byte, error)

GetActivePoolKeyHashes retrieves the key hashes of all currently active pools. A pool is active if it has a registration and either no retirement or the retirement epoch is in the future.

This delegates to GetActivePoolKeyHashesAtSlot using the current tip's slot, ensuring consistent same-slot certificate handling via block_index and cert_index ordering (ORDER BY added_slot DESC, block_index DESC, cert_index DESC).

func (*MetadataStoreSqlite) GetActivePoolKeyHashesAtSlot added in v0.22.0

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

GetActivePoolKeyHashesAtSlot retrieves the key hashes of pools that were active at the given slot. A pool was active at a slot if:

  1. It had a registration with added_slot <= slot
  2. Either no retirement with added_slot <= slot, OR the retirement was for an epoch that hadn't started by the given slot

This implementation only fetches pools that have at least one registration at or before the given slot, avoiding loading all pools for early slot queries. Uses window functions to get the latest registration/retirement per pool directly in SQLite, minimizing memory usage.

func (*MetadataStoreSqlite) GetActivePoolRelays added in v0.21.0

func (d *MetadataStoreSqlite) GetActivePoolRelays(
	txn types.Txn,
) ([]models.PoolRegistrationRelay, error)

GetActivePoolRelays returns all relays from currently active pools. A pool is considered active if it has a registration and either: - No retirement, or - The retirement epoch is in the future

Implementation note: This function loads all registrations and retirements per pool and filters in Go rather than using complex SQL JOINs. This approach is necessary because:

  1. GORM's Preload with Limit(1) applies the limit globally, not per-parent
  2. Determining the "latest" registration/retirement requires comparing added_slot values which is cumbersome in a single query
  3. The filtering logic (retirement epoch vs current epoch) is clearer in Go

For networks with thousands of pools, this may use significant memory. Future optimization could use raw SQL with window functions (ROW_NUMBER) or batch processing if memory becomes a concern.

func (*MetadataStoreSqlite) GetAddressesByStakingKey added in v0.22.0

func (d *MetadataStoreSqlite) GetAddressesByStakingKey(
	stakingKey []byte,
	limit int,
	offset int,
	txn types.Txn,
) ([]models.AddressTransaction, error)

GetAddressesByStakingKey returns distinct addresses mapped to a staking key.

func (*MetadataStoreSqlite) GetAssetByPolicyAndName added in v0.18.0

func (d *MetadataStoreSqlite) GetAssetByPolicyAndName(
	policyId lcommon.Blake2b224,
	assetName []byte,
	txn types.Txn,
) (models.Asset, error)

GetAssetByPolicyAndName returns an asset by policy ID and asset name

func (*MetadataStoreSqlite) GetAssetQuantityByPolicyAndName added in v0.36.0

func (d *MetadataStoreSqlite) GetAssetQuantityByPolicyAndName(
	policyId lcommon.Blake2b224,
	assetName []byte,
	txn types.Txn,
) (uint64, error)

GetAssetQuantityByPolicyAndName returns the total live quantity for an asset across all matching UTxOs.

func (*MetadataStoreSqlite) GetAssetsByPolicy added in v0.18.0

func (d *MetadataStoreSqlite) GetAssetsByPolicy(
	policyId lcommon.Blake2b224,
	txn types.Txn,
) ([]models.Asset, error)

GetAssetsByPolicy returns all assets for a given policy ID

func (*MetadataStoreSqlite) GetAssetsByUTxO added in v0.18.0

func (d *MetadataStoreSqlite) GetAssetsByUTxO(
	txId []byte,
	idx uint32,
	txn types.Txn,
) ([]models.Asset, error)

GetAssetsByUTxO returns all assets for a given UTxO using transaction ID and output index

func (*MetadataStoreSqlite) GetBackfillCheckpoint added in v0.22.0

func (d *MetadataStoreSqlite) GetBackfillCheckpoint(
	phase string,
	txn types.Txn,
) (*models.BackfillCheckpoint, error)

GetBackfillCheckpoint retrieves a backfill checkpoint by phase. Returns nil (not error) if no checkpoint exists for the phase.

func (*MetadataStoreSqlite) GetBlockNonce added in v0.11.0

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

GetBlockNonce retrieves the block nonce for a specific block

func (*MetadataStoreSqlite) GetBlockNoncesInSlotRange added in v0.22.0

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

GetBlockNoncesInSlotRange retrieves all block nonces where slot >= startSlot and slot < endSlot.

func (*MetadataStoreSqlite) GetCommitTimestamp added in v0.4.0

func (d *MetadataStoreSqlite) GetCommitTimestamp() (int64, error)

func (*MetadataStoreSqlite) GetCommitteeActiveCount added in v0.22.0

func (d *MetadataStoreSqlite) GetCommitteeActiveCount(
	txn types.Txn,
) (int, error)

GetCommitteeActiveCount returns the total number of active (non-resigned) committee members. This is used for CC threshold calculations.

func (*MetadataStoreSqlite) GetCommitteeMember added in v0.22.0

func (d *MetadataStoreSqlite) GetCommitteeMember(
	coldKey []byte,
	txn types.Txn,
) (*models.AuthCommitteeHot, error)

GetCommitteeMember retrieves a committee member by cold key. Returns the latest authorization (ordered by added_slot DESC).

func (*MetadataStoreSqlite) GetCommitteeMembers added in v0.22.0

func (d *MetadataStoreSqlite) GetCommitteeMembers(
	txn types.Txn,
) ([]*models.CommitteeMember, error)

GetCommitteeMembers retrieves all active (non-deleted) snapshot-imported committee members.

func (*MetadataStoreSqlite) GetCommitteeMembersIncludeDeleted added in v0.37.0

func (d *MetadataStoreSqlite) GetCommitteeMembersIncludeDeleted(
	txn types.Txn,
) ([]*models.CommitteeMember, error)

GetCommitteeMembersIncludeDeleted returns every committee member row including soft-deleted ones. ccEverSeated uses this to distinguish "never seated" from "voted out by NoConfidence".

func (*MetadataStoreSqlite) GetCommitteeQuorum added in v0.37.0

func (d *MetadataStoreSqlite) GetCommitteeQuorum(
	txn types.Txn,
) (*types.Rat, error)

GetCommitteeQuorum retrieves the latest enacted committee quorum. A most-recent marker row with a non-positive quorum represents a NoConfidence-driven clear and is reported as "no quorum enacted".

func (*MetadataStoreSqlite) GetConstitution added in v0.22.0

func (d *MetadataStoreSqlite) GetConstitution(
	txn types.Txn,
) (*models.Constitution, error)

GetConstitution retrieves the current constitution. Returns nil if the constitution has been soft-deleted.

func (*MetadataStoreSqlite) GetDRepVotingPower added in v0.22.0

func (d *MetadataStoreSqlite) GetDRepVotingPower(
	drepCredential []byte,
	txn types.Txn,
) (uint64, error)

GetDRepVotingPower calculates the voting power for a DRep by summing the current stake of all accounts delegated to it, including live UTxO balance plus reward-account balance.

TODO: This implementation uses current live balances as an approximation. A future implementation should accept an epoch parameter and use epoch-based stake snapshots for accurate voting power at a specific point in time.

The voting power is computed by: 1. Finding all accounts whose drep field matches the DRep credential 2. Summing those accounts' UTxO values

Returns 0 if the DRep has no delegators.

func (*MetadataStoreSqlite) GetDRepVotingPowerBatch added in v0.37.0

func (d *MetadataStoreSqlite) GetDRepVotingPowerBatch(
	drepCredentials [][]byte,
	txn types.Txn,
) (map[string]uint64, error)

GetDRepVotingPowerBatch returns a credential-to-voting-power map for the given DRep credentials in a single query. Credentials with no active delegators are omitted; credentials with active delegators whose delegated stake sums to zero are present with stake = 0. This is the batch variant of GetDRepVotingPower and avoids N+1 queries when tallying governance votes across many active DReps.

func (*MetadataStoreSqlite) GetDRepVotingPowerByType added in v0.37.0

func (d *MetadataStoreSqlite) GetDRepVotingPowerByType(
	drepTypes []uint64,
	txn types.Txn,
) (map[uint64]uint64, error)

GetDRepVotingPowerByType returns voting power grouped by DRep delegation type. It is used for predefined DRep options, which carry no credential.

func (*MetadataStoreSqlite) GetDatum added in v0.9.0

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

GetDatum returns a datum by its hash

func (*MetadataStoreSqlite) GetDrep added in v0.7.0

func (d *MetadataStoreSqlite) GetDrep(
	cred []byte,
	includeInactive bool,
	txn types.Txn,
) (*models.Drep, error)

GetDrep gets a drep

func (*MetadataStoreSqlite) GetEpoch added in v0.22.0

func (d *MetadataStoreSqlite) GetEpoch(
	epochId uint64,
	txn types.Txn,
) (*models.Epoch, error)

GetEpoch returns a single epoch by its ID, or nil if not found.

func (*MetadataStoreSqlite) GetEpochBySlot added in v0.37.0

func (d *MetadataStoreSqlite) GetEpochBySlot(
	slot uint64,
	txn types.Txn,
) (*models.Epoch, error)

GetEpochBySlot returns the epoch containing the given slot, or nil if not found.

func (*MetadataStoreSqlite) GetEpochSummary added in v0.21.0

func (d *MetadataStoreSqlite) GetEpochSummary(
	epoch uint64,
	txn types.Txn,
) (*models.EpochSummary, error)

GetEpochSummary retrieves an epoch summary by epoch number

func (*MetadataStoreSqlite) GetEpochs added in v0.6.0

func (d *MetadataStoreSqlite) GetEpochs(
	txn types.Txn,
) ([]models.Epoch, error)

GetEpochs returns the list of epochs

func (*MetadataStoreSqlite) GetEpochsByEra added in v0.4.3

func (d *MetadataStoreSqlite) GetEpochsByEra(
	eraId uint,
	txn types.Txn,
) ([]models.Epoch, error)

GetEpochsByEra returns the list of epochs by era

func (*MetadataStoreSqlite) GetExpiredDReps added in v0.22.0

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

GetExpiredDReps retrieves all active DReps whose expiry epoch is at or before the given epoch. These DReps have been inactive for longer than the dRepInactivityPeriod and should be considered expired for voting power purposes.

func (*MetadataStoreSqlite) GetExpiringGovernanceProposals added in v0.37.0

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

GetExpiringGovernanceProposals returns proposals whose expires_epoch is strictly less than the given epoch and that have not yet been enacted, expired, or soft-deleted. Used at epoch boundaries to mark expired proposals and trigger deposit returns.

func (*MetadataStoreSqlite) GetGovernanceProposal added in v0.22.0

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

GetGovernanceProposal retrieves a governance proposal by transaction hash and action index. Returns nil if the proposal has been soft-deleted.

func (*MetadataStoreSqlite) GetGovernanceVotes added in v0.22.0

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

GetGovernanceVotes retrieves all votes for a governance proposal.

func (*MetadataStoreSqlite) GetImportCheckpoint added in v0.22.0

func (d *MetadataStoreSqlite) GetImportCheckpoint(
	importKey string,
	txn types.Txn,
) (*models.ImportCheckpoint, error)

GetImportCheckpoint retrieves the checkpoint for a given import key. Returns nil if no checkpoint exists.

func (*MetadataStoreSqlite) GetLastBlockNonceInRange added in v0.35.1

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

GetLastBlockNonceInRange retrieves the block nonce with the highest slot in [startSlot, endSlot). Returns nil nonce and no error if none found.

func (*MetadataStoreSqlite) GetLastEnactedGovernanceProposal added in v0.37.0

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

GetLastEnactedGovernanceProposal returns the most recently enacted proposal whose action_type is in actionTypes, or nil if none exist. The set form lets callers group action types that share a chain root per CIP-1694 (e.g., NoConfidence and UpdateCommittee).

func (*MetadataStoreSqlite) GetLatestEpochSummary added in v0.21.0

func (d *MetadataStoreSqlite) GetLatestEpochSummary(
	txn types.Txn,
) (*models.EpochSummary, error)

GetLatestEpochSummary retrieves the most recent epoch summary

func (*MetadataStoreSqlite) GetLiveUtxosBySlot added in v0.37.0

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

GetLiveUtxosBySlot returns the references of all live UTxOs (deleted_slot = 0) created at the given slot. Only TxId and OutputIdx are populated.

func (*MetadataStoreSqlite) GetNetworkState added in v0.22.0

func (d *MetadataStoreSqlite) GetNetworkState(
	txn types.Txn,
) (*models.NetworkState, error)

GetNetworkState retrieves the most recent network state.

func (*MetadataStoreSqlite) GetNodeSettings added in v0.31.0

func (d *MetadataStoreSqlite) GetNodeSettings() (*types.NodeSettings, error)

GetNodeSettings returns the persisted node settings, or nil if the database has never been initialised.

func (*MetadataStoreSqlite) GetPParamUpdates added in v0.4.2

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

GetPParamUpdates returns a list of protocol parameter updates for a given epoch. Updates are returned in descending order by ID (most recent first).

func (*MetadataStoreSqlite) GetPParams added in v0.4.2

func (d *MetadataStoreSqlite) GetPParams(
	epoch uint64,
	eraId uint,
	txn types.Txn,
) ([]models.PParams, error)

GetPParams returns the latest protocol-parameters row at epoch <= the supplied epoch whose era_id matches the supplied era.

func (*MetadataStoreSqlite) GetPool added in v0.6.0

func (d *MetadataStoreSqlite) GetPool(
	pkh lcommon.PoolKeyHash,
	includeInactive bool,
	txn types.Txn,
) (*models.Pool, error)

GetPool gets a pool

func (*MetadataStoreSqlite) GetPoolByVrfKeyHash added in v0.22.0

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

GetPoolByVrfKeyHash retrieves an active pool by its VRF key hash. Returns nil if no active pool uses this VRF key.

func (*MetadataStoreSqlite) GetPoolRegistrations added in v0.4.2

func (d *MetadataStoreSqlite) GetPoolRegistrations(
	pkh lcommon.PoolKeyHash,
	txn types.Txn,
) ([]lcommon.PoolRegistrationCertificate, error)

GetPoolRegistrations returns pool registration certificates

func (*MetadataStoreSqlite) GetPoolStakeSnapshot added in v0.21.0

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

GetPoolStakeSnapshot retrieves a specific pool's stake snapshot

func (*MetadataStoreSqlite) GetPoolStakeSnapshotsByEpoch added in v0.21.0

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

GetPoolStakeSnapshotsByEpoch retrieves all pool stake snapshots for an epoch

func (*MetadataStoreSqlite) GetPools added in v0.30.0

func (d *MetadataStoreSqlite) GetPools(
	pkhs []lcommon.PoolKeyHash,
	txn types.Txn,
) ([]models.Pool, error)

GetPools gets pools by key hash.

func (*MetadataStoreSqlite) GetRatifiedGovernanceProposals added in v0.37.0

func (d *MetadataStoreSqlite) GetRatifiedGovernanceProposals(
	txn types.Txn,
) ([]*models.GovernanceProposal, error)

GetRatifiedGovernanceProposals returns proposals that have been ratified but not yet enacted. Used at epoch start to apply enactment effects.

func (*MetadataStoreSqlite) GetResignedCommitteeMembers added in v0.37.0

func (d *MetadataStoreSqlite) GetResignedCommitteeMembers(
	coldKeys [][]byte,
	txn types.Txn,
) (map[string]bool, error)

GetResignedCommitteeMembers returns cold credentials whose latest resignation is after their latest authorization.

func (*MetadataStoreSqlite) GetScript added in v0.18.0

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

GetScript returns the script content by its hash

func (*MetadataStoreSqlite) GetStakeByPool added in v0.22.0

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

GetStakeByPool returns the total delegated stake and delegator count for a pool.

func (*MetadataStoreSqlite) GetStakeByPools added in v0.22.0

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

GetStakeByPools returns delegated stake for multiple pools in a single query. Stake is computed by joining active accounts with their live UTxOs (deleted_slot = 0) and summing the UTxO amounts per pool.

func (*MetadataStoreSqlite) GetStakeRegistrations added in v0.4.2

func (d *MetadataStoreSqlite) GetStakeRegistrations(
	stakingKey []byte,
	txn types.Txn,
) ([]lcommon.StakeRegistrationCertificate, error)

GetStakeRegistrations returns stake registration certificates

func (*MetadataStoreSqlite) GetSyncState added in v0.22.0

func (d *MetadataStoreSqlite) GetSyncState(
	key string,
	txn types.Txn,
) (string, error)

GetSyncState retrieves a sync state value by key.

func (*MetadataStoreSqlite) GetTip added in v0.4.2

func (d *MetadataStoreSqlite) GetTip(
	txn types.Txn,
) (ocommon.Tip, error)

GetTip returns the current metadata Tip as ocommon.Tip

func (*MetadataStoreSqlite) GetTotalActiveStake added in v0.21.0

func (d *MetadataStoreSqlite) GetTotalActiveStake(
	epoch uint64,
	snapshotType string,
	txn types.Txn,
) (uint64, error)

GetTotalActiveStake returns the total active stake for an epoch. It uses the pre-calculated total from EpochSummary when available, falling back to summing individual pool snapshots.

func (*MetadataStoreSqlite) GetTransactionByHash added in v0.18.0

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

GetTransactionByHash returns a transaction by its hash

func (*MetadataStoreSqlite) GetTransactionHashesAfterSlot added in v0.22.0

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

GetTransactionHashesAfterSlot returns transaction hashes for transactions added after the given slot. This is used for blob cleanup during rollback/truncation.

func (*MetadataStoreSqlite) GetTransactionIDByHash added in v0.37.0

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

GetTransactionIDByHash returns the primary-key ID of the transaction with the given hash without preloading any related rows. Returns (0, false, nil) when no such transaction exists.

func (*MetadataStoreSqlite) GetTransactionSlotByHash added in v0.37.0

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

GetTransactionSlotByHash returns the slot of the transaction with the given hash without preloading any related rows. Returns (0, false, nil) when no such transaction exists.

func (*MetadataStoreSqlite) GetTransactionsByAddress added in v0.22.0

func (d *MetadataStoreSqlite) GetTransactionsByAddress(
	paymentKey []byte,
	stakingKey []byte,
	limit int,
	offset int,
	order string,
	txn types.Txn,
) ([]models.Transaction, error)

GetTransactionsByAddress returns transactions that involve the given payment/staking key with pagination support.

func (*MetadataStoreSqlite) GetTransactionsByBlockHash added in v0.22.0

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

GetTransactionsByBlockHash returns all transactions for a given block hash, ordered by their position within the block.

func (*MetadataStoreSqlite) GetTransactionsByHashes added in v0.33.0

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

GetTransactionsByHashes returns transactions for the provided hashes.

func (*MetadataStoreSqlite) GetTransactionsByMetadataLabel added in v0.28.0

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

GetTransactionsByMetadataLabel returns transactions containing a metadata entry for the requested label.

func (*MetadataStoreSqlite) GetUtxo added in v0.4.2

func (d *MetadataStoreSqlite) GetUtxo(
	txId []byte,
	idx uint32,
	txn types.Txn,
) (*models.Utxo, error)

GetUtxo returns a Utxo by reference

func (*MetadataStoreSqlite) GetUtxoIncludingSpent added in v0.22.0

func (d *MetadataStoreSqlite) GetUtxoIncludingSpent(
	txId []byte,
	idx uint32,
	txn types.Txn,
) (*models.Utxo, error)

GetUtxoIncludingSpent returns a Utxo by reference, including spent (consumed) UTxOs.

func (*MetadataStoreSqlite) GetUtxosAddedAfterSlot added in v0.4.3

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

GetUtxosAddedAfterSlot returns a list of Utxos added after a given slot

func (*MetadataStoreSqlite) GetUtxosBatch added in v0.21.0

func (d *MetadataStoreSqlite) GetUtxosBatch(
	refs []UtxoRef,
	txn types.Txn,
) (map[string]*models.Utxo, error)

GetUtxosBatch retrieves multiple UTXOs by their references in a single query. Returns a map keyed by "txid:outputidx" for easy lookup. Large batches are automatically chunked to avoid SQLite expression limits.

func (*MetadataStoreSqlite) GetUtxosByAddress added in v0.4.2

func (d *MetadataStoreSqlite) GetUtxosByAddress(
	addr ledger.Address,
	txn types.Txn,
) ([]models.Utxo, error)

GetUtxosByAddress returns a list of Utxos

func (*MetadataStoreSqlite) GetUtxosByAddressAtSlot added in v0.22.0

func (d *MetadataStoreSqlite) GetUtxosByAddressAtSlot(
	addr lcommon.Address,
	slot uint64,
	txn types.Txn,
) ([]models.Utxo, error)

GetUtxosByAddressAtSlot returns UTxOs for an address that existed at a specific slot.

func (*MetadataStoreSqlite) GetUtxosByAddressWithOrdering added in v0.27.5

func (d *MetadataStoreSqlite) GetUtxosByAddressWithOrdering(
	q *models.UtxoWithOrderingQuery,
	txn types.Txn,
) ([]models.UtxoWithOrdering, error)

GetUtxosByAddressWithOrdering returns UTxOs matching q (OR of addresses, optional asset).

func (*MetadataStoreSqlite) GetUtxosByAssets added in v0.21.0

func (d *MetadataStoreSqlite) GetUtxosByAssets(
	policyId []byte,
	assetName []byte,
	txn types.Txn,
) ([]models.Utxo, error)

GetUtxosByAssets returns a list of Utxos that contain the specified assets policyId: the policy ID of the asset (required) assetName: the asset name (pass nil to match all assets under the policy, or empty []byte{} to match assets with empty names)

func (*MetadataStoreSqlite) GetUtxosDeletedBeforeSlot added in v0.4.3

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

GetUtxosDeletedBeforeSlot returns a list of Utxos marked as deleted before a given slot

func (*MetadataStoreSqlite) ImportAccount added in v0.22.0

func (d *MetadataStoreSqlite) ImportAccount(
	account *models.Account,
	txn types.Txn,
) error

ImportAccount upserts an account (insert or update delegation fields on conflict).

func (*MetadataStoreSqlite) ImportDrep added in v0.22.0

func (d *MetadataStoreSqlite) ImportDrep(
	drep *models.Drep,
	reg *models.RegistrationDrep,
	txn types.Txn,
) error

ImportDrep upserts a DRep and creates a registration record.

func (*MetadataStoreSqlite) ImportPool added in v0.22.0

func (d *MetadataStoreSqlite) ImportPool(
	pool *models.Pool,
	reg *models.PoolRegistration,
	txn types.Txn,
) error

ImportPool upserts a pool and creates a registration record.

func (*MetadataStoreSqlite) ImportUtxos added in v0.22.0

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

ImportUtxos inserts UTxOs in bulk, ignoring duplicates. Assets are inserted in a second pass to avoid cascading the associated Assets into the same bulk INSERT, which can push the variable count over SQLite limits.

func (*MetadataStoreSqlite) InsertDrepIfAbsent added in v0.37.0

func (d *MetadataStoreSqlite) InsertDrepIfAbsent(
	cred []byte,
	slot uint64,
	url string,
	hash []byte,
	active bool,
	txn types.Txn,
) error

InsertDrepIfAbsent inserts a DRep row only when no record exists for the given credential. Existing rows are left untouched so the repair path cannot clobber real registration metadata.

func (*MetadataStoreSqlite) IsCommitteeMemberResigned added in v0.22.0

func (d *MetadataStoreSqlite) IsCommitteeMemberResigned(
	coldKey []byte,
	txn types.Txn,
) (bool, error)

IsCommitteeMemberResigned checks if a committee member has resigned. Returns true only if the latest resignation is after the latest authorization (handles resign-then-rejoin scenarios). Uses (added_slot, id) for deterministic ordering when events occur in the same block.

func (*MetadataStoreSqlite) IterateLiveUtxos added in v0.37.0

func (d *MetadataStoreSqlite) IterateLiveUtxos(
	txn types.Txn,
	fn func(*models.Utxo) error,
) error

IterateLiveUtxos invokes fn for every live UTxO row in unspecified order, paging through the table to avoid loading the full set at once. See the MetadataStore interface for semantics.

func (*MetadataStoreSqlite) MarkUtxosDeletedAtSlot added in v0.37.0

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

MarkUtxosDeletedAtSlot marks every live UTxO row matching one of refs as deleted at atSlot. See the MetadataStore interface for semantics.

func (*MetadataStoreSqlite) Order added in v0.4.0

func (d *MetadataStoreSqlite) Order(args any) *gorm.DB

Order orders a DB query

func (*MetadataStoreSqlite) ReadDB added in v0.22.0

func (d *MetadataStoreSqlite) ReadDB() *gorm.DB

ReadDB returns the read-only database handle. For file-based databases this is a separate connection pool optimized for concurrent reads via WAL mode. For in-memory databases this returns the same handle as DB().

func (*MetadataStoreSqlite) ReadTransaction added in v0.22.0

func (d *MetadataStoreSqlite) ReadTransaction() types.Txn

ReadTransaction creates a read-only transaction using the read connection pool. For file-based databases this avoids contending with the write connection; for in-memory databases it falls back to the write connection.

func (*MetadataStoreSqlite) RestoreAccountStateAtSlot added in v0.21.0

func (d *MetadataStoreSqlite) RestoreAccountStateAtSlot(
	slot uint64,
	txn types.Txn,
) error

RestoreAccountStateAtSlot reverts account delegation state to the given slot. For accounts modified after the slot, this restores their Pool and Drep delegations to the state they had at the given slot, or deletes them if they were registered after that slot.

This implementation uses batch fetching to avoid N+1 query patterns: instead of querying certificates per-account, it fetches all relevant certificates for all affected accounts upfront (one query per table), then processes them in memory.

func (*MetadataStoreSqlite) RestoreDrepStateAtSlot added in v0.21.0

func (d *MetadataStoreSqlite) RestoreDrepStateAtSlot(
	slot uint64,
	txn types.Txn,
) error

RestoreDrepStateAtSlot reverts DRep state to the given slot.

This function handles two cases for DReps modified after the rollback slot:

  1. DReps with no registration certificates at or before the slot are deleted (they didn't exist at that point in the chain).
  2. DReps with prior registrations have their state restored by examining all relevant certificates (registration, deregistration, update) and determining the correct Active status and anchor data.

The Active status follows these rules:

  • A registration certificate activates a DRep
  • A deregistration certificate deactivates a DRep
  • An update certificate can modify anchor data but cannot reactivate a deregistered DRep (per Cardano protocol rules)

The added_slot field is set to the slot of the most recent effective certificate that modified the DRep's state at or before the rollback slot.

This implementation uses batch fetching to avoid N+1 query patterns: instead of querying certificates per-DRep, it fetches all relevant certificates for all affected DReps upfront (one query per table), then processes them in memory.

func (*MetadataStoreSqlite) RestoreNormalPragmas added in v0.22.0

func (d *MetadataStoreSqlite) RestoreNormalPragmas() error

RestoreNormalPragmas restores SQLite PRAGMAs to production settings after bulk loading is complete.

func (*MetadataStoreSqlite) RestorePoolStateAtSlot added in v0.21.0

func (d *MetadataStoreSqlite) RestorePoolStateAtSlot(
	slot uint64,
	txn types.Txn,
) error

RestorePoolStateAtSlot reverts pool state to the given slot.

This function handles two cases for pools:

  1. Pools with no registration certificates at or before the slot are deleted (they didn't exist at that point in the chain).
  2. Pools with at least one registration at or before the slot have their denormalized fields (Pledge, Cost, Margin, VrfKeyHash, RewardAccount) restored from the most recent such registration.

Child records are automatically removed via CASCADE constraints when pools are deleted. PoolRegistration records after the slot are removed separately by DeleteCertificatesAfterSlot.

This implementation uses batch fetching to avoid N+1 query patterns: instead of querying certificates per-pool, it fetches all relevant registrations for all affected pools upfront in one query with a JOIN to the certs table to get cert_index for deterministic same-slot ordering.

func (*MetadataStoreSqlite) SaveEpochSummary added in v0.21.0

func (d *MetadataStoreSqlite) SaveEpochSummary(
	summary *models.EpochSummary,
	txn types.Txn,
) error

SaveEpochSummary saves an epoch summary

func (*MetadataStoreSqlite) SavePoolStakeSnapshot added in v0.21.0

func (d *MetadataStoreSqlite) SavePoolStakeSnapshot(
	snapshot *models.PoolStakeSnapshot,
	txn types.Txn,
) error

SavePoolStakeSnapshot saves a pool stake snapshot

func (*MetadataStoreSqlite) SavePoolStakeSnapshots added in v0.21.0

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

SavePoolStakeSnapshots saves multiple pool stake snapshots in batch

func (*MetadataStoreSqlite) SetAccount added in v0.6.0

func (d *MetadataStoreSqlite) SetAccount(
	stakeKey, pkh, drep []byte,
	slot uint64,
	active bool,
	txn types.Txn,
) error

SetAccount saves an account

func (*MetadataStoreSqlite) SetBackfillCheckpoint added in v0.22.0

func (d *MetadataStoreSqlite) SetBackfillCheckpoint(
	checkpoint *models.BackfillCheckpoint,
	txn types.Txn,
) error

SetBackfillCheckpoint creates or updates a backfill checkpoint, upserting on the Phase column.

func (*MetadataStoreSqlite) SetBlockNonce added in v0.11.0

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

SetBlockNonce inserts or updates a block nonce. The (hash, slot) uniqueIndex makes this safe to call repeatedly for the same block, which happens when the metadata backfill resumes from a checkpoint that pre-dates a previously-written nonce row.

func (*MetadataStoreSqlite) SetBulkLoadPragmas added in v0.22.0

func (d *MetadataStoreSqlite) SetBulkLoadPragmas() error

SetBulkLoadPragmas configures SQLite PRAGMAs optimized for bulk loading. These settings trade crash safety for speed, which is acceptable because immutable chunk data can always be reloaded.

func (*MetadataStoreSqlite) SetCommitTimestamp added in v0.4.0

func (d *MetadataStoreSqlite) SetCommitTimestamp(
	timestamp int64,
	txn types.Txn,
) error

func (*MetadataStoreSqlite) SetCommitteeMembers added in v0.22.0

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

SetCommitteeMembers upserts committee members imported from a Mithril snapshot. On conflict (same cold_cred_hash), the expires_epoch and added_slot are updated.

func (*MetadataStoreSqlite) SetCommitteeQuorum added in v0.37.0

func (d *MetadataStoreSqlite) SetCommitteeQuorum(
	quorum *types.Rat,
	slot uint64,
	txn types.Txn,
) error

SetCommitteeQuorum stores the quorum threshold enacted with a committee. Invariant: at most one committee-quorum mutation per slot (added_slot is uniquely indexed). Governance ratifies at most one committee-purpose action per epoch tick, so SetCommitteeQuorum and ClearCommitteeQuorum cannot race at the same slot under normal operation; the upsert's overwrite semantics exist to keep import/replay idempotent.

func (*MetadataStoreSqlite) SetConstitution added in v0.22.0

func (d *MetadataStoreSqlite) SetConstitution(
	constitution *models.Constitution,
	txn types.Txn,
) error

SetConstitution sets the constitution.

func (*MetadataStoreSqlite) SetDatum added in v0.9.0

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

SetDatum saves a datum

func (*MetadataStoreSqlite) SetDrep added in v0.7.0

func (d *MetadataStoreSqlite) SetDrep(
	cred []byte,
	slot uint64,
	url string,
	hash []byte,
	active bool,
	txn types.Txn,
) error

SetDrep saves a drep

func (*MetadataStoreSqlite) SetEpoch added in v0.4.2

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

SetEpoch saves an epoch

func (*MetadataStoreSqlite) SetGapBlockTransaction added in v0.22.0

func (d *MetadataStoreSqlite) SetGapBlockTransaction(
	tx lcommon.Transaction,
	point ocommon.Point,
	idx uint32,
	txn types.Txn,
) error

SetGapBlockTransaction stores a transaction record and its produced outputs without looking up or consuming input UTxOs. Gap blocks from mithril sync have their UTxO state already reflected in the snapshot, so input processing must be skipped entirely.

func (*MetadataStoreSqlite) SetGenesisStaking added in v0.22.0

func (d *MetadataStoreSqlite) SetGenesisStaking(
	pools map[string]lcommon.PoolRegistrationCertificate,
	stakeDelegations map[string]string,
	blockHash []byte,
	txn types.Txn,
) error

SetGenesisStaking stores genesis pool registrations and stake delegations from the shelley-genesis.json staking section. It creates Pool, PoolRegistration, and Account records at slot 0.

func (*MetadataStoreSqlite) SetGenesisTransaction added in v0.22.0

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

SetGenesisTransaction stores a genesis transaction record. Genesis transactions have no inputs, witnesses, or fees - just outputs.

func (*MetadataStoreSqlite) SetGovernanceProposal added in v0.22.0

func (d *MetadataStoreSqlite) SetGovernanceProposal(
	proposal *models.GovernanceProposal,
	txn types.Txn,
) error

SetGovernanceProposal creates or updates a governance proposal.

func (*MetadataStoreSqlite) SetGovernanceVote added in v0.22.0

func (d *MetadataStoreSqlite) SetGovernanceVote(
	vote *models.GovernanceVote,
	txn types.Txn,
) error

SetGovernanceVote records a vote on a governance proposal.

func (*MetadataStoreSqlite) SetImportCheckpoint added in v0.22.0

func (d *MetadataStoreSqlite) SetImportCheckpoint(
	checkpoint *models.ImportCheckpoint,
	txn types.Txn,
) error

SetImportCheckpoint creates or updates a checkpoint.

func (*MetadataStoreSqlite) SetLogger added in v0.24.0

func (d *MetadataStoreSqlite) SetLogger(logger *slog.Logger)

func (*MetadataStoreSqlite) SetNetworkState added in v0.22.0

func (d *MetadataStoreSqlite) SetNetworkState(
	treasury, reserves uint64,
	slot uint64,
	txn types.Txn,
) error

SetNetworkState stores the treasury and reserves balances.

func (*MetadataStoreSqlite) SetNodeSettings added in v0.31.0

func (d *MetadataStoreSqlite) SetNodeSettings(
	s *types.NodeSettings,
) error

SetNodeSettings persists the immutable node settings, inserting the singleton row if it does not already exist.

func (*MetadataStoreSqlite) SetPParamUpdate added in v0.4.2

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

SetPParamUpdate saves a protocol parameter update

func (*MetadataStoreSqlite) SetPParams added in v0.4.2

func (d *MetadataStoreSqlite) SetPParams(
	params []byte,
	slot, epoch uint64,
	eraId uint,
	txn types.Txn,
) error

SetPParams saves protocol parameters

func (*MetadataStoreSqlite) SetSyncState added in v0.22.0

func (d *MetadataStoreSqlite) SetSyncState(
	key, value string,
	txn types.Txn,
) error

SetSyncState stores or updates a sync state value.

func (*MetadataStoreSqlite) SetTip added in v0.4.2

func (d *MetadataStoreSqlite) SetTip(
	tip ochainsync.Tip,
	txn types.Txn,
) error

SetTip saves a tip

func (*MetadataStoreSqlite) SetTransaction added in v0.18.0

func (d *MetadataStoreSqlite) SetTransaction(
	tx lcommon.Transaction,
	point ocommon.Point,
	idx uint32,
	certDeposits map[int]uint64,
	txn types.Txn,
) error

SetTransaction adds a new transaction to the database and processes all certificates

func (*MetadataStoreSqlite) SetTransactionBatched added in v0.41.0

func (d *MetadataStoreSqlite) SetTransactionBatched(
	tx lcommon.Transaction,
	point ocommon.Point,
	idx uint32,
	certDeposits map[int]uint64,
	acc *BatchAccumulator,
	txn types.Txn,
) error

SetTransactionBatched performs the same logical work as SetTransaction but accumulates all per-item metadata rows into acc for later bulk flushing via FlushBatch. The transaction record itself is still written immediately so that downstream foreign-key dependencies (witness, script, etc.) can reference its auto-increment ID.

Items written immediately (FK or ordering dependency):

  • Transaction record (upsert)
  • Collateral / reference-input UTXO marker UPDATEs
  • Certificates and governance records
  • storeTransactionDatums hash index

Items deferred to acc:

  • UTxO outputs, collateral return, UTxO spends
  • Key witnesses, witness scripts, scripts, plutus data, redeemers
  • Address-transaction index rows

func (*MetadataStoreSqlite) SetUtxoDeletedAtSlot added in v0.4.4

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

SetUtxoDeletedAtSlot marks a UTxO as deleted at the given slot and records the hash of the transaction that consumed it. The update uses the same optimistic-locking predicate as the normal consume path and also repairs same-slot rows that are still missing spent_at_tx_id.

func (*MetadataStoreSqlite) SetUtxosNotDeletedAfterSlot added in v0.4.3

func (d *MetadataStoreSqlite) SetUtxosNotDeletedAfterSlot(
	slot uint64,
	txn types.Txn,
) error

SetUtxosNotDeletedAfterSlot marks a list of Utxos as not deleted after a given slot. Both deleted_slot and spent_at_tx_id must be cleared so the restored row satisfies the spend predicate (deleted_slot = 0 AND spent_at_tx_id IS NULL); otherwise the UTxO appears live but cannot be re-spent.

func (*MetadataStoreSqlite) SoftDeleteAllCommitteeMembers added in v0.37.0

func (d *MetadataStoreSqlite) SoftDeleteAllCommitteeMembers(
	slot uint64,
	txn types.Txn,
) error

SoftDeleteAllCommitteeMembers marks all active committee members as removed. Used by governance enactment for NoConfidence actions.

func (*MetadataStoreSqlite) SoftDeleteCommitteeMembers added in v0.37.0

func (d *MetadataStoreSqlite) SoftDeleteCommitteeMembers(
	coldCredHashes [][]byte,
	slot uint64,
	txn types.Txn,
) error

SoftDeleteCommitteeMembers marks the given cold credential hashes as removed by setting deleted_slot. Used by governance enactment to remove members listed in an UpdateCommittee action.

func (*MetadataStoreSqlite) Start added in v0.18.0

func (d *MetadataStoreSqlite) Start() error

Start implements the plugin.Plugin interface

func (*MetadataStoreSqlite) Stop added in v0.18.0

func (d *MetadataStoreSqlite) Stop() error

Stop implements the plugin.Plugin interface

func (*MetadataStoreSqlite) Transaction added in v0.4.0

func (d *MetadataStoreSqlite) Transaction() types.Txn

Transaction creates a gorm transaction

func (*MetadataStoreSqlite) UpdateDRepActivity added in v0.22.0

func (d *MetadataStoreSqlite) UpdateDRepActivity(
	drepCredential []byte,
	activityEpoch uint64,
	inactivityPeriod uint64,
	txn types.Txn,
) error

UpdateDRepActivity updates the DRep's last activity epoch and recalculates the expiry epoch. Called when a DRep votes, registers, or updates their registration. The expiryEpoch is set to activityEpoch + inactivityPeriod. Returns ErrDrepActivityNotUpdated if no matching DRep record was found.

func (*MetadataStoreSqlite) Where added in v0.4.0

func (d *MetadataStoreSqlite) Where(
	query any,
	args ...any,
) *gorm.DB

Where constrains a DB query

type NodeSettings added in v0.31.0

type NodeSettings struct {
	ID          uint   `gorm:"primarykey"`
	StorageMode string `gorm:"size:16;not null"`
	Network     string `gorm:"size:64;not null"`
}

NodeSettings persists immutable node configuration so that storage mode and network cannot be changed after the database has been initialised.

func (NodeSettings) TableName added in v0.31.0

func (NodeSettings) TableName() string

type SqliteOptionFunc added in v0.18.0

type SqliteOptionFunc func(*MetadataStoreSqlite)

func WithDataDir added in v0.18.0

func WithDataDir(dataDir string) SqliteOptionFunc

WithDataDir specifies the data directory to use for storage

func WithLogger added in v0.18.0

func WithLogger(logger *slog.Logger) SqliteOptionFunc

WithLogger specifies the logger object to use for logging messages

func WithMaxConnections added in v0.21.0

func WithMaxConnections(maxConnections int) SqliteOptionFunc

WithMaxConnections specifies the maximum number of database connections. This should match the DatabaseWorkers configuration to avoid connection pool exhaustion or unnecessary contention on SQLite's lock infrastructure.

func WithPromRegistry added in v0.18.0

func WithPromRegistry(
	registry prometheus.Registerer,
) SqliteOptionFunc

WithPromRegistry specifies the prometheus registry to use for metrics

func WithStorageMode added in v0.22.0

func WithStorageMode(mode string) SqliteOptionFunc

WithStorageMode specifies the storage tier. "core" = consensus only, "api" = full tx metadata.

type UtxoRef added in v0.21.0

type UtxoRef struct {
	TxId      []byte
	OutputIdx uint32
}

UtxoRef represents a reference to a UTXO by transaction ID and output index

Jump to

Keyboard shortcuts

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