Documentation
¶
Overview ¶
Package ledger owns Dingo's consensus-critical state: the UTxO set, protocol parameters, stake distribution, certificates, governance actions, epoch/nonce bookkeeping, and Plutus script execution. It is the authority on whether a block or transaction is valid under the active era's rules.
LedgerState is the top-level type. It is created by the node at startup, wired to the database and event bus, and consulted by the mempool, the ouroboros handlers, and the block forger.
Rollback and state restoration ¶
When the primary chain rolls back to an earlier point, LedgerState replays state restoration against the metadata store. State restoration logic is implemented by the selected metadata backend (RestoreAccountStateAtSlot, RestorePoolStateAtSlot, RestoreDrepStateAtSlot, DeleteCertificatesAfterSlot). This package orchestrates the calls in the correct order and emits TransactionEvent with Rollback=true for each undone transaction so downstream consumers can undo their own derived state.
Epoch nonces (Ouroboros Praos) ¶
Epoch nonce computation differs between TPraos (Shelley–Alonzo) and Praos (Babbage–Conway). The per-era formulas live in ledger/eras/, and CalculateEtaVConway / CalculateEtaVBabbage apply the Praos "N"-prefixed VRF domain separation before accumulating into the rolling nonce. The stability window for nonce freezing is 4k/f (Praos), not 3k/f (TPraos) — this matters on devnets where 4k/f can exceed the epoch length.
Sub-packages ¶
- ledger/forging — block production (BlockForger, BlockBuilder)
- ledger/leader — VRF leader election for block production
- ledger/snapshot — stake snapshot capture at epoch boundaries
- ledger/eras — per-era validation rule implementations
Index ¶
- Constants
- Variables
- func ApplyDijkstraDirectDeposits(ctx context.Context, db *database.Database, tx common.Transaction, slot uint64, ...) error
- func EraForVersion(eraList []eras.EraDesc, majorVersion uint) (uint, bool)
- func GenesisBlockHash(cfg *cardano.CardanoNodeConfig) ([32]byte, error)
- func HeaderProtocolMajor(header lcommon.BlockHeader) (uint, bool)
- func IsCommitteeThresholdMet(yesVotes int, totalActiveMembers int, thresholdNumerator uint64, ...) bool
- func IsHardForkTransition(eraList []eras.EraDesc, oldVersion, newVersion ProtocolVersion) bool
- func IsHeaderVerificationContextTransient(err error) bool
- func IsHeaderVerificationDeferred(err error) bool
- func IsHeaderVerificationWithheld(err error) bool
- func LeiosEndorserBlockBasisHash(header ledger.BlockHeader) []byte
- func LeiosValidationParentHash(header ledger.BlockHeader) []byte
- func PreviousEraEpoch(epochs []models.Epoch, epochID uint64, epochEraID, blockEraID uint) (models.Epoch, bool)
- func ShelleyStabilityWindow(sg *shelley.ShelleyGenesis) (uint64, error)
- func TransactionLevels(tx common.Transaction) []common.Transaction
- func TransactionLevelsForApply(tx common.Transaction) []common.Transaction
- func ValidateChainsyncHeaderCapacity(admittedHeadroom int) error
- func ValidateCheckpoint(checkpoints map[uint64]string, blockNo uint64, hash string) error
- func ValidateHeaderCheckpoint(checkpoints map[uint64]string, header ledger.BlockHeader) error
- func ValidateHeaderProtocolVersion(header lcommon.BlockHeader, curPvMajor uint, isMainnet bool) error
- func WithEvaluationSource(ctx context.Context, peerAddr string) context.Context
- type BlockAction
- type BlockEvent
- type BlockfetchEvent
- type BlockfetchLatencyFunc
- type BlockfetchLatencyMedianFunc
- type BlockfetchRequestRangeFunc
- type ChainsyncAwaitReplyEvent
- type ChainsyncEvent
- type ChainsyncState
- type CheckpointMismatchError
- type ClearSeenHeadersFromFunc
- type ConnectionClosedEvent
- type ConnectionLiveFunc
- type ConnectionRecycleRequestedEvent
- type ConnectionSwitchFunc
- type DatabaseOperation
- type DatabaseResult
- type DatabaseWorkerPool
- type DatabaseWorkerPoolConfig
- type DeferredBoundarySnapshot
- type DijkstraDirectDepositEffect
- type EndorserBlockDataProviderFunc
- type EndorserBlockFetcherFunc
- type EndorserBlockProviderFunc
- type EndorserBlockValidationFunc
- type EndorserBlockValidationStatus
- type EpochInfo
- type EpochRolloverResult
- type EraTransitionResult
- type FatalErrorFunc
- type ForgedBlockChecker
- type GenesisSelectionStateFunc
- type GetActiveConnectionFunc
- type GetPeerObservedTipFunc
- type GetPeerSyncTargetFunc
- type HardForkInfo
- type HeaderProtocolVersionTooHighError
- type LedgerDelta
- type LedgerDeltaBatch
- type LedgerErrorEvent
- type LedgerState
- func (ls *LedgerState) AcquireQueryView(ctx context.Context, at QueryPoint) (*QueryView, error)
- func (ls *LedgerState) AcquiredPointPinCountForTesting() int
- func (ls *LedgerState) ActiveSlotCoeff() float64
- func (ls *LedgerState) ActiveSlotCoeffRat() *big.Rat
- func (ls *LedgerState) AdoptLocalForgedSibling(ctx context.Context, block gledger.Block) (bool, error)
- func (ls *LedgerState) ApplyTrustedBatch(ctx context.Context, expected ocommon.Point, blocks []ledger.Block) (ocommon.Point, error)
- func (ls *LedgerState) AwaitAppliedSlot(ctx context.Context, slot uint64) error
- func (ls *LedgerState) AwaitChainsyncHeaderAdmission(ctx context.Context, e ChainsyncEvent) (bool, error)
- func (ls *LedgerState) AwaitChainsyncHeaderCapacity(ctx context.Context, admittedHeadroom int) error
- func (ls *LedgerState) AwaitObserverHeaderHorizon(ctx context.Context, e ChainsyncEvent) error
- func (ls *LedgerState) BlockByHash(ctx context.Context, hash []byte) (models.Block, error)
- func (ls *LedgerState) BlockByHashIncludingRolledBack(ctx context.Context, hash []byte) (models.Block, error)
- func (ls *LedgerState) BlockProcessingSlot() (uint64, bool)
- func (ls *LedgerState) BlockTransactionCount(ctx context.Context, block models.Block) (int, error)
- func (ls *LedgerState) BlockTransactions(ctx context.Context, block models.Block) ([]lcommon.Transaction, error)
- func (ls *LedgerState) BlockfetchRangeExpectedBytes(start, end ocommon.Point) uint64
- func (ls *LedgerState) ByronProtocolMagic() (uint32, error)
- func (ls *LedgerState) ByronProtocolParameters() (*eras.ByronProtocolParameters, error)
- func (ls *LedgerState) CardanoNodeConfig() *cardano.CardanoNodeConfig
- func (ls *LedgerState) CertifiedClosureTransactions(ctx context.Context, decoded ledger.Block) ([]lcommon.Transaction, error)
- func (ls *LedgerState) Chain() *chain.Chain
- func (ls *LedgerState) ChainTipSlot() uint64
- func (ls *LedgerState) CheckLeiosCertificationTiming(announcingSlot uint64, slot uint64) error
- func (ls *LedgerState) Close() (retErr error)
- func (ls *LedgerState) ConsensusModeForEpoch(epoch uint64) (consensus.ConsensusMode, error)
- func (ls *LedgerState) CountTransactionsByAddress(ctx context.Context, addr lcommon.Address, ...) (int, error)
- func (ls *LedgerState) CountTransactionsByMetadataLabel(label uint64) (int, error)
- func (ls *LedgerState) CurrentEpoch() uint64
- func (ls *LedgerState) CurrentHeaderCryptoVerificationGeneration() uint64
- func (ls *LedgerState) CurrentOrTipSlot() uint64
- func (ls *LedgerState) CurrentSlot() (uint64, error)
- func (ls *LedgerState) CurrentTransitionInfo() hardfork.TransitionInfo
- func (ls *LedgerState) Database() *database.Database
- func (ls *LedgerState) Datums(ctx context.Context, hashes [][]byte) ([]*models.Datum, error)
- func (ls *LedgerState) DelegatorInactivityConfig() (enabled bool, window uint64)
- func (ls *LedgerState) DrainTrustedPrune(ctx context.Context) error
- func (ls *LedgerState) ElectingPoolStake(slot uint64, poolKeyHash lcommon.PoolKeyHash) (uint64, error)
- func (ls *LedgerState) EndorserBlockWaitDuration() time.Duration
- func (ls *LedgerState) EpochBoundaryJobPending() bool
- func (ls *LedgerState) EpochInfo(epoch uint64) (models.Epoch, error)
- func (ls *LedgerState) EpochNonce(ctx context.Context, epoch uint64) []byte
- func (ls *LedgerState) EraIDForEpoch(epoch uint64) (uint, error)
- func (ls *LedgerState) EvaluateTx(tx lcommon.Transaction) (uint64, lcommon.ExUnits, map[lcommon.RedeemerKey]lcommon.ExUnits, error)
- func (ls *LedgerState) EvaluateTxContext(ctx context.Context, tx lcommon.Transaction) (uint64, lcommon.ExUnits, map[lcommon.RedeemerKey]lcommon.ExUnits, error)
- func (ls *LedgerState) ExistingTransactionHashes(ctx context.Context, hashes [][]byte) ([][]byte, error)
- func (ls *LedgerState) ForgeTipSnapshot() (ochainsync.Tip, int)
- func (ls *LedgerState) GenesisDelegateForGenesisKey(genesisKeyHash lcommon.Blake2b224, slot uint64) (lcommon.Blake2b224, bool, error)
- func (ls *LedgerState) GenesisDelegateKeyHashes(slot uint64) ([]lcommon.Blake2b224, error)
- func (ls *LedgerState) GenesisUpdateQuorum() (uint, error)
- func (ls *LedgerState) GetBlock(point ocommon.Point) (models.Block, error)
- func (ls *LedgerState) GetBlockContext(ctx context.Context, point ocommon.Point) (models.Block, error)
- func (ls *LedgerState) GetChainFromPoint(point ocommon.Point, inclusive bool) (*chain.ChainIterator, error)
- func (ls *LedgerState) GetChainFromPointContext(ctx context.Context, point ocommon.Point, inclusive bool) (*chain.ChainIterator, error)
- func (ls *LedgerState) GetChainFromPointReverse(point ocommon.Point, inclusive bool) (*chain.ChainIterator, error)
- func (ls *LedgerState) GetChainFromPointReverseContext(ctx context.Context, point ocommon.Point, inclusive bool) (*chain.ChainIterator, error)
- func (ls *LedgerState) GetCurrentPParams() lcommon.ProtocolParameters
- func (ls *LedgerState) GetCurrentPParamsForReporting() lcommon.ProtocolParameters
- func (ls *LedgerState) GetEpochs() ([]models.Epoch, error)
- func (ls *LedgerState) GetIntersectPoint(ctx context.Context, points []ocommon.Point) (*ocommon.Point, error)
- func (ls *LedgerState) GetPParamsForEpoch(epoch uint64, era eras.EraDesc) (lcommon.ProtocolParameters, error)
- func (ls *LedgerState) GetTransactionsByAddress(addr lcommon.Address, limit int, offset int) ([]models.Transaction, error)
- func (ls *LedgerState) GetTransactionsByAddressWithOrder(ctx context.Context, addr lcommon.Address, limit int, offset int, order string, ...) ([]models.Transaction, error)
- func (ls *LedgerState) GetTransactionsByBlockHash(blockHash []byte) ([]models.Transaction, error)
- func (ls *LedgerState) GetTransactionsByHashes(hashes [][]byte) ([]models.Transaction, error)
- func (ls *LedgerState) HardForkSummary() (*hardfork.Summary, error)
- func (ls *LedgerState) HeaderCryptoVerificationGenerationCurrent(generation uint64) bool
- func (ls *LedgerState) HeaderVerificationSettledChan() <-chan struct{}
- func (ls *LedgerState) HoldEpochBoundaryJobForTesting(epoch uint64) (release func())
- func (ls *LedgerState) HoldNetworkIngest() (release func())
- func (ls *LedgerState) ImmutablePoint(ctx context.Context) (ocommon.Point, bool, error)
- func (ls *LedgerState) IntersectPoints(ctx context.Context, count int) ([]ocommon.Point, error)
- func (ls *LedgerState) IsAtTip() bool
- func (ls *LedgerState) IsByronEra() bool
- func (ls *LedgerState) LatestOpCertSequence(poolID [28]byte) (sequence uint64, found bool, err error)
- func (ls *LedgerState) LedgerPeerSnapshot(ctx context.Context) (olocalstatequery.LedgerPeerSnapshotResult, error)
- func (ls *LedgerState) LedgerTipIntersectPoints(ctx context.Context, count int) ([]ocommon.Point, error)
- func (ls *LedgerState) MarkReachedTipForTesting()
- func (ls *LedgerState) MaxBlockSize() uint64
- func (ls *LedgerState) MaxTxSize(txEraId uint) (uint, bool)
- func (ls *LedgerState) MempoolSubmissionCapacity() int
- func (ls *LedgerState) MinPoolMargin() *big.Rat
- func (ls *LedgerState) NetworkIngestHeld() bool
- func (ls *LedgerState) NewView(txn *database.Txn) *LedgerView
- func (ls *LedgerState) NextEpochNonceReadyEpoch() (uint64, bool)
- func (ls *LedgerState) NextSlotTime() (time.Time, error)
- func (ls *LedgerState) OldestRequiredSnapshotEpoch() (uint64, bool)
- func (ls *LedgerState) OldestRetainedSlot() (slot uint64, ok bool)
- func (ls *LedgerState) PauseChainIngest() (resume func())
- func (ls *LedgerState) PendingRewardCredit(txn *database.Txn, credentialTag uint8, stakingKey []byte) (uint64, error)
- func (ls *LedgerState) Phase2ResultCache() *eras.Phase2ResultCache
- func (ls *LedgerState) PinAcquiredPoint(slot uint64) (release func())
- func (ls *LedgerState) PinHeaderCryptoVerificationGeneration(generation uint64) (func(), bool)
- func (ls *LedgerState) PlutusEvalContextCache() *eras.PlutusEvalContextCache
- func (ls *LedgerState) PoolRegistrationVRFKeyHash(poolID [28]byte) (vrfHash [32]byte, found bool, err error)
- func (ls *LedgerState) PoolStakeDistribution(ctx context.Context, poolFilter []lcommon.PoolKeyHash, at QueryPoint, ...) (*PoolStakeDistribution, error)
- func (ls *LedgerState) PoolStakeDistributionBounded(ctx context.Context, poolFilter []lcommon.PoolKeyHash, at QueryPoint, ...) (*PoolStakeDistribution, error)
- func (ls *LedgerState) PrepareEpochCacheForStartup(ctx context.Context) error
- func (ls *LedgerState) PrimaryChainTip() ochainsync.Tip
- func (ls *LedgerState) PrimaryChainTipRelation(point ocommon.Point) (ochainsync.Tip, uint64, bool, error)
- func (ls *LedgerState) PrimaryChainTipRelationAndHeader(point ocommon.Point) (ochainsync.Tip, ochainsync.Tip, uint64, bool, error)
- func (ls *LedgerState) PrimaryChainTipSlot() uint64
- func (ls *LedgerState) ProcessTrustedBlockBatches(ctx context.Context, batches <-chan []ledger.Block) error
- func (ls *LedgerState) ProtocolParameterUpdateWindow(slot uint64) (uint64, uint64, error)
- func (ls *LedgerState) ProtocolParamsForSlot(slot uint64) lcommon.ProtocolParameters
- func (ls *LedgerState) PrunePoolSnapshotsWithRetentionFloor(defaultBefore uint64, minBefore uint64, prune func(before uint64) error) error
- func (ls *LedgerState) Query(ctx context.Context, query any, at QueryPoint) (any, error)
- func (ls *LedgerState) QueryWithProtocolVersion(ctx context.Context, query any, at QueryPoint, protocolVersion uint16) (any, error)
- func (ls *LedgerState) RecentChainPoints(ctx context.Context, count int) ([]ocommon.Point, error)
- func (ls *LedgerState) ReconcileLivePrimaryChainLedgerDivergence(reason string, connId ouroboros.ConnectionId) (bool, error)
- func (ls *LedgerState) RecordForgedBlock(block ledger.Block, blockCbor []byte, forgingLatency time.Duration)
- func (ls *LedgerState) RecoverAfterLocalRollback(ctx context.Context, connIds []ouroboros.ConnectionId, point ocommon.Point) LocalRollbackRecoveryResult
- func (ls *LedgerState) RecoverCommitTimestampConflict(ctx context.Context) error
- func (ls *LedgerState) RewardStakeInputsIncomplete(txn *database.Txn, from uint64, through uint64) (bool, error)
- func (ls *LedgerState) RollbackWindowIntersectAnchor(ctx context.Context) (ocommon.Point, bool, error)
- func (ls *LedgerState) ScanUtxosByAddress(ctx context.Context, q *models.UtxoWithOrderingQuery, maxCandidates int, ...) (ochainsync.Tip, error)
- func (ls *LedgerState) SecurityParam() int
- func (ls *LedgerState) SetCurrentBoundarySPOStakeHook(...)
- func (ls *LedgerState) SetDeferredEpochBoundarySnapshotHooks(capture func(*database.Txn, event.EpochTransitionEvent) error, ...)
- func (ls *LedgerState) SetEpochBoundaryDeferredStakeInputsHook(fn func(*database.Txn) (uint64, uint64, []*models.RewardStakeInput, bool))
- func (ls *LedgerState) SetEpochBoundarySnapshotHook(fn func(*database.Txn, event.EpochTransitionEvent) error)
- func (ls *LedgerState) SetEpochBoundarySnapshotStakeHook(fn func(*database.Txn, event.EpochTransitionEvent) error)
- func (ls *LedgerState) SetForgedBlockChecker(checker ForgedBlockChecker)
- func (ls *LedgerState) SetForgingEnabled(enabled bool)
- func (ls *LedgerState) SetMempool(mempool MempoolProvider)
- func (ls *LedgerState) SetSlotBattleRecorder(recorder SlotBattleRecorder)
- func (ls *LedgerState) SetTipForTesting(tip ochainsync.Tip)
- func (ls *LedgerState) ShouldVerifyChainSelectionHeaderCrypto(slot uint64) bool
- func (ls *LedgerState) SignatureResultCache() *eras.SignatureResultCache
- func (ls *LedgerState) SlotToEpoch(slot uint64) (models.Epoch, error)
- func (ls *LedgerState) SlotToTime(slot uint64) (time.Time, error)
- func (ls *LedgerState) SlotToTimeWithHorizonFrom(horizonAnchorSlot uint64, slot uint64) (time.Time, error)
- func (ls *LedgerState) SlotsBehindHead() uint64
- func (ls *LedgerState) SlotsPerEpoch() uint64
- func (ls *LedgerState) SlotsPerKESPeriod() uint64
- func (ls *LedgerState) StabilityWindow() uint64
- func (ls *LedgerState) Start(ctx context.Context) error
- func (ls *LedgerState) SubmitAsyncDBOperation(opFunc func(db *database.Database) error) error
- func (ls *LedgerState) SubmitAsyncDBReadTxn(ctx context.Context, opFunc func(txn *database.Txn) error) error
- func (ls *LedgerState) SubmitAsyncDBTxn(ctx context.Context, opFunc func(txn *database.Txn) error, readWrite bool) error
- func (ls *LedgerState) SyncProgress() float64
- func (ls *LedgerState) SystemStart() (time.Time, error)
- func (ls *LedgerState) TachysDistribution(ctx context.Context, snapshotEpoch uint64) (_ *nodeconsensus.TachysDistribution, err error)
- func (ls *LedgerState) TimeToSlot(t time.Time) (uint64, error)
- func (ls *LedgerState) Tip() ochainsync.Tip
- func (ls *LedgerState) TransactionByHash(ctx context.Context, hash []byte) (*models.Transaction, error)
- func (ls *LedgerState) UpstreamSyncStatus() (uint64, bool)
- func (ls *LedgerState) UpstreamSyncTip() (ochainsync.Tip, bool)
- func (ls *LedgerState) UpstreamTipSlot() uint64
- func (ls *LedgerState) UtxoBalanceByAddressAtSlot(ctx context.Context, addr lcommon.Address, slot uint64) (models.AddressBalance, error)
- func (ls *LedgerState) UtxoByRef(txId []byte, outputIdx uint32) (*models.Utxo, error)
- func (ls *LedgerState) UtxoByRefIncludingSpent(txId []byte, outputIdx uint32) (*models.Utxo, error)
- func (ls *LedgerState) UtxosByAddress(ctx context.Context, addrs []ledger.Address) ([]models.Utxo, error)
- func (ls *LedgerState) UtxosByAddressBoundedPage(ctx context.Context, q *models.UtxoWithOrderingQuery, maxCandidates int, ...) (models.UtxoAddressPage, error)
- func (ls *LedgerState) UtxosByRefs(refs []models.UtxoId) ([]models.Utxo, error)
- func (ls *LedgerState) UtxosByRefsBounded(ctx context.Context, refs []models.UtxoId, maxBytes int64) ([]models.Utxo, error)
- func (ls *LedgerState) ValidateBlockHeaderCrypto(header ledger.BlockHeader) error
- func (ls *LedgerState) ValidateBlockReferenceScripts(ctx context.Context, block ledger.Block) error
- func (ls *LedgerState) ValidateChainSelectionHeaderCrypto(header ledger.BlockHeader) error
- func (ls *LedgerState) ValidateChainSelectionHeaderCryptoWithGeneration(header ledger.BlockHeader) (uint64, error)
- func (ls *LedgerState) ValidateForgedBlock(ctx context.Context, block ledger.Block, _ []byte) error
- func (ls *LedgerState) ValidateHeaderCheckpoint(header ledger.BlockHeader) error
- func (ls *LedgerState) ValidateLeiosAnnouncementHeader(header ledger.BlockHeader) (LeiosAnnouncementOCINStaleness, error)
- func (ls *LedgerState) ValidateLeiosEndorserBlockTransactions(ctx context.Context, header ledger.BlockHeader, basis []byte, txs [][]byte) error
- func (ls *LedgerState) ValidatePeerChainSelectionHeaderCrypto(connId ouroboros.ConnectionId, header ledger.BlockHeader) error
- func (ls *LedgerState) ValidatePeerChainSelectionHeaderCryptoWithGeneration(connId ouroboros.ConnectionId, header ledger.BlockHeader) (uint64, error)
- func (ls *LedgerState) ValidatePraosHeader(ctx context.Context, block ledger.Block, allowEpochCacheAdvance bool, ...) error
- func (ls *LedgerState) ValidateTachysHeader(ctx context.Context, block gledger.Block, allowEpochCacheAdvance bool, ...) error
- func (ls *LedgerState) ValidateTx(tx lcommon.Transaction) error
- func (ls *LedgerState) ValidateTxWithOverlay(tx lcommon.Transaction, consumedUtxos map[utxoref.Key]struct{}, ...) error
- func (ls *LedgerState) VerifyPeerHeaderAncestry(ctx context.Context, conn ouroboros.ConnectionId, header gledger.BlockHeader, ...) (VerifiedPeerHeaderAncestry, error)
- func (ls *LedgerState) VerifyPointOnChain(ctx context.Context, at QueryPoint) error
- func (ls *LedgerState) VerifyPointQueryable(ctx context.Context, txn *database.Txn, at QueryPoint) error
- func (ls *LedgerState) WaitEpochBoundaryJob(ctx context.Context) error
- func (ls *LedgerState) WallClockSlotFromConfirmedHistory() (uint64, bool, error)
- func (ls *LedgerState) WithResolvingTxValidationSession(ctx context.Context, fn func(...) error) error
- func (ls *LedgerState) WithTxValidationSession(ctx context.Context, fn func(...) error) error
- func (ls *LedgerState) WithTxValidationSessionAtParent(ctx context.Context, parentHash []byte, fn func(...) error) error
- type LedgerStateConfig
- type LedgerView
- func (lv *LedgerView) ByronProtocolMagic() (uint32, error)
- func (lv *LedgerView) ByronProtocolParameters() (*eras.ByronProtocolParameters, error)
- func (lv *LedgerView) CalculateRewards(adaPots lcommon.AdaPots, rewardSnapshot lcommon.RewardSnapshot, ...) (*lcommon.RewardCalculationResult, error)
- func (lv *LedgerView) CommitteeCredentialIsElected(coldCredential lcommon.Credential) (bool, error)
- func (lv *LedgerView) CommitteeCredentialMember(coldCredential lcommon.Credential) (*lcommon.CommitteeMember, error)
- func (lv *LedgerView) CommitteeHotCredentialColdCredentials(hotCredential lcommon.Credential) ([]lcommon.Credential, error)
- func (lv *LedgerView) CommitteeHotCredentialMember(hotCredential lcommon.Credential) (*lcommon.CommitteeMember, error)
- func (lv *LedgerView) CommitteeHotCredentialMembers(hotCredential lcommon.Credential) ([]*lcommon.CommitteeMember, error)
- func (lv *LedgerView) CommitteeMember(coldKey lcommon.Blake2b224) (*lcommon.CommitteeMember, error)
- func (lv *LedgerView) CommitteeMembers() ([]lcommon.CommitteeMember, error)
- func (lv *LedgerView) CommitteeStateAvailable() (bool, error)
- func (lv *LedgerView) Constitution() (*lcommon.Constitution, error)
- func (lv *LedgerView) CostModels() map[lcommon.PlutusLanguage]lcommon.CostModel
- func (lv *LedgerView) DRepDelegation(cred lcommon.Credential) (*lcommon.Drep, error)
- func (lv *LedgerView) DRepRegistration(credential lcommon.Credential) (*lcommon.DRepRegistration, error)
- func (lv *LedgerView) DRepRegistrations() ([]lcommon.DRepRegistration, error)
- func (lv *LedgerView) DijkstraBlsProofDomain() lcommon.DijkstraBlsProofDomain
- func (lv *LedgerView) EpochForSlot(slot uint64) (uint64, error)
- func (lv *LedgerView) EvaluationContext() context.Context
- func (lv *LedgerView) GenesisDelegState(slot uint64) (eras.GenesisDelegState, error)
- func (lv *LedgerView) GenesisDelegateForGenesisKey(genesisKeyHash lcommon.Blake2b224, slot uint64) (lcommon.Blake2b224, bool, error)
- func (lv *LedgerView) GenesisDelegateKeyHashes(slot uint64) ([]lcommon.Blake2b224, error)
- func (lv *LedgerView) GenesisUpdateQuorum() (uint, error)
- func (lv *LedgerView) GetAdaPots() lcommon.AdaPots
- func (lv *LedgerView) GetAdaPotsWithError() (lcommon.AdaPots, error)
- func (lv *LedgerView) GetCommitteeAuthorizedCount() (int, error)
- func (lv *LedgerView) GetDRepVotingPower(credentialTag uint8, drepCredential []byte) (uint64, error)
- func (lv *LedgerView) GetExpiredDReps(epoch uint64) ([]*models.Drep, error)
- func (lv *LedgerView) GetLeiosKeys(epoch uint64, poolKeyHashes []lcommon.PoolKeyHash) (map[string]*lcommon.LeiosKey, error)
- func (lv *LedgerView) GetPoolStake(epoch uint64, poolKeyHash []byte) (uint64, error)
- func (lv *LedgerView) GetRewardSnapshot(epoch uint64) (lcommon.RewardSnapshot, error)
- func (lv *LedgerView) GetStakeDistribution(epoch uint64) (*StakeDistribution, error)
- func (lv *LedgerView) GetTotalActiveStake(epoch uint64) (uint64, error)
- func (lv *LedgerView) GovActionById(id lcommon.GovActionId) (*lcommon.GovActionState, error)
- func (lv *LedgerView) GovActionExists(id lcommon.GovActionId) bool
- func (lv *LedgerView) GovPurposeRoots() (*lcommon.GovPurposeRoots, error)
- func (lv *LedgerView) IsBlsKeyInUse(publicKey []byte) (bool, lcommon.PoolKeyHash, error)
- func (lv *LedgerView) IsFutureVrfKeyInUse(vrfKeyHash lcommon.Blake2b256) (bool, lcommon.PoolKeyHash, error)
- func (lv *LedgerView) IsPoolRegistered(pkh lcommon.PoolKeyHash) bool
- func (lv *LedgerView) IsRewardAccountRegistered(cred lcommon.Credential) bool
- func (lv *LedgerView) IsStakeCredentialRegistered(cred lcommon.Credential) bool
- func (lv *LedgerView) IsVrfKeyInUse(vrfKeyHash lcommon.Blake2b256) (bool, lcommon.PoolKeyHash, error)
- func (lv *LedgerView) MIRDelegState(slot uint64, additive bool) (eras.MIRDelegState, error)
- func (lv *LedgerView) MinPoolMargin() *big.Rat
- func (lv *LedgerView) NetworkId() uint
- func (lv *LedgerView) PendingInstantaneousRewards(source uint, cred lcommon.Credential) (*big.Int, error)
- func (lv *LedgerView) Phase2ResultCache() *eras.Phase2ResultCache
- func (lv *LedgerView) PlutusEvalContextCache() *eras.PlutusEvalContextCache
- func (lv *LedgerView) PoolCurrentState(pkh lcommon.PoolKeyHash) (*lcommon.PoolRegistrationCertificate, *uint64, error)
- func (lv *LedgerView) PoolRegistration(pkh lcommon.PoolKeyHash) ([]lcommon.PoolRegistrationCertificate, error)
- func (lv *LedgerView) PreverifiedSignatures() *lcommon.PreverifiedSignatures
- func (lv *LedgerView) ProtocolParameterUpdateWindow(slot uint64) (uint64, uint64, error)
- func (lv *LedgerView) RewardAccountBalance(cred lcommon.Credential) (*uint64, error)
- func (lv *LedgerView) SignatureResultCache() *eras.SignatureResultCache
- func (lv *LedgerView) SkipPhase2Validation() bool
- func (lv *LedgerView) SlotToTime(slot uint64) (time.Time, error)
- func (lv *LedgerView) StakeCredentialDeposit(cred lcommon.Credential) (*uint64, error)
- func (lv *LedgerView) StakeRegistration(stakingKey []byte) ([]lcommon.StakeRegistrationCertificate, error)
- func (lv *LedgerView) StakeRegistrationByCredential(cred lcommon.Credential) ([]lcommon.StakeRegistrationCertificate, error)
- func (lv *LedgerView) StorageErr() error
- func (lv *LedgerView) SyntheticV2CostModelInEffect() bool
- func (lv *LedgerView) TimeToSlot(t time.Time) (uint64, error)
- func (lv *LedgerView) TreasuryValue() (uint64, error)
- func (lv *LedgerView) UpdateAdaPots(adaPots lcommon.AdaPots) error
- func (lv *LedgerView) UtxoById(utxoId lcommon.TransactionInput) (lcommon.Utxo, error)
- type LeiosAnnouncementOCINStaleness
- type LocalRollbackRecoveryResult
- type LocalStateQueryLimitError
- type MempoolProvider
- type NetworkIngestHoldTracker
- type PeerHeaderLookupFunc
- type PeersWithBlockFunc
- type PendingTransaction
- type PoolRelay
- type PoolRelayProvider
- type PoolStakeDistribution
- type PoolStakeShare
- type PoolStateRestoredEvent
- type ProtocolVersion
- type QueryPoint
- type QueryView
- type RecordBlockfetchLatencyFunc
- type RecordBlockfetchThroughputFunc
- type ReportSlotClockAliveFunc
- type ReportTipGapFunc
- type ScheduledTask
- type Scheduler
- type SchedulerConfig
- type SelectBlockfetchPeerFunc
- type SelectBlockfetchRetryPeerFunc
- type SlotBattleRecorder
- type SlotClock
- func (sc *SlotClock) CurrentEpoch() (EpochInfo, error)
- func (sc *SlotClock) CurrentSlot() (uint64, error)
- func (sc *SlotClock) GetEpochForSlot(slot uint64) (EpochInfo, error)
- func (sc *SlotClock) IsEpochBoundary(slot uint64) (bool, error)
- func (sc *SlotClock) LastEmittedEpoch() uint64
- func (sc *SlotClock) MarkEpochEmitted(epoch uint64) bool
- func (sc *SlotClock) NextSlotTime() (time.Time, error)
- func (sc *SlotClock) SetLastEmittedEpoch(epoch uint64)
- func (sc *SlotClock) SlotToTime(slot uint64) (time.Time, error)
- func (sc *SlotClock) Start(ctx context.Context)
- func (sc *SlotClock) Stop()
- func (sc *SlotClock) Subscribe() <-chan SlotTick
- func (sc *SlotClock) TimeUntilNextEpoch() (time.Duration, error)
- func (sc *SlotClock) TimeUntilSlot(slot uint64) (time.Duration, error)
- func (sc *SlotClock) Unsubscribe(ch <-chan SlotTick)
- type SlotClockConfig
- type SlotTick
- type SlotTimeConverter
- func (c *SlotTimeConverter) EndorserBlockWaitDuration(waitSlots uint64) time.Duration
- func (c *SlotTimeConverter) EpochInfo(epoch uint64) (models.Epoch, error)
- func (c *SlotTimeConverter) SlotToEpoch(slot uint64) (models.Epoch, error)
- func (c *SlotTimeConverter) SlotToTime(slot uint64) (time.Time, error)
- func (c *SlotTimeConverter) SlotToTimeWithHorizonFrom(horizonAnchorSlot uint64, slot uint64) (time.Time, error)
- func (c *SlotTimeConverter) TimeToSlot(t time.Time) (uint64, error)
- type SlotTimeConverterDeps
- type SlotTimeProvider
- type StakeDistribution
- type TransactionEvent
- type TransactionRecord
- type UnsupportedHeaderProtocolVersionError
- type VerifiedPeerHeaderAncestry
Constants ¶
const ( // BlockfetchBatchSize is the maximum number of blocks this chainsync // client requests in a single BlockFetch range, so as not to exceed the // configured recv queue size in the block-fetch protocol. Exported so // the server-side floor on how many blocks a single BlockFetch range // request is served (ouroboros.blockfetchMaxBlocksFloor) can assert it // stays comfortably above this client's own usage. BlockfetchBatchSize = 500 // BlockfetchMaxRangeBytes bounds the estimated wire size of a single // BlockFetch range this client requests, so a run of large blocks (15-20 // MB per 500 blocks on heavy Preview epochs) is split across ranges // instead of forming one oversized request. A single block larger than // this still forms a range of its own. See // chain.Chain.HeaderRangeAfterBytes and the peer connection's in-flight // byte budget, which is sized as a multiple of this value. BlockfetchMaxRangeBytes = 8 << 20 )
const ( // ChainsyncEventBufferSize bounds headers admitted by protocol callbacks // but not yet reflected in the chain header queue. Keep it aligned with // the peer request window so one network pipeline can drain without a // round trip while EventBus backpressure stops further admission. ChainsyncEventBufferSize = ochainsync.DefaultPipelineLimit BlockfetchEventType event.EventType = "ledger.blockfetch" BlockEventType event.EventType = "ledger.block" ChainsyncEventType event.EventType = "ledger.chainsync" ChainsyncAwaitReplyEventType event.EventType = "ledger.chainsync_await_reply" ConnectionClosedEventType event.EventType = "ledger.conn_closed" ConnectionRecycleRequestedEventType event.EventType = "ledger.connection_recycle_requested" LedgerErrorEventType event.EventType = "ledger.error" PoolStateRestoredEventType event.EventType = event.PoolStateRestoredEventType TransactionEventType event.EventType = "ledger.tx" )
const MaxLocalStateQueryItems = 1000
MaxLocalStateQueryItems bounds caller-controlled credential filters on query paths that perform per-item work or build account maps from batched reads. Explicit over-limit filters are rejected before database access.
const MaxTrustedBatchBlocks = 8 * batchSize
MaxTrustedBatchBlocks is the most blocks one ApplyTrustedBatch call accepts. The whole batch is one coordinated transaction, and its blob half (a transaction-offset key per transaction and a UTxO-offset key per output) is a single Badger transaction, which Badger refuses once it exceeds 15% of the memtable (about 20 MB and 200,000 entries at the default 128 MB). At a few hundred keys for a busy mainnet block, eight live-loop transactions' worth of blocks is expected to stay inside that, but block density is not bounded by it, so ApplyTrustedBatch splits a batch Badger refuses rather than relying on this bound alone. A mainnet immutable chunk holds about 1,100 blocks, so callers split a chunk into several batches.
Variables ¶
var ( CloseDBWorkerPoolShutdownTimeout = 15 * time.Second // A Leios block-processing transaction can include a large endorser // closure and legitimately outlive the short blockfetch waits. Keep this // below Node's default 30-second shutdown budget so the later ledger and // database cleanup stages retain time to finish if processing is stuck. CloseProcessBlocksDrainTimeout = 20 * time.Second CloseBlockPipelineDrainTimeout = 10 * time.Second CloseBlockfetchDrainTimeout = 10 * time.Second CloseResultReplayTimeout = 10 * time.Second // BlockPipelineRollbackDrainTimeout bounds how long an asynchronous // rollback (chainsync fork resolution or a peer-reported rollback -- // see rollbackChainAndStateDeferred) waits for ls.blockPipeline to drain // in-flight decode/validate work before proceeding. See // drainBlockPipelineBeforeRollback's doc comment for what this // protects against and, just as importantly, what it does not. // Exported, like the Close* timeouts above, so tests can shrink it // instead of running a real multi-second wait. BlockPipelineRollbackDrainTimeout = 5 * time.Second )
CloseDBWorkerPoolShutdownTimeout, CloseProcessBlocksDrainTimeout, and CloseBlockfetchDrainTimeout bound the corresponding waits in Close() below. Exported (not local consts) so tests — including cross-package node-level tests exercising how a caller reacts to Close failing to confirm drain — can shrink them instead of running real multi-second timeouts.
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.
var ErrChainIngestNotPaused = errors.New(
"trusted batch applied while chain ingest is not paused",
)
ErrChainIngestNotPaused reports an ApplyTrustedBatch call made outside a PauseChainIngest/resume pair.
var ErrChainTruncatedLedgerRollbackFailed = errors.New(
"primary chain truncated but ledger rollback failed",
)
ErrChainTruncatedLedgerRollbackFailed reports the one rollback outcome that left the node's two halves disagreeing: the primary chain truncation committed and the ledger rollback that follows it did not, so the ledger tip names a block the chain has deleted. It is deliberately distinct from the refusal errors above, which mean no state changed and a re-intersect is enough; recovering from this one the same way resumes from the stale ledger tip. See LedgerState.reportFailedLedgerRollbackAfterTruncation.
var ErrChainsyncHeaderDisconnected = errors.New(
"chainsync header does not connect to the local chain",
)
ErrChainsyncHeaderDisconnected is returned by AwaitChainsyncHeaderAdmission for a header past the forecast horizon whose predecessor remains neither the chain tip, the header tip, nor any header or block the local chain holds after queued and in-flight local work has had a chance to advance the chain. The connection must then re-intersect from the local chain instead of waiting.
var ErrChainsyncHeaderNeedsResync = errors.New(
"chainsync header forecast has no local block work to advance it",
)
ErrChainsyncHeaderNeedsResync is returned when a forecast-held header connects to the local chain but no queued or in-flight blockfetch, and no stored block the ledger has yet to apply, can publish state that advances the forecast horizon. Re-intersection makes the peer replay from the local chain; this is not a peer fault.
var ErrEndorserBlockFetchNoPeer = errors.New(
"no leios-fetch connection available",
)
ErrEndorserBlockFetchNoPeer reports that an EndorserBlockFetcherFunc had no connection to ask. It says nothing about whether any peer holds the endorser block, so the ledger pipeline does not count it toward its deterministic-halt threshold.
var ErrEpochBoundaryJobPending = errors.New("epoch boundary job still running")
ErrEpochBoundaryJobPending is wrapped, with the context's own error, by a wait for an epoch boundary's deferred job that ended before the job settled.
var ErrEvaluationBusy = errors.New("transaction evaluation capacity exhausted")
ErrEvaluationBusy reports that every transaction-evaluation slot is in use. Evaluation runs scripts on the caller's goroutine, so admission is refused outright rather than queued.
"%w: retained header ancestry unavailable",
errHeaderVerificationDeferred,
)
ErrHeaderAncestryUnavailable means a peer header's retained predecessors cannot be reconstructed. It is deferred, not evidence of an invalid header. With no local block to apply, recovery requires re-delivery of that history rather than waiting for a ledger snapshot publication.
var ErrHeaderBeyondForecastHorizon = errors.New(
"header beyond the ledger forecast horizon",
)
ErrHeaderBeyondForecastHorizon marks a header whose slot lies past the ledger's forecast horizon. Such an error also satisfies IsHeaderVerificationDeferred, but unlike the other deferred causes the header cannot be validated at all until the applied ledger advances, so it must not count for chain selection or reach blockfetch before then (ouroboros-consensus ChainSync.Client, OutsideForecastRange).
var ( // ErrHeaderVerificationWithheld means chain selection cannot authenticate // a candidate yet. The peer is not at fault, but the header must not // influence selection until its chain-dependent state is reconstructable. ErrHeaderVerificationWithheld = errors.New( "header verification withheld from chain selection", ) )
"historical ledger state unavailable for the requested point",
)
ErrHistoricalStateUnavailable indicates a caller pinned a Query to a point this node cannot answer historically -- either because retained history (a stake snapshot, a spent-UTxO row) has already been pruned past it, or because the requested field's historical reconstruction is not implemented for a point that far from the live tip. errors.Is distinguishes this from a generic query failure or ErrPointNotOnChain.
var ErrInvalidLeiosEndorserBlockTransactions = errors.New(
"invalid leios endorser block transactions",
)
ErrInvalidLeiosEndorserBlockTransactions marks a deterministic transaction verdict for an endorser block. Other validation errors describe local state or storage failures and remain retryable.
ErrLeaderStakeSnapshotUnavailable reports that the stake distribution electing leaders at a slot cannot be read: the slot lies in an epoch the ledger has not reached, or the distribution is missing, empty, pruned, reconstructed after its boundary, or has no usable denominator. It never means the pool is ineligible.
var ErrLedgerViewStorageFault = errors.New("ledger view storage fault")
ErrLedgerViewStorageFault marks an error recorded by a boolean LedgerState predicate (IsStakeCredentialRegistered, IsPoolRegistered, IsRewardAccountRegistered, GovActionExists) when its underlying storage lookup fails for a reason other than "not found". gouroboros's common.LedgerState interface returns only a bool from these predicates, so a genuine storage fault (a timeout, a lost connection) cannot propagate through the interface and would otherwise silently become a false (unregistered/does-not-exist) verdict that the calling ledger rule cannot distinguish from the real thing. Every ValidateTxFunc/EvaluateTxFunc call site that builds a LedgerView must check storageFaultOrErr after the rule returns, and prefer this fault over whatever verdict the rule produced from the false negative.
var ErrLeiosCommitteeNotYetAvailable = errors.New(
"leios committee not yet available",
)
ErrLeiosCommitteeNotYetAvailable marks a LedgerStateConfig.LeiosCommittee failure that only means the committee cannot be built yet, because the stake snapshot it is drawn from has no pools. It is the one failure that leaves the next committee out of the reply; every other failure fails the query.
var ErrLeiosInvalidCertificate = errors.New("invalid Leios certificate")
ErrLeiosInvalidCertificate is the verdict on a certifying ranking block whose certificate does not verify against its parent's announcement, as in the reference Forker.applyBlock (LeiosInvalidCertificate). A LedgerStateConfig.ValidateLeiosCertificate implementation wraps it only for a verdict on the certificate itself; the ledger rejects the block for that error alone and retries any other.
var ErrLeiosValidationParentSuperseded = errors.New(
"leios announcing parent is no longer the current ledger tip",
)
"leios announcement parent is not the current ledger tip",
)
var ErrLocalStateQueryLimitExceeded = errors.New(
"local state query item limit exceeded",
)
ErrLocalStateQueryLimitExceeded identifies a LocalStateQuery request whose caller-controlled item count exceeds MaxLocalStateQueryItems.
var ErrNilDecodedOutput = errors.New("nil decoded output")
ErrNilDecodedOutput is returned when a decoded UTxO output is nil.
var ErrNoAppliedAncestorBelowContestedSlot = errors.New(
"no applied ancestor below contested slot",
)
ErrNoAppliedAncestorBelowContestedSlot reports that a rollback target shares the applied tip's slot with a different hash and no applied ancestor below that slot could be found to rewind to. The contested slot's effects cannot be truncated in place, so the rollback fails loudly rather than reporting a repair that left the UTxO set diverged.
var ErrNotChainTipSibling = errors.New(
"block does not compete with the current chain tip",
)
ErrNotChainTipSibling reports a block offered to AdoptLocalForgedSibling that does not in fact compete with the current chain tip: it does not share the tip's parent, does not carry the tip's block number, or the chain has no resolvable predecessor to fork from. Such a block is never adopted, because the rollback that adoption performs is only ever one block deep and only ever to the block the two candidates already agree on.
var ErrNotImplemented = errors.New("not implemented")
ErrNotImplemented marks LedgerView stubs that are not implemented yet.
var ErrPointNotOnChain = errors.New(
"acquired point is not on the current chain",
)
ErrPointNotOnChain indicates a pinned Query's QueryPoint does not match what this node's current chain has at that slot: either the block was rolled back after the caller acquired it, or the point never existed on this node's view of the chain. Distinguished from ErrHistoricalStateUnavailable because the fix is different -- a caller seeing this should re-acquire a current point, not simply pick an older one.
var ErrPoolStakeDistributionLimitExceeded = errors.New(
"pool stake distribution limit exceeded",
)
ErrPoolStakeDistributionLimitExceeded reports that a bounded distribution contains more pools than its caller can retain.
var ErrQueryNotAnswered = errors.New("query not answered")
ErrQueryNotAnswered identifies a query Dingo decodes but does not answer because a faithful reply needs state it does not hold. A wrong answer would be taken for the node's, so the query fails instead. LocalStateQuery has no failure reply to a query, so the failure ends the client's session; the error names the query and what is missing so the connection log explains it.
var ErrQueryViewClosed = errors.New("ledger query view is closed")
ErrQueryViewClosed is returned by QueryView.Query once the view has been closed, whether by its owner or by a forced expiry.
var ErrRollbackBelowUtxoPruneFloor = errors.New(
"rollback below consumed UTxO prune floor",
)
ErrRollbackBelowUtxoPruneFloor reports a rollback target below the slot the consumed-UTxO sweep has hard-deleted spent rows at or below. Those rows are gone, and database.TruncateAfterSlot restores spent UTxOs with an UPDATE, so the rewind cannot reconstruct the live set the target implies. The rollback is refused with the ledger untouched rather than performed and reported as a repair.
var ErrRollbackExceedsMithrilBoundary = errors.New(
"rollback exceeds Mithril trust boundary",
)
var ErrRollbackLoopDetected = errors.New(
"rollback loop detected: same slot rolled back too many times within window",
)
ErrRollbackLoopDetected is returned by handleEventChainsyncRollback when the same peer repeatedly requests a rollback to the same slot within the rollback loop detection window. The rollback is skipped to break the loop, and the caller should trigger a chainsync re-sync to recover.
var ErrStaleBatch = errors.New("ledger tip moved since batch was prepared")
ErrStaleBatch reports that the ledger tip is no longer the point a trusted batch was prepared against. The caller discards the batch and prepares it again from the current tip.
var ErrTrustedBatchBelowMithrilBoundary = errors.New(
"trusted batch at or below the Mithril trust boundary",
)
ErrTrustedBatchBelowMithrilBoundary reports a batch that reaches at or below the Mithril trust boundary (mithril_ledger_slot). The apply loop treats such blocks as already reflected in the imported ledger state and skips them, so applying them here would silently do nothing.
var ErrTrustedBatchTooLarge = errors.New("trusted batch exceeds block limit")
ErrTrustedBatchTooLarge reports a batch longer than MaxTrustedBatchBlocks.
var ErrUtxoAlreadyConsumed = errors.New("UTxO already consumed")
ErrUtxoAlreadyConsumed is returned when a UTxO has been consumed by a pending transaction.
Functions ¶
func ApplyDijkstraDirectDeposits ¶ added in v0.74.0
func ApplyDijkstraDirectDeposits( ctx context.Context, db *database.Database, tx common.Transaction, slot uint64, txn *database.Txn, ) error
ApplyDijkstraDirectDeposits credits the registered reward accounts declared by one valid Dijkstra transaction body. The transaction body's hash is the journal source so rollback removes the credit with that body.
func EraForVersion ¶ added in v0.22.0
EraForVersion returns the era ID for a given protocol major version, resolved against the provided runtime era table. Returns false if no era covers the given version.
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 HeaderProtocolMajor ¶ added in v0.45.0
func HeaderProtocolMajor(header lcommon.BlockHeader) (uint, bool)
HeaderProtocolMajor extracts the protocol major version stored in a block header. Returns (0, false) for Byron-era headers, which use a different consensus mechanism (PBFT) and do not carry a Praos-style ProtVer field.
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 IsHardForkTransition ¶ added in v0.22.0
func IsHardForkTransition( eraList []eras.EraDesc, oldVersion, newVersion ProtocolVersion, ) bool
IsHardForkTransition returns true if the new protocol version triggers an era change compared to the old version.
func IsHeaderVerificationContextTransient ¶ added in v0.90.3
IsHeaderVerificationContextTransient reports a snapshot publication or validation transition that requires retrying the same header against a stable ledger view. Unlike missing epoch data, this can settle without applying the header's own block.
func IsHeaderVerificationDeferred ¶ added in v0.69.0
IsHeaderVerificationDeferred reports whether header-only verification could not proceed because required ledger state, retained peer ancestry, epoch data, or stake snapshot data is not available yet. errEpochNonceUnavailable is included: a cached epoch entry with no published nonce yet (Byron always, or a post-Byron epoch transiently) is the same "not ready, not proof of invalidity" condition as a slot outside the published cache entirely -- treating it as a hard failure would let a chain-selection or Leios-announcement caller wrongly reject and recycle an honest peer over a transient local gap instead of retrying once the nonce is published (matches how errBlockPipelineEta0Unavailable, which wraps the same sentinel, is already treated as non-fatal on the block-pipeline path).
func IsHeaderVerificationWithheld ¶ added in v0.87.0
IsHeaderVerificationWithheld reports that a header lacks enough chain-dependent context to be authenticated for chain selection. Callers retain its ancestry for later headers without observing or applying it.
func LeiosEndorserBlockBasisHash ¶ added in v0.89.0
func LeiosEndorserBlockBasisHash(header ledger.BlockHeader) []byte
LeiosEndorserBlockBasisHash returns the ledger-point hash an announced endorser block validates against: the announcing ranking block itself. CIP-164 makes the endorser block's transactions a valid extension of the ledger state that block leaves, which includes the transactions of any endorser block it certifies and its own body transactions, so they can spend outputs neither the block's parent state nor its own transactions alone contain. The block that certifies the endorser block is the next one, whose parent is the announcing block, so this is also the state those transactions are applied on.
func LeiosValidationParentHash ¶ added in v0.82.0
func LeiosValidationParentHash(header ledger.BlockHeader) []byte
LeiosValidationParentHash returns the canonical ledger-point hash named by an announcing header. The first block uses a null prev_hash on the wire, but the typed header accessor represents it as a zero Blake2b-256 value while the ledger origin point has an empty hash. Block number zero proves this is that origin representation; every later block retains its exact 32 bytes.
func PreviousEraEpoch ¶ added in v0.82.0
func PreviousEraEpoch( epochs []models.Epoch, epochID uint64, epochEraID, blockEraID uint, ) (models.Epoch, bool)
PreviousEraEpoch returns the last epoch before epochID whose era is blockEraID, for a block of an earlier era than the era epochEraID recorded for its epoch. The epoch that starts an era is recorded with the successor era, while transaction validation judges a block of the previous era applied there under the previous era's parameters, those of that era's last epoch. Historical paths that select protocol parameters by epoch use the returned epoch so they apply the same parameters. ok is false for a block of its epoch's era, or when no earlier epoch of the block's era is known.
func ShelleyStabilityWindow ¶ added in v0.87.0
func ShelleyStabilityWindow(sg *shelley.ShelleyGenesis) (uint64, error)
ShelleyStabilityWindow returns the Shelley-era stability window, 3k/f slots rounded up, from the Shelley genesis. It is the window the ledger uses from Shelley onwards, so callers that need it before a LedgerState exists, such as a snapshot restore sizing the history it keeps, agree with the ledger's own StabilityWindow.
func TransactionLevels ¶ added in v0.74.0
func TransactionLevels(tx common.Transaction) []common.Transaction
TransactionLevels returns the Dijkstra sub-transaction bodies in encoded order followed by the enclosing transaction body. Each level exposes its own body hash, witnesses, metadata, and ledger effects while retaining the validity of the enclosing transaction.
func TransactionLevelsForApply ¶ added in v0.74.0
func TransactionLevelsForApply(tx common.Transaction) []common.Transaction
TransactionLevelsForApply excludes Dijkstra sub-transactions when the enclosing transaction is invalid; only its collateral effects are applied.
func ValidateChainsyncHeaderCapacity ¶ added in v0.82.0
ValidateChainsyncHeaderCapacity checks that admitted ChainSync work fits between the working header target and the chain's minimum queue capacity.
func ValidateCheckpoint ¶ added in v0.56.0
ValidateCheckpoint enforces a set of configured chain checkpoints against a single block. The checkpoints map is keyed by block number (height) with the expected block hash as a hex string.
It returns nil when no checkpoints are configured, when there is no checkpoint at the given height, or when the block hash matches the configured checkpoint (case-insensitively). It returns a *CheckpointMismatchError when the height is checkpointed but the hash differs.
Honest chains always agree with the shipped checkpoints, so this rule can only reject a block on a divergent chain; it never rejects a block on the canonical chain.
func ValidateHeaderCheckpoint ¶ added in v0.92.0
func ValidateHeaderCheckpoint( checkpoints map[uint64]string, header ledger.BlockHeader, ) error
ValidateHeaderCheckpoint applies configured checkpoints to a peer header, so a header on a chain that diverges at a checkpointed height is refused before it can join a candidate chain. Header validity does not depend on the validation mode or on Mithril coverage, matching the block-apply rule.
Byron epoch boundary block headers share the preceding block's number and are skipped, as in validateBlockCheckpoint. The header hash is computed only when a checkpoint exists at the header's height.
func ValidateHeaderProtocolVersion ¶ added in v0.45.0
func ValidateHeaderProtocolVersion( header lcommon.BlockHeader, curPvMajor uint, isMainnet bool, ) error
ValidateHeaderProtocolVersion enforces cardano-ledger's BBODY-rule check that a block header's protocol major version is not more than one ahead of the current pparams protocol major version. A header equal to or one greater than current is accepted; anything beyond that is rejected with HeaderProtocolVersionTooHighError.
The check is skipped on testnets (isMainnet == false) while the current pparams major version is below Dijkstra (12). This mirrors the relaxation that cardano-ledger allows to support ephemeral testnets that enable experimental hard forks or rebuild chains in much older eras.
Byron-era headers are also skipped, as they have no ProtVer field.
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
RawBlock []byte // Original block CBOR used to invalidate rejected decode-cache entries
Point ocommon.Point // Chain point for block
Type uint // Block type ID
BatchDone bool // Set to true for a BatchDone event
// RequestId identifies the RequestRange call this event belongs to, from
// gouroboros' CallbackContext.RequestId (numbered from 1 in send order,
// per connection). A BatchDone event releases the ledger's in-flight
// entry for this request rather than the connection's oldest one, since
// pipelining keeps more than one request outstanding per connection.
// Zero means unnumbered and falls back to the oldest entry.
RequestId uint64
// RangeErr carries a BatchDone event's terminal outcome. gouroboros'
// RangeDoneFunc reports every pipelined request's resolution -- success,
// NoBlocks, or any transport/protocol failure -- exactly once through this
// same callback, so a BatchDone event is no longer necessarily a success.
// nil means the range completed successfully.
RangeErr error
}
BlockfetchEvent represents either a Block or BatchDone blockfetch event. We use a single event type for both to make synchronization easier.
type BlockfetchLatencyFunc ¶ added in v0.39.0
type BlockfetchLatencyFunc func(ouroboros.ConnectionId) (time.Duration, bool)
BlockfetchLatencyFunc returns the EWMA first-block latency for the given connection and whether any samples have been recorded. Used to gate shadow blockfetch dispatch on primary peer slowness.
type BlockfetchLatencyMedianFunc ¶ added in v0.39.0
BlockfetchLatencyMedianFunc returns the median EWMA first-block latency across all tracked peers and the sample count contributing to it. Used to adapt the shadow blockfetch gate to the observed peer population (primary > 1.5× median triggers shadow dispatch).
type BlockfetchRequestRangeFunc ¶
type BlockfetchRequestRangeFunc func(ouroboros.ConnectionId, ocommon.Point, ocommon.Point) (uint64, error)
BlockfetchRequestRangeFunc describes a callback function used to start a blockfetch request for a range of blocks. It returns the request ID the underlying client assigned the range (0 on error), which a future caller can use to distinguish this request's events from another outstanding on the same connection.
type ChainsyncAwaitReplyEvent ¶ added in v0.27.7
type ChainsyncAwaitReplyEvent struct {
ConnectionId ouroboros.ConnectionId
}
ChainsyncAwaitReplyEvent is emitted when a chainsync peer explicitly reports it has no additional headers to send right now.
type ChainsyncEvent ¶
type ChainsyncEvent struct {
ConnectionId ouroboros.ConnectionId // Connection ID associated with event
BlockHeader ledger.BlockHeader
// HeaderCryptoVerificationGeneration identifies the immutable ledger
// context in which the exact BlockHeader passed the chain-selection crypto
// verifier. Zero means no reusable verdict.
HeaderCryptoVerificationGeneration uint64
// ArrivalTime is recorded immediately when the ChainSync callback receives
// a roll-forward header. It lets ledger admission judge the peer's clock at
// arrival even if event delivery or header processing is delayed.
ArrivalTime time.Time
// ForecastHorizonWait is called once after admission establishes that this
// connected header must wait for ledger progress.
ForecastHorizonWait func()
Point ocommon.Point // Chain point for roll forward/backward
Tip ochainsync.Tip // Upstream chain tip
// SyncTarget is the event-paired, policy-approved target eligible for
// publication only after this header is admitted.
SyncTarget ochainsync.Tip
SyncTargetTrusted bool
// PeerTipUpdate is promoted into selector-visible state only after the
// ledger admits BlockHeader. A nil value is used by locally-built events.
PeerTipUpdate *chainselection.PeerTipUpdateEvent
// PeerTipAdmission reports definite admission or rejection synchronously
// to the ingress owner. It is not called while the header is buffered for a
// connection switch; the callback travels with that buffered event.
PeerTipAdmission func(admitted bool)
// InvalidatePeerHeaderHistory removes this point and its dependent suffix
// from the ingress owner's observed-header ancestry.
InvalidatePeerHeaderHistory func()
BlockNumber uint64
Type uint // Block or header type ID
Rollback bool // Set to true for a Rollback event
// contains filtered or unexported fields
}
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 CheckpointMismatchError ¶ added in v0.56.0
CheckpointMismatchError is returned when a block at a configured checkpoint height has a hash that differs from the expected one. This is an envelope-validity failure: the block sits on a chain that diverges from the known-good chain at a checkpointed height, so it must be rejected regardless of any other validity it might have.
func (*CheckpointMismatchError) Error ¶ added in v0.56.0
func (e *CheckpointMismatchError) Error() string
type ClearSeenHeadersFromFunc ¶ added in v0.27.7
type ClearSeenHeadersFromFunc func(fromSlot uint64)
ClearSeenHeadersFromFunc clears the header dedup cache for slots beyond the given slot. This allows headers that were discarded (e.g. by clearQueuedHeaders) to be re-delivered on reconnection.
type ConnectionClosedEvent ¶ added in v0.55.0
type ConnectionClosedEvent struct {
ConnectionId ouroboros.ConnectionId
Error error
}
ConnectionClosedEvent is emitted by the node layer when a connection closes. Ledger subscribes to this ledger-owned event type instead of connmanager directly, so ledger/ does not need to import connmanager/.
type ConnectionLiveFunc ¶ added in v0.32.2
type ConnectionLiveFunc func(ouroboros.ConnectionId) bool
ConnectionLiveFunc reports whether a connection is still registered with the connection manager. This allows the ledger to drop late chainsync events that arrive after teardown.
type ConnectionRecycleRequestedEvent ¶ added in v0.55.0
type ConnectionRecycleRequestedEvent struct {
ConnectionId ouroboros.ConnectionId
Reason string
}
ConnectionRecycleRequestedEvent is emitted by the ledger when a peer connection must be replaced. Node wiring translates this to a connmanager recycle request, keeping ledger/ free of connmanager/ imports.
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(drainTimeout time.Duration) error
Shutdown stops accepting new operations, then waits for every already accepted one to finish and the worker goroutines to exit.
The drain wait is bounded by drainTimeout -- callers pass CloseDBWorkerPoolShutdownTimeout, the same budget LedgerState.Close's own outer wait around the goroutine that calls Shutdown already uses. Close's outer wait keeps Close itself from blocking past that budget regardless of what Shutdown does, but a bound is still needed here: without one, a caller of Shutdown that gives up (like that outer wait) leaves nothing waiting on the drain at all, so a still-running worker's operation (and the resources it holds, e.g. this pool's db) would never be observed finishing -- and the fix could recur for any future operation slower than expected, not just the O(n^2) query bug this once surfaced as (see the account-lookup fix this guards against regressing).
The wait itself selects the drained channel directly rather than spawning a goroutine to block on a sync.WaitGroup: WaitGroup.Wait cannot be selected against a timeout, so a wrapper goroutine bridging it to a channel would still block for the slow operation's full remaining duration after Shutdown times out and returns -- trading the caller's leak for an internal one instead of removing it. drained is closed by whichever of Shutdown or operationDone observes the closed-and-drained transition first, so no goroutine is ever spawned here.
drainTimeout is a parameter rather than a direct read of CloseDBWorkerPoolShutdownTimeout so a test that mutates that var for isolation (see state_test.go) cannot race this call: Close evaluates the argument once, synchronously, before calling Shutdown.
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
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 DeferredBoundarySnapshot ¶ added in v0.75.0
type DeferredBoundarySnapshot interface {
SPOStakeRows() []*models.PoolStakeSnapshot
Write(txn *database.Txn) error
}
DeferredBoundarySnapshot is a boundary's mark snapshot prepared on a read transaction pinned at the boundary's commit, written through another.
type DijkstraDirectDepositEffect ¶ added in v0.74.0
type DijkstraDirectDepositEffect struct {
Credential common.Credential
Amount uint64
}
DijkstraDirectDepositEffect identifies one reward-account credit declared by a Dijkstra transaction body.
func DijkstraDirectDepositEffects ¶ added in v0.74.0
func DijkstraDirectDepositEffects( tx common.Transaction, ) ([]DijkstraDirectDepositEffect, error)
DijkstraDirectDepositEffects decodes the reward-account keys for one body.
type EndorserBlockDataProviderFunc ¶ added in v0.87.0
type EndorserBlockDataProviderFunc func( ebHash []byte, ebSlot uint64, ) (manifest []byte, txs []cbor.RawMessage, ok bool)
EndorserBlockDataProviderFunc returns the verified manifest and complete transaction bodies for the exact endorser-block occurrence. It lets ledger read paths serve a just-applied certified block before asynchronous historical persistence finishes.
type EndorserBlockFetcherFunc ¶ added in v0.58.0
EndorserBlockFetcherFunc actively fetches the endorser block identified by (ebSlot, ebHash) over leios-fetch (manifest plus all transaction bodies) and caches it so a subsequent EndorserBlockProviderFunc call returns it. It returns an error when no fetch connection is available or the relay does not serve the block; the former must wrap ErrEndorserBlockFetchNoPeer. The endorser block shares the slot of the ranking block that references it (they are co-produced), so ebSlot is the ranking block's slot.
ctx bounds the whole fetch, including its per-connection failover. The caller owns the budget: block application waits for this fetch, so an implementation must not outlive the context it was handed.
type EndorserBlockProviderFunc ¶ added in v0.56.0
type EndorserBlockProviderFunc func( ebHash []byte, ebSlot uint64, ) (txs []cbor.RawMessage, ok bool)
EndorserBlockProviderFunc returns the complete set of standalone transaction CBORs of the Leios endorser block identified by (ebHash, ebSlot), when exactly that occurrence has been fetched and fully cached; ok is false otherwise. ebSlot is required, not merely advisory: the manifest is content-addressed, so the same hash can be a live, independently required occurrence at more than one slot at once, and the provider must resolve exactly the occurrence the caller's own reference names rather than whichever one happens to be cached for the hash. It is used to apply an endorser block's transactions to the ledger when the referencing Dijkstra ranking block is processed.
type EndorserBlockValidationFunc ¶ added in v0.82.0
type EndorserBlockValidationFunc func( ebHash []byte, ebSlot uint64, ) EndorserBlockValidationStatus
EndorserBlockValidationFunc reports the cached semantic verdict for an endorser block identified by hash and slot.
type EndorserBlockValidationStatus ¶ added in v0.82.0
type EndorserBlockValidationStatus uint8
EndorserBlockValidationStatus reports the semantic-validation state of one cached endorser-block occurrence.
const ( // EndorserBlockValidationUnknown means no cached verdict is available. EndorserBlockValidationUnknown EndorserBlockValidationStatus = iota // EndorserBlockValidationPending means validation has not completed. EndorserBlockValidationPending // EndorserBlockValidationValid means cached validation succeeded. EndorserBlockValidationValid // EndorserBlockValidationInvalid means cached validation rejected the block. EndorserBlockValidationInvalid )
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
// RealV2CostModelObserved is true when this rollover's enacted governance
// ParamUpdate explicitly carried a PlutusV2 cost model
// (governance.EnactmentResult.PlutusV2CostModelWritten), not merely
// whether the post-enactment pparams happen to contain one. Provenance
// is tracked from the enacted delta itself rather than by comparing
// before/after values, because DefaultPlutusV2CostModel is the real
// canonical mainnet value: real governance re-affirming it verbatim
// would be indistinguishable from "unchanged" under a value-comparison
// approach, which would then never clear
// LedgerState.syntheticV2CostModel on a real network.
RealV2CostModelObserved bool
}
EpochRolloverResult holds computed state from epoch rollover
type EraTransitionResult ¶ added in v0.21.0
type EraTransitionResult struct {
NewPParams lcommon.ProtocolParameters
NewEra eras.EraDesc
// InjectedSyntheticV2CostModel is true when this specific transition is
// the one that fabricated a PlutusV2 cost model (HardForkBabbage's
// default), as opposed to one carried forward from a real source. See
// LedgerState.syntheticV2CostModel.
InjectedSyntheticV2CostModel bool
}
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. Chainsync uses it to attribute the local side of same-slot and restricted-window Praos battles.
type GenesisSelectionStateFunc ¶ added in v0.69.0
GenesisSelectionStateFunc returns whether authoritative fork resolution should use Ouroboros Genesis density and the active window in slots.
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 GetPeerObservedTipFunc ¶ added in v0.70.1
type GetPeerObservedTipFunc func( ouroboros.ConnectionId, ) (ochainsync.Tip, bool)
GetPeerObservedTipFunc returns the delivered frontier tracked for a peer. The boolean is false when the connection is no longer tracked.
type GetPeerSyncTargetFunc ¶ added in v0.70.3
type GetPeerSyncTargetFunc func( ouroboros.ConnectionId, ) (ochainsync.Tip, bool)
GetPeerSyncTargetFunc returns a corroborated remote sync target.
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 HeaderProtocolVersionTooHighError ¶ added in v0.45.0
HeaderProtocolVersionTooHighError is returned when a block header's protocol major version is more than one ahead of the current pparams protocol major version. Mirrors cardano-ledger's HeaderProtVerTooHigh failure from the BBODY rule.
func (*HeaderProtocolVersionTooHighError) Error ¶ added in v0.45.0
func (e *HeaderProtocolVersionTooHighError) Error() string
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 LedgerState ¶
type LedgerState struct {
Scheduler *Scheduler
sync.RWMutex
// contains filtered or unexported fields
}
func NewLedgerState ¶
func NewLedgerState(cfg LedgerStateConfig) (*LedgerState, error)
func (*LedgerState) AcquireQueryView ¶ added in v0.79.0
func (ls *LedgerState) AcquireQueryView( ctx context.Context, at QueryPoint, ) (*QueryView, error)
AcquireQueryView opens a snapshot of the ledger and validates at against it. An unpinned at (the zero QueryPoint) snapshots the live tip; a pinned at must pass VerifyPointQueryable, and its error is returned unchanged so the caller can map the ErrPointNotOnChain and ErrHistoricalStateUnavailable sentinels to protocol-level Acquire failures.
The snapshot is a database.NewReadSnapshotContext: its blob and metadata views are opened at one commit boundary, and it counts against the read snapshot admission cap, which keeps one metadata read connection free for the rest of the node however many views are held. When the cap is reached AcquireQueryView waits for a view to close, and returns ctx's error if ctx ends first. ctx bounds only opening the view, not the view's lifetime. Opening also waits for the latest epoch boundary's deferred job, and an error from a ctx that ends during that wait wraps ErrEpochBoundaryJobPending.
func (*LedgerState) AcquiredPointPinCountForTesting ¶ added in v0.79.1
func (ls *LedgerState) AcquiredPointPinCountForTesting() int
AcquiredPointPinCountForTesting reports how many acquired-point pins are live, so a test outside this package can prove every path that clears an acquired point also releases its pin. A leaked pin is otherwise invisible until it has held pruning back for days.
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) ActiveSlotCoeffRat ¶ added in v0.69.0
func (ls *LedgerState) ActiveSlotCoeffRat() *big.Rat
ActiveSlotCoeffRat returns the active slot coefficient (f) as an exact *big.Rat taken straight from the Shelley genesis, with no float64 roundtrip. Returns nil when the genesis is unavailable.
Prefer this over ActiveSlotCoeff for anything that feeds a leader check. ActiveSlotCoeff divides the genesis numerator and denominator as float64, and the nearest double to a value like 1/20 is strictly larger than 1/20, so a threshold derived from it is strictly larger than the reference node's and admits a strict superset of eligible slots. Both the header-verification path and the leader-schedule precompute must use this exact value so they cannot disagree with each other or with the reference.
func (*LedgerState) AdoptLocalForgedSibling ¶ added in v0.70.14
func (ls *LedgerState) AdoptLocalForgedSibling(ctx context.Context, block gledger.Block, ) (bool, error)
AdoptLocalForgedSibling offers a locally forged block that competes with the current chain tip, rather than extending it, to chain selection.
This is the local counterpart of what a peer-delivered competing block does today. When a peer sends a header that does not fit our tip, chainsync's tryResolveFork compares it against the local tip with praos.ComparePraosTips, and if it wins, rolls the chain and ledger back to the common ancestor and adopts the peer's chain from there. A block this node forges itself at a slot a rival already occupies is the same situation with the same arbitration, but it arrives through the forger rather than through a connection, so it cannot enter that path: tryResolveFork is keyed on a ChainsyncEvent, a peer connection, that peer's retained header history and a blockfetch restart, none of which exist here.
What is shared is the decision and the mutation:
- The decision is praos.ComparePraosTips on the two tips and their select views, the same comparison tryResolveFork makes, with no preference for the local block. A candidate that does not strictly win is dropped.
- The mutation is rollbackChainAndStateDeferred to the common parent followed by the adoption of the winner, the same sequence tryResolveFork performs. It runs under chainsyncMutex, which is the lock that path holds, so a rollback driven from the forge loop is serialized against concurrent chainsync header handling exactly as one driven from a peer is.
The rollback is always exactly one block deep, to the block both candidates name as parent, and it is only reached after the candidate has been checked to be a genuine sibling of the tip.
It reports whether the block was adopted. Losing chain selection is a normal outcome and returns (false, nil): the rival keeps the slot and the forged block is discarded undiffused.
func (*LedgerState) ApplyTrustedBatch ¶ added in v0.87.0
func (ls *LedgerState) ApplyTrustedBatch( ctx context.Context, expected ocommon.Point, blocks []ledger.Block, ) (ocommon.Point, error)
ApplyTrustedBatch applies blocks, which must extend expected, as trusted history: their effects are applied as under TrustedReplay, with no rule or script validation. The caller vouches for the blocks, for example because they lie at or below a certified immutable tip. It returns the new ledger tip.
It must be called between PauseChainIngest and its resume, which makes it the ledger's only block-apply writer. If the ledger tip is not expected it returns ErrStaleBatch and changes nothing. A tip that moves after that check -- a rollback while the batch applies, or a block appended to the primary chain while paused -- also surfaces as ErrStaleBatch, with no metadata committed. A batch longer than MaxTrustedBatchBlocks, or one reaching at or below the Mithril trust boundary, is refused before anything is stored.
The blocks are stored in the primary chain first, in blob-only transactions, because UTxO and transaction rows hold offsets into the stored block CBOR. Their effects are then committed in one metadata transaction, in which an output both created and spent by the batch is removed before commit. An epoch boundary inside the batch is the exception: the blocks before it, the epoch rollover and the blocks after it commit in three transactions, as they do on every other apply path.
A batch whose commit Badger refuses as too big for one transaction is applied again as two halves, each its own commit with the same tip guard, recursively down to a single block, so a dense range is applied in smaller commits instead of failing on every attempt. Nothing is skipped: a single block Badger still refuses fails the call.
After the first batch of a process, and then once every trustedBatchPruneEvery committed batches, spent UTxO rows up to the tip are hard-deleted with the routine consumed-UTxO cleanup (see pruneConsumedUtxosAfterTrustedBatch); DrainTrustedPrune runs the cleanup the batches since still owe. API storage mode keeps them.
A failure after the blocks are stored leaves the ledger tip where it was. Calling again with the same expected point and blocks reuses the stored blocks; nothing else needs undoing.
func (*LedgerState) AwaitAppliedSlot ¶ added in v0.87.0
func (ls *LedgerState) AwaitAppliedSlot( ctx context.Context, slot uint64, ) error
AwaitAppliedSlot blocks until the applied ledger tip has reached slot, or ctx ends, in which case it returns ctx's error. The applied tip is published only after the block's transaction commits, so once this returns a fresh read snapshot sees a tip at or beyond slot.
func (*LedgerState) AwaitChainsyncHeaderAdmission ¶ added in v0.70.1
func (ls *LedgerState) AwaitChainsyncHeaderAdmission( ctx context.Context, e ChainsyncEvent, ) (bool, error)
AwaitChainsyncHeaderAdmission enforces the Ouroboros ChainSync future-header rule against the timestamp recorded at network ingress. It must run from the per-peer ChainSync callback before the header updates observed-tip, dedup, or ledger state; callers must not invoke it while holding the node-wide chainsync dispatch mutex.
A header received no more than defaultHeaderClockSkew before its slot waits for slot onset and is accepted. A header received earlier is deliberately dropped by returning (false, nil): local clock skew cannot by itself justify penalizing the peer. A header past the ledger's forecast horizon cannot be validated, so it waits until the applied ledger advances far enough to forecast its slot before the onset check runs, as the reference ChainSync client does for OutsideForecastRange; until then it must not influence chain selection or reach blockfetch. A header whose predecessor does not connect to the local chain waits while queued or in-flight local work may connect it; otherwise it returns an error wrapping ErrChainsyncHeaderDisconnected. A connected header also returns ErrChainsyncHeaderNeedsResync when no queued or in-flight blockfetch, and no stored block the ledger has yet to apply, can publish state to advance the forecast. Other conversion failures fail closed. A zero timestamp is retained for compatibility with synthetic/internal events that never crossed the network ingress path. As with other Go APIs that accept a context, ctx must not be nil.
func (*LedgerState) AwaitChainsyncHeaderCapacity ¶ added in v0.82.0
func (ls *LedgerState) AwaitChainsyncHeaderCapacity( ctx context.Context, admittedHeadroom int, ) error
AwaitChainsyncHeaderCapacity pauses ChainSync before header admission when a running BlockFetch leaves too little room for admitted EventBus work. The initial fill may reach the working header target so BlockFetch can start. Once a fetch is active or pending, the wait resumes after it drains one batch, retaining several ready batches without reaching the hard queue cap.
func (*LedgerState) AwaitObserverHeaderHorizon ¶ added in v0.90.2
func (ls *LedgerState) AwaitObserverHeaderHorizon( ctx context.Context, e ChainsyncEvent, ) error
AwaitObserverHeaderHorizon blocks until the published ledger state can forecast e's slot, or ctx ends. It serves observer connections, whose headers are never fetched: unlike AwaitChainsyncHeaderAdmission it starts no blockfetch and requests no re-intersection, because the ingress connections advance the horizon and an observer only has to stop reading ahead of it.
Every held observer wakes on every publication, so a wake must not walk the peer's ancestry again: the fork anchor is resolved once and reused until the local chain withdraws a block or the ledger tip falls to it.
func (*LedgerState) BlockByHash ¶ added in v0.21.0
BlockByHash returns a block by its hash.
func (*LedgerState) BlockByHashIncludingRolledBack ¶ added in v0.87.0
func (ls *LedgerState) BlockByHashIncludingRolledBack( ctx context.Context, hash []byte, ) (models.Block, error)
BlockByHashIncludingRolledBack returns a block by its hash, also finding a block that a primary-chain rollback removed from the database but the chain manager still caches. Use it only to reconstruct what a rollback undid; BlockByHash is the lookup for blocks on the current chain.
func (*LedgerState) BlockProcessingSlot ¶ added in v0.92.0
func (ls *LedgerState) BlockProcessingSlot() (uint64, bool)
BlockProcessingSlot returns the highest slot successfully processed inside a block-apply transaction and whether any block has completed during this LedgerState's lifetime. It is a local work signal, not a committed tip or a validation/readiness verdict. The slot never decreases, so retrying the same failed batch cannot report fresh progress. The boolean distinguishes slot zero from a ledger that has not processed a block.
func (*LedgerState) BlockTransactionCount ¶ added in v0.91.0
func (ls *LedgerState) BlockTransactionCount( ctx context.Context, block models.Block, ) (int, error)
BlockTransactionCount counts the top-level transactions represented by a stored block, retaining the integrity checks used by BlockTransactions.
func (*LedgerState) BlockTransactions ¶ added in v0.87.0
func (ls *LedgerState) BlockTransactions( ctx context.Context, block models.Block, ) ([]lcommon.Transaction, error)
BlockTransactions returns the ledger transactions represented by a stored block. A Dijkstra certifying ranking block represents the transaction bodies in the endorser block announced by its parent; those bodies are retained separately from the ranking block CBOR.
func (*LedgerState) BlockfetchRangeExpectedBytes ¶ added in v0.74.0
func (ls *LedgerState) BlockfetchRangeExpectedBytes( start, end ocommon.Point, ) uint64
BlockfetchRangeExpectedBytes returns the estimated wire size of the blocks start through end, summed from the queued headers, for use as a block-fetch request's expected size. It returns 0, meaning no estimate, when the range holds a header whose size is unknown (Byron) or one that is no longer queued (after a rollback or eviction); a partial sum would understate the request.
It takes only the chain's read lock, so it is safe to call without chainsyncBlockfetchMutex, as the external request dispatch does.
func (*LedgerState) ByronProtocolMagic ¶ added in v0.70.0
func (ls *LedgerState) ByronProtocolMagic() (uint32, error)
ByronProtocolMagic returns the protocol magic configured in Byron genesis.
func (*LedgerState) ByronProtocolParameters ¶ added in v0.74.0
func (ls *LedgerState) ByronProtocolParameters() ( *eras.ByronProtocolParameters, error, )
ByronProtocolParameters returns the Byron protocol parameters adopted as of the ledger tip, or the Byron genesis parameters before the update state has been built. Block application validates against the parameters adopted for each block's own epoch instead, passed as its pparams.
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) CertifiedClosureTransactions ¶ added in v0.89.0
func (ls *LedgerState) CertifiedClosureTransactions( ctx context.Context, decoded ledger.Block, ) ([]lcommon.Transaction, error)
CertifiedClosureTransactions returns the transactions a certifying ranking block applies from the certified closure: the endorser block its parent announced, in manifest order. It returns nil for a block that certifies nothing. The ledger applies these transactions with the ranking block, so they are as confirmed as the block's own transactions, and a rollback of the block undoes them; the mempool uses this to evict them and, on a rollback, to restore them, exactly as it does for the block's own transactions.
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) CheckLeiosCertificationTiming ¶ added in v0.86.0
func (ls *LedgerState) CheckLeiosCertificationTiming( announcingSlot uint64, slot uint64, ) error
CheckLeiosCertificationTiming reports whether a ranking block at slot may certify the endorser block announced by the ranking block at announcingSlot. It returns nil when it may, errLeiosCertificateAcrossEpochBoundary when the announcement was made in another epoch, and errLeiosCertificateTooYoung when the certification gap has not elapsed. Any other error means the node could not decide, which says nothing about the block.
func (*LedgerState) Close ¶
func (ls *LedgerState) Close() (retErr error)
func (*LedgerState) ConsensusModeForEpoch ¶ added in v0.39.3
func (ls *LedgerState) ConsensusModeForEpoch( epoch uint64, ) (consensus.ConsensusMode, error)
ConsensusModeForEpoch returns the Praos consensus variant that governs leader eligibility for the given epoch.
func (*LedgerState) CountTransactionsByAddress ¶ added in v0.33.0
func (ls *LedgerState) CountTransactionsByAddress( ctx context.Context, addr lcommon.Address, from *models.AddressTransactionPosition, to *models.AddressTransactionPosition, ) (int, error)
CountTransactionsByAddress returns the total number of transactions involving the given address.
func (*LedgerState) CountTransactionsByMetadataLabel ¶ added in v0.34.0
func (ls *LedgerState) CountTransactionsByMetadataLabel( label uint64, ) (int, error)
CountTransactionsByMetadataLabel returns the total number of transactions that include metadata for the requested label.
func (*LedgerState) CurrentEpoch ¶ added in v0.22.0
func (ls *LedgerState) CurrentEpoch() uint64
CurrentEpoch returns the current epoch number.
func (*LedgerState) CurrentHeaderCryptoVerificationGeneration ¶ added in v0.86.0
func (ls *LedgerState) CurrentHeaderCryptoVerificationGeneration() uint64
CurrentHeaderCryptoVerificationGeneration returns the current generation, or zero while the consensus and tip snapshots are not jointly stable.
func (*LedgerState) CurrentOrTipSlot ¶ added in v0.32.0
func (ls *LedgerState) CurrentOrTipSlot() uint64
CurrentOrTipSlot returns the current wall-clock slot if available, or the current chain tip slot when the slot clock is unavailable. When both are available, it returns whichever slot is ahead.
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) CurrentTransitionInfo ¶ added in v0.36.0
func (ls *LedgerState) CurrentTransitionInfo() hardfork.TransitionInfo
CurrentTransitionInfo returns the current TransitionInfo from the lock-free consensus snapshot.
func (*LedgerState) Database ¶ added in v0.22.0
func (ls *LedgerState) Database() *database.Database
Database returns the underlying database for transaction operations.
func (*LedgerState) Datums ¶ added in v0.90.0
Datums looks up datums by hash in one read transaction for query.ReadData. The result is aligned with hashes; an entry is nil when that datum is not stored.
func (*LedgerState) DelegatorInactivityConfig ¶ added in v0.69.0
func (ls *LedgerState) DelegatorInactivityConfig() (enabled bool, window uint64)
DelegatorInactivityConfig reports the CIP-0163 delegator-inactivity gate as this LedgerState was actually constructed with. Exported so callers outside the ledger package (e.g. a regression test proving these values survive a live restore/truncate's LedgerState reinitialization, the same kind of construction-site drift MinPoolMargin/PledgeLeverageEnabled/ PledgeLeverage/FullPotRewardsEnabled were previously found missing from) can verify it without reaching into the unexported config field.
func (*LedgerState) DrainTrustedPrune ¶ added in v0.89.0
func (ls *LedgerState) DrainTrustedPrune(ctx context.Context) error
DrainTrustedPrune runs the consumed-UTxO cleanup that trusted batches still owe, up to the tip the last of them committed, until nothing prunable is left there or ctx ends. Unlike the cleanup a batch runs, it has no time budget, and it waits out another cleanup run rather than skipping, so a catch-up that calls it before resuming chain ingest leaves the backlog a cleanup after every batch would leave. It returns ctx's error when ctx ends first and the cleanup's error when it fails; the rows it did not reach stay marked spent for the periodic cleanup.
The node does not leave catch-up until the drain returns, so when cleanup is owed it logs its start and its end, with the rows it deleted, at Info.
func (*LedgerState) ElectingPoolStake ¶ added in v0.89.0
func (ls *LedgerState) ElectingPoolStake( slot uint64, poolKeyHash lcommon.PoolKeyHash, ) (uint64, error)
ElectingPoolStake returns the pool's stake in the distribution that elects leaders at slot: the same snapshot, and the same choice between the mark snapshot and a Mithril-imported active distribution, that header verification checks a block from that pool at that slot against. A pool absent from a populated distribution has zero stake and no error.
func (*LedgerState) EndorserBlockWaitDuration ¶ added in v0.66.2
func (ls *LedgerState) EndorserBlockWaitDuration() time.Duration
EndorserBlockWaitDuration returns the wall-clock window to wait for a referenced/certified endorser block's transaction closure to become available, derived from the Leios pipeline timing (EndorserBlockWaitSlots, the certify-by deadline) and the Shelley slot length. It returns 0 when the wait is disabled or the slot length is unknown. This is the same window ledger application uses to gate a ranking block on its endorser block (see ensureReferencedEndorserBlocks), so NtC serving and ledger application wait for the same healthy closure-delivery window.
func (*LedgerState) EpochBoundaryJobPending ¶ added in v0.87.0
func (ls *LedgerState) EpochBoundaryJobPending() bool
EpochBoundaryJobPending reports whether the most recent boundary's deferred work is still running, so WaitEpochBoundaryJob would block. A boundary that has committed but not yet published its job is not reported.
func (*LedgerState) EpochInfo ¶ added in v0.63.0
func (ls *LedgerState) EpochInfo(epoch uint64) (models.Epoch, error)
EpochInfo returns boundary information for the given epoch. See SlotTimeConverter.EpochInfo for details.
func (*LedgerState) EpochNonce ¶ added in v0.22.0
func (ls *LedgerState) EpochNonce(ctx context.Context, 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) EraIDForEpoch ¶ added in v0.89.0
func (ls *LedgerState) EraIDForEpoch( epoch uint64, ) (uint, error)
EraIDForEpoch returns the ledger era governing an epoch.
Resolution order, mirroring how the leader-election caller can be computing the schedule for the current epoch or pre-computing the next one across a scheduled hard fork:
- Look up the epoch's stored EraId in epochCache (set by the epoch rollover when the epoch is created).
- If we don't have that epoch yet (precompute path) and a hard fork has been confirmed via HardForkInitiation, transitionInfo pins the first epoch of the next era; advance once when the target epoch is at or past that boundary.
- Otherwise forecast the era forward from the current era using the schedule's TriggerAtEpoch trigger (TestXHardForkAtEpoch overrides surface here too), advancing once per scheduled boundary at-or-before the target epoch.
- Fall back to the current era if nothing applies.
Step 3 is a forecast, so it fails closed: an era shape the node configuration cannot supply returns an error rather than the current era's mode. Silently answering with the current era's mode for a future epoch is what a scheduled hard fork changes, and the wrong mode changes both the VRF leader-value derivation and the threshold, so callers must decline to answer instead of producing a mode nothing established. Steps 1, 2 and 4 read state the node already holds and never error.
func (*LedgerState) EvaluateTx ¶ added in v0.16.0
func (ls *LedgerState) EvaluateTx( tx lcommon.Transaction, ) (uint64, lcommon.ExUnits, map[lcommon.RedeemerKey]lcommon.ExUnits, error)
EvaluateTx evaluates the scripts in the provided transaction and returns the calculated fee, per-redeemer ExUnits, and total ExUnits.
func (*LedgerState) EvaluateTxContext ¶ added in v0.81.0
func (ls *LedgerState) EvaluateTxContext( ctx context.Context, tx lcommon.Transaction, ) (uint64, lcommon.ExUnits, map[lcommon.RedeemerKey]lcommon.ExUnits, error)
EvaluateTxContext evaluates transaction scripts until completion or context cancellation, using ctx to cancel storage work.
func (*LedgerState) ExistingTransactionHashes ¶ added in v0.90.0
func (ls *LedgerState) ExistingTransactionHashes( ctx context.Context, hashes [][]byte, ) ([][]byte, error)
ExistingTransactionHashes returns the subset of hashes that have a transaction record, in no particular order, from one read transaction.
func (*LedgerState) ForgeTipSnapshot ¶ added in v0.77.0
func (ls *LedgerState) ForgeTipSnapshot() (ochainsync.Tip, int)
ForgeTipSnapshot returns the applied tip and its era's security parameter from matching published ledger generations.
func (*LedgerState) GenesisDelegateForGenesisKey ¶ added in v0.73.1
func (ls *LedgerState) GenesisDelegateForGenesisKey( genesisKeyHash lcommon.Blake2b224, slot uint64, ) (lcommon.Blake2b224, bool, error)
GenesisDelegateForGenesisKey resolves the active delegate for a Shelley genesis key at slot.
func (*LedgerState) GenesisDelegateKeyHashes ¶ added in v0.73.1
func (ls *LedgerState) GenesisDelegateKeyHashes( slot uint64, ) ([]lcommon.Blake2b224, error)
GenesisDelegateKeyHashes returns the active Shelley genesis delegate keys used by the classic PPUP and MIR rules at slot.
func (*LedgerState) GenesisUpdateQuorum ¶ added in v0.73.1
func (ls *LedgerState) GenesisUpdateQuorum() (uint, error)
GenesisUpdateQuorum returns the quorum configured by Shelley genesis.
func (*LedgerState) GetBlockContext ¶ added in v0.90.0
func (ls *LedgerState) GetBlockContext( ctx context.Context, point ocommon.Point, ) (models.Block, error)
GetBlockContext is GetBlock with a caller-supplied context that cancels the metadata lookup. The blob read that follows takes no context, so a read already in flight finishes before the call returns.
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) GetChainFromPointContext ¶ added in v0.49.1
func (ls *LedgerState) GetChainFromPointContext( ctx context.Context, point ocommon.Point, inclusive bool, ) (*chain.ChainIterator, error)
GetChainFromPointContext returns a ChainIterator that inherits cancellation from ctx.
func (*LedgerState) GetChainFromPointReverse ¶ added in v0.47.0
func (ls *LedgerState) GetChainFromPointReverse( point ocommon.Point, inclusive bool, ) (*chain.ChainIterator, error)
GetChainFromPointReverse returns a ChainIterator that walks backward from the specified point toward chain origin. If inclusive is true the iterator yields the start point first; otherwise it yields the preceding block.
func (*LedgerState) GetChainFromPointReverseContext ¶ added in v0.49.1
func (ls *LedgerState) GetChainFromPointReverseContext( ctx context.Context, point ocommon.Point, inclusive bool, ) (*chain.ChainIterator, error)
GetChainFromPointReverseContext returns a reverse ChainIterator that inherits cancellation from ctx.
func (*LedgerState) GetCurrentPParams ¶
func (ls *LedgerState) GetCurrentPParams() lcommon.ProtocolParameters
GetCurrentPParams returns the currentPParams value
func (*LedgerState) GetCurrentPParamsForReporting ¶ added in v0.70.7
func (ls *LedgerState) GetCurrentPParamsForReporting() lcommon.ProtocolParameters
GetCurrentPParamsForReporting returns the current protocol parameters with HardForkBabbage's fabricated PlutusV2 cost model omitted for as long as it hasn't been replaced by real governance/protocol-update data -- matching what a real cardano-node reports. This is for external reporting surfaces only: LocalStateQuery's GetCurrentProtocolParams (ledger/queries.go), and the Blockfrost/UTXORPC/Mesh API adapters that separately surface protocol parameters. Every other caller (script validation, block-building limits, Leios committee parameters, governance proposal decoding) must keep calling GetCurrentPParams: internal logic needs the real fabricated default unconditionally, since a genuine PlutusV2 script can arrive before the real update lands.
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( ctx context.Context, 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) GetTransactionsByAddressWithOrder ¶ added in v0.33.0
func (ls *LedgerState) GetTransactionsByAddressWithOrder( ctx context.Context, addr lcommon.Address, limit int, offset int, order string, from *models.AddressTransactionPosition, to *models.AddressTransactionPosition, ) ([]models.Transaction, error)
GetTransactionsByAddressWithOrder returns transactions involving the given address with explicit ordering.
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) GetTransactionsByHashes ¶ added in v0.33.0
func (ls *LedgerState) GetTransactionsByHashes( hashes [][]byte, ) ([]models.Transaction, error)
GetTransactionsByHashes returns transactions for the provided hashes.
func (*LedgerState) HardForkSummary ¶ added in v0.37.0
func (ls *LedgerState) HardForkSummary() (*hardfork.Summary, error)
HardForkSummary constructs a hardfork.Summary describing the chain's era history from the LedgerState's current epoch cache, tip, current era, and transition info.
The returned Summary's past eras are closed with bounds computed by walking the epoch cache grouped by EraId. The current era is passed through hardfork.BuildSummary with the safe zone from the configured era Shape and the ledger's current TransitionInfo. This gives in-memory callers the same bounded forecast inputs used by the NtC HardForkEraHistory query.
The forecast horizon is measured from the published tip. Callers that know a more recent applied block must use hardForkSummaryAnchoredAt instead.
The result is cached per hardForkSummaryCacheKey (see its doc comment); the underlying epoch-cache walk is O(known epochs), which otherwise grows without bound as the chain ages.
The returned Summary is shared by every caller holding the same cache entry and must be treated as read only. Callers must not assign to its fields, append to Eras, or write through an interior pointer such as the one CurrentEra returns; doing so would corrupt the era boundaries every concurrent reader sees. Copy it first if a mutable Summary is needed. The alternative — returning a deep copy per call — would restore the per-call allocation this cache exists to remove.
func (*LedgerState) HeaderCryptoVerificationGenerationCurrent ¶ added in v0.86.0
func (ls *LedgerState) HeaderCryptoVerificationGenerationCurrent( generation uint64, ) bool
HeaderCryptoVerificationGenerationCurrent reports whether a producer authorization verdict still matches the live ledger snapshots.
func (*LedgerState) HeaderVerificationSettledChan ¶ added in v0.90.2
func (ls *LedgerState) HeaderVerificationSettledChan() <-chan struct{}
HeaderVerificationSettledChan returns a channel closed by the next snapshot publication or finished validation transition. Callers retrying a deferred header verification obtain it before the attempt, so a publication during the attempt still wakes them.
func (*LedgerState) HoldEpochBoundaryJobForTesting ¶ added in v0.87.0
func (ls *LedgerState) HoldEpochBoundaryJobForTesting( epoch uint64, ) (release func())
HoldEpochBoundaryJobForTesting publishes an epoch boundary job for epoch that stays pending until release runs, for tests of readers that wait on one. The job has no pending-ratification record in the database.
func (*LedgerState) HoldNetworkIngest ¶ added in v0.87.0
func (ls *LedgerState) HoldNetworkIngest() (release func())
HoldNetworkIngest stops the ledger storing anything Ouroboros delivers until release is called. Peers stay connected and the inbound chainsync and blockfetch servers keep serving committed history, but client chainsync headers and rollbacks are dropped without being queued and no blockfetch is issued. The headers already queued and any blockfetch batch in flight are discarded before it returns, so on return the network adds nothing to the chain and an external writer, such as ApplyTrustedBatch, meets no queued header.
Holds nest: ingest resumes when every release has been called, and calling one release more than once has no further effect. The last release resets the header and blockfetch pipeline and publishes a ChainsyncResyncEvent with reason ChainsyncResyncReasonNetworkIngestReleased at the current chain tip, which closes every chainsync client so each reconnects and re-intersects from that tip. With a NetworkIngestHoldTracker configured, a connection that existed during the hold stays dropped after the release until it closes.
func (*LedgerState) ImmutablePoint ¶ added in v0.79.1
ImmutablePoint returns the primary-chain point k blocks behind the applied ledger tip. found is false while the retained chain is too short to have a non-origin immutable point.
func (*LedgerState) IntersectPoints ¶ added in v0.27.1
IntersectPoints returns chainsync FindIntersect candidates ordered from newest to oldest. The point list stays dense near the tip and spreads out deeper in history so lagging peers intersect recent chain state instead of falling back to origin after only a small tip gap.
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) IsByronEra ¶ added in v0.83.0
func (ls *LedgerState) IsByronEra() bool
IsByronEra reports whether the applied ledger is still in the Byron era.
func (*LedgerState) LatestOpCertSequence ¶ added in v0.43.0
func (ls *LedgerState) LatestOpCertSequence( poolID [28]byte, ) (sequence uint64, found bool, err error)
LatestOpCertSequence returns the highest opcert issue-number counter observed for poolID, honoring the same Mithril trust boundary block application enforces (see latestOpCertCounterAfterMithril): a plain MAX over the whole table would trust rows a Mithril import left below the certified boundary, giving startup and forge-loop credential checks a baseline block application itself does not use.
func (*LedgerState) LedgerPeerSnapshot ¶ added in v0.90.0
func (ls *LedgerState) LedgerPeerSnapshot( ctx context.Context, ) (olocalstatequery.LedgerPeerSnapshotResult, error)
LedgerPeerSnapshot returns the relays that active pools registered, with their stake, as of the current tip: what GetLedgerPeerSnapshot reports for every ledger peer. It lets a component of the same process learn peers from the ledger without going through a local socket.
func (*LedgerState) LedgerTipIntersectPoints ¶ added in v0.89.0
func (ls *LedgerState) LedgerTipIntersectPoints( ctx context.Context, count int, ) ([]ocommon.Point, error)
LedgerTipIntersectPoints returns chainsync FindIntersect candidates ordered from newest to oldest, starting at the applied ledger tip rather than at any primary-chain header ahead of it. Like IntersectPoints, it includes the Mithril trust boundary.
func (*LedgerState) MarkReachedTipForTesting ¶ added in v0.88.0
func (ls *LedgerState) MarkReachedTipForTesting()
MarkReachedTipForTesting latches the flag a node sets the first time it reaches the stability window, as a live node at its tip has. It exists for black-box tests that drive a started ledger as a live node without an upstream connection: until the flag latches, the chain-iterator loop holds each under-full batch while it waits for more blocks.
func (*LedgerState) MaxBlockSize ¶ added in v0.81.0
func (ls *LedgerState) MaxBlockSize() uint64
MaxBlockSize returns the largest serialized block this chain admits for a stored block of any era: persisted and current header/body limits plus framing, or the Byron genesis block size limit when that is larger. A stored block was admitted under its own era's limits, and Byron main and epoch boundary blocks are bounded by the genesis maxBlockSize rather than the much smaller Shelley-family limits, so the current limits alone would refuse Byron history. It returns 0 when neither limit is known, which callers treat as unknown.
The persisted limits are read once. While the ledger runs, a new row is written only by an epoch transition, as the parameters it makes current, so folding in the current limits on each call keeps the bound complete without re-reading the history on every archive download.
func (*LedgerState) MaxTxSize ¶ added in v0.88.0
func (ls *LedgerState) MaxTxSize(txEraId uint) (uint, bool)
MaxTxSize returns the MaxTxSize that ledger validation applies to a transaction of the current era. It reports false for every other era so the ledger returns the typed era-mismatch error instead of an early size error. It also reports false when the current era has no transaction validator, Dijkstra validation is skipped, or the parameters are unknown or have the wrong type.
func (*LedgerState) MempoolSubmissionCapacity ¶ added in v0.88.0
func (ls *LedgerState) MempoolSubmissionCapacity() int
MempoolSubmissionCapacity returns the coordinated metadata snapshot limit. The mempool uses it to keep validation below the backing read pool's operational reserve.
func (*LedgerState) MinPoolMargin ¶ added in v0.67.0
func (ls *LedgerState) MinPoolMargin() *big.Rat
MinPoolMargin returns the CIP-23 minimum pool margin as a rational in [0, 1], or nil when disabled (config value 0). It satisfies the eras package MinPoolMarginProvider interface used by the Dijkstra pool-margin-floor certificate rule; the Dijkstra-only era gate is inherent because only ValidateTxDijkstra consults it.
func (*LedgerState) NetworkIngestHeld ¶ added in v0.87.0
func (ls *LedgerState) NetworkIngestHeld() bool
NetworkIngestHeld reports whether a HoldNetworkIngest is outstanding.
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) NextEpochNonceReadyEpoch ¶ added in v0.27.3
func (ls *LedgerState) NextEpochNonceReadyEpoch() (uint64, bool)
NextEpochNonceReadyEpoch reports the upcoming epoch when the current epoch has already crossed the nonce stability cutoff and the next leader schedule can be precomputed immediately.
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) OldestRequiredSnapshotEpoch ¶ added in v0.70.6
func (ls *LedgerState) OldestRequiredSnapshotEpoch() (uint64, bool)
OldestRequiredSnapshotEpoch returns the oldest pool-stake snapshot epoch that a currently queued/deferred header still needs for leader-eligibility validation, so snapshot pruning can retain it instead of removing it out from under the deferred header. It locks the deferred-header set and delegates to oldestRequiredSnapshotEpochLocked. Prefer PrunePoolSnapshotsWithRetentionFloor for the prune path, which holds the lock across both the floor read and the prune so admission cannot interleave; this public method exists for observation and tests.
func (*LedgerState) OldestRetainedSlot ¶ added in v0.92.2
func (ls *LedgerState) OldestRetainedSlot() (slot uint64, ok bool)
OldestRetainedSlot returns the slot of the oldest block whose body is still stored locally, as last computed by the history-expiry pruner. ok is false when that is not known. It reads only memory.
func (*LedgerState) PauseChainIngest ¶ added in v0.87.0
func (ls *LedgerState) PauseChainIngest() (resume func())
PauseChainIngest stops the ledger's chain-iterator loop from applying blocks until resume is called. It waits for the loop to finish the read result it is applying, so on return no block-apply transaction of the loop is in flight. Nested pauses are counted: the loop resumes when every resume has been called, and calling one resume more than once has no further effect.
While paused the loop may still read the chain ahead of the ledger tip, but it applies nothing. A read taken before ApplyTrustedBatch moved the tip is discarded on resume and the loop restarts from the new tip.
It must not be called from the chain-iterator loop's goroutine or from a ledger event handler the loop waits on: the call waits for the loop to finish its current read result, so it would wait on itself.
func (*LedgerState) PendingRewardCredit ¶ added in v0.73.4
func (ls *LedgerState) PendingRewardCredit( txn *database.Txn, credentialTag uint8, stakingKey []byte, ) (uint64, error)
PendingRewardCredit returns the part of a credential's reward balance that an applied reward round has not written to its account row yet. A reader of the account row's reward adds it, read in the same txn, to report the balance.
func (*LedgerState) Phase2ResultCache ¶ added in v0.90.5
func (ls *LedgerState) Phase2ResultCache() *eras.Phase2ResultCache
Phase2ResultCache returns the cache of transactions whose scripts succeeded. Returns nil for a bare-constructed LedgerState that skipped NewLedgerState (test-only), which validation treats as no cache.
func (*LedgerState) PinAcquiredPoint ¶ added in v0.79.1
func (ls *LedgerState) PinAcquiredPoint(slot uint64) (release func())
PinAcquiredPoint records slot as currently acquired and returns a function that releases it. The caller must call release exactly once, on Release, re-Acquire, an Acquire of a tip, or disconnect. Calling it again is a no-op, so a release on an already-cleared path is safe.
Register the pin before verifying the point, not after: the pin is what stops a concurrent prune from removing state the verify just approved.
func (*LedgerState) PinHeaderCryptoVerificationGeneration ¶ added in v0.86.0
func (ls *LedgerState) PinHeaderCryptoVerificationGeneration( generation uint64, ) (func(), bool)
PinHeaderCryptoVerificationGeneration keeps a current producer- authorization generation stable until the returned release function runs.
func (*LedgerState) PlutusEvalContextCache ¶ added in v0.75.0
func (ls *LedgerState) PlutusEvalContextCache() *eras.PlutusEvalContextCache
PlutusEvalContextCache returns the shared PlutusEvalContextCache script evaluation reuses across every redeemer, transaction, and block this LedgerState validates or evaluates. Returns nil for a bare-constructed LedgerState that skipped NewLedgerState (test-only); callers must treat a nil cache as "no cache available" rather than dereferencing it.
func (*LedgerState) PoolRegistrationVRFKeyHash ¶ added in v0.43.0
func (ls *LedgerState) PoolRegistrationVRFKeyHash( poolID [28]byte, ) (vrfHash [32]byte, found bool, err error)
PoolRegistrationVRFKeyHash returns the VRF key hash required by the elected stake snapshot at the applied ledger tip. Without an electing snapshot, it uses the epoch-effective registration. found is false for an unregistered pool.
func (*LedgerState) PoolStakeDistribution ¶ added in v0.70.0
func (ls *LedgerState) PoolStakeDistribution( ctx context.Context, poolFilter []lcommon.PoolKeyHash, at QueryPoint, txn *database.Txn, ) (*PoolStakeDistribution, error)
PoolStakeDistribution reads the active stake distribution across block-producing pools.
The distribution comes from the mark snapshot at praos.StakeSnapshotEpoch, the same one leader election reads, rather than from live stake. A caller checking a leadership schedule against the node would otherwise be told they lead slots the node will not let them mint.
poolFilter restricts which pools are reported. A nil filter reports every pool in the snapshot. A non-nil filter reports only the pools it names, which for an empty non-nil filter is no pools at all -- the distinction matters because GetPoolDistr2's wire form can carry an explicit empty set, which means "no pools" rather than "every pool" (see olocalstatequery.ShelleyPoolDistr2Query.PoolFilter). Filtering never renormalises: TotalActiveStake stays the whole snapshot's total and each fraction stays a share of it.
A pool holding snapshot stake with no registration on record is omitted rather than reported with a zero VRF key hash, which would read as a real key. Its stake stays in TotalActiveStake, so every reported pool's own fraction is unaffected by the omission.
at pins the distribution to the historical point instead of live-right-now: unpinned means live (the existing default). A pinned at resolves to the epoch that governed that slot and uses that epoch's mark snapshot instead of the live tip's -- this is a real historical reconstruction, not an approximation, because the mark snapshot is already persisted per-epoch for leader election. checkAsOfEpochRecency rejects a historical epoch already outside the mark-snapshot retention window (ledger/snapshot's pool-snapshot pruning), since those rows are physically gone. at.Slot ahead of the transaction tip is rejected directly (not just by epoch): GetEpochBySlot can resolve a future slot within the live epoch to that same live epoch, which would otherwise let a future-slot pin silently pass as "live epoch, therefore fine" despite naming a point that has not happened yet.
txn reuses an already-open transaction (Query's point-validation transaction, when called through it) rather than opening a fresh one, so a pinned call's point-validation and this read share one consistent snapshot -- nil opens and releases one internally, for a caller (a direct, unpinned RPC handler) with no such transaction of its own.
func (*LedgerState) PoolStakeDistributionBounded ¶ added in v0.86.0
func (ls *LedgerState) PoolStakeDistributionBounded( ctx context.Context, poolFilter []lcommon.PoolKeyHash, at QueryPoint, txn *database.Txn, maxPools int, ) (*PoolStakeDistribution, error)
PoolStakeDistributionBounded reads a distribution only when it contains at most maxPools entries.
func (*LedgerState) PrepareEpochCacheForStartup ¶ added in v0.61.0
func (ls *LedgerState) PrepareEpochCacheForStartup(ctx context.Context) error
PrepareEpochCacheForStartup loads epoch metadata and the applied tip before LedgerState.Start(). It is startup-only: callers use this when another component needs slot conversion before the ledger processing loop is running. The tip is part of that preparation because it anchors the current era's forecast horizon; an epoch cache published against the origin tip can reject historical slots near the persisted tip as past the era horizon.
func (*LedgerState) PrimaryChainTip ¶ added in v0.31.1
func (ls *LedgerState) PrimaryChainTip() ochainsync.Tip
PrimaryChainTip returns the tip of the primary chain. This can be ahead of Tip() while the ledger pipeline is still replaying blocks into committed metadata state.
func (*LedgerState) PrimaryChainTipRelation ¶ added in v0.77.0
func (ls *LedgerState) PrimaryChainTipRelation( point ocommon.Point, ) (ochainsync.Tip, uint64, bool, error)
PrimaryChainTipRelation checks point against one locked snapshot of the primary chain and returns that snapshot's tip and block distance.
func (*LedgerState) PrimaryChainTipRelationAndHeader ¶ added in v0.90.0
func (ls *LedgerState) PrimaryChainTipRelationAndHeader( point ocommon.Point, ) (ochainsync.Tip, ochainsync.Tip, uint64, bool, error)
PrimaryChainTipRelationAndHeader returns the primary tip, crypto-verified queued-header frontier, and applied-point relation from one chain snapshot.
func (*LedgerState) PrimaryChainTipSlot ¶ added in v0.31.1
func (ls *LedgerState) PrimaryChainTipSlot() uint64
PrimaryChainTipSlot returns the slot number of the primary chain tip. This can be ahead of ChainTipSlot() while the ledger pipeline is still replaying blocks into committed metadata state.
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) ProtocolParameterUpdateWindow ¶ added in v0.73.1
func (ls *LedgerState) ProtocolParameterUpdateWindow( slot uint64, ) (uint64, uint64, error)
ProtocolParameterUpdateWindow returns the current epoch and the first slot where proposals target the following epoch.
func (*LedgerState) ProtocolParamsForSlot ¶ added in v0.39.2
func (ls *LedgerState) ProtocolParamsForSlot( slot uint64, ) lcommon.ProtocolParameters
ProtocolParamsForSlot returns the protocol parameters that should govern a block forged at the given slot. For a slot in a later epoch it applies the in-era update the next boundary enacts, then each successor era's HardForkFunc up to the era the ledger enters at that boundary: an era with a configured TriggerAtEpoch ends at that epoch, and an era with a version trigger ends once the forecast protocol version names a later era and at least k blocks of the current epoch lie at or past the voting deadline.
The forger uses this to pick the era of the block it builds, and the epoch boundary check applies the same decision to the block that opens the epoch, so a block forged in the returned era is the one the ledger accepts there and a block in any other era is refused. It returns nil when that decision or the parameters cannot be resolved, so callers cannot forge or verify a future slot using stale current parameters.
func (*LedgerState) PrunePoolSnapshotsWithRetentionFloor ¶ added in v0.70.6
func (ls *LedgerState) PrunePoolSnapshotsWithRetentionFloor( defaultBefore uint64, minBefore uint64, prune func(before uint64) error, ) error
PrunePoolSnapshotsWithRetentionFloor is the snapshot manager's retention guard (wired via Manager.SetPoolSnapshotRetentionGuard). Under the deferred-header lock it evicts abandoned headers and computes the retention floor as ONE atomic decision, RELEASES the lock, and only then runs the caller's pool-snapshot prune. The prune must NOT run under the lock: it opens the single sqlite write connection (SetMaxOpenConns(1)) via Transaction(true), and block apply holds that connection before taking this same mutex through consumeDeferredHeaderValidation. Holding the mutex across prune therefore inverts the lock order (mutex→write-conn here vs. write-conn→mutex on apply) and deadlocks the node on the single write connection. Under the lock it, in order:
- Evicts abandoned deferred headers that are beyond the rollback horizon (tip minus the stability window). A canonical deferred header is consumed when the cursor applies it, so one still present that deep is on a fork chain selection can no longer re-adopt and would otherwise pin its snapshot forever (finding 5). The horizon — rather than the bare tip — is what makes eviction safe: eviction also drops the durable marker, and a point evicted while still re-adoptable would apply with required == false and skip its stateful header check. Eviction lets the floor rise; the evicted markers' persisted rows are deleted after the lock is released (best effort — they cannot affect a resolved header).
- Computes the retention floor over the surviving deferred headers and lowers defaultBefore (cleanup's currentEpoch-3 pool boundary) to it when a header needs an older snapshot (or to 0 = retain everything while any deferred slot is unmappable).
- Clamps the boundary UP to minBefore, a hard backstop (currentEpoch - poolSnapshotRetentionMaxDepth) that bounds how many historical epochs the pin can ever hold, so a stuck header cannot pin pool snapshots without limit (finding 5).
The eviction+floor read is atomic (one lock hold), so `before` reflects a coherent view of the deferred set; a header admitted after the lock is released — during or after prune — cannot corrupt this invocation's boundary. A header admitted in that window that needs a below-floor snapshot is a deeply lagged header (its need is < defaultBefore = currentEpoch-3); this invocation may prune a snapshot it wants, but the retention floor is a lower-watermark that is RE-COMPUTED every cleanup pass, so the next pass pins at the lower floor and the header resolves then. This narrow re-admit window is accepted in exchange for never inverting the lock order; it replaces the prior design that held the lock across prune and deadlocked.
prune must perform and COMMIT the pool-snapshot delete before returning; it must not touch ledger locks or the deferred set.
func (*LedgerState) Query ¶
func (ls *LedgerState) Query( ctx context.Context, query any, at QueryPoint, ) (any, error)
Query answers a decoded LocalStateQuery message against Dingo's live ledger state, or against the historical point at named by QueryPoint.
When at is pinned, Query first verifies at against this node's current chain (verifyPointOnChain) before dispatching, so every point-sensitive query type below shares one fork-safety check rather than repeating it. at reaches every query type that reads ledger or consensus state, each of which answers as of at; queryShelleyLeaf's doc comment audits every case, and only genesis config and the ledger peer snapshot are live by design.
Query reads current state on every call, so successive calls may observe different blocks. A session that needs consistent reads across calls uses AcquireQueryView instead, which answers every query from one snapshot.
func (*LedgerState) QueryWithProtocolVersion ¶ added in v0.70.13
func (ls *LedgerState) QueryWithProtocolVersion(ctx context.Context, query any, at QueryPoint, protocolVersion uint16, ) (any, error)
QueryWithProtocolVersion answers a LocalStateQuery using the negotiated node-to-client version when a result has version-dependent wire encoding. A zero version preserves the direct-call behavior used by non-network callers and selects the current result layout only where the result itself is constructed as such.
func (*LedgerState) RecentChainPoints ¶
func (ls *LedgerState) RecentChainPoints( ctx context.Context, count int, ) ([]ocommon.Point, error)
RecentChainPoints returns the requested count of recent chain points in descending order from the authoritative ledger tip. This avoids exposing blob-backed primary-chain points that have not yet been replayed into the metadata/ledger state.
func (*LedgerState) ReconcileLivePrimaryChainLedgerDivergence ¶ added in v0.47.1
func (ls *LedgerState) ReconcileLivePrimaryChainLedgerDivergence( reason string, connId ouroboros.ConnectionId, ) (bool, error)
ReconcileLivePrimaryChainLedgerDivergence is the exported entry point into the live-divergence reconciler. The plateau watchdog (internal/chainsyncrecycler) calls this when local tip has not advanced for plateau_duration while peers report a higher tip: if primary chain has advanced but the ledger pipeline is stuck on an abandoned same-slot fork, this rolls back the ledger to the latest common ancestor so forward application from the canonical chain can resume without a process or container restart. Returns (true, nil) when reconciliation happened, (false, nil) when no divergence was found.
reconcileLivePrimaryChainLedgerDivergence propagates ErrRollbackExceedsMithrilBoundary as a plain error, since its other two callers (handleEventChainsyncRollback, tryResolveFork -- both call it directly, not through this wrapper) classify and publish the matching resync themselves via handleMithrilBoundaryRollback, using peer-tip context this wrapper's only caller does not have. The plateau watchdog has no pending event batch or peer rollback handler of its own to classify this with, and chainsyncrecycler deliberately does not import ledger to inspect the error type (see that package's own doc comment), so this wrapper classifies and publishes it here instead, the same way reconcileLivePrimaryChainLedgerDivergence itself used to before that responsibility moved to each caller.
func (*LedgerState) RecordForgedBlock ¶ added in v0.46.2
func (ls *LedgerState) RecordForgedBlock( block ledger.Block, blockCbor []byte, forgingLatency time.Duration, )
RecordForgedBlock records observability for a block that this node successfully forged. Adoption into the local chain is tracked separately.
func (*LedgerState) RecoverAfterLocalRollback ¶ added in v0.27.7
func (ls *LedgerState) RecoverAfterLocalRollback( ctx context.Context, connIds []ouroboros.ConnectionId, point ocommon.Point, ) LocalRollbackRecoveryResult
RecoverAfterLocalRollback resets chainsync-local queued state after a ledger rollback, then replays any peer-local header history that still fits the new tip. This keeps rollback recovery local to the node instead of re-entering FindIntersect on live ChainSync sessions. The result reports whether peer history was replayed and whether connection closure should be skipped because the primary chain tip is already past the completed rollback point.
func (*LedgerState) RecoverCommitTimestampConflict ¶ added in v0.11.0
func (ls *LedgerState) RecoverCommitTimestampConflict( ctx context.Context, ) error
func (*LedgerState) RewardStakeInputsIncomplete ¶ added in v0.85.0
func (ls *LedgerState) RewardStakeInputsIncomplete( txn *database.Txn, from uint64, through uint64, ) (bool, error)
RewardStakeInputsIncomplete reports whether any snapshot labelled in [from, through) still has incomplete reward_stake_input rows: its deferred write has not committed the last chunk and no reward round has rebuilt it yet. A read-only reader cannot complete them, so it must not present the snapshot's rows as the whole distribution.
func (*LedgerState) RollbackWindowIntersectAnchor ¶ added in v0.70.10
func (ls *LedgerState) RollbackWindowIntersectAnchor(ctx context.Context) ( ocommon.Point, bool, error, )
RollbackWindowIntersectAnchor reports the point that may safely seed a chainsync intersect list while a rollback's metadata truncation is in flight, and whether such a point exists.
It is the ledger's authoritative answer to "is this node mid-rewind, and if so what has it actually applied": ok is true only when the ledger tip's own block row is absent (the signature of the window) AND the primary chain tip sits strictly below the ledger tip (a rewind target the ledger has already applied, not unapplied forward work).
Callers outside the ledger must use this rather than reading the primary chain tip directly. A raw chain tip can be an unapplied fork ahead of the ledger tip that does not descend from it, and advertising that would break the primary-chain ancestor invariant.
func (*LedgerState) ScanUtxosByAddress ¶ added in v0.90.0
func (ls *LedgerState) ScanUtxosByAddress( ctx context.Context, q *models.UtxoWithOrderingQuery, maxCandidates int, maxBytes int64, visit func([]models.UtxoWithOrdering) error, ) (ochainsync.Tip, error)
ScanUtxosByAddress visits every UTxO matching q's exact address patterns one bounded page at a time from a single database snapshot and returns the tip stored in that snapshot. See database.Database.ScanUtxosByAddress.
func (*LedgerState) SecurityParam ¶ added in v0.20.0
func (ls *LedgerState) SecurityParam() int
SecurityParam returns the security parameter for the current era. It takes a brief read lock around ls.currentEra, which ledgerProcessBlocks mutates under the write lock during epoch rollover/era transitions — reading it unlocked here raced with those writes (caught by -race in TestLiveTruncateUnderRealForgingAndNetworking, which runs real forging concurrently with the stall recycler's periodic SecurityParam() calls).
func (*LedgerState) SetCurrentBoundarySPOStakeHook ¶ added in v0.72.0
func (ls *LedgerState) SetCurrentBoundarySPOStakeHook( fn func(*database.Txn, event.EpochTransitionEvent, uint) ([]*models.PoolStakeSnapshot, error), )
SetCurrentBoundarySPOStakeHook installs (or clears, with a nil fn) the same-boundary SPO stake-rows callback governance.ProcessEpoch's RATIFY phase uses for every SPO-gated action (HardForkInitiation, NoConfidence, UpdateCommittee, and a ParameterChange touching the security-parameter group). It is wired at node startup to the snapshot manager's CurrentBoundarySPOStakeRows, alongside SetEpochBoundarySnapshotStakeHook.
Why this hook exists: governance.stakeEpochFor resolves to NewEpoch, i.e. this same boundary's own mark snapshot, but that row is written only at the end of the rollover (epochSnapshotHook), after RATIFY has already run -- see stakeEpochFor's doc comment for the upstream derivation. Without this hook installed, governance falls back to reading the not-yet-written pool_stake_snapshot row, which holds no stake at all -- so every SPO-gated action would tally a zero denominator and never ratify, which is strictly worse than the epoch-lag bug this fixed: permanent non-ratification instead of a wrong but eventually-correct epoch. governance.ProcessEpoch rejects that empty read with governance.ErrMissingCurrentBoundarySPOState, so the boundary fails rather than tally a zero denominator -- but only once mark[NewEpoch-1] holds stake, which is the signal that distinguishes a missing hook from a chain with no earlier mark. A boundary with no earlier mark keeps the silent outcome: it ratifies nothing and reports no error, which TestHardForkInitiation_NeverRatifiesWithoutCurrentBoundaryHook pins. A production node must always wire this alongside the other two epoch-boundary hooks. The callback also receives the incoming era ID because RATIFY runs before the epoch row carrying that ID is persisted.
func (*LedgerState) SetDeferredEpochBoundarySnapshotHooks ¶ added in v0.75.0
func (ls *LedgerState) SetDeferredEpochBoundarySnapshotHooks( capture func(*database.Txn, event.EpochTransitionEvent) error, discard func(epoch uint64), prepare func(*database.Txn, event.EpochTransitionEvent) ( DeferredBoundarySnapshot, error, ), )
SetDeferredEpochBoundarySnapshotHooks installs what a boundary needs to leave mark[NewEpoch] to its background job: capture runs in the boundary transaction at the SNAP point, discard withdraws that capture for a boundary that finds after SNAP that it must capture the snapshot itself, and prepare builds the snapshot reading only the given transaction. Without them every boundary captures its snapshot itself.
func (*LedgerState) SetEpochBoundaryDeferredStakeInputsHook ¶ added in v0.73.4
func (ls *LedgerState) SetEpochBoundaryDeferredStakeInputsHook( fn func(*database.Txn) (uint64, uint64, []*models.RewardStakeInput, bool), )
SetEpochBoundaryDeferredStakeInputsHook installs (or clears, with a nil fn) the hook that returns the epoch, boundary slot and reward_stake_input rows the authoritative epoch-boundary capture staged in a transaction instead of writing them. The ledger writes them in the background once that transaction commits. Install it together with a capture configured to defer those rows (snapshot.Manager.SetDeferRewardStakeInputs).
func (*LedgerState) SetEpochBoundarySnapshotHook ¶ added in v0.66.0
func (ls *LedgerState) SetEpochBoundarySnapshotHook( fn func(*database.Txn, event.EpochTransitionEvent) error, )
SetEpochBoundarySnapshotHook installs (or clears, with a nil fn) the authoritative epoch-boundary snapshot capture. It is wired at node startup to the snapshot manager's CaptureEpochBoundarySnapshot before block sync begins. When no hook is set the ledger relies solely on the event-driven fallback capture, preserving the pre-wiring behavior.
func (*LedgerState) SetEpochBoundarySnapshotStakeHook ¶ added in v0.69.0
func (ls *LedgerState) SetEpochBoundarySnapshotStakeHook( fn func(*database.Txn, event.EpochTransitionEvent) error, )
SetEpochBoundarySnapshotStakeHook installs (or clears, with a nil fn) the SNAP-point stake read of the authoritative epoch-boundary capture. It is wired at node startup to the snapshot manager's ComputeEpochBoundarySnapshot, alongside SetEpochBoundarySnapshotHook.
cardano-ledger runs SNAP before POOLREAP and before governance enactment, so the mark snapshot's stake must be read immediately after the delayed reward update and MIR — the boundary rules that precede SNAP — while the snapshot row itself can only be written at the end of the rollover, where the new epoch's nonce and the post-enactment protocol version exist. This hook is the read half; epochSnapshotHook is the write half. Both run in the same rollover transaction. With no stake hook installed the write half reads the stake itself using boundary-aware historical reconstruction.
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) SetTipForTesting ¶ added in v0.66.0
func (ls *LedgerState) SetTipForTesting(tip ochainsync.Tip)
SetTipForTesting replaces the in-memory tip and publishes a matching snapshot generation. It exists for black-box tests that cannot use the ledger package's white-box snapshot helpers.
func (*LedgerState) ShouldVerifyChainSelectionHeaderCrypto ¶ added in v0.70.3
func (ls *LedgerState) ShouldVerifyChainSelectionHeaderCrypto( slot uint64, ) bool
ShouldVerifyChainSelectionHeaderCrypto reports whether a header at the given slot is eligible to have its cryptography verified right now via ValidateChainSelectionHeaderCrypto. Verification is skipped only for slots already covered by an imported Mithril snapshot, since those slots were authenticated by the certificate chain during import and the restored database does not retain every historical epoch nonce. It is not exempted merely because bulk historical/catch-up loading has not yet enabled live validation. A caller that skips verification because this returns false must still treat the header as eligible, not reject it -- the same trust boundary the ledger's own pipeline already extends to this data.
Unlike shouldEnforceBlockPipelineCrypto (the ledger's own chainsync header-queue gate), this does NOT also skip when the epoch nonce isn't cached yet: that gate can rely on a later retry once the nonce becomes available, but chain selection has no such retry -- a header this returns false for is never re-verified. ValidateChainSelectionHeaderCrypto already handles a not-yet-available epoch by returning a deferred error (see IsHeaderVerificationDeferred) rather than failing, so it's always safe to attempt verification here and let the verifier decide. A deferred result must remain outside chain selection until a later header verifies.
func (*LedgerState) SignatureResultCache ¶ added in v0.90.5
func (ls *LedgerState) SignatureResultCache() *eras.SignatureResultCache
SignatureResultCache returns the cache of witness signature verification outcomes. Returns nil for a bare-constructed LedgerState that skipped NewLedgerState (test-only), which validation treats as no cache.
func (*LedgerState) SlotToEpoch ¶ added in v0.6.0
func (ls *LedgerState) SlotToEpoch(slot uint64) (models.Epoch, error)
SlotToEpoch returns the epoch containing the given slot. See SlotTimeConverter.SlotToEpoch for details.
func (*LedgerState) SlotToTime ¶ added in v0.6.0
func (ls *LedgerState) SlotToTime(slot uint64) (time.Time, error)
SlotToTime returns the wall-clock start time of the given slot. See SlotTimeConverter.SlotToTime for details.
func (*LedgerState) SlotToTimeWithHorizonFrom ¶ added in v0.70.7
func (ls *LedgerState) SlotToTimeWithHorizonFrom( horizonAnchorSlot uint64, slot uint64, ) (time.Time, error)
SlotToTimeWithHorizonFrom returns the wall-clock start time of the given slot with the forecast horizon measured from horizonAnchorSlot. See SlotTimeConverter.SlotToTimeWithHorizonFrom.
func (*LedgerState) SlotsBehindHead ¶ added in v0.58.0
func (ls *LedgerState) SlotsBehindHead() uint64
SlotsBehindHead reports how many slots the applied ledger tip is behind the wall-clock head (0 if at or ahead of it, or if the wall slot is unknown). Unlike IsAtTip it distinguishes "chainsync reached the head" from "the ledger has actually applied up to the head", which matters during a from-scratch catch-up where the ledger replays a large backlog while chainsync is already at the head.
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) StabilityWindow ¶ added in v0.39.0
func (ls *LedgerState) StabilityWindow() uint64
StabilityWindow returns the Ouroboros security stability window for the current era in slots. For Byron the window is 2k; for Shelley+ it is 3k/f. It is safe to call from multiple goroutines.
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(ctx context.Context, 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( ctx context.Context, 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), 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) TachysDistribution ¶ added in v0.89.0
func (ls *LedgerState) TachysDistribution( ctx context.Context, snapshotEpoch uint64, ) (_ *nodeconsensus.TachysDistribution, err error)
TachysDistribution reads a complete mark-snapshot distribution and its denominator through one metadata transaction.
func (*LedgerState) TimeToSlot ¶ added in v0.6.0
func (ls *LedgerState) TimeToSlot(t time.Time) (uint64, error)
TimeToSlot returns the slot containing the given wall-clock time. See SlotTimeConverter.TimeToSlot for details.
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(ctx context.Context, hash []byte, ) (*models.Transaction, error)
TransactionByHash returns a transaction record by its hash.
func (*LedgerState) UpstreamSyncStatus ¶ added in v0.70.3
func (ls *LedgerState) UpstreamSyncStatus() (uint64, bool)
UpstreamSyncStatus reports whether a live upstream is selected and its corroborated target. An active upstream with target 0 is still syncing.
func (*LedgerState) UpstreamSyncTip ¶ added in v0.77.0
func (ls *LedgerState) UpstreamSyncTip() (ochainsync.Tip, bool)
UpstreamSyncTip returns the corroborated upstream tip with its block number while preserving the active-connection generation check used by UpstreamSyncStatus.
func (*LedgerState) UpstreamTipSlot ¶ added in v0.22.0
func (ls *LedgerState) UpstreamTipSlot() uint64
UpstreamTipSlot returns the corroborated remote sync target while an upstream connection is active. The admitted frontier is retained separately for admission bookkeeping.
func (*LedgerState) UtxoBalanceByAddressAtSlot ¶ added in v0.90.0
func (ls *LedgerState) UtxoBalanceByAddressAtSlot( ctx context.Context, addr lcommon.Address, slot uint64, ) (models.AddressBalance, error)
UtxoBalanceByAddressAtSlot aggregates a historical address balance without materializing its UTxO set.
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( ctx context.Context, addrs []ledger.Address, ) ([]models.Utxo, error)
UtxosByAddress returns all UTxOs that belong to any of the specified addresses
func (*LedgerState) UtxosByAddressBoundedPage ¶ added in v0.86.0
func (ls *LedgerState) UtxosByAddressBoundedPage( ctx context.Context, q *models.UtxoWithOrderingQuery, maxCandidates int, maxBytes int64, ) (models.UtxoAddressPage, error)
UtxosByAddressBoundedPage returns an ordered, resumable UTxO page while bounding candidate work and retained CBOR.
func (*LedgerState) UtxosByRefs ¶ added in v0.70.0
UtxosByRefs returns the live UTxOs matching the given references in a single batch. Refs with no matching live UTxO are simply absent from the result.
func (*LedgerState) UtxosByRefsBounded ¶ added in v0.90.0
func (ls *LedgerState) UtxosByRefsBounded( ctx context.Context, refs []models.UtxoId, maxBytes int64, ) ([]models.Utxo, error)
UtxosByRefsBounded is UtxosByRefs for query.ReadUtxos: it observes ctx and stops loading CBOR once maxBytes is exceeded, returning database.ErrUtxoBytesExceeded.
func (*LedgerState) ValidateBlockHeaderCrypto ¶ added in v0.69.0
func (ls *LedgerState) ValidateBlockHeaderCrypto( header ledger.BlockHeader, ) error
ValidateBlockHeaderCrypto validates a header using the current ledger state. It is used by protocol handlers that receive a header without its block body (for example LeiosNotify announcements) and must not let an unauthenticated header influence shared state.
func (*LedgerState) ValidateBlockReferenceScripts ¶ added in v0.70.9
func (ls *LedgerState) ValidateBlockReferenceScripts( ctx context.Context, block ledger.Block, ) error
ValidateBlockReferenceScripts checks a locally built block's aggregate reference-script budget before adoption. It does not run header crypto or transaction scripts, and is required even when full self-validation is off.
func (*LedgerState) ValidateChainSelectionHeaderCrypto ¶ added in v0.70.3
func (ls *LedgerState) ValidateChainSelectionHeaderCrypto( header ledger.BlockHeader, ) error
ValidateChainSelectionHeaderCrypto verifies a header's VRF/KES cryptography and, where the local ledger's stake/pool state has already caught up to the header's epoch, its leader eligibility. It lets chain selection require that a peer-reported header has passed the same checks as the applied chain before the header is allowed to influence Genesis density or corroboration, independent of whether that header will ever be applied to the ledger.
It never advances the shared epoch cache (matching ValidateBlockHeaderCrypto's no-mutation contract for header-only validation), but unlike ValidateBlockHeaderCrypto it tolerates ledger state that has not yet caught up to the header's slot: that is the normal condition for a peer legitimately racing ahead of local ledger application during fast sync or Genesis bootstrap. Use IsHeaderVerificationDeferred to distinguish that case (the peer is not at fault, but the header is not selection-eligible) from a header this node can already prove is invalid.
func (*LedgerState) ValidateChainSelectionHeaderCryptoWithGeneration ¶ added in v0.82.0
func (ls *LedgerState) ValidateChainSelectionHeaderCryptoWithGeneration( header ledger.BlockHeader, ) (uint64, error)
ValidateChainSelectionHeaderCryptoWithGeneration validates a header and returns the immutable ledger-state generation used by that validation. A concurrent publication makes the verdict non-reusable and is reported as a deferred result so callers can retry it at ledger admission.
func (*LedgerState) ValidateForgedBlock ¶ added in v0.58.0
func (ls *LedgerState) ValidateForgedBlock(ctx context.Context, block ledger.Block, _ []byte, ) error
ValidateForgedBlock validates a locally-forged block before it is adopted onto the chain and diffused to peers. It runs three checks in order:
- Header crypto — VRF proof and KES signature verification (skipped for Byron-era blocks which use PBFT consensus and have no VRF/KES fields).
- Body-hash consistency — verifies that the body hash in the header is non-zero, catching any builder bug that would embed an all-zero hash.
- Aggregate reference-script limits, then per-transaction ledger rules. Each transaction in the block is validated against the current UTxO state. An intra-block overlay is maintained so that transactions spending outputs created earlier in the same block are correctly resolved.
A non-nil error means the block is invalid and must not be adopted or diffused. This function satisfies the forging.BlockValidator interface.
func (*LedgerState) ValidateHeaderCheckpoint ¶ added in v0.92.0
func (ls *LedgerState) ValidateHeaderCheckpoint( header ledger.BlockHeader, ) error
ValidateHeaderCheckpoint applies the ledger's configured checkpoints to a peer header. It is safe for concurrent use: the checkpoint map is set at construction and never mutated.
func (*LedgerState) ValidateLeiosAnnouncementHeader ¶ added in v0.70.2
func (ls *LedgerState) ValidateLeiosAnnouncementHeader( header ledger.BlockHeader, ) (LeiosAnnouncementOCINStaleness, error)
ValidateLeiosAnnouncementHeader validates the announcement's header crypto before classifying its op-cert counter against the selected primary chain's immutable-tip state. Counter equality and arbitrary forward movement are fresh because this lagging view cannot enforce an upper bound. A lower or as-yet-unknown counter is stale, not invalid.
The result is deliberately a ledger verdict only. The Ouroboros composition layer owns whether a stale peer message is recorded, published, or relayed.
func (*LedgerState) ValidateLeiosEndorserBlockTransactions ¶ added in v0.73.4
func (ls *LedgerState) ValidateLeiosEndorserBlockTransactions( ctx context.Context, header ledger.BlockHeader, basis []byte, txs [][]byte, ) error
ValidateLeiosEndorserBlockTransactions validates an announced endorser block against the exact ledger snapshot named by basis, which must be the applied ledger tip. Peers and voters pass LeiosEndorserBlockBasisHash; a forger checking its own announcement before the ranking block is adopted passes LeiosValidationParentHash, which is equivalent only because a locally built announcing block carries no transactions of its own and excludes the transactions of the endorser block it certifies. It uses one repeatable-read transaction and applies transaction effects in manifest order so later transactions can spend earlier outputs.
func (*LedgerState) ValidatePeerChainSelectionHeaderCrypto ¶ added in v0.87.0
func (ls *LedgerState) ValidatePeerChainSelectionHeaderCrypto( connId ouroboros.ConnectionId, header ledger.BlockHeader, ) error
ValidatePeerChainSelectionHeaderCrypto verifies a peer header against the nonce and operational-certificate state of the candidate chain that delivered it. A fork that diverges before the candidate nonce freezes can have a different nonce in the next epoch, even while it remains within the rollback window.
func (*LedgerState) ValidatePeerChainSelectionHeaderCryptoWithGeneration ¶ added in v0.87.0
func (ls *LedgerState) ValidatePeerChainSelectionHeaderCryptoWithGeneration( connId ouroboros.ConnectionId, header ledger.BlockHeader, ) (uint64, error)
ValidatePeerChainSelectionHeaderCryptoWithGeneration validates a header against connection-scoped ancestry and returns the immutable ledger-state generation used by that validation. A concurrent publication makes the verdict non-reusable and is reported as a deferred result so callers can retry it at ledger admission.
func (*LedgerState) ValidatePraosHeader ¶ added in v0.87.0
func (ls *LedgerState) ValidatePraosHeader( ctx context.Context, block ledger.Block, allowEpochCacheAdvance bool, allowStateDefer bool, ) error
ValidatePraosHeader runs Dingo's Praos header checks against ledger-owned state. Consensus providers call this entry point rather than duplicating nonce, epoch, stake, or rollback state.
func (*LedgerState) ValidateTachysHeader ¶ added in v0.89.0
func (ls *LedgerState) ValidateTachysHeader( ctx context.Context, block gledger.Block, allowEpochCacheAdvance bool, allowStateDefer bool, ) error
ValidateTachysHeader retains every Praos cryptographic and ledger-state check while replacing only private-threshold issuer authorization with the public CIP-0177 schedule.
func (*LedgerState) ValidateTx ¶
func (ls *LedgerState) ValidateTx( tx lcommon.Transaction, ) error
ValidateTx runs ledger validation on a transaction from the current era.
func (*LedgerState) ValidateTxWithOverlay ¶ added in v0.23.0
func (ls *LedgerState) ValidateTxWithOverlay( tx lcommon.Transaction, consumedUtxos map[utxoref.Key]struct{}, createdUtxos map[utxoref.Key]lcommon.Utxo, accounts *utxoref.StateOverlay, ) 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.
func (*LedgerState) VerifyPeerHeaderAncestry ¶ added in v0.91.0
func (ls *LedgerState) VerifyPeerHeaderAncestry( ctx context.Context, conn ouroboros.ConnectionId, header gledger.BlockHeader, base ochainsync.Tip, limit int, ) (VerifiedPeerHeaderAncestry, error)
VerifyPeerHeaderAncestry authenticates the complete bounded path from base to header. Missing delivery callbacks are not evidence: an unapplied suffix must pass peer-relative crypto, state and opcert-counter verification, and its older prefix must be exactly on the applied canonical chain.
func (*LedgerState) VerifyPointOnChain ¶ added in v0.70.12
func (ls *LedgerState) VerifyPointOnChain(ctx context.Context, at QueryPoint) error
VerifyPointOnChain validates at against this node's current chain, the same way Query does for a pinned point, but callable at Acquire time rather than deferred to the first Query. An unpinned at (the live/no-pin zero value) always succeeds -- there is nothing to validate.
Ordinary LocalStateQuery clients (a real cardano-node included) validate a specific-point Acquire synchronously, replying with a graceful AcquireFailure over the wire when the point is not (yet, or no longer) on the chain. Deferring this check to the first Query instead, as this node's Acquire handling used to, hits a real gap in that later stage: there is no equivalent graceful-failure path once Acquire has already signaled success, so a query-time rejection propagates as a fatal protocol error and the whole LocalStateQuery connection is torn down -- observed live at close to 100% of the time for any client whose Acquire races dingo's own block application (extremely common at real block cadence, since dingo and the client's own reference node sync independently and rarely advance in lockstep). Callers should map the returned error's sentinel (ErrPointNotOnChain / ErrHistoricalStateUnavailable) to gouroboros's own olocalstatequery.ErrAcquireFailurePointNotOnChain / ErrAcquireFailurePointTooOld so the server replies gracefully instead of closing the connection.
func (*LedgerState) VerifyPointQueryable ¶ added in v0.72.0
func (ls *LedgerState) VerifyPointQueryable( ctx context.Context, txn *database.Txn, at QueryPoint, ) error
VerifyPointQueryable checks that at, once Acquired, is guaranteed to be answerable by every point-aware query type below -- not just that it is still on this node's chain (verifyPointOnChain), but that it is not older than the strictest per-query-type retention floor (UTxO whole/by-ref via checkUtxoRetentionWindow, stake/pool distribution via PoolStakeDistribution's own recency check, current protocol parameters via queryShelleyCurrentProtocolParams's persisted-row lookup, current era via queryHardFork's HardForkCurrentEraQuery case, which independently returns ErrHistoricalStateUnavailable and so must be covered here too).
Called from the LocalStateQuery server's Acquire handler (ouroboros/localstatequery.go), not from Query itself: the Ouroboros LocalStateQuery wire protocol has no way to fail an individual query after a successful Acquire -- confirmed against gouroboros' own StateMap, whose Querying state has exactly one transition (Result) and no Failure transition at all, unlike Acquiring (which supports AcquireFailurePointTooOld/PointNotOnChain). A point Acquire allowed but a later query could not actually answer therefore has no protocol-legal way to report that: the connection simply drops ("protocol is shutting down" client-side) instead of returning a clean rejection, for any of the retention-bounded query types above, whenever their own floor is stricter than whatever check an earlier, successful call on the same connection happened to exercise.
Real cardano-node never hits this: its own historical retention is one uniform window (the security parameter k) shared by every query type, so a successful Acquire there already guarantees every query answers. Checking every one of Dingo's independent, differently-sized retention windows here, upfront, gives Dingo that same guarantee instead of discovering the gap mid-query. The cost is symmetric: a connection that only ever intended to ask a genuinely unbounded query (queryShelleyEpochNo) at a point older than UTxO's or stake distribution's own floor is now also refused at Acquire, even though that specific query alone could have answered -- accepted deliberately, since the protocol gives no way to know in advance which query type a session will ask, and refusing a point upfront is a well-defined, protocol-legal AcquireFailure, unlike discovering the same gap mid-query.
Unpinned (at.pinned() false) always succeeds: the live tip trivially satisfies every retention window.
Snapshot guarantee: pass the read transaction a QueryView holds (as AcquireQueryView does) and this check and every later query in the session read one snapshot, so a retention prune or rollback committed after the check cannot make an acquired point stop answering. Called with a nil txn the check runs in its own transaction, which closes before the caller records the point, and proves nothing about later reads.
Pruning itself still runs concurrently with the check. The caller pins the point with PinAcquiredPoint first; checkAnnouncedPruneFloors below then refuses a point a concurrent prune has already committed to removing, and a prune that announces after the pin lands sees the pin and retains the point. Protocol-parameter rows are not age-pruned at all -- only DeletePParamsAfterSlot removes them, on rollback, which verifyPointOnChain already covers.
func (*LedgerState) WaitEpochBoundaryJob ¶ added in v0.75.0
func (ls *LedgerState) WaitEpochBoundaryJob(ctx context.Context) error
WaitEpochBoundaryJob blocks until the most recent boundary's deferred work is durable: its RATIFY decision and, when the boundary left it, its mark snapshot. A reader of ratified or expired marks, or of that epoch's mark snapshot, sees what the boundary decided.
func (*LedgerState) WallClockSlotFromConfirmedHistory ¶ added in v0.70.13
func (ls *LedgerState) WallClockSlotFromConfirmedHistory() ( uint64, bool, error, )
WallClockSlotFromConfirmedHistory returns the absolute slot corresponding to the current wall-clock time derived only from the confirmed era history, and false when the wall clock falls past that history's forecast horizon.
Only the past-horizon case reports false. Any other failure -- an empty epoch cache, a summary that will not build, a wall clock before genesis -- is returned as an error instead. The distinction matters to the block producer: false means "cannot judge yet, defer and let the per-slot gate enforce", so conflating a genuine internal failure with it would silently downgrade a hard startup failure into a warning. Note that before-genesis reaches here as hardfork.ErrBeforeGenesis, a different sentinel from ledger.ErrBeforeGenesis, and returning it as an error keeps that case a hard failure regardless of which sentinel a caller happens to check.
In the false case CurrentSlot can only extrapolate the wall clock through the newest confirmed era's slot length, which does not reflect chains whose later eras have not been applied yet: a mainnet node importing from genesis judges the wall clock with Byron's 20s slots even though the real chain moved to one-second slots at epoch 208. Operational callers that must make a time-sensitive judgement against the wall-clock slot — such as the block producer's operational-certificate KES-period preflight — should use this instead of the extrapolated CurrentSlot, and defer the judgement until the confirmed era history spans the wall clock again.
func (*LedgerState) WithResolvingTxValidationSession ¶ added in v0.88.0
func (ls *LedgerState) WithResolvingTxValidationSession(ctx context.Context, fn func( validate func( tx ledger.Transaction, consumedUtxos map[utxoref.Key]struct{}, createdUtxos map[utxoref.Key]lcommon.Utxo, accounts *utxoref.StateOverlay, ) error, stillCurrent func() bool, commitIfCurrent func(func() error) (bool, error), resolve func(refs []models.UtxoId) ([]models.Utxo, error), ) error, ) error
WithResolvingTxValidationSession is WithTxValidationSession for mempool admission. resolve returns the live confirmed outputs among refs from the session's database transaction, the snapshot its validations read.
func (*LedgerState) WithTxValidationSession ¶ added in v0.69.0
func (ls *LedgerState) WithTxValidationSession(ctx context.Context, fn func( validate func( tx ledger.Transaction, consumedUtxos map[utxoref.Key]struct{}, createdUtxos map[utxoref.Key]lcommon.Utxo, accounts *utxoref.StateOverlay, ) error, stillCurrent func() bool, commitIfCurrent func(func() error) (bool, error), ) error, ) error
func (*LedgerState) WithTxValidationSessionAtParent ¶ added in v0.89.0
func (ls *LedgerState) WithTxValidationSessionAtParent(ctx context.Context, parentHash []byte, fn func( validate func( tx ledger.Transaction, consumedUtxos map[utxoref.Key]struct{}, createdUtxos map[utxoref.Key]lcommon.Utxo, accounts *utxoref.StateOverlay, ) error, stillCurrent func() bool, commitIfCurrent func(func() error) (bool, error), ) error, ) error
WithTxValidationSessionAtParent is WithTxValidationSession pinned to a ledger tip of parentHash: when the published tip is anything else, fn is not called and the error wraps forging.ErrTxValidationParentMismatch. The block forger selects an announced endorser block's transactions through it, so they are validated against the state of the ranking block's parent rather than a trailing ledger that has not yet applied it.
type LedgerStateConfig ¶
type LedgerStateConfig struct {
Consensus nodeconsensus.Provider
// ConsensusStateRestoredFunc synchronously invalidates provider-owned
// production state after rollback publishes its replacement snapshot.
ConsensusStateRestoredFunc func()
// MaxConcurrentEvaluations bounds transaction evaluations running at
// once across every API front end. Zero leaves one logical processor for
// consensus work when possible.
MaxConcurrentEvaluations int
PromRegistry prometheus.Registerer
Logger *slog.Logger
Database *database.Database
ChainManager *chain.ChainManager
EventBus *event.EventBus
CardanoNodeConfig *cardano.CardanoNodeConfig
// Network is the CLI/YAML/env network selector dingo was started with
// (e.g. "mainnet", "preprod", "prime-mainnet"). Shelley genesis alone
// cannot distinguish real Cardano mainnet from a foreign chain that
// reuses its identity for wire compatibility -- see isMainnet in
// header_protocol_version.go. Empty when dingo was configured with a
// raw NetworkMagic instead of a named network.
Network string
// DijkstraBlsProofDomain selects the network's pool-registration proof
// domain. Zero retains the IETF proof domain.
DijkstraBlsProofDomain lcommon.DijkstraBlsProofDomain
BlockfetchRequestRangeFunc BlockfetchRequestRangeFunc
RejectBlockDecodeCacheFunc func(uint, []byte)
PeersWithBlockFunc PeersWithBlockFunc
SelectBlockfetchPeerFunc SelectBlockfetchPeerFunc
SelectBlockfetchRetryPeerFunc SelectBlockfetchRetryPeerFunc
RecordBlockfetchLatencyFunc RecordBlockfetchLatencyFunc
BlockfetchLatencyFunc BlockfetchLatencyFunc
BlockfetchLatencyMedianFunc BlockfetchLatencyMedianFunc
GetActiveConnectionFunc GetActiveConnectionFunc
GetPeerObservedTipFunc GetPeerObservedTipFunc
GetPeerSyncTargetFunc GetPeerSyncTargetFunc
ConnectionLiveFunc ConnectionLiveFunc
NetworkIngestHoldTracker NetworkIngestHoldTracker
ConnectionSwitchFunc ConnectionSwitchFunc
ClearSeenHeadersFromFunc ClearSeenHeadersFromFunc
PeerHeaderLookupFunc PeerHeaderLookupFunc
GenesisSelectionStateFunc GenesisSelectionStateFunc
FatalErrorFunc FatalErrorFunc
ReportTipGapFunc ReportTipGapFunc
ReportSlotClockAliveFunc ReportSlotClockAliveFunc
ForgedBlockChecker ForgedBlockChecker
SlotBattleRecorder SlotBattleRecorder
EndorserBlockProvider EndorserBlockProviderFunc
EndorserBlockDataProvider EndorserBlockDataProviderFunc
EndorserBlockValidation EndorserBlockValidationFunc
// RecordBlockfetchThroughputFunc receives each completed batch's
// delivery rate: the bytes that followed the first block and the time
// they took to arrive.
RecordBlockfetchThroughputFunc RecordBlockfetchThroughputFunc
// EndorserBlockFetcher actively fetches a referenced endorser block (its
// manifest and all transaction bodies) by point and caches it, so the
// EndorserBlockProvider can then supply it. Unlike the tip path, which waits
// for the relay to diffuse an endorser block it is already pushing, this is
// used during historical catch-up: the prototype relay serves any endorser
// block by point on demand (MsgLeiosBlockRequest), so the node can backfill
// the endorser-resident outputs of older ranking blocks instead of trusting
// the chain and leaving the UTxO set incomplete. Nil disables backfill.
EndorserBlockFetcher EndorserBlockFetcherFunc
// ValidateLeiosAnnouncement validates a cached endorser block while the
// announcing block is the applied ledger tip. Header
// admission remains independent: an unavailable or invalid endorser block
// receives no vote but does not invalidate its ranking block.
ValidateLeiosAnnouncement func(context.Context, ledger.BlockHeader) error
// LeiosAnnouncementAtTip is called, without blocking, when an apply chunk
// commits with a live announcing ranking block as the ledger tip. That
// is the state its endorser block validates against, so a voter acts on
// it now instead of at the next block, which may be outside the vote
// window by then. Nil disables the notification.
LeiosAnnouncementAtTip func(ledger.BlockHeader)
// EndorserBlockWaitSlots is the number of slots that block processing
// waits at the chain tip for a Dijkstra ranking block's referenced
// endorser block to finish fetching before applying it. It is sourced from
// the Leios pipeline timing (CertifyByDeadlineSlots, not the shorter
// DiffuseWindowSlots: by the time a ranking block references an endorser
// block that block has already been certified, so the certify-by deadline
// is the bound for when it is actually available to fetch) rather than a
// hardcoded duration; the ledger converts it to wall-clock using the
// Shelley slot length. Zero disables best-effort announcement waiting, but
// does not permit a certifying ranking block to commit without its
// certified closure.
EndorserBlockWaitSlots uint64
// ValidateLeiosCertificate verifies a Dijkstra certificate before any
// certified endorser-block transactions are fetched or applied. An error
// wrapping ErrLeiosInvalidCertificate is a verdict that the certificate
// does not verify, and the certifying block is rejected. Any other error
// means the certificate could not be checked, and the block is retried.
ValidateLeiosCertificate func(
epoch uint64,
announcingBlockHash []byte,
signers []byte,
aggregatedSignature []byte,
) error
// SkipLeaderStakeThresholdCheck, when true, downgrades a failed Praos
// stake-derived leader-eligibility check from a hard header rejection to a
// logged warning (the block is trusted). It defaults to false so the check
// is enforced everywhere unless explicitly disabled.
//
// The leadership stake includes reward-account balances.
// refreshRewardLiveStakeAggregate stores total_stake =
// utxo_stake + reward_stake, with reward_stake read from account.reward,
// and GetLiveStakeInputsForPools selects total_stake; the historical
// reconstruction adds the same term in getStakeByPoolsAtSlot.
// LedgerView.CalculateRewards and LedgerView.GetAdaPots are still
// unimplemented, but RewardAccountBalance is not, and neither gates the
// reward term above. An earlier version of this comment said the stake
// was delegated UTxO only; that claim was stale, and a wedge diagnosis
// was built on it rather than on the code. Verified on preview: the epoch
// 17-20 mark totals equal cardano-node's active stake for epochs 18-21
// exactly.
//
// Separately, TPraos bootstrap epochs with decentralization still active
// validate genesis overlay assignment in verify_header.go, then skip only
// the local pool stake-threshold check while d remains active.
// The same flag also gates every other path where the stake-derived
// threshold cannot be evaluated at all (zero total active stake, a
// missing/nonpositive active-slot coefficient, a post-Mithril mark
// snapshot reconstructed after its target boundary). Network profiles never
// enable this flag; it exists for explicit test and embedder configuration.
SkipLeaderStakeThresholdCheck bool
// StakePoolStateQuery answers the GetStakePoolState local state query
// (Shelley sub-query 40). Released Haskell nodes do not support that
// query, so it is a Leios prototype extension: node_ledger_config.go sets
// it only from Config.musashiPrototypeIdentity, whose strict identity
// check cannot be met by a mainnet, preprod, preview or sancho
// configuration. The zero value leaves the query unsupported, exactly as
// for any other query dingo does not answer.
StakePoolStateQuery bool
// LeiosCommittee answers the GetLeiosCommittee local state query
// (Shelley sub-query 41) with the seats of the Leios voting committee of
// an epoch. Released Haskell nodes do not support that query, so it is a
// Leios prototype extension: node_ledger_config.go sets it only from
// Config.musashiPrototypeIdentity. A nil value leaves the query
// unsupported, exactly as for any other query dingo does not answer.
LeiosCommittee func(
epoch uint64,
) ([]olocalstatequery.LeiosCommitteeSeat, error)
// SkipDijkstraTxValidation, when true, skips the Dijkstra per-transaction
// validation rule set entirely. It applies to Dijkstra-era transactions
// only. Network profiles never enable this flag; it exists for explicit test
// and embedder configuration.
SkipDijkstraTxValidation bool
// Praos2ChainDepState selects the Praos2 serialisation of the
// chain-dependent state in a GetChainDepState reply for the Dijkstra
// era: version 1 with nine fields, the ninth being the Leios
// announcement of the last applied header. Only the Leios prototype
// network (Musashi) runs the Dijkstra era on Praos2; released Haskell
// consensus runs Dijkstra on plain Praos, so the era alone must never
// select it. The zero value keeps the Praos layout, and node_ledger_config.go
// sets it only from Config.musashiPrototypeIdentity, whose strict
// identity check cannot be met by a mainnet, preprod, preview or sancho
// configuration.
Praos2ChainDepState bool
// MinPoolMargin is the CIP-23 minimum pool margin (minimum variable fee) in
// basis points, [0, 10000] (150 = 1.5%); 0 disables it. It is a consensus-
// affecting operator setting (not derived from the network) that takes
// effect only in Dijkstra and later. Enable a nonzero value only on a
// network where every node also enables the same value.
MinPoolMargin uint
// PledgeLeverageEnabled enables the experimental pre-Dijkstra pledge
// leverage override. Dijkstra uses the enacted protocol parameter instead.
PledgeLeverageEnabled bool
// PledgeLeverage is the experimental pre-Dijkstra L value. It is used only
// when PledgeLeverageEnabled is true.
PledgeLeverage uint
// FullPotRewardsEnabled turns on CIP-0163 full-pot reward distribution: the
// entire epoch reward pot is apportioned across pools that earned a base
// reward instead of returning the saturation/pledge/performance residual to
// reserves. It is a consensus-affecting feature gate that defaults false;
// enable it only on a network where every node also enables it (mainnet and
// the public testnets keep it off). Like the CIP-50 pledge-leverage gate it
// is set from operator config in node.go, not derived from the network.
FullPotRewardsEnabled bool
// DelegatorInactivityEnabled turns on CIP-0163 reward-account inactivity
// expiry. Consensus-affecting; defaults false. Set from operator config in
// node.go (serve mode) and internal/node/load.go (load/replay mode), not
// derived from the network. Must match across the network.
DelegatorInactivityEnabled bool
// DelegatorInactivity is the inactivity window in epochs, used only when
// DelegatorInactivityEnabled is true.
DelegatorInactivity uint64
ValidateHistorical bool
// CIP0203Enabled includes the build version in dev-mode forged headers.
CIP0203Enabled bool
EnableDijkstra bool
// WarmGenesisStake makes the first reward rounds of a network that
// declares Shelley at epoch 0 pay from genesis staking, as the Leios
// prototype networks do. A standard cardano-node leaves those rounds
// empty, so only prototype networks set it; knowing the Dijkstra era is
// not a reason to.
WarmGenesisStake bool
StartInDijkstra bool
TrustedReplay bool
ManualBlockProcessing bool
ForgeBlocks bool
DatabaseWorkerPoolConfig DatabaseWorkerPoolConfig
// VerifyReplayHeaders makes ledger apply run the full VRF, KES,
// operational-certificate and leader-eligibility check on every block
// that no Mithril certificate covers, as if admission had deferred it.
// Replay feeds blocks that never passed admission, so apply is the only
// place their headers can be checked before they reach ledger state.
VerifyReplayHeaders bool
// BlockPipelineEnabled turns on parallel block decode in the chainsync
// replay loop (ledgerReadChainIterator): blocks read back from the
// primary chain are decoded by a small worker pool (gouroboros'
// pipeline package) instead of one at a time inline, then re-sequenced
// before being handed to ledgerProcessBlocksFromSource exactly as
// today. Validation and apply are untouched -- this only changes how
// CBOR decode work is scheduled. Off by default: throughput and
// stability are still being proven. See
// ARCHITECTURE.md ("Block Processing Pipeline").
//
// A rollback drains blockPipeline's in-flight decode/validate backlog
// (drainBlockPipelineBeforeRollback) before it
// proceeds, to shrink -- not eliminate -- the window in which an
// already-in-flight batch from an abandoned fork could otherwise be
// applied after the rollback. See ARCHITECTURE.md ("Phase 5: rollback
// coordination").
BlockPipelineEnabled bool
// BlockPipelineValidateEnabled checks header cryptography serially in
// decodeReadChainBatch for blocks read back during replay; the pipeline
// itself only decodes. The check covers VRF, KES,
// and the OpCert cold-key signature; Dingo's supplement re-runs that
// cold-key signature check as defense in depth and adds the
// state-dependent MaxKESEvolutions expiry check the generic verifier
// cannot perform, so a validated header pays two Ed25519 verifications
// of the same opcert. That duplication is not specific to this flag:
// VerifyBlock checks the OpCert cold signature ungated by any
// VerifyConfig Skip field, so the default serial path pays it too, where
// verifyBlockHeaderCrypto calls verifyBlockHeaderHex and
// verifyOpCertHeaderCrypto back to back. See ARCHITECTURE.md
// ("Operational Certificate Validation").
// It enforces results only where the serial path has validation state:
// not trusted historical/Mithril replay and only with a cached epoch
// nonce. A rejection is returned as headerValidationError so the already-
// persisted chain can be rewound rather than retried forever.
//
// This is defense in depth, not a replacement for admission validation.
// Headers and blocks remain fully checked before entering ls.chain because
// that chain is served to downstream clients before ledger apply. See
// ARCHITECTURE.md ("Block Processing Pipeline").
//
// This flag's extra CPU cost (two dedicated VRF/KES workers) can make
// block-apply throughput fall behind header arrival during bursty
// near-tip conditions more easily than decode-only phase 1 or the
// pre-pipeline baseline hit in practice; if that happens for long
// enough, the chain's queued-header backlog can reach capacity while a
// fork is being resolved. tryResolveFork's failure handling used to
// silently strand that backlog in exactly that case, stalling sync
// with no error logged above WARN until chainsyncrecycler's
// local-tip-plateau watchdog eventually forced a resync (~20 minutes
// with default config) -- this was a general, pre-existing gap in
// tryResolveFork, not specific to this flag (reproduced live under
// this flag, under decode-only, and under the pre-pipeline baseline
// alike); the flag's throughput cost just makes it easier to reach.
// See ensureBlockfetchDrainingAfterForkQueueFailure and
// ARCHITECTURE.md ("Fork-resolution header-queue overflow must still
// restart blockfetch") for the fix and the full explanation.
BlockPipelineValidateEnabled bool
// LedgerPrefetchAheadEnabled resolves the input UTxOs of block k+1 on a
// separate goroutine, from a read-only transaction, while block k applies
// within one block-apply chunk. Inputs consumed by earlier blocks of the
// chunk are never served from it, and any input it does not resolve is
// read inside the write transaction as without the flag. Only blocks
// under normal validation are prefetched; historical, TrustedReplay and
// Mithril-covered blocks read no inputs. Not consensus-affecting. The
// zero value is off; node configuration turns it on by default.
LedgerPrefetchAheadEnabled bool
// ApplyRowBatchingEnabled writes the accumulated deltas of blocks that
// are not validated through the metadata store's batched path in core
// storage mode, as API storage mode already does. Validated blocks, Leios
// endorser-block applies, and batches applied with closure context keep
// the per-transaction path in every storage mode. Off by default; the stored
// state is identical either way. See ARCHITECTURE.md ("Block Processing
// Pipeline").
ApplyRowBatchingEnabled bool
// LedgerValidateAheadEnabled runs the validation work that reads no ledger
// state ahead of the serial apply loop: the vkey and bootstrap witness
// signatures of every validated block of a block-apply chunk are verified
// on worker goroutines while earlier blocks of the chunk validate and
// write. Each result is bound to its transaction body and witness set, and
// every rule still runs against the write transaction, so verdicts and
// stored state are identical either way. Dijkstra ranking bodies use this
// path independently of certified-closure signature verification. Byron
// blocks and TrustedReplay (which preverifies the whole chunk itself) are
// not covered. Not consensus-affecting. The zero value is off; node
// configuration turns it on by default.
LedgerValidateAheadEnabled bool
// BlockfetchLowWatermarkEnabled starts blockfetch once one blockfetch
// range of headers is queued while the node is far from the peer tip,
// instead of waiting for allowedQueuedHeaders. The header queue capacity
// (chain.MaxQueuedHeaders) is unchanged. Off by default.
BlockfetchLowWatermarkEnabled bool
}
type LedgerView ¶
type LedgerView struct {
// contains filtered or unexported fields
}
func (*LedgerView) ByronProtocolMagic ¶ added in v0.70.0
func (lv *LedgerView) ByronProtocolMagic() (uint32, error)
func (*LedgerView) ByronProtocolParameters ¶ added in v0.74.0
func (lv *LedgerView) ByronProtocolParameters() ( *eras.ByronProtocolParameters, error, )
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) CommitteeCredentialIsElected ¶ added in v0.73.4
func (lv *LedgerView) CommitteeCredentialIsElected( coldCredential lcommon.Credential, ) (bool, error)
CommitteeCredentialIsElected reports whether an exact tagged cold credential is seated in the enacted committee of this view's snapshot. It implements the membership half of gOuroboros common.CommitteeVotingState. Expired members stay seated until an enacted action removes them, and members that appear only in pending UpdateCommittee proposals are not elected, matching cardano-ledger's authorizedElectedHotCommitteeCredentials.
func (*LedgerView) CommitteeCredentialMember ¶ added in v0.70.5
func (lv *LedgerView) CommitteeCredentialMember( coldCredential lcommon.Credential, ) (*lcommon.CommitteeMember, error)
CommitteeCredentialMember resolves a committee member by full tagged cold credential identity: its latest seated term, or else a potential future member that a pending UpdateCommittee proposal would add.
A seated member's resignation stays in force for as long as it is seated, even while a pending proposal would re-elect it: cardano-ledger keeps a seated member's committee state across every epoch boundary, and GOVCERT rejects any further certificate from a resigned cold credential (ConwayCommitteeHasPreviouslyResigned).
func (*LedgerView) CommitteeHotCredentialColdCredentials ¶ added in v0.73.4
func (lv *LedgerView) CommitteeHotCredentialColdCredentials( hotCredential lcommon.Credential, ) ([]lcommon.Credential, error)
CommitteeHotCredentialColdCredentials returns every cold credential whose committee state currently authorizes this exact tagged hot credential, seated or not and regardless of expiry, omitting resigned members. It implements the lookup half of gOuroboros common.CommitteeVotingState; the PV11 elected-voter rule applies the enacted-committee filter through CommitteeCredentialIsElected.
func (*LedgerView) CommitteeHotCredentialMember ¶ added in v0.70.5
func (lv *LedgerView) CommitteeHotCredentialMember( hotCredential lcommon.Credential, ) (*lcommon.CommitteeMember, error)
CommitteeHotCredentialMember resolves a committee authorization by exact tagged hot credential identity, preferring a seated member.
Deliberately not filtered by term expiry. The Conway GOV rule resolves a committee voter against the authorization map, which excludes only resigned members, and its protocol-version-11 elected-voter gate intersects committee membership by cold credential alone. Expiry is applied later, in the RATIFY tally and in the committeeMinSize active count, so skipping an expired member here would raise UnknownVoterError on a vote cardano-ledger accepts. A resigned member is excluded, matching the upstream authorization set.
A cold credential that is not seated authorizes a hot credential only for the rest of the epoch its authorization was recorded in; see committeeHotAuthorizations.
func (*LedgerView) CommitteeHotCredentialMembers ¶ added in v0.73.4
func (lv *LedgerView) CommitteeHotCredentialMembers( hotCredential lcommon.Credential, ) ([]*lcommon.CommitteeMember, error)
CommitteeHotCredentialMembers returns every current cold-credential authorization for this exact tagged hot credential. The Conway certificate overlay uses the full set when same-transaction certificates move one shared hot credential without invalidating another cold credential's authorization.
func (*LedgerView) CommitteeMember ¶ added in v0.21.0
func (lv *LedgerView) CommitteeMember( coldKey lcommon.Blake2b224, ) (*lcommon.CommitteeMember, error)
CommitteeMember preserves the legacy hash-only contract. It returns nil when key and script credentials with the same hash are both members rather than choosing one by iteration order.
func (*LedgerView) CommitteeMembers ¶ added in v0.21.0
func (lv *LedgerView) CommitteeMembers() ([]lcommon.CommitteeMember, error)
CommitteeMembers returns all seated committee members.
Resolution runs off the single GetCommitteeMembers load rather than calling CommitteeCredentialMember per seat, which would reload the whole set for every member. Resignations are fetched for the whole set in one query.
func (*LedgerView) CommitteeStateAvailable ¶ added in v0.70.5
func (lv *LedgerView) CommitteeStateAvailable() (bool, error)
CommitteeStateAvailable reports whether this view can authoritatively answer committee credential queries for its snapshot.
Persisted history establishes authority even after every member is removed. An explicitly empty Conway genesis committee is also authoritative, though genesis initialization has no members to persist. Without either source, an empty store alone cannot establish non-membership.
func (*LedgerView) Constitution ¶ added in v0.21.0
func (lv *LedgerView) Constitution() (*lcommon.Constitution, error)
Constitution returns the enacted constitution: its anchor URL, anchor hash, and optional guardrails policy hash.
Constitution state that is missing or malformed fails closed with governance.ErrConstitutionUnavailable; a constitution store that cannot be read at all returns the wrapped store error. Neither reports an empty-but-valid constitution, which gouroboros' guardrails rule would read as "no guardrails script required".
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) DRepDelegation ¶ added in v0.67.0
func (lv *LedgerView) DRepDelegation( cred lcommon.Credential, ) (*lcommon.Drep, error)
DRepDelegation returns the DRep that the given stake credential is vote-delegated to, or nil when the credential is not registered or is not delegated to any DRep. It satisfies gouroboros' common.DRepDelegationState, which the ledger rules use to validate reward withdrawals on protocol versions 10 and 11 (a withdrawal from a credential not delegated to a DRep is rejected).
func (*LedgerView) DRepRegistration ¶ added in v0.21.0
func (lv *LedgerView) DRepRegistration( credential lcommon.Credential, ) (*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) DijkstraBlsProofDomain ¶ added in v0.91.0
func (lv *LedgerView) DijkstraBlsProofDomain() lcommon.DijkstraBlsProofDomain
DijkstraBlsProofDomain returns the immutable pool-proof policy shared by block application, mempool validation, and transaction evaluation.
func (*LedgerView) EpochForSlot ¶ added in v0.70.7
func (lv *LedgerView) EpochForSlot(slot uint64) (uint64, error)
EpochForSlot returns the epoch containing the given slot, satisfying gouroboros' optional common.EpochState capability.
Several ledger rules are expressed relative to the current epoch and degrade to a weaker check when the ledger state cannot supply one. Without this the pool-deposit decision cannot tell a retired pool from a registered one, so a registration for an already-retired pool is charged no deposit and the transaction fails value conservation by exactly that amount; the retirement-epoch bound on pool retirement certificates is skipped for the same reason.
func (*LedgerView) EvaluationContext ¶ added in v0.81.0
func (lv *LedgerView) EvaluationContext() context.Context
EvaluationContext returns the context governing this ledger operation.
func (*LedgerView) GenesisDelegState ¶ added in v0.78.0
func (lv *LedgerView) GenesisDelegState( slot uint64, ) (eras.GenesisDelegState, error)
GenesisDelegState implements eras.GenesisDelegStateProvider.
func (*LedgerView) GenesisDelegateForGenesisKey ¶ added in v0.73.1
func (lv *LedgerView) GenesisDelegateForGenesisKey( genesisKeyHash lcommon.Blake2b224, slot uint64, ) (lcommon.Blake2b224, bool, error)
func (*LedgerView) GenesisDelegateKeyHashes ¶ added in v0.73.1
func (lv *LedgerView) GenesisDelegateKeyHashes( slot uint64, ) ([]lcommon.Blake2b224, error)
func (*LedgerView) GenesisUpdateQuorum ¶ added in v0.73.1
func (lv *LedgerView) GenesisUpdateQuorum() (uint, error)
func (*LedgerView) GetAdaPots ¶ added in v0.18.0
func (lv *LedgerView) GetAdaPots() lcommon.AdaPots
GetAdaPots returns the current Ada pots, or a zero AdaPots when they cannot be produced.
It exists to satisfy common.RewardState, which gives it no way to report an error, so an unavailable value is indistinguishable here from genuinely zero pots. Every caller that can handle the difference must use GetAdaPotsWithError; this one returns a zero value because a ledger rule reaching it through the interface would otherwise kill the node.
func (*LedgerView) GetAdaPotsWithError ¶ added in v0.49.0
func (lv *LedgerView) GetAdaPotsWithError() (lcommon.AdaPots, error)
GetAdaPotsWithError returns the current Ada pots. TODO: implement the complete Ada pots retrieval. Treasury and reserves are tracked in network_state, but this interface also needs the current fee and reward pots as one coherent validation snapshot.
func (*LedgerView) GetCommitteeAuthorizedCount ¶ added in v0.78.0
func (lv *LedgerView) GetCommitteeAuthorizedCount() (int, error)
GetCommitteeAuthorizedCount returns the number of seated, non-resigned committee members that hold a current hot-key authorization. Members without a hot key are not counted and term expiry is not applied.
func (*LedgerView) GetDRepVotingPower ¶ added in v0.22.0
func (lv *LedgerView) GetDRepVotingPower( credentialTag uint8, drepCredential []byte, ) (uint64, error)
GetDRepVotingPower returns the voting power for a DRep by summing the current stake of all delegated accounts, approximated from live UTxO balance plus reward-account balance.
TODO: Accept an epoch parameter and use epoch-based stake snapshots for accurate voting power. The current implementation approximates voting power using current live balances.
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) GetLeiosKeys ¶ added in v0.70.0
func (lv *LedgerView) GetLeiosKeys( epoch uint64, poolKeyHashes []lcommon.PoolKeyHash, ) (map[string]*lcommon.LeiosKey, error)
GetLeiosKeys returns the Dijkstra/Leios BLS key frozen with each named pool's Mark stake snapshot for epoch. A pool absent from the result has no captured key. A key is aged against the committee epoch the snapshot selects (epoch plus one), matching the reference ledger. The returned keys are raw; callers must verify proof of possession before treating a key as usable.
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.
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 mark stake distribution at the requested snapshot epoch. Callers choose the Praos-active epoch before calling.
func (*LedgerView) GetTotalActiveStake ¶ added in v0.22.0
func (lv *LedgerView) GetTotalActiveStake(epoch uint64) (uint64, error)
GetTotalActiveStake returns the total stake from the requested mark snapshot.
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) GovPurposeRoots ¶ added in v0.70.1
func (lv *LedgerView) GovPurposeRoots() (*lcommon.GovPurposeRoots, error)
GovPurposeRoots returns the latest enacted action for each CIP-1694 governance purpose. A non-nil result with nil fields means Dingo has authoritatively determined that the corresponding purpose has no root.
func (*LedgerView) IsBlsKeyInUse ¶ added in v0.88.0
func (lv *LedgerView) IsBlsKeyInUse( publicKey []byte, ) (bool, lcommon.PoolKeyHash, error)
IsBlsKeyInUse reports whether an active or deferred pool registration claims the given BLS voting public key.
func (*LedgerView) IsFutureVrfKeyInUse ¶ added in v0.83.0
func (lv *LedgerView) IsFutureVrfKeyInUse( vrfKeyHash lcommon.Blake2b256, ) (bool, lcommon.PoolKeyHash, error)
IsFutureVrfKeyInUse checks the VRF key retained by a pool's latest deferred parameter update in the view's current epoch.
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).
A key is claimed by the registration effective as of the start of the current epoch, and also by a pool's latest deferred re-registration: that update is held until the next boundary (cardano-ledger's psFutureStakePoolParams) but its VRF key is already in psVRFKeyHashes, so another pool cannot register it. The pool's prior key stays reserved until the boundary. The effective owner is reported first. See GetPoolByVrfKeyHash. The epoch boundary used is lv.epochStartSlot, pinned once at view construction -- not re-read from the live consensus snapshot here, per epochStartSlot's field doc comment.
func (*LedgerView) MIRDelegState ¶ added in v0.72.0
func (lv *LedgerView) MIRDelegState( slot uint64, additive bool, ) (eras.MIRDelegState, error)
MIRDelegState returns the move instantaneous rewards DELEG state that a certificate at slot is checked against: the chain account pots, the distributions and pot transfers committed this epoch at or before slot, and the epoch's too-late cutoff. additive selects how repeated distributions to one credential fold, per eras.MIRDelegState.Pending.
Every transaction's certificates are written to the database immediately after that transaction validates (see ledgerProcessBlock), before the next transaction in the same block validates, so this already reflects every prior transaction's MIR certificates this epoch, same block or earlier. Certificates within the transaction being validated are folded in memory by the eras package as it walks the certificate list.
The epoch start slot comes from lv.epochStartSlot, pinned from the same snapshot pp was captured from (see its field doc comment), never a fresh read of LedgerState.currentEpoch, which a concurrent writer could advance mid-validation.
func (*LedgerView) MinPoolMargin ¶ added in v0.67.0
func (lv *LedgerView) MinPoolMargin() *big.Rat
MinPoolMargin forwards the CIP-23 minimum pool margin from the underlying ledger state so that a *LedgerView (the value passed to ValidateTx*) satisfies the eras.MinPoolMarginProvider interface. Without this, the Dijkstra pool-margin-floor certificate rule would never see the configured floor.
func (*LedgerView) NetworkId ¶
func (lv *LedgerView) NetworkId() uint
func (*LedgerView) PendingInstantaneousRewards ¶ added in v0.79.1
func (lv *LedgerView) PendingInstantaneousRewards( source uint, cred lcommon.Credential, ) (*big.Int, error)
PendingInstantaneousRewards returns the instantaneous rewards pending for cred in the pot named by source (0 reserves, 1 treasury): the sum of the distributions committed earlier in the current epoch, or nil when there are none. The gouroboros DELEG rule reads it only from protocol version 5, where repeated distributions add, so the fold is always additive.
The range is open-ended because a transaction's certificates are stored only after it validates and a rollback deletes them, so everything stored in the epoch precedes the transaction being validated.
func (*LedgerView) Phase2ResultCache ¶ added in v0.90.5
func (lv *LedgerView) Phase2ResultCache() *eras.Phase2ResultCache
Phase2ResultCache forwards the underlying LedgerState's Phase2ResultCache, so a *LedgerView satisfies eras.Phase2ResultCacheProvider. Returns nil for a bare-constructed LedgerView with no ls (test-only).
func (*LedgerView) PlutusEvalContextCache ¶ added in v0.75.0
func (lv *LedgerView) PlutusEvalContextCache() *eras.PlutusEvalContextCache
PlutusEvalContextCache forwards the underlying LedgerState's shared PlutusEvalContextCache so that a *LedgerView (the value passed to ValidateTx*/EvaluateTx*) satisfies eras.PlutusEvalContextCacheProvider. Returns nil for a bare-constructed LedgerView with no ls (test-only), which era script evaluation already treats as "no cache available".
func (*LedgerView) PoolCurrentState ¶ added in v0.17.0
func (lv *LedgerView) PoolCurrentState( pkh lcommon.PoolKeyHash, ) (*lcommon.PoolRegistrationCertificate, *uint64, error)
PoolCurrentState returns the epoch-effective 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) PreverifiedSignatures ¶ added in v0.84.0
func (lv *LedgerView) PreverifiedSignatures() *lcommon.PreverifiedSignatures
PreverifiedSignatures exposes a transaction-bound signature result to the era validation composition. A nil result selects inline verification.
func (*LedgerView) ProtocolParameterUpdateWindow ¶ added in v0.73.1
func (lv *LedgerView) ProtocolParameterUpdateWindow( slot uint64, ) (uint64, uint64, 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. Missing and inactive reward accounts are represented by a nil balance, as required by the gouroboros reward-state contract. A registered account with a zero balance returns a non-nil pointer to zero.
func (*LedgerView) SignatureResultCache ¶ added in v0.90.5
func (lv *LedgerView) SignatureResultCache() *eras.SignatureResultCache
SignatureResultCache forwards the underlying LedgerState's SignatureResultCache, so a *LedgerView satisfies eras.SignatureResultCacheProvider. Returns nil for a bare-constructed LedgerView with no ls (test-only).
func (*LedgerView) SkipPhase2Validation ¶ added in v0.50.0
func (lv *LedgerView) SkipPhase2Validation() bool
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.
This is the converter transaction validation sees, and a Plutus script context must convert the transaction's validity interval through it. The forecast horizon stays in force, matching cardano-ledger's TimeTranslationPastHorizon failure, but it is measured from this view's horizon anchor so a block being applied is judged against its own predecessor rather than a tip that has not been published yet.
func (*LedgerView) StakeCredentialDeposit ¶ added in v0.70.4
func (lv *LedgerView) StakeCredentialDeposit( cred lcommon.Credential, ) (*uint64, error)
StakeCredentialDeposit returns the registration deposit currently held for a registered stake credential. The account lookup preserves the live registration semantics used by IsStakeCredentialRegistered, while the registration history carries the deposit actually paid rather than the current protocol-parameter value.
func (*LedgerView) StakeRegistration ¶
func (lv *LedgerView) StakeRegistration( stakingKey []byte, ) ([]lcommon.StakeRegistrationCertificate, error)
func (*LedgerView) StakeRegistrationByCredential ¶ added in v0.55.0
func (lv *LedgerView) StakeRegistrationByCredential( cred lcommon.Credential, ) ([]lcommon.StakeRegistrationCertificate, error)
StakeRegistrationByCredential returns stake registration certificates for the full stake credential identity, preserving key/script credential separation.
func (*LedgerView) StorageErr ¶ added in v0.70.10
func (lv *LedgerView) StorageErr() error
StorageErr returns the first non-not-found storage error recorded by a boolean LedgerState predicate on this view, or nil. A ValidateTxFunc or EvaluateTxFunc call site must prefer this over the rule's own return value -- see storageFaultOrErr.
func (*LedgerView) SyntheticV2CostModelInEffect ¶ added in v0.70.9
func (lv *LedgerView) SyntheticV2CostModelInEffect() bool
SyntheticV2CostModelInEffect reports whether the PlutusV2 cost model currently in force is still HardForkBabbage's fabricated default rather than real governance/protocol-update data -- see LedgerState.syntheticV2CostModel. ledger/eras validation code (which cannot import this package) type-asserts its lcommon.LedgerState parameter against a locally declared interface with this exact method signature to reach it without a package cycle.
Returns the value pinSyntheticV2CostModel recorded, not a live read of ls.loadConsensusSnapshot() -- see syntheticV2CostModel's field doc comment for why a live read would be unsound here. A *LedgerView this wasn't called on (e.g. a test constructing one directly) reports false, matching the field's zero value.
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 treasury value visible to this ledger view. A view used for transaction validation carries the same database transaction as the rest of that validation, so epoch-boundary pot changes and rollback are read from one atomic ledger snapshot.
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 LeiosAnnouncementOCINStaleness ¶ added in v0.70.2
type LeiosAnnouncementOCINStaleness uint8
LeiosAnnouncementOCINStaleness reports whether an otherwise-valid dangling Leios announcement uses an operational-certificate issue number accepted by the chain-dependent state at the immutable tip.
const ( // LeiosAnnouncementFreshOCIN means the announcement counter is equal to or // ahead of the immutable-tip counter and may be processed and relayed. LeiosAnnouncementFreshOCIN LeiosAnnouncementOCINStaleness = iota // LeiosAnnouncementStaleOCIN means the announcement counter is lower than // the immutable-tip counter, or its issuer is unknown at that point. The // peer message is accepted, but networking must not process or relay it. LeiosAnnouncementStaleOCIN )
type LocalRollbackRecoveryResult ¶ added in v0.31.1
type LocalStateQueryLimitError ¶ added in v0.70.6
type LocalStateQueryLimitError struct {
QueryName string
SubmittedItemCount int
MaximumAllowedItemCount int
}
LocalStateQueryLimitError describes an over-limit LocalStateQuery request. In-process callers can use errors.Is for the stable category and errors.As for QueryName, SubmittedItemCount, and MaximumAllowedItemCount. Node-to-client protocol errors terminate the connection, so an over-the-wire client observes a closed connection rather than this Go error value.
func (*LocalStateQueryLimitError) Error ¶ added in v0.70.6
func (e *LocalStateQueryLimitError) Error() string
func (*LocalStateQueryLimitError) Unwrap ¶ added in v0.70.6
func (e *LocalStateQueryLimitError) Unwrap() error
type MempoolProvider ¶ added in v0.14.0
type MempoolProvider interface {
Transactions() []PendingTransaction
// RemoveTxsByHash removes confirmed transactions without cascading to
// chained descendants, which remain valid against the updated ledger.
RemoveTxsByHash(hashes []string)
}
MempoolProvider provides pending transactions without exposing mempool DTOs.
type NetworkIngestHoldTracker ¶ added in v0.87.0
type NetworkIngestHoldTracker interface {
SetNetworkIngestHeld(held bool)
ConnectionIngestHeld(connId ouroboros.ConnectionId) bool
}
NetworkIngestHoldTracker is told when network ingest is held and released, and reports which connections existed while it was held. A connection that did keeps being dropped after the release until it closes: its chainsync cursor moved past the chain while its headers were discarded.
type PeerHeaderLookupFunc ¶ added in v0.27.7
type PeerHeaderLookupFunc func( connId ouroboros.ConnectionId, hash []byte, ) (ChainsyncEvent, []byte, bool)
PeerHeaderLookupFunc looks up a previously observed header for a peer connection, even if that header was suppressed before entering the ledger queue. It returns the recorded chainsync event, the header's prev-hash, and whether the header was found.
type PeersWithBlockFunc ¶ added in v0.38.0
type PeersWithBlockFunc func( origin ouroboros.ConnectionId, point ocommon.Point, ) []ouroboros.ConnectionId
PeersWithBlockFunc returns all tracked connection IDs — excluding origin — that have a recorded observed header at the given point. Used to locate shadow peers for parallel blockfetch dispatch.
type PendingTransaction ¶ added in v0.55.0
PendingTransaction is the transaction view ledger block construction needs.
type PoolRelay ¶ added in v0.55.0
type PoolRelay struct {
Hostname string
IPv4 *net.IP
IPv6 *net.IP
Port uint
// PoolKeyHash identifies the pool that registered this relay.
PoolKeyHash []byte
// Stake is the delegated stake, in lovelace, of the pool owning the
// relay. StakeKnown reports whether the lookup succeeded.
Stake uint64
// StakeKnown distinguishes a successful zero-stake lookup from absent data.
StakeKnown bool
// IsMultiHost marks a MultiHostName relay: a hostname with no port,
// whose port comes from an SRV record.
IsMultiHost bool
}
PoolRelay represents a stake pool relay as exposed by the ledger/database boundary.
type PoolRelayProvider ¶ added in v0.55.0
type PoolRelayProvider struct {
// contains filtered or unexported fields
}
PoolRelayProvider exposes active stake pool relays from the ledger/database without depending on peer-governance policy types.
func NewPoolRelayProvider ¶ added in v0.55.0
func NewPoolRelayProvider( ledgerState *LedgerState, db *database.Database, eventBus *event.EventBus, ) (*PoolRelayProvider, error)
NewPoolRelayProvider creates a new ledger pool relay provider. Returns an error if ledgerState or db is nil.
func (*PoolRelayProvider) Close ¶ added in v0.69.0
func (p *PoolRelayProvider) Close()
Close unsubscribes the cache-invalidation handler registered in NewPoolRelayProvider. Safe to call on a provider constructed with a nil eventBus (no-op) and safe to call more than once.
func (*PoolRelayProvider) CurrentSlot ¶ added in v0.55.0
func (p *PoolRelayProvider) CurrentSlot() uint64
CurrentSlot returns the current chain tip slot number.
func (*PoolRelayProvider) GetPoolRelays ¶ added in v0.55.0
func (p *PoolRelayProvider) GetPoolRelays(ctx context.Context) ( []PoolRelay, error, )
GetPoolRelays returns all active pool relays from the ledger.
func (*PoolRelayProvider) InvalidateCache ¶ added in v0.55.0
func (p *PoolRelayProvider) InvalidateCache()
InvalidateCache clears the cached pool relays, forcing the next GetPoolRelays call to fetch fresh data from the database.
type PoolStakeDistribution ¶ added in v0.70.0
type PoolStakeDistribution struct {
// Tip is the chain tip read inside the same transaction as the stake rows.
// It is what the distribution was evaluated against, so a caller reporting
// a "the state as of" point must use this rather than sampling the tip
// again afterwards: between the two reads the chain can advance, and across
// an epoch boundary the later tip names an epoch whose snapshot is not the
// one these rows came from.
Tip ochainsync.Tip
// SnapshotEpoch names the mark snapshot the distribution was read from,
// which is the snapshot this node elects leaders from rather than live
// stake.
SnapshotEpoch uint64
// TotalActiveStake is the whole snapshot's total, clamped to a minimum of
// one. The clamp is inherited from totalActiveStake, where it exists
// because cardano clients decode this as a NonZero value; see its doc
// comment. It is the denominator every StakeFraction is taken over.
TotalActiveStake uint64
// TotalCirculatingSupply is genesis MaxLovelaceSupply minus the live
// reserves pot, clamped the same way as TotalActiveStake. It is a
// different total from TotalActiveStake -- see totalCirculatingSupply's
// doc comment for why GetStakeDistribution, and only GetStakeDistribution,
// needs this one instead.
TotalCirculatingSupply uint64
// Pools is ordered by PoolKeyHash. Callers that place this in a repeated
// protobuf field or any other ordered encoding depend on that: without it
// the order is Go map iteration order, so two identical requests against
// an unchanged snapshot would differ.
Pools []PoolStakeShare
}
PoolStakeDistribution is the stake distribution across block-producing pools as of SnapshotEpoch.
type PoolStakeShare ¶ added in v0.70.0
type PoolStakeShare struct {
Stake uint64
// is a share of the whole snapshot even when a filter was applied, so a
// filtered distribution's fractions sum to less than one.
StakeFraction *cbor.Rat
VrfKeyHash ledger.Blake2b256
}
PoolStakeShare is one pool's entry in the active stake distribution.
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
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 QueryPoint ¶ added in v0.70.9
QueryPoint pins a Query call to a specific historical block instead of live-right-now. The zero value (Slot 0, no Hash) means no pin -- the existing, default behavior of answering from whatever is live right now -- matching the same "0 accepts the live/published value" convention SlotToTimeWithHorizonFrom's horizonAnchorSlot already uses elsewhere in this package.
Hash is required whenever Slot is non-zero: identifying a historical point by slot alone is ambiguous across a rollback (a fork switch can leave a different block at the same slot than the one the caller acquired), so Query verifies Hash against this node's current chain before answering -- see verifyPointOnChain.
type QueryView ¶ added in v0.79.0
type QueryView struct {
// contains filtered or unexported fields
}
QueryView is a read-only snapshot of the ledger that a LocalStateQuery session holds between Acquire and Release. Every query answered through it reads one database read transaction opened at acquire time, so a block applied or a rollback committed afterwards is not visible to the session.
A view pins a database read transaction for its whole lifetime, which holds back WAL checkpoints and a read connection; owners must Close it promptly and bound how long they let it live. The one exception is GetUTxOWhole, which can run for minutes: it releases the view's transaction and answers as of the view's block from short transactions, and a later query reopens a snapshot pinned to that block (see detachForUtxoWhole).
type RecordBlockfetchLatencyFunc ¶ added in v0.38.0
type RecordBlockfetchLatencyFunc func(ouroboros.ConnectionId, time.Duration)
RecordBlockfetchLatencyFunc records a delivery estimate for a connection: first-block latency after success or the watchdog duration after timeout.
type RecordBlockfetchThroughputFunc ¶ added in v0.79.0
type RecordBlockfetchThroughputFunc func( connId ouroboros.ConnectionId, bytes uint64, elapsed time.Duration, )
RecordBlockfetchThroughputFunc records how many bytes a batch delivered after its first block and how long that took.
type ReportSlotClockAliveFunc ¶ added in v0.80.0
type ReportSlotClockAliveFunc func()
ReportSlotClockAliveFunc is called each slot the slot clock pauses its ticks because era history does not reach the wall-clock slot. The clock is running and has nothing to emit, so a liveness heartbeat fed from the ticks can tell that pause from a stopped clock. Optional; nil disables the report.
type ReportTipGapFunc ¶ added in v0.70.13
type ReportTipGapFunc func(gapSlots uint64)
ReportTipGapFunc receives the wall-clock-to-tip distance in slots on every slot-clock tick, the same value the dingo_tip_gap_slots gauge carries. It exists so a caller can classify sync health without scraping Prometheus: the node's readiness probe reads it. Optional; nil disables the report.
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 NewSchedulerWithConfig ¶ added in v0.19.0
func NewSchedulerWithConfig( interval time.Duration, config SchedulerConfig, ) *Scheduler
func (*Scheduler) ChangeInterval ¶ added in v0.14.0
ChangeInterval updates the tick interval of the Scheduler at runtime. It returns an error if newInterval is not positive.
The new interval is applied when run() next reaches its select, including when the call precedes Start or run() is servicing a tick. The call never blocks on run(): updateIntervalChan holds one pending interval, and a full buffer holds a value this call supersedes, so it is drained and the send retried.
type SchedulerConfig ¶ added in v0.19.0
func DefaultSchedulerConfig ¶ added in v0.19.0
func DefaultSchedulerConfig() SchedulerConfig
type SelectBlockfetchPeerFunc ¶ added in v0.79.0
type SelectBlockfetchPeerFunc func( origin ouroboros.ConnectionId, rangeEnd ocommon.Point, ) ouroboros.ConnectionId
SelectBlockfetchPeerFunc returns the connection to fetch the range that ends at the given point from. origin is the connection that delivered the header and is the answer when nothing better is known.
type SelectBlockfetchRetryPeerFunc ¶ added in v0.82.0
type SelectBlockfetchRetryPeerFunc func( excluded []ouroboros.ConnectionId, rangeEnd ocommon.Point, timeoutPenalty time.Duration, ) (selected ouroboros.ConnectionId, found, available bool)
SelectBlockfetchRetryPeerFunc records the failed peer's timeout penalty and returns another eligible connection that announced the range end. A zero timeoutPenalty records nothing. Excluded connections are never valid results. available is false when lifecycle contention prevented both the penalty and selection.
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:
- Query methods (CurrentSlot, CurrentEpoch, GetEpochForSlot, etc.) that work in all modes (catch up, load, synced) and can be called anytime.
- 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
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
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
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
IsEpochBoundary returns true if the given slot is the first slot of an epoch.
func (*SlotClock) LastEmittedEpoch ¶ added in v0.22.0
LastEmittedEpoch returns the last epoch for which an event was emitted.
func (*SlotClock) MarkEpochEmitted ¶ added in v0.22.0
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
NextSlotTime returns the time when the next slot will start
func (*SlotClock) SetLastEmittedEpoch ¶ added in v0.22.0
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
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
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
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
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
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
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.
// Set high enough to ride out normal Go scheduler / GC pause jitter on a busy
// node — only sustained or large drifts indicate a real timing problem.
// Default: 500ms.
ClockTolerance time.Duration
// OnBehindHorizon, when set, is called with the wall-clock slot each time
// a tick is skipped because era history does not yet reach that slot. It
// lets wall-clock-derived metrics stay live while ticks are paused, and
// carries no epoch information.
OnBehindHorizon func(wallSlot uint64)
}
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 SlotTimeConverter ¶ added in v0.69.0
type SlotTimeConverter struct {
// contains filtered or unexported fields
}
SlotTimeConverter converts between Cardano slots and wall-clock time.
Era-boundary math is delegated to a hardfork.Summary obtained from the injected HardForkSummary accessor; this type layers the operational near-now fallbacks on top (see withinOperationalWindow) so the slot clock can keep resolving the next slot boundary while the applied ledger is behind the wall clock (from-genesis sync, `dingo load`, restart after downtime).
A SlotTimeConverter holds no lock of its own: era history and genesis are read fresh from the injected accessors on every call, so it is safe for concurrent use as long as those accessors are.
func NewSlotTimeConverter ¶ added in v0.69.0
func NewSlotTimeConverter(deps SlotTimeConverterDeps) *SlotTimeConverter
NewSlotTimeConverter creates a SlotTimeConverter with the given dependencies.
func (*SlotTimeConverter) EndorserBlockWaitDuration ¶ added in v0.69.0
func (c *SlotTimeConverter) EndorserBlockWaitDuration( waitSlots uint64, ) time.Duration
EndorserBlockWaitDuration returns the wall-clock window corresponding to waitSlots slots at the Shelley-era slot length, or 0 when waitSlots is 0 or the slot length is unknown.
func (*SlotTimeConverter) EpochInfo ¶ added in v0.69.0
func (c *SlotTimeConverter) EpochInfo(epoch uint64) (models.Epoch, error)
EpochInfo returns boundary information for the given epoch.
Epochs within the known epoch cache resolve to cached-era parameters; epochs past the cache are projected using the current era's parameters only through the configured safe-zone horizon. Returns an error for an empty cache or for epochs outside that range.
func (*SlotTimeConverter) SlotToEpoch ¶ added in v0.69.0
func (c *SlotTimeConverter) SlotToEpoch(slot uint64) (models.Epoch, error)
SlotToEpoch returns the epoch containing the given slot.
Slots within the known epoch cache resolve to the cached epoch's parameters; slots past the cache are projected using the current era's parameters only through the configured safe-zone horizon. Returns an error for an empty cache or for slots outside that range.
func (*SlotTimeConverter) SlotToTime ¶ added in v0.69.0
func (c *SlotTimeConverter) SlotToTime(slot uint64) (time.Time, error)
SlotToTime returns the wall-clock start time of the given slot.
Slot 0 always maps to Shelley genesis SystemStart, regardless of whether the epoch cache is populated. Other slots are resolved via the hardfork.Summary built from the current epoch cache. The current era can be projected only through its configured safe-zone horizon.
func (*SlotTimeConverter) SlotToTimeWithHorizonFrom ¶ added in v0.70.7
func (c *SlotTimeConverter) SlotToTimeWithHorizonFrom( horizonAnchorSlot uint64, slot uint64, ) (time.Time, error)
SlotToTimeWithHorizonFrom converts a slot with the forecast horizon measured from horizonAnchorSlot rather than from the published tip, and keeps the horizon: a slot past the anchored bound still returns hardfork.ErrPastHorizon.
Transaction validation needs this. Building a Plutus script context converts the transaction's validity interval to POSIX time, and cardano-ledger fails the transaction when that translation is refused (TimeTranslationPastHorizon, eras/alonzo/impl Cardano.Ledger.Alonzo.Plutus.TxInfo), so the bound itself is consensus-relevant and must stay. What diverged was the horizon's input: the published tip advances only when a whole block batch commits, while the reference measures the safe zone from the applied block's immediate predecessor. applySafeZone snaps up to an epoch boundary, so a tip trailing by a single block can cost a full epoch of horizon and reject a canonical block.
The near-now extrapolation SlotToTime applies is deliberately absent: it exists so the operational slot clock can tick while the ledger is behind the wall clock, and transaction validation must answer from era history alone.
func (*SlotTimeConverter) TimeToSlot ¶ added in v0.69.0
func (c *SlotTimeConverter) TimeToSlot(t time.Time) (uint64, error)
TimeToSlot returns the slot containing the given wall-clock time.
Returns ErrBeforeGenesis when t is before SystemStart. Near-now calls used by the operational slot clock retain current-era extrapolation when the ledger is empty or behind the HFC forecast horizon; arbitrary time queries remain bounded.
type SlotTimeConverterDeps ¶ added in v0.69.0
type SlotTimeConverterDeps struct {
// HardForkSummary returns the current hardfork.Summary describing era
// history, or an error when it cannot be built (e.g. no epochs known
// yet). The current era's forecast horizon is measured from
// max(the published tip slot, horizonAnchorSlot); 0 accepts the
// published tip.
HardForkSummary func(horizonAnchorSlot uint64) (*hardfork.Summary, error)
// ShelleyGenesis returns the Shelley genesis config, or nil if it has
// not been loaded.
ShelleyGenesis func() *shelley.ShelleyGenesis
// EpochCache returns the current epoch cache snapshot, most-recent-last.
EpochCache func() []models.Epoch
}
SlotTimeConverterDeps supplies the accessors a SlotTimeConverter needs to convert between slots and wall-clock time. LedgerState remains the source of truth for era history (the consensus snapshot) and genesis config; the converter depends on them only through this narrow set of read-only callbacks, so it never reaches back into LedgerState's locking or working state directly.
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 after a transaction Apply commits durably, or before an applied transaction is rolled back. Check the Rollback field to determine direction.
type TransactionRecord ¶ added in v0.18.0
type TransactionRecord struct {
Tx lcommon.Transaction
Index int
}
type UnsupportedHeaderProtocolVersionError ¶ added in v0.92.2
UnsupportedHeaderProtocolVersionError is returned when a block header's protocol major version is newer than the eras enabled by this node.
func (*UnsupportedHeaderProtocolVersionError) Error ¶ added in v0.92.2
func (e *UnsupportedHeaderProtocolVersionError) Error() string
type VerifiedPeerHeaderAncestry ¶ added in v0.91.0
type VerifiedPeerHeaderAncestry struct {
Points []ochainsync.Tip
Generation uint64
// contains filtered or unexported fields
}
VerifiedPeerHeaderAncestry is an ordinary-header path authenticated against one immutable ledger publication. Current must be checked while its generation is pinned, immediately before consuming Points.
func (VerifiedPeerHeaderAncestry) Current ¶ added in v0.91.0
func (p VerifiedPeerHeaderAncestry) Current() bool
Current reports whether the publication and chain withdrawal fence captured by this proof still hold. It performs no storage reads.
func (VerifiedPeerHeaderAncestry) Unwithdrawn ¶ added in v0.91.0
func (p VerifiedPeerHeaderAncestry) Unwithdrawn() bool
Unwithdrawn reports whether the authenticated path has survived every raw chain withdrawal. It does not establish freshness of a crypto generation.
Source Files
¶
- account_expiry.go
- account_expiry_activate.go
- account_expiry_renew.go
- account_expiry_rollback.go
- acquired_point_pins.go
- avvm_removal.go
- block_era_epoch.go
- block_event.go
- block_processing_progress.go
- block_reference_scripts.go
- boundary_era.go
- byron_pbft.go
- candidate_nonce.go
- certs.go
- chainsync.go
- chainsync_behind_peer.go
- chainsync_blockfetch_pipeline.go
- chainsync_opening_rollback.go
- chainsync_unrecoverable_rollback.go
- checkpoints.go
- continuation_audit.go
- delta.go
- dijkstra_direct_deposit.go
- doc.go
- electing_stake.go
- electing_vrf_memo.go
- envelope_validation.go
- epoch_lab_nonce.go
- epoch_rollover_phase_timing.go
- era_mismatch.go
- era_summary.go
- event.go
- external_ingest.go
- extra_entropy.go
- fork_header_nonce.go
- genesis_network_state.go
- genesis_pools.go
- hardfork_rule.go
- hardfork_summary.go
- header_admission_settle.go
- header_protocol_version.go
- header_validation_recovery.go
- header_verdict_cache.go
- heal_mithril_gap_nonce.go
- heal_truncate_gap_nonce.go
- history_bound.go
- leios_apply.go
- leios_apply_prefix.go
- leios_block_transactions.go
- leios_certification.go
- local_sibling.go
- metrics.go
- metrics_adoption.go
- metrics_sync.go
- mir.go
- network_hold.go
- peer_fork_opcert.go
- peer_provider.go
- peer_snapshot_query.go
- pending_publish.go
- pool_stake_distribution.go
- poolreap.go
- protocol_version.go
- queries.go
- queries_chaindepstate.go
- queries_currentprotocolparams.go
- queries_leioscommittee.go
- queries_notanswered.go
- queries_pooldistr2.go
- queries_poolparams.go
- queries_poolstate.go
- queries_rewardprovenance.go
- queries_stakedistribution.go
- queries_stakepoolstate.go
- queries_utxo_encoding.go
- queries_utxowhole.go
- queryview.go
- queued_blockfetch_flush.go
- ratification_deferred.go
- replay_header_preverify.go
- replay_recovery.go
- reward_calculation.go
- reward_credit_compaction.go
- reward_credit_pending.go
- reward_precompute_chunked.go
- reward_stake_input_deferred.go
- reward_stake_input_retention.go
- rollback_intent.go
- signature_preverify.go
- slot.go
- slot_battle.go
- slot_clock.go
- slot_time_converter.go
- stability_window.go
- state.go
- tachys.go
- timer.go
- tracing_block.go
- transaction_levels.go
- uint32_width.go
- utxo_prefetch.go
- utxo_prefetch_ahead.go
- validate_forged.go
- verified_peer_ancestry.go
- verify_header.go
- verify_header_vrf.go
- verify_opcert.go
- view.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package byronupdate implements the Byron update-system state transition: update proposal registration, votes, confirmation, protocol-version endorsement and adoption at an epoch boundary.
|
Package byronupdate implements the Byron update-system state transition: update proposal registration, votes, confirmation, protocol-version endorsement and adoption at an epoch boundary. |
|
Package forging contains types and utilities for block production.
|
Package forging contains types and utilities for block production. |
|
Package hardfork provides the HardFork Combinator primitives used by the ledger to reason about multi-era chain time, epoch, and slot conversions.
|
Package hardfork provides the HardFork Combinator primitives used by the ledger to reason about multi-era chain time, epoch, and slot conversions. |
|
Package leader provides Ouroboros Praos leader election functionality for block production.
|
Package leader provides Ouroboros Praos leader election functionality for block production. |
|
Package leios implements the Dijkstra top-N voting committee, stake-quorum vote tallying, and endorser-block certificate construction and validation.
|
Package leios implements the Dijkstra top-N voting committee, stake-quorum vote tallying, and endorser-block certificate construction and validation. |
|
Package rewards implements the Shelley stake-pool reward calculation.
|
Package rewards implements the Shelley stake-pool reward calculation. |
|
Package snapshot provides stake snapshot management for Ouroboros Praos leader election.
|
Package snapshot provides stake snapshot management for Ouroboros Praos leader election. |