ledger

package
v0.26.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	BlockfetchEventType        event.EventType = "ledger.blockfetch"
	BlockEventType             event.EventType = "ledger.block"
	ChainsyncEventType         event.EventType = "ledger.chainsync"
	LedgerErrorEventType       event.EventType = "ledger.error"
	PoolStateRestoredEventType event.EventType = "ledger.pool_restored"
	TransactionEventType       event.EventType = "ledger.tx"
)

Variables

View Source
var ErrBeforeGenesis = errors.New("time is before genesis start")

ErrBeforeGenesis is returned by TimeToSlot when the given time is before the chain's genesis start. The caller should wait until genesis.

View Source
var ErrNilDecodedOutput = errors.New("nil decoded output")

ErrNilDecodedOutput is returned when a decoded UTxO output is nil.

View Source
var ErrUtxoAlreadyConsumed = errors.New("UTxO already consumed")

ErrUtxoAlreadyConsumed is returned when a UTxO has been consumed by a pending transaction.

Functions

func CalculateMinFee added in v0.22.0

func CalculateMinFee(
	txSize uint64,
	exUnits lcommon.ExUnits,
	minFeeA uint,
	minFeeB uint,
	pricesMem *big.Rat,
	pricesSteps *big.Rat,
) uint64

CalculateMinFee computes the minimum fee for a transaction using the Cardano fee formula:

fee = (minFeeA * txSize) + minFeeB + scriptFee

where:

scriptFee = ceil(pricesMem * exUnits.Memory)
          + ceil(pricesSteps * exUnits.Steps)

All arithmetic uses big.Int to match the Haskell reference implementation. Overflow is impossible with Cardano protocol parameters.

func DeclaredExUnits added in v0.22.0

func DeclaredExUnits(
	tx lcommon.Transaction,
) (lcommon.ExUnits, error)

DeclaredExUnits returns the total execution units declared across all redeemers in a transaction's witness set. Returns an error if the summation would overflow int64.

func EraForVersion added in v0.22.0

func EraForVersion(majorVersion uint) (uint, bool)

EraForVersion returns the era ID for a given protocol major version using the ProtocolMajorVersionToEra map in ledger/eras/. Returns false if the version is not mapped.

func GenesisBlockHash added in v0.22.0

func GenesisBlockHash(cfg *cardano.CardanoNodeConfig) ([32]byte, error)

GenesisBlockHash returns the Byron genesis hash from config, which is used as the block hash for the synthetic genesis block that holds genesis UTxO data. This mirrors how the Shelley epoch nonce uses the Shelley genesis hash.

func IsCommitteeThresholdMet added in v0.22.0

func IsCommitteeThresholdMet(
	yesVotes int,
	totalActiveMembers int,
	thresholdNumerator uint64,
	thresholdDenominator uint64,
) bool

IsCommitteeThresholdMet checks whether a committee vote threshold is met. Returns true if yesVotes / totalActiveMembers >= threshold.

Edge cases per CIP-1694:

  • If yesVotes or totalActiveMembers is negative, returns false
  • If totalActiveMembers is 0, the threshold is trivially met (no committee means no committee can block)
  • If threshold numerator is 0, any vote count satisfies it
  • If threshold denominator is 0, this is treated as an error condition and returns false

func IsCompatibleEra added in v0.22.0

func IsCompatibleEra(txEraId, ledgerEraId uint) bool

IsCompatibleEra checks if a transaction era is valid for the current ledger era. Cardano allows transactions from the current era and (current era - 1).

func IsHardForkTransition added in v0.22.0

func IsHardForkTransition(
	oldVersion, newVersion ProtocolVersion,
) bool

IsHardForkTransition returns true if the new protocol version triggers an era change compared to the old version.

func ProcessGovernanceProposals added in v0.22.0

func ProcessGovernanceProposals(
	tx lcommon.Transaction,
	point ocommon.Point,
	currentEpoch uint64,
	govActionLifetime uint64,
	db *database.Database,
	txn *database.Txn,
) error

ProcessGovernanceProposals extracts governance proposals from a Conway-era transaction and persists them to the database. Each proposal procedure in the transaction body is mapped to a GovernanceProposal model with the appropriate action type, parent action, anchor, and deposit information.

The govActionLifetime parameter determines how many epochs a proposal remains active before expiring.

func ProcessGovernanceVotes added in v0.22.0

func ProcessGovernanceVotes(
	tx lcommon.Transaction,
	point ocommon.Point,
	currentEpoch uint64,
	drepInactivityPeriod uint64,
	db *database.Database,
	txn *database.Txn,
) error

ProcessGovernanceVotes extracts voting procedures from a Conway-era transaction and persists them to the database. Each vote maps a voter (CC member, DRep, or SPO) and a governance action to a vote choice.

When a DRep votes, their activity epoch is updated to the current epoch, which resets their expiry countdown based on the dRepInactivityPeriod.

func TxBodySize added in v0.22.0

func TxBodySize(tx lcommon.Transaction) uint64

TxBodySize is a deprecated alias for TxSizeForFee.

func TxSizeForFee added in v0.22.0

func TxSizeForFee(tx lcommon.Transaction) uint64

TxSizeForFee computes the transaction size used in the Cardano fee formula. See eras.TxSizeForFee.

func ValidateTxEra added in v0.22.0

func ValidateTxEra(
	tx lcommon.Transaction,
	ledgerEraId uint,
) error

ValidateTxEra checks that a transaction's era is compatible with the current ledger era. Returns an error if the transaction era is not the current era or the immediately previous era.

func ValidateTxExUnits added in v0.22.0

func ValidateTxExUnits(
	totalExUnits lcommon.ExUnits,
	maxTxExUnits lcommon.ExUnits,
) error

ValidateTxExUnits checks that total execution units do not exceed the protocol parameter per-transaction limits.

func ValidateTxFee added in v0.22.0

func ValidateTxFee(
	tx lcommon.Transaction,
	minFeeA uint,
	minFeeB uint,
	pricesMem *big.Rat,
	pricesSteps *big.Rat,
) error

ValidateTxFee checks that the fee declared in the transaction body is at least the calculated minimum fee, including both the base fee component and the script execution fee component.

func ValidateTxSize added in v0.22.0

func ValidateTxSize(
	tx lcommon.Transaction,
	maxTxSize uint,
) error

ValidateTxSize checks that the transaction size does not exceed the protocol parameter maximum.

Types

type BlockAction added in v0.22.0

type BlockAction string

It represents the direction a block is applied to the ledger.

const (
	BlockActionApply BlockAction = "Apply"
	BlockActionUndo  BlockAction = "Undo"
)

type BlockEvent added in v0.22.0

type BlockEvent struct {
	Action BlockAction
	Block  models.Block
	Point  ocommon.Point
}

It represents a persisted block apply or rollback action.

type BlockfetchEvent

type BlockfetchEvent struct {
	ConnectionId ouroboros.ConnectionId // Connection ID associated with event
	Block        ledger.Block
	Point        ocommon.Point // Chain point for block
	Type         uint          // Block type ID
	BatchDone    bool          // Set to true for a BatchDone event
}

BlockfetchEvent represents either a Block or BatchDone blockfetch event. We use a single event type for both to make synchronization easier.

type BlockfetchRequestRangeFunc

type BlockfetchRequestRangeFunc func(ouroboros.ConnectionId, ocommon.Point, ocommon.Point) error

BlockfetchRequestRangeFunc describes a callback function used to start a blockfetch request for a range of blocks

type ChainsyncEvent

type ChainsyncEvent struct {
	ConnectionId ouroboros.ConnectionId // Connection ID associated with event
	BlockHeader  ledger.BlockHeader
	Point        ocommon.Point  // Chain point for roll forward/backward
	Tip          ochainsync.Tip // Upstream chain tip
	BlockNumber  uint64
	Type         uint // Block or header type ID
	Rollback     bool // Set to true for a Rollback event
}

ChainsyncEvent represents either a RollForward or RollBackward chainsync event. We use a single event type for both to make synchronization easier.

type ChainsyncState added in v0.12.0

type ChainsyncState string
const (
	InitChainsyncState     ChainsyncState = "init"
	RollbackChainsyncState ChainsyncState = "rollback"
	SyncingChainsyncState  ChainsyncState = "syncing"
)

type ConnectionSwitchFunc added in v0.22.0

type ConnectionSwitchFunc func()

ConnectionSwitchFunc is called when the active chainsync connection changes. Implementations should clear any per-connection state such as the header dedup cache so the new connection can re-deliver blocks.

type DatabaseOperation added in v0.19.0

type DatabaseOperation struct {
	// Operation function that performs the database work
	OpFunc func(db *database.Database) error
	// Channel to send the result back. Must be non-nil and buffered to avoid blocking.
	// If nil, the operation will be executed but the result will be discarded (fire and forget).
	ResultChan chan<- DatabaseResult
}

DatabaseOperation represents an asynchronous database operation

type DatabaseResult added in v0.19.0

type DatabaseResult struct {
	Error error
}

DatabaseResult represents the result of a database operation

type DatabaseWorkerPool added in v0.19.0

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

DatabaseWorkerPool manages a pool of workers for async database operations

func NewDatabaseWorkerPool added in v0.19.0

func NewDatabaseWorkerPool(
	db *database.Database,
	config DatabaseWorkerPoolConfig,
) *DatabaseWorkerPool

NewDatabaseWorkerPool creates a new database worker pool

func (*DatabaseWorkerPool) Shutdown added in v0.19.0

func (p *DatabaseWorkerPool) Shutdown()

Shutdown gracefully shuts down the worker pool

func (*DatabaseWorkerPool) Submit added in v0.19.0

func (p *DatabaseWorkerPool) Submit(op DatabaseOperation)

Submit submits a database operation for async execution

type DatabaseWorkerPoolConfig added in v0.19.0

type DatabaseWorkerPoolConfig struct {
	WorkerPoolSize int
	TaskQueueSize  int
	Disabled       bool
}

DatabaseWorkerPoolConfig holds configuration for the database worker pool

func DefaultDatabaseWorkerPoolConfig added in v0.19.0

func DefaultDatabaseWorkerPoolConfig() DatabaseWorkerPoolConfig

DefaultDatabaseWorkerPoolConfig returns the default configuration for the database worker pool

type EpochInfo added in v0.22.0

type EpochInfo struct {
	EpochId       uint64
	StartSlot     uint64
	LengthInSlots uint
}

EpochInfo contains epoch boundary information

func (EpochInfo) EndSlot added in v0.22.0

func (e EpochInfo) EndSlot() uint64

EndSlot returns the first slot of the next epoch (one past the last slot of this epoch)

type EpochRolloverResult added in v0.21.0

type EpochRolloverResult struct {
	NewEpochCache             []models.Epoch
	NewCurrentEpoch           models.Epoch
	NewCurrentEra             eras.EraDesc
	NewCurrentPParams         lcommon.ProtocolParameters
	NewEpochNum               float64
	CheckpointWrittenForEpoch bool
	SchedulerIntervalMs       uint
	// HardFork is non-nil when a protocol version change
	// in the updated pparams triggers an era transition.
	HardFork *HardForkInfo
}

EpochRolloverResult holds computed state from epoch rollover

type EraTransitionResult added in v0.21.0

type EraTransitionResult struct {
	NewPParams lcommon.ProtocolParameters
	NewEra     eras.EraDesc
}

EraTransitionResult holds computed state from an era transition

type FatalErrorFunc added in v0.21.0

type FatalErrorFunc func(err error)

FatalErrorFunc is a callback invoked when a fatal error occurs that requires the node to shut down. The callback should trigger graceful shutdown.

type ForgedBlockChecker added in v0.22.0

type ForgedBlockChecker interface {
	// WasForgedByUs returns the block hash and true if the local node
	// forged a block for the given slot, or nil and false otherwise.
	WasForgedByUs(slot uint64) (blockHash []byte, ok bool)
}

ForgedBlockChecker is an interface for checking whether the local node recently forged a block for a given slot. This is used by chainsync to detect slot battles when an incoming block from a peer occupies the same slot as a locally forged block.

type GetActiveConnectionFunc added in v0.21.0

type GetActiveConnectionFunc func() *ouroboros.ConnectionId

GetActiveConnectionFunc is a callback to retrieve the currently active chainsync connection ID for chain selection purposes.

type HardForkInfo added in v0.22.0

type HardForkInfo struct {
	OldVersion ProtocolVersion
	NewVersion ProtocolVersion
	FromEra    uint
	ToEra      uint
}

HardForkInfo holds details about a detected hard fork transition, populated when a protocol parameter update at an epoch boundary changes the protocol major version into a new era.

type LedgerDelta added in v0.7.0

type LedgerDelta struct {
	Point        ocommon.Point
	BlockEraId   uint
	BlockNumber  uint64
	Transactions []TransactionRecord
	Offsets      *database.BlockIngestionResult // pre-computed CBOR offsets for this block
	// contains filtered or unexported fields
}

func NewLedgerDelta added in v0.18.0

func NewLedgerDelta(
	point ocommon.Point,
	blockEraId uint,
	blockNumber uint64,
) *LedgerDelta

func (*LedgerDelta) Release added in v0.18.0

func (d *LedgerDelta) Release()

type LedgerDeltaBatch added in v0.8.0

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

func NewLedgerDeltaBatch added in v0.18.0

func NewLedgerDeltaBatch() *LedgerDeltaBatch

func (*LedgerDeltaBatch) Release added in v0.18.0

func (b *LedgerDeltaBatch) Release()

type LedgerErrorEvent added in v0.21.0

type LedgerErrorEvent struct {
	Error     error         // The actual error that occurred
	Operation string        // The operation that failed (e.g., "block_header", "rollback")
	Point     ocommon.Point // Chain point where the error occurred, if applicable
}

LedgerErrorEvent represents an error that occurred during ledger processing.

type LedgerPeerProviderAdapter added in v0.21.0

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

LedgerPeerProviderAdapter implements peergov.LedgerPeerProvider using the ledger state and database to discover stake pool relays.

func NewLedgerPeerProvider added in v0.21.0

func NewLedgerPeerProvider(
	ledgerState *LedgerState,
	db *database.Database,
	eventBus *event.EventBus,
) (*LedgerPeerProviderAdapter, error)

NewLedgerPeerProvider creates a new LedgerPeerProvider adapter. Returns an error if ledgerState or db is nil.

func (*LedgerPeerProviderAdapter) CurrentSlot added in v0.21.0

func (p *LedgerPeerProviderAdapter) CurrentSlot() uint64

CurrentSlot returns the current chain tip slot number.

func (*LedgerPeerProviderAdapter) GetPoolRelays added in v0.21.0

func (p *LedgerPeerProviderAdapter) GetPoolRelays() (
	[]peergov.PoolRelay,
	error,
)

GetPoolRelays returns all active pool relays from the ledger.

func (*LedgerPeerProviderAdapter) InvalidateCache added in v0.22.0

func (p *LedgerPeerProviderAdapter) InvalidateCache()

InvalidateCache clears the cached pool relays, forcing the next GetPoolRelays call to fetch fresh data from the database.

type LedgerState

type LedgerState struct {
	Scheduler *Scheduler

	sync.RWMutex
	// contains filtered or unexported fields
}

func NewLedgerState

func NewLedgerState(cfg LedgerStateConfig) (*LedgerState, error)

func (*LedgerState) ActiveSlotCoeff added in v0.22.0

func (ls *LedgerState) ActiveSlotCoeff() float64

ActiveSlotCoeff returns the active slot coefficient (f parameter). This is used in the Ouroboros Praos leader election probability.

func (*LedgerState) BlockByHash added in v0.21.0

func (ls *LedgerState) BlockByHash(hash []byte) (models.Block, error)

BlockByHash returns a block by its hash.

func (*LedgerState) CardanoNodeConfig added in v0.21.0

func (ls *LedgerState) CardanoNodeConfig() *cardano.CardanoNodeConfig

CardanoNodeConfig returns the Cardano node configuration used for this ledger state.

func (*LedgerState) Chain

func (ls *LedgerState) Chain() *chain.Chain

func (*LedgerState) ChainTipSlot added in v0.22.0

func (ls *LedgerState) ChainTipSlot() uint64

ChainTipSlot returns the slot number of the current chain tip.

func (*LedgerState) Close

func (ls *LedgerState) Close() error

func (*LedgerState) CurrentEpoch added in v0.22.0

func (ls *LedgerState) CurrentEpoch() uint64

CurrentEpoch returns the current epoch number.

func (*LedgerState) CurrentSlot added in v0.22.0

func (ls *LedgerState) CurrentSlot() (uint64, error)

CurrentSlot returns the current slot number based on wall-clock time. Delegates to the internal slot clock.

func (*LedgerState) Database added in v0.22.0

func (ls *LedgerState) Database() *database.Database

Database returns the underlying database for transaction operations.

func (*LedgerState) Datum added in v0.18.0

func (ls *LedgerState) Datum(hash []byte) (*models.Datum, error)

Datum looks up a datum by hash & adding this for implementing query.ReadData #741

func (*LedgerState) EpochNonce added in v0.22.0

func (ls *LedgerState) EpochNonce(epoch uint64) []byte

EpochNonce returns the nonce for the given epoch. The epoch nonce is used for VRF-based leader election. Returns nil if the epoch nonce is not available (e.g., for Byron era).

When the slot clock fires an epoch transition before block processing crosses the boundary, the nonce for the next epoch (currentEpoch+1) is computed speculatively from the current epoch's data. This eliminates the forging gap at epoch boundaries where the leader schedule would otherwise be unavailable until a peer's block triggers epoch rollover.

func (*LedgerState) EvaluateTx added in v0.16.0

EvaluateTx evaluates the scripts in the provided transaction and returns the calculated fee, per-redeemer ExUnits, and total ExUnits

func (*LedgerState) GetBlock

func (ls *LedgerState) GetBlock(point ocommon.Point) (models.Block, error)

func (*LedgerState) GetChainFromPoint

func (ls *LedgerState) GetChainFromPoint(
	point ocommon.Point,
	inclusive bool,
) (*chain.ChainIterator, error)

GetChainFromPoint returns a ChainIterator starting at the specified point. If inclusive is true, the iterator will start at the requested point, otherwise it will start at the next block.

func (*LedgerState) GetCurrentPParams

func (ls *LedgerState) GetCurrentPParams() lcommon.ProtocolParameters

GetCurrentPParams returns the currentPParams value

func (*LedgerState) GetEpochs added in v0.21.0

func (ls *LedgerState) GetEpochs() ([]models.Epoch, error)

It returns all epochs stored in the database.

func (*LedgerState) GetIntersectPoint

func (ls *LedgerState) GetIntersectPoint(
	points []ocommon.Point,
) (*ocommon.Point, error)

GetIntersectPoint returns the intersect between the specified points and the current chain

func (*LedgerState) GetPParamsForEpoch added in v0.21.0

func (ls *LedgerState) GetPParamsForEpoch(
	epoch uint64,
	era eras.EraDesc,
) (lcommon.ProtocolParameters, error)

It returns protocol parameters for the specific epoch.

func (*LedgerState) GetTransactionsByAddress added in v0.22.0

func (ls *LedgerState) GetTransactionsByAddress(
	addr lcommon.Address,
	limit int,
	offset int,
) ([]models.Transaction, error)

GetTransactionsByAddress returns transactions involving the given address.

func (*LedgerState) GetTransactionsByBlockHash added in v0.22.0

func (ls *LedgerState) GetTransactionsByBlockHash(
	blockHash []byte,
) ([]models.Transaction, error)

GetTransactionsByBlockHash returns all transactions for a given block hash.

func (*LedgerState) IsAtTip added in v0.25.1

func (ls *LedgerState) IsAtTip() bool

IsAtTip reports whether the node has caught up to the chain tip at least once since boot. This is used to gate metrics that are only meaningful when processing live blocks (e.g., block delay CDF). Unlike validationEnabled (which starts true when ValidateHistorical is set), reachedTip only flips when the node actually reaches the stability window.

func (*LedgerState) NewView added in v0.22.0

func (ls *LedgerState) NewView(txn *database.Txn) *LedgerView

NewView creates a new LedgerView for querying ledger state within a transaction.

func (*LedgerState) NextSlotTime added in v0.22.0

func (ls *LedgerState) NextSlotTime() (time.Time, error)

NextSlotTime returns the wall-clock time when the next slot begins.

func (*LedgerState) ProcessTrustedBlockBatches added in v0.25.0

func (ls *LedgerState) ProcessTrustedBlockBatches(
	ctx context.Context,
	batches <-chan []ledger.Block,
) error

ProcessTrustedBlockBatches processes already-decoded trusted block batches synchronously. This is used by immutable load so blocks can be replayed directly without first being reread from the chain store.

func (*LedgerState) Query

func (ls *LedgerState) Query(query any) (any, error)

func (*LedgerState) RecentChainPoints

func (ls *LedgerState) RecentChainPoints(
	count int,
) ([]ocommon.Point, error)

RecentChainPoints returns the requested count of recent chain points in descending order. This is used mostly for building a set of intersect points when acting as a chainsync client.

Points are first collected from the in-memory chain state, which is always up-to-date even when the blob store has not yet flushed recent writes. Database points are then appended to fill the requested count, with duplicates removed.

func (*LedgerState) RecoverCommitTimestampConflict added in v0.11.0

func (ls *LedgerState) RecoverCommitTimestampConflict() error

func (*LedgerState) SecurityParam added in v0.20.0

func (ls *LedgerState) SecurityParam() int

SecurityParam returns the security parameter for the current era

func (*LedgerState) SetForgedBlockChecker added in v0.22.0

func (ls *LedgerState) SetForgedBlockChecker(checker ForgedBlockChecker)

SetForgedBlockChecker sets the forged block checker used for slot battle detection. This is typically called after the block forger is initialized, since the forger is created after the ledger state.

func (*LedgerState) SetForgingEnabled added in v0.22.0

func (ls *LedgerState) SetForgingEnabled(enabled bool)

SetForgingEnabled sets the forging_enabled metric gauge. Call with true after the block forger has been initialised successfully.

func (*LedgerState) SetMempool added in v0.14.0

func (ls *LedgerState) SetMempool(mempool MempoolProvider)

Sets the mempool for accessing transactions

func (*LedgerState) SetSlotBattleRecorder added in v0.22.0

func (ls *LedgerState) SetSlotBattleRecorder(
	recorder SlotBattleRecorder,
)

SetSlotBattleRecorder sets the recorder used to increment the slot battle metric. This is typically called after the block forger is initialized.

func (*LedgerState) SlotToEpoch added in v0.6.0

func (ls *LedgerState) SlotToEpoch(slot uint64) (models.Epoch, error)

SlotToEpoch returns an epoch by slot number. For slots within known epochs, returns the exact epoch. For slots beyond known epochs, projects forward using the last known epoch's parameters (epoch length, slot length) to calculate the future epoch.

func (*LedgerState) SlotToTime added in v0.6.0

func (ls *LedgerState) SlotToTime(slot uint64) (time.Time, error)

SlotToTime returns the current time for a given slot based on known epochs

func (*LedgerState) SlotsPerEpoch added in v0.22.0

func (ls *LedgerState) SlotsPerEpoch() uint64

SlotsPerEpoch returns the number of slots in an epoch for the current era.

func (*LedgerState) SlotsPerKESPeriod added in v0.22.0

func (ls *LedgerState) SlotsPerKESPeriod() uint64

SlotsPerKESPeriod returns the number of slots in a KES period.

func (*LedgerState) Start added in v0.11.0

func (ls *LedgerState) Start(ctx context.Context) error

func (*LedgerState) SubmitAsyncDBOperation added in v0.19.0

func (ls *LedgerState) SubmitAsyncDBOperation(
	opFunc func(db *database.Database) error,
) error

SubmitAsyncDBOperation submits a database operation for execution on the worker pool. This method blocks waiting for the result and must be called after Start() and before Close(). If the worker pool is disabled, it falls back to synchronous execution.

func (*LedgerState) SubmitAsyncDBReadTxn added in v0.19.0

func (ls *LedgerState) SubmitAsyncDBReadTxn(
	opFunc func(txn *database.Txn) error,
) error

SubmitAsyncDBReadTxn submits a read-only database transaction operation for execution on the worker pool. This method blocks waiting for the result and must be called after Start() and before Close().

func (*LedgerState) SubmitAsyncDBTxn added in v0.19.0

func (ls *LedgerState) SubmitAsyncDBTxn(
	opFunc func(txn *database.Txn) error,
	readWrite bool,
) error

SubmitAsyncDBTxn submits a database transaction operation for execution on the worker pool. This method blocks waiting for the result and must be called after Start() and before Close(). If a partial commit occurs (blob committed but metadata failed), this method will attempt to trigger database recovery to restore consistency.

func (*LedgerState) SyncProgress added in v0.22.0

func (ls *LedgerState) SyncProgress() float64

SyncProgress returns the current sync progress as a value between 0.0 (unknown/just started) and 1.0 (fully synced). This implements the peergov.SyncProgressProvider interface, allowing the peer governor to exit bootstrap mode once sync reaches its threshold.

func (*LedgerState) SystemStart added in v0.21.0

func (ls *LedgerState) SystemStart() (time.Time, error)

It returns the system start timestamp from the Shelley genesis.

func (*LedgerState) TimeToSlot added in v0.6.0

func (ls *LedgerState) TimeToSlot(t time.Time) (uint64, error)

TimeToSlot returns the slot number for a given time based on known epochs

func (*LedgerState) Tip

func (ls *LedgerState) Tip() ochainsync.Tip

Tip returns the current chain tip

func (*LedgerState) TransactionByHash added in v0.21.0

func (ls *LedgerState) TransactionByHash(
	hash []byte,
) (*models.Transaction, error)

TransactionByHash returns a transaction record by its hash.

func (*LedgerState) UpstreamTipSlot added in v0.22.0

func (ls *LedgerState) UpstreamTipSlot() uint64

UpstreamTipSlot returns the latest known tip slot from upstream peers. Returns 0 if no upstream tip is known yet.

func (*LedgerState) UtxoByRef

func (ls *LedgerState) UtxoByRef(
	txId []byte,
	outputIdx uint32,
) (*models.Utxo, error)

UtxoByRef returns a single UTxO by reference

func (*LedgerState) UtxoByRefIncludingSpent added in v0.22.0

func (ls *LedgerState) UtxoByRefIncludingSpent(
	txId []byte,
	outputIdx uint32,
) (*models.Utxo, error)

UtxoByRefIncludingSpent returns a UTxO by reference, including spent outputs. This is needed for APIs that must resolve consumed inputs to display source address and amount.

func (*LedgerState) UtxosByAddress

func (ls *LedgerState) UtxosByAddress(
	addr ledger.Address,
) ([]models.Utxo, error)

UtxosByAddress returns all UTxOs that belong to the specified address

func (*LedgerState) UtxosByAddressAtSlot added in v0.22.0

func (ls *LedgerState) UtxosByAddressAtSlot(
	addr lcommon.Address,
	slot uint64,
) ([]models.Utxo, error)

UtxosByAddressAtSlot returns all UTxOs belonging to the specified address that existed at the given slot.

func (*LedgerState) ValidateTx

func (ls *LedgerState) ValidateTx(
	tx lcommon.Transaction,
) error

ValidateTx runs ledger validation on the provided transaction. It accepts transactions from the current era and the immediately previous era (era-1), as Cardano allows during the overlap period after a hard fork.

func (*LedgerState) ValidateTxWithOverlay added in v0.23.0

func (ls *LedgerState) ValidateTxWithOverlay(
	tx lcommon.Transaction,
	consumedUtxos map[string]struct{},
	createdUtxos map[string]lcommon.Utxo,
) error

ValidateTxWithOverlay runs ledger validation with a UTxO overlay from pending mempool transactions. consumedUtxos contains inputs already spent by pending TXs (double-spend check), createdUtxos contains outputs created by pending TXs (dependent TX chaining). Both may be nil for no overlay.

type LedgerStateConfig

type LedgerStateConfig struct {
	PromRegistry               prometheus.Registerer
	Logger                     *slog.Logger
	Database                   *database.Database
	ChainManager               *chain.ChainManager
	EventBus                   *event.EventBus
	CardanoNodeConfig          *cardano.CardanoNodeConfig
	BlockfetchRequestRangeFunc BlockfetchRequestRangeFunc
	GetActiveConnectionFunc    GetActiveConnectionFunc
	ConnectionSwitchFunc       ConnectionSwitchFunc
	FatalErrorFunc             FatalErrorFunc
	ForgedBlockChecker         ForgedBlockChecker
	SlotBattleRecorder         SlotBattleRecorder
	ValidateHistorical         bool
	TrustedReplay              bool
	ManualBlockProcessing      bool
	ForgeBlocks                bool
	DatabaseWorkerPoolConfig   DatabaseWorkerPoolConfig
}

type LedgerView

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

func (*LedgerView) CalculateRewards added in v0.18.0

func (lv *LedgerView) CalculateRewards(
	adaPots lcommon.AdaPots,
	rewardSnapshot lcommon.RewardSnapshot,
	rewardParams lcommon.RewardParameters,
) (*lcommon.RewardCalculationResult, error)

CalculateRewards calculates rewards for the given stake keys. TODO: implement reward calculation. Requires reward formulas from the Cardano Shelley formal specification and integration with stake snapshots.

func (*LedgerView) CommitteeMember added in v0.21.0

func (lv *LedgerView) CommitteeMember(
	coldKey lcommon.Blake2b224,
) (*lcommon.CommitteeMember, error)

CommitteeMember returns a committee member by cold key. Returns nil if the cold key is not an authorized committee member.

func (*LedgerView) CommitteeMembers added in v0.21.0

func (lv *LedgerView) CommitteeMembers() ([]lcommon.CommitteeMember, error)

CommitteeMembers returns all active (non-resigned) committee members.

func (*LedgerView) Constitution added in v0.21.0

func (lv *LedgerView) Constitution() (*lcommon.Constitution, error)

Constitution returns the current constitution. Returns nil if no constitution has been established on-chain.

func (*LedgerView) CostModels added in v0.21.0

func (lv *LedgerView) CostModels() map[lcommon.PlutusLanguage]lcommon.CostModel

CostModels returns which Plutus language versions have cost models defined in the current protocol parameters.

NOTE: lcommon.CostModel is currently struct{} in gouroboros (a placeholder type). The returned map values carry no cost parameter data -- callers use map membership to check version availability. When gouroboros extends CostModel with real fields, this function should be updated to populate them from the raw []int64 cost parameters.

Map keys use PlutusLanguage encoding: PlutusV1=1, PlutusV2=2, PlutusV3=3, corresponding to cost model map keys 0, 1, 2.

func (*LedgerView) DRepRegistration added in v0.21.0

func (lv *LedgerView) DRepRegistration(
	credential lcommon.Blake2b224,
) (*lcommon.DRepRegistration, error)

DRepRegistration returns a DRep registration by credential. Returns nil if the credential is not registered as an active DRep.

func (*LedgerView) DRepRegistrations added in v0.21.0

func (lv *LedgerView) DRepRegistrations() ([]lcommon.DRepRegistration, error)

DRepRegistrations returns all active DRep registrations.

func (*LedgerView) GetAdaPots added in v0.18.0

func (lv *LedgerView) GetAdaPots() lcommon.AdaPots

GetAdaPots returns the current Ada pots. TODO: implement Ada pots retrieval. Requires tracking of treasury, reserves, fees, and rewards pots which are not yet stored in the database.

func (*LedgerView) GetCommitteeActiveCount added in v0.22.0

func (lv *LedgerView) GetCommitteeActiveCount() (int, error)

GetCommitteeActiveCount returns the number of active (non-resigned) committee members.

func (*LedgerView) GetDRepVotingPower added in v0.22.0

func (lv *LedgerView) GetDRepVotingPower(
	drepCredential []byte,
) (uint64, error)

GetDRepVotingPower returns the voting power for a DRep by summing the stake of all accounts delegated to it. Uses the current live UTxO set.

TODO: Accept an epoch parameter and use epoch-based stake snapshots for accurate voting power. The current implementation approximates voting power using the live UTxO set.

func (*LedgerView) GetExpiredDReps added in v0.22.0

func (lv *LedgerView) GetExpiredDReps(
	epoch uint64,
) ([]*models.Drep, error)

GetExpiredDReps returns all active DReps whose expiry epoch is at or before the given epoch.

func (*LedgerView) GetPoolStake added in v0.22.0

func (lv *LedgerView) GetPoolStake(
	epoch uint64,
	poolKeyHash []byte,
) (uint64, error)

GetPoolStake returns the stake for a specific pool from the snapshot. Returns 0 if the pool has no stake in the snapshot. Callers pass currentEpoch-2 so the epoch offset accounts for Mark→Set→Go rotation.

func (*LedgerView) GetRewardSnapshot added in v0.18.0

func (lv *LedgerView) GetRewardSnapshot(
	epoch uint64,
) (lcommon.RewardSnapshot, error)

GetRewardSnapshot returns the current reward snapshot. TODO: implement reward snapshot retrieval. Requires per-stake-credential reward tracking which is not yet stored in the database.

func (*LedgerView) GetStakeDistribution added in v0.22.0

func (lv *LedgerView) GetStakeDistribution(
	epoch uint64,
) (*StakeDistribution, error)

GetStakeDistribution returns the stake distribution for leader election. Uses the "mark" snapshot at the given epoch. Callers pass currentEpoch-2 so the epoch offset already accounts for the Mark→Set→Go rotation.

func (*LedgerView) GetTotalActiveStake added in v0.22.0

func (lv *LedgerView) GetTotalActiveStake(epoch uint64) (uint64, error)

GetTotalActiveStake returns the total active stake from the snapshot. Callers pass currentEpoch-2 so the epoch offset accounts for rotation.

func (*LedgerView) GovActionById added in v0.21.0

func (lv *LedgerView) GovActionById(
	id lcommon.GovActionId,
) (*lcommon.GovActionState, error)

GovActionById returns a governance action by its ID. Returns nil if the governance action does not exist.

func (*LedgerView) GovActionExists added in v0.21.0

func (lv *LedgerView) GovActionExists(id lcommon.GovActionId) bool

GovActionExists returns whether a governance action exists.

func (*LedgerView) IsPoolRegistered added in v0.21.0

func (lv *LedgerView) IsPoolRegistered(pkh lcommon.PoolKeyHash) bool

IsPoolRegistered checks if a pool is currently registered

func (*LedgerView) IsRewardAccountRegistered added in v0.21.0

func (lv *LedgerView) IsRewardAccountRegistered(
	cred lcommon.Credential,
) bool

IsRewardAccountRegistered checks if a reward account is registered

func (*LedgerView) IsStakeCredentialRegistered added in v0.21.0

func (lv *LedgerView) IsStakeCredentialRegistered(
	cred lcommon.Credential,
) bool

IsStakeCredentialRegistered checks if a stake credential is currently registered

func (*LedgerView) IsVrfKeyInUse added in v0.22.0

func (lv *LedgerView) IsVrfKeyInUse(
	vrfKeyHash lcommon.Blake2b256,
) (bool, lcommon.PoolKeyHash, error)

IsVrfKeyInUse checks if a VRF key hash is registered by another pool. Returns (inUse, owningPoolId, error).

func (*LedgerView) NetworkId

func (lv *LedgerView) NetworkId() uint

func (*LedgerView) PoolCurrentState added in v0.17.0

func (lv *LedgerView) PoolCurrentState(
	pkh lcommon.PoolKeyHash,
) (*lcommon.PoolRegistrationCertificate, *uint64, error)

It returns the most recent active pool registration certificate and the epoch of any pending retirement for the given pool key hash.

func (*LedgerView) PoolRegistration

func (lv *LedgerView) PoolRegistration(
	pkh lcommon.PoolKeyHash,
) ([]lcommon.PoolRegistrationCertificate, error)

func (*LedgerView) RewardAccountBalance added in v0.21.0

func (lv *LedgerView) RewardAccountBalance(
	cred lcommon.Credential,
) (*uint64, error)

RewardAccountBalance returns the current reward balance for a stake credential. TODO: implement reward account balance retrieval. Requires per-account reward balance tracking which is not yet stored in the database.

func (*LedgerView) SlotToTime added in v0.17.0

func (lv *LedgerView) SlotToTime(slot uint64) (time.Time, error)

SlotToTime returns the current time for a given slot based on known epochs

func (*LedgerView) StakeRegistration

func (lv *LedgerView) StakeRegistration(
	stakingKey []byte,
) ([]lcommon.StakeRegistrationCertificate, error)

func (*LedgerView) TimeToSlot added in v0.17.0

func (lv *LedgerView) TimeToSlot(t time.Time) (uint64, error)

TimeToSlot returns the slot number for a given time based on known epochs

func (*LedgerView) TreasuryValue added in v0.21.0

func (lv *LedgerView) TreasuryValue() (uint64, error)

TreasuryValue returns the current treasury value. TODO: implement treasury value retrieval. Requires Ada pots tracking which is not yet stored in the database. The treasury value is part of the Ada pots (reserves, treasury, fees, rewards).

func (*LedgerView) UpdateAdaPots added in v0.18.0

func (lv *LedgerView) UpdateAdaPots(adaPots lcommon.AdaPots) error

UpdateAdaPots updates the Ada pots. TODO: implement Ada pots update. Requires Ada pots storage in the database.

func (*LedgerView) UtxoById

func (lv *LedgerView) UtxoById(
	utxoId lcommon.TransactionInput,
) (lcommon.Utxo, error)

type MempoolProvider added in v0.14.0

type MempoolProvider interface {
	Transactions() []mempool.MempoolTransaction
}

In ledger/state.go or a shared package

type PoolStateRestoredEvent added in v0.22.0

type PoolStateRestoredEvent struct {
	Slot uint64 // The slot to which pool state was restored
}

PoolStateRestoredEvent is emitted after pool state is restored during a rollback. Subscribers (like peer providers) can use this to invalidate cached pool data.

type ProtocolVersion added in v0.22.0

type ProtocolVersion struct {
	Major uint
	Minor uint
}

ProtocolVersion represents the major and minor protocol version numbers used in Cardano protocol parameters.

func GetProtocolVersion added in v0.22.0

func GetProtocolVersion(
	pparams lcommon.ProtocolParameters,
) (ProtocolVersion, error)

GetProtocolVersion extracts the protocol version from protocol parameters. This works across all eras by type- switching on the concrete pparams type. Returns an error if the pparams type is not recognized or nil.

type ScheduledTask added in v0.14.0

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

type Scheduler added in v0.14.0

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

func NewScheduler added in v0.14.0

func NewScheduler(interval time.Duration) *Scheduler

func NewSchedulerWithConfig added in v0.19.0

func NewSchedulerWithConfig(
	interval time.Duration,
	config SchedulerConfig,
) *Scheduler

func (*Scheduler) ChangeInterval added in v0.14.0

func (st *Scheduler) ChangeInterval(newInterval time.Duration) error

ChangeInterval updates the tick interval of the Scheduler at runtime. It returns an error if newInterval is not positive.

func (*Scheduler) Register added in v0.14.0

func (st *Scheduler) Register(
	interval int,
	taskFunc func(),
	runFailFunc func(),
)

Adds a new task to be scheduler

func (*Scheduler) Start added in v0.14.0

func (st *Scheduler) Start()

Start the timer (run goroutine once)

func (*Scheduler) Stop added in v0.14.0

func (st *Scheduler) Stop()

Stop the timer (terminates)

type SchedulerConfig added in v0.19.0

type SchedulerConfig struct {
	WorkerPoolSize int
	TaskQueueSize  int
}

func DefaultSchedulerConfig added in v0.19.0

func DefaultSchedulerConfig() SchedulerConfig

type SlotBattleRecorder added in v0.22.0

type SlotBattleRecorder interface {
	// RecordSlotBattle increments the slot battle counter.
	RecordSlotBattle()
}

SlotBattleRecorder records slot battle events for metrics.

type SlotClock added in v0.22.0

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

SlotClock provides slot-boundary-aware timing for the Cardano node. It ticks at each slot boundary and notifies subscribers, enabling time-based operations like epoch transitions and block production that don't depend on incoming blocks.

The SlotClock provides two categories of functionality:

  1. Query methods (CurrentSlot, CurrentEpoch, GetEpochForSlot, etc.) that work in all modes (catch up, load, synced) and can be called anytime.
  2. Tick notifications that fire at real-time slot boundaries, useful for leader election and proactive epoch detection when synced to tip.

func NewSlotClock added in v0.22.0

func NewSlotClock(
	provider SlotTimeProvider,
	config SlotClockConfig,
) *SlotClock

NewSlotClock creates a new SlotClock with the given provider and configuration

func (*SlotClock) CurrentEpoch added in v0.22.0

func (sc *SlotClock) CurrentEpoch() (EpochInfo, error)

CurrentEpoch returns the current epoch based on wall-clock time. This works regardless of sync state and can be called during catch up or load.

func (*SlotClock) CurrentSlot added in v0.22.0

func (sc *SlotClock) CurrentSlot() (uint64, error)

CurrentSlot returns the current slot number based on wall-clock time. This works regardless of sync state and can be called during catch up or load.

func (*SlotClock) GetEpochForSlot added in v0.22.0

func (sc *SlotClock) GetEpochForSlot(slot uint64) (EpochInfo, error)

GetEpochForSlot returns epoch information for the given slot. This works regardless of sync state and can be called during catch up or load.

func (*SlotClock) IsEpochBoundary added in v0.22.0

func (sc *SlotClock) IsEpochBoundary(slot uint64) (bool, error)

IsEpochBoundary returns true if the given slot is the first slot of an epoch.

func (*SlotClock) LastEmittedEpoch added in v0.22.0

func (sc *SlotClock) LastEmittedEpoch() uint64

LastEmittedEpoch returns the last epoch for which an event was emitted.

func (*SlotClock) MarkEpochEmitted added in v0.22.0

func (sc *SlotClock) MarkEpochEmitted(epoch uint64) bool

MarkEpochEmitted records that an epoch transition event was emitted for the given epoch. This is used to coordinate between slot-based and block-based epoch detection to avoid duplicate events. Returns true if this is a new epoch (not previously emitted), false if duplicate.

func (*SlotClock) NextSlotTime added in v0.22.0

func (sc *SlotClock) NextSlotTime() (time.Time, error)

NextSlotTime returns the time when the next slot will start

func (*SlotClock) SetLastEmittedEpoch added in v0.22.0

func (sc *SlotClock) SetLastEmittedEpoch(epoch uint64)

SetLastEmittedEpoch sets the last emitted epoch. Used during startup to initialize the tracker based on stored state.

func (*SlotClock) SlotToTime added in v0.22.0

func (sc *SlotClock) SlotToTime(slot uint64) (time.Time, error)

SlotToTime returns the time when the given slot starts. This works regardless of sync state and can be called during catch up or load.

func (*SlotClock) Start added in v0.22.0

func (sc *SlotClock) Start(ctx context.Context)

Start begins the slot clock ticking loop. The clock will emit SlotTick notifications at each slot boundary. Returns immediately; the tick loop runs in a goroutine.

func (*SlotClock) Stop added in v0.22.0

func (sc *SlotClock) Stop()

Stop halts the slot clock and waits for the tick loop to exit. All subscriber channels will be closed, causing any goroutines blocked on receiving from them to exit cleanly.

func (*SlotClock) Subscribe added in v0.22.0

func (sc *SlotClock) Subscribe() <-chan SlotTick

Subscribe returns a channel that will receive SlotTick notifications. The channel is buffered to prevent blocking the clock loop. Call Unsubscribe to stop receiving notifications and close the channel.

func (*SlotClock) TimeUntilNextEpoch added in v0.22.0

func (sc *SlotClock) TimeUntilNextEpoch() (time.Duration, error)

TimeUntilNextEpoch returns the duration until the next epoch boundary. This works regardless of sync state and can be called during catch up or load.

func (*SlotClock) TimeUntilSlot added in v0.22.0

func (sc *SlotClock) TimeUntilSlot(slot uint64) (time.Duration, error)

TimeUntilSlot returns the duration until the given slot starts. Returns negative duration if the slot is in the past.

func (*SlotClock) Unsubscribe added in v0.22.0

func (sc *SlotClock) Unsubscribe(ch <-chan SlotTick)

Unsubscribe removes a subscriber channel from the notification list. The channel will be closed after this call.

type SlotClockConfig added in v0.22.0

type SlotClockConfig struct {
	// Logger for slot clock events
	Logger *slog.Logger
	// ClockTolerance is the maximum drift allowed when waking at slot boundaries.
	// If we wake up more than this much after the slot boundary, we log a warning.
	// Default: 100ms
	ClockTolerance time.Duration
}

SlotClockConfig holds configuration for the SlotClock

func DefaultSlotClockConfig added in v0.22.0

func DefaultSlotClockConfig() SlotClockConfig

DefaultSlotClockConfig returns the default configuration

type SlotTick added in v0.22.0

type SlotTick struct {
	// Slot is the current slot number
	Slot uint64
	// SlotStart is the time when this slot started
	SlotStart time.Time
	// Epoch is the current epoch number
	Epoch uint64
	// EpochSlot is the slot number within the current epoch (0-indexed)
	EpochSlot uint64
	// IsEpochStart indicates whether this is the first slot of a new epoch
	IsEpochStart bool
	// SlotsUntilEpoch is the number of slots until the next epoch boundary
	SlotsUntilEpoch uint64
}

SlotTick represents a notification that a slot boundary has been reached

type SlotTimeProvider added in v0.22.0

type SlotTimeProvider interface {
	SlotToTime(slot uint64) (time.Time, error)
	TimeToSlot(t time.Time) (uint64, error)
	SlotToEpoch(slot uint64) (EpochInfo, error)
}

SlotTimeProvider defines the interface for slot/time conversion This allows testing with mock time

type StakeDistribution added in v0.22.0

type StakeDistribution struct {
	Epoch      uint64            // Epoch this snapshot is for
	PoolStakes map[string]uint64 // poolKeyHash (hex) -> total stake
	TotalStake uint64            // Sum of all pool stakes
}

StakeDistribution represents the stake distribution at an epoch boundary. Used for leader election in Ouroboros Praos.

type TransactionEvent added in v0.22.0

type TransactionEvent struct {
	Transaction ledger.Transaction
	Point       ocommon.Point
	BlockNumber uint64
	TxIndex     uint32
	Rollback    bool
}

TransactionEvent is emitted when a transaction is applied or rolled back. Check the Rollback field to determine direction.

type TransactionRecord added in v0.18.0

type TransactionRecord struct {
	Tx    lcommon.Transaction
	Index int
}

Directories

Path Synopsis
Package forging contains types and utilities for block production.
Package forging contains types and utilities for block production.
Package leader provides Ouroboros Praos leader election functionality for block production.
Package leader provides Ouroboros Praos leader election functionality for block production.
Package snapshot provides stake snapshot management for Ouroboros Praos leader election.
Package snapshot provides stake snapshot management for Ouroboros Praos leader election.

Jump to

Keyboard shortcuts

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