ledgerstate

package
v0.70.7 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	EraByron = iota
	EraShelley
	EraAllegra
	EraMary
	EraAlonzo
	EraBabbage
	EraConway
)

Era name constants for logging and error messages.

View Source
const (
	CredentialTypeKey          uint64 = 0 // Key hash credential
	CredentialTypeScript       uint64 = 1 // Script hash credential
	CredentialTypeAbstain      uint64 = 2 // AlwaysAbstain pseudo-DRep
	CredentialTypeNoConfidence uint64 = 3 // AlwaysNoConfidence pseudo-DRep
)

Credential type constants matching CBOR encoding. Types 0 and 1 are standard key/script credentials with a 28-byte hash. Types 2 and 3 are pseudo-DRep targets used only in DRep delegation (not valid as staking credentials); they carry no hash.

View Source
const MaxTelescopeDepth = 16

MaxTelescopeDepth caps recursion in the nested telescope traversal. Cardano has 7 eras (Byron through Conway) so 16 is generous while still preventing stack exhaustion from attacker-controlled CBOR.

Variables

View Source
var ErrLedgerDirNotFound = errors.New("ledger directory not found")

ErrLedgerDirNotFound is returned when the ledger directory cannot be located within an extracted snapshot.

View Source
var ErrNoUsableLedgerState = errors.New("no usable ledger state")

ErrNoUsableLedgerState reports a tree that holds no ledger state a caller can use: no ledger directory at all, or none at or below the slot asked for.

It is the only outcome a caller searching several trees may treat as "look somewhere else". Everything else means the tree holds something unusable, and moving on from that would let planted content pick which tree gets imported.

View Source
var ErrNotPoolParams = errors.New("not pool params shape")

ErrNotPoolParams signals that the input CBOR is not shaped like a full PoolParams registration (either not an array or too short). Callers can use errors.Is(err, ErrNotPoolParams) to decide whether to try decoding the input as the compact PoolDistr shape. Any other decode failure indicates the value looked like PoolParams but was malformed, and must not silently fall back.

View Source
var ErrTableDigestMismatch = errors.New(
	"UTxO table is not the file the digest covers",
)

ErrTableDigestMismatch reports a UTxO-HD table whose mapped contents are not the contents the caller's digest covers.

View Source
var ErrUnsafeSnapshotPath = errors.New("unsafe snapshot path")

ErrUnsafeSnapshotPath reports an entry in a snapshot tree that is a symlink, that is not the kind of thing it should be, or that was replaced between being opened and being checked.

Functions

func ActivePoolDistributionSnapshots added in v0.61.2

func ActivePoolDistributionSnapshots(
	pools []ParsedActivePoolStake,
	epoch uint64,
	capturedSlot uint64,
) []*models.PoolStakeSnapshot

ActivePoolDistributionSnapshots converts NewEpochState.pool-distr entries into pool_stake_snapshot rows under the "actv" type. TotalStake stores the rational numerator and StakeDenominator stores the matching denominator.

func AggregatePoolStake

func AggregatePoolStake(
	snap *ParsedSnapShot,
	epoch uint64,
	snapshotType string,
	capturedSlot uint64,
) []*models.PoolStakeSnapshot

AggregatePoolStake aggregates per-credential stake into per-pool totals, producing PoolStakeSnapshot models suitable for database storage.

func EraName

func EraName(eraIndex int) string

EraName returns the human-readable name for an era index.

func FindLedgerStateFile

func FindLedgerStateFile(extractedDir string) (string, error)

FindLedgerStateFile searches the extracted snapshot directory for the ledger state file. It supports two formats:

  • Legacy: ledger/<slot>.lstate or ledger/<slot>
  • UTxO-HD: ledger/<slot>/state

Returns the path to the state file.

For trees the caller controls. It resolves pathnames and follows symlinks, so what it returns describes the tree only for as long as nobody else can write to it — and the name is resolved again by whoever opens it. Use OpenSnapshotAtOrBefore for a tree that was vetted, or that lives anywhere a concurrent writer might reach; it discovers through a directory handle and hands back the files already open. Mithril bootstrap uses that one.

func FindLedgerStateFileAtOrBefore added in v0.69.0

func FindLedgerStateFileAtOrBefore(
	extractedDir string,
	maxSlot uint64,
) (string, error)

FindLedgerStateFileAtOrBefore searches the extracted snapshot directory for the newest ledger state whose filename slot is at or before maxSlot. Mithril ancillary archives can contain a newer ledger state from the node's volatile database in addition to states anchored by certified ImmutableDB content. Callers that use a ledger state as a trust anchor must cap selection at the certified immutable tip.

func FindUTxOTableFile

func FindUTxOTableFile(extractedDir string) string

FindUTxOTableFile searches for the UTxO table file in UTxO-HD format. Current snapshots store the table as ledger/<slot>/tables, while older exports used ledger/<slot>/tables/tvar. Returns an empty string if not found (legacy format).

func FindUTxOTableFileForState added in v0.69.0

func FindUTxOTableFileForState(statePath string) string

FindUTxOTableFileForState returns the UTxO-HD table that belongs to the selected ledger state. Legacy ledger-state files embed their UTxO table and return an empty path.

func ImportLedgerState

func ImportLedgerState(
	ctx context.Context,
	cfg ImportConfig,
) error

ImportLedgerState orchestrates the full import of parsed ledger state data into Dingo's metadata store. If ImportKey is set, completed phases are checkpointed so a failed import can resume from the last successful phase.

func ParseUTxOsFromFile

func ParseUTxOsFromFile(
	path string,
	callback UTxOCallback,
) (int, error)

ParseUTxOsFromFile reads and streams UTxOs from a UTxO-HD tvar file. The tvar format is array(1) containing a map of TxIn->TxOut entries. The map may use indefinite-length encoding (0xbf...0xff).

Note: The CBOR stream decoder requires a contiguous byte slice, so the file is mmap'd read-only to avoid copying large UTxO-HD tables into Go heap.

func ParseUTxOsStreaming

func ParseUTxOsStreaming(
	data cbor.RawMessage,
	callback UTxOCallback,
) (int, error)

ParseUTxOsStreaming decodes the UTxO map from raw CBOR data and calls the callback for each batch of parsed UTxOs. This avoids loading the entire UTxO set into memory. Both definite-length and indefinite-length (0xbf) CBOR maps are supported.

func UTxOToModel

func UTxOToModel(u *ParsedUTxO, slot uint64) models.Utxo

UTxOToModel converts a ParsedUTxO to a Dingo database Utxo model.

func VerifyChecksumFile

func VerifyChecksumFile(lstatePath string) error

VerifyChecksumFile verifies the CRC32 checksum of a ledger state file against its companion .checksum file.

func VerifySnapshotDigest

func VerifySnapshotDigest(
	archivePath string,
	expectedDigest string,
) error

VerifySnapshotDigest computes the SHA-256 digest of a snapshot archive file and compares it against the expected digest from the Mithril aggregator.

Types

type Credential

type Credential struct {
	Hash []byte
	Type uint64
}

Credential pairs a credential type with its hash. For types 0 (key) and 1 (script), Hash is a 28-byte Blake2b-224. For types 2 (AlwaysAbstain) and 3 (AlwaysNoConfidence), Hash is nil.

type EpochLengthFunc

type EpochLengthFunc func(eraId uint) (
	slotLength, epochLength uint, err error,
)

EpochLengthFunc resolves the slot length (ms) and epoch length (in slots) for a given era ID using the Cardano node config. Returns (0, 0, err) if the era is unknown or the config does not contain the needed genesis parameters.

type EraBound

type EraBound struct {
	Slot  uint64
	Epoch uint64
}

EraBound represents the start boundary of an era in the HardFork telescope. Slot is the first slot of the era and Epoch is the epoch number at that slot.

type ImportConfig

type ImportConfig struct {
	Database   *database.Database
	State      *RawLedgerState
	Logger     *slog.Logger
	OnProgress func(ImportProgress)
	// EpochLength resolves era parameters from the node config.
	// If nil, epoch generation falls back to computing from
	// era bounds.
	EpochLength EpochLengthFunc
	// ImportKey identifies this import for resume tracking.
	// Format: "{digest}:{slot}". If empty, resume is disabled.
	ImportKey string
	// Reconcile enables Mithril v2 catch-up reconciliation: after the import
	// completes, every live database row absent from this (newer) snapshot's
	// live set is marked inactive (UTxOs tombstoned, accounts/DReps
	// deactivated, pools retired). It is false for a fresh bootstrap, where
	// there is nothing stale to reconcile. Reconcile requires resume to be
	// disabled (empty ImportKey) so the import pass always runs in full and the
	// snapshot key set is complete.
	Reconcile bool
	// contains filtered or unexported fields
}

ImportConfig holds configuration for the ledger state import.

type ImportProgress

type ImportProgress struct {
	Stage       string
	Current     int
	Total       int
	Percent     float64
	Description string
}

ImportProgress reports progress during ledger state import.

type MapEntry

type MapEntry struct {
	KeyRaw   []byte
	ValueRaw []byte
}

MapEntry holds a raw key-value pair from a CBOR map.

type ParsedAccount

type ParsedAccount struct {
	StakingKey  Credential // staking credential (type + hash)
	PoolKeyHash []byte     // 28-byte pool key hash (delegation target)
	DRepCred    Credential // DRep credential (vote delegation)
	Reward      uint64     // reward balance in lovelace
	Deposit     *uint64    // deposit in lovelace; nil when absent from the source
	Active      bool
}

ParsedAccount represents a stake account with its delegation.

type ParsedActivePoolStake added in v0.61.2

type ParsedActivePoolStake struct {
	PoolKeyHash             []byte
	StakeNumerator          uint64
	StakeDenominator        uint64
	VrfKeyHash              []byte
	LeiosKeyPublic          []byte
	LeiosKeyPossessionProof []byte
}

ParsedActivePoolStake represents one pool in NewEpochState.pool-distr. StakeNumerator/StakeDenominator are the exact sigma fraction used by Praos leader eligibility.

func ParseActivePoolDistribution added in v0.61.2

func ParseActivePoolDistribution(
	data cbor.RawMessage,
) ([]ParsedActivePoolStake, error)

ParseActivePoolDistribution decodes NewEpochState.pool-distr: map[PoolKeyHash][UnitInterval, active stake, VrfKeyHash, LeiosKey]. Older states omit active stake and/or LeiosKey. The UnitInterval is the exact active stake fraction (sigma) used by Praos leader eligibility.

type ParsedAsset

type ParsedAsset struct {
	PolicyId []byte // 28 bytes
	Name     []byte
	Amount   uint64
}

ParsedAsset represents a native asset within a UTxO.

type ParsedCertState

type ParsedCertState struct {
	Accounts              []ParsedAccount
	Pools                 []ParsedPool
	DReps                 []ParsedDRep
	CommitteeHotKeys      []ParsedCommitteeHotKey
	CommitteeResignations []Credential
}

ParsedCertState holds the parsed delegation, pool, and DRep state.

func ParseCertState

func ParseCertState(data cbor.RawMessage) (*ParsedCertState, error)

ParseCertState decodes the CertState from raw CBOR. CertState = [VState, PState, DState]

type ParsedCommitteeHotKey added in v0.70.5

type ParsedCommitteeHotKey struct {
	Cold Credential
	Hot  Credential
}

type ParsedCommitteeMember

type ParsedCommitteeMember struct {
	ColdCredential Credential // cold credential (type + hash)
	ExpiresEpoch   uint64
}

ParsedCommitteeMember holds a committee member credential and expiration.

type ParsedConstitution

type ParsedConstitution struct {
	AnchorURL    string
	AnchorHash   []byte // 32 bytes
	PolicyHash   []byte // 28 bytes, nil if no guardrails script
	ParseWarning error  // non-fatal warning from decoding
}

ParsedConstitution holds decoded constitution data.

type ParsedDRep

type ParsedDRep struct {
	Credential  Credential // credential (type + hash)
	AnchorURL   string
	AnchorHash  []byte
	Deposit     uint64
	ExpiryEpoch uint64 // epoch when this DRep expires (0 = unknown)
	Active      bool
}

ParsedDRep represents a DRep registration.

type ParsedGovActionId added in v0.42.0

type ParsedGovActionId struct {
	TxHash      []byte // 32 bytes
	ActionIndex uint32
}

ParsedGovActionId holds a decoded GovActionId (txHash + index).

type ParsedGovProposal

type ParsedGovProposal struct {
	TxHash       []byte // 32 bytes
	ActionIndex  uint32
	ActionType   uint8
	Deposit      uint64
	ReturnAddr   []byte
	AnchorURL    string
	AnchorHash   []byte
	ProposedIn   uint64
	ExpiresAfter uint64
	// ParentTxHash is the parent gov-action's tx hash for chained action
	// types (ParameterChange, HardForkInitiation, NoConfidence,
	// UpdateCommittee, NewConstitution). Nil for unchained actions
	// (TreasuryWithdrawals, InfoAction) and for chained actions with no
	// prior enacted predecessor (SNothing in cardano-ledger terms).
	ParentTxHash []byte
	// ParentActionIdx is the action index that pairs with ParentTxHash.
	// nil iff ParentTxHash is nil; otherwise points to the parent's
	// uint32 index.
	ParentActionIdx *uint32
	// GovActionCbor is the raw CBOR bytes of the gov action body (the
	// govAction element inside the ProposalProcedure). Persisted on
	// import so the enactment path (ledger/governance/enact.go) can
	// decode the action's payload (e.g. HardForkInitiation's protocol
	// version, ParameterChange's pparam delta) at the boundary tick
	// that enacts a previously-ratified proposal. Without it, ENACT
	// fails to decode and aborts the entire boundary tick, halting
	// the chain at the first enactment after a Mithril boot.
	GovActionCbor []byte
}

ParsedGovProposal holds a decoded governance proposal.

type ParsedGovState

type ParsedGovState struct {
	Constitution         *ParsedConstitution
	Committee            []ParsedCommitteeMember
	CommitteeQuorum      *cbor.Rat
	Proposals            []ParsedGovProposal
	PrevGovActionIds     *ParsedPrevGovActionIds
	RatifiedGovActionIds []ParsedGovActionId
}

ParsedGovState holds all decoded governance state components.

func ParseGovState

func ParseGovState(
	data cbor.RawMessage,
	eraIndex int,
) (*ParsedGovState, error)

ParseGovState decodes governance state from raw CBOR. Returns nil, nil for pre-Conway eras (eraIndex < 6).

Conway GovState structure (7 fields):

[proposals, committee, constitution,
 cur_pparams, prev_pparams, future_pparams,
 drep_pulsing_state]

Constitution, committee, and proposals are parsed. Errors from committee and proposals parsing are collected and returned alongside partial results so the caller can log them.

type ParsedPool

type ParsedPool struct {
	PoolKeyHash                []byte // 28 bytes
	VrfKeyHash                 []byte // 32 bytes
	Pledge                     uint64
	Cost                       uint64
	MarginNum                  uint64
	MarginDen                  uint64
	RewardAccount              []byte
	RewardAccountCredentialTag uint8
	Owners                     [][]byte // list of 28-byte key hashes
	Relays                     []ParsedRelay
	MetadataUrl                string
	MetadataHash               []byte // 32 bytes
	Deposit                    uint64
	// LeiosKeyPublic and LeiosKeyPossessionProof are the pool's registered
	// Dijkstra/Leios BLS voting key and its proof of possession, or nil when
	// the snapshot's pool params carry no leiosKey field. Proof-of-possession
	// verification does not happen here (ledgerstate must not depend on
	// ledger/leios's BLS primitives); it happens where these keys are read
	// back out for committee construction.
	LeiosKeyPublic          []byte // 96 bytes
	LeiosKeyPossessionProof []byte // 48 bytes
}

ParsedPool represents a stake pool registration.

type ParsedPrevGovActionIds added in v0.42.0

type ParsedPrevGovActionIds struct {
	PParamUpdate *ParsedGovActionId
	HardFork     *ParsedGovActionId
	Committee    *ParsedGovActionId
	Constitution *ParsedGovActionId
}

ParsedPrevGovActionIds holds the per-purpose chain roots from cgsProposals's GovRelation (the first element of the proposals container). Each pointer is non-nil when the corresponding purpose has an enacted predecessor (SJust); nil means SNothing (no enacted predecessor for that purpose).

type ParsedRelay

type ParsedRelay struct {
	Type     uint8  // 0=SingleHostAddr, 1=SingleHostName, 2=MultiHostName
	Port     uint16 // 0 if not specified
	IPv4     []byte // 4 bytes, nil if not specified
	IPv6     []byte // 16 bytes, nil if not specified
	Hostname string // for SingleHostName and MultiHostName
}

ParsedRelay represents a pool relay from the stake pool registration certificate.

type ParsedSnapShot

type ParsedSnapShot struct {
	// Stake maps credential-hex to staked lovelace.
	Stake map[string]uint64
	// StakeTags maps the same credential-hex to the credential type
	// (0 = key hash, 1 = script hash). The Stake key is the hash alone, and
	// a script credential can share a hash with a key credential, so the
	// type has to be carried separately or per-credential reward and
	// leadership stake attach to the wrong one.
	//
	// Both parsed shapes populate it, the compact UTxO-HD map included --
	// that shape does encode the type, and dropping it there was the defect
	// this field exists to prevent. An entry can still be missing, though,
	// so a credential absent from this map is treated as a key hash; that
	// default is a fallback, not a statement about any particular shape.
	StakeTags map[string]uint8
	// Delegations maps credential-hex to pool key hash.
	Delegations map[string][]byte
	// PoolParams maps pool-hex to pool parameters.
	PoolParams map[string]*ParsedPool
}

ParsedSnapShot represents a single stake distribution snapshot.

type ParsedSnapShots

type ParsedSnapShots struct {
	Mark ParsedSnapShot
	Set  ParsedSnapShot
	Go   ParsedSnapShot
	Fee  uint64
}

ParsedSnapShots holds the three stake distribution snapshots (mark, set, go) from the ledger state.

func ParseSnapShots

func ParseSnapShots(data cbor.RawMessage) (*ParsedSnapShots, error)

ParseSnapShots decodes the stake distribution snapshots (mark, set, go) from the EpochState. SnapShots = [mark, set, go, fee] Each SnapShot is [Stake, Delegations, PoolParams] in older ledger states. Current UTxO-HD snapshots encode [StakeWithPool, PoolParams], where each stake value is [Coin, PoolKeyHash].

type ParsedUTxO

type ParsedUTxO struct {
	TxHash        []byte // 32 bytes
	OutputIndex   uint32
	Address       []byte // raw address bytes
	PaymentKey    []byte // 28 bytes, extracted from address
	StakingKey    []byte // 28 bytes, extracted from address
	CredentialTag uint8  // stake credential tag: 0 key hash, 1 script hash
	PaymentScript bool   // true when payment credential is a script hash
	Amount        uint64 // lovelace
	Assets        []ParsedAsset
	DatumHash     []byte // optional
	Datum         []byte // optional inline datum CBOR
	ScriptRef     []byte // optional reference script CBOR
}

ParsedUTxO represents a parsed unspent transaction output ready for conversion to Dingo's database model.

type RawLedgerState

type RawLedgerState struct {
	// EraIndex identifies the current era (0=Byron … 6=Conway).
	EraIndex int
	// Epoch is the epoch number at the time of the snapshot.
	Epoch uint64
	// Tip is the chain tip recorded in the snapshot.
	Tip *SnapshotTip
	// Treasury is the treasury balance in lovelace.
	Treasury uint64
	// Reserves is the reserves balance in lovelace.
	Reserves uint64
	// Fees is the fee pot accumulated so far in the snapshot's epoch, taken
	// from UTxOState. It is an addend of the reward pot, so it is carried
	// here to let the import seed a complete RewardAdaPots row.
	Fees uint64
	// UTxOData is the deferred CBOR for the UTxO map.
	UTxOData cbor.RawMessage
	// CertStateData is the deferred CBOR for [VState, PState, DState].
	CertStateData cbor.RawMessage
	// GovStateData is the deferred CBOR for governance state.
	GovStateData cbor.RawMessage
	// PParamsData is the deferred CBOR for protocol parameters.
	PParamsData cbor.RawMessage
	// PrevPParamsData is the deferred CBOR for the protocol parameters that
	// were in force during the preceding epoch. Cardano ledger state keeps
	// this alongside the current parameters because delayed reward
	// calculation consumes it after the epoch has ended.
	PrevPParamsData cbor.RawMessage
	// SnapShotsData is the deferred CBOR for mark/set/go stake snapshots.
	SnapShotsData cbor.RawMessage
	// PoolDistrData is the deferred CBOR for the active consensus pool
	// distribution in NewEpochState.pool-distr.
	PoolDistrData cbor.RawMessage
	// BlocksPrev and BlocksCur are NewEpochState.nesBprev and
	// NewEpochState.nesBcur: the blocks each pool minted during the epoch
	// before the snapshot's epoch, and during the snapshot's epoch up to and
	// including the anchor block. Keys are 28-byte pool cold-key hashes
	// encoded as strings; a pool absent from a map minted nothing.
	//
	// The ledger keeps both because pool performance for a reward round is
	// beta/sigma_a with beta the pool's share of the blocks minted in the
	// performance epoch, and a node that reconstructs its state from a
	// snapshot has no local history for those epochs to count. nesBprev is
	// the performance epoch of the first reward round the node crosses after
	// the import, and nesBcur is the pre-anchor half of the second one.
	BlocksPrev map[string]uint64
	BlocksCur  map[string]uint64
	// EraBounds holds the start boundaries of all eras extracted
	// from the telescope. Each entry gives the (Slot, Epoch) at
	// which that era began. Used to generate the full epoch
	// history needed for SlotToTime/TimeToSlot.
	EraBounds []EraBound
	// EraBoundSlot is the slot number at which the current era
	// started, extracted from the telescope Bound.
	EraBoundSlot uint64
	// EraBoundEpoch is the epoch number at which the current era
	// started, extracted from the telescope Bound.
	EraBoundEpoch uint64
	// EpochNonce is the epoch nonce from the consensus state,
	// used for VRF leader election. It is a 32-byte Blake2b hash,
	// or nil if the nonce is neutral.
	EpochNonce []byte
	// EvolvingNonce is the rolling nonce (eta_v) from the consensus
	// state, updated with each block's VRF output. Stored as the
	// tip block nonce so that subsequent block processing computes
	// correct rolling nonces after a mithril snapshot restore.
	EvolvingNonce []byte
	// CandidateNonce is the Praos candidate nonce as of the imported
	// tip. This is required to correctly continue nonce accumulation
	// from snapshot tip to epoch boundary.
	CandidateNonce []byte
	// LastEpochBlockNonce is the Praos last applied block hash from
	// consensus state (used in epoch nonce calculation).
	LastEpochBlockNonce []byte
	// OpCertCounters is the certified per-pool operational-certificate
	// counter state from the Praos HeaderState. Keys are 28-byte pool cold-key
	// hashes encoded as strings so they remain comparable.
	OpCertCounters map[string]uint64
	// EraBoundsWarning holds a non-fatal error from era bounds
	// extraction. When set, epoch generation falls back to
	// the single-epoch path.
	EraBoundsWarning error
	// UTxOTablePath is the path to the UTxO table file (UTxO-HD
	// format). When set, UTxOs are streamed from this file instead
	// of from UTxOData.
	UTxOTablePath string
	// UTxOTableFile, when set, is an already-open handle on the UTxO table
	// that the import reads instead of resolving UTxOTablePath.
	//
	// A caller that vetted the snapshot tree needs this: resolving the
	// pathname here would read whatever occupies that name at import time,
	// which need not be the file the caller checked. UTxOTablePath stays set
	// alongside it for messages. The caller keeps ownership and must hold the
	// file open for the duration of the import.
	UTxOTableFile *os.File
	// UTxOTableDigest, when set, is the hex SHA-256 the table's contents must
	// have, checked against the mapped bytes immediately before they are
	// decoded.
	//
	// A caller holding a signature over the table needs this rather than
	// hashing UTxOTableFile itself: the table is mapped rather than read, so a
	// digest taken from the descriptor beforehand describes a read that then
	// happens again. Handing the digest down means the bytes that are checked
	// and the bytes that are decoded are one mapping.
	//
	// Empty means nothing signed this table — v1, and any tree nothing
	// vouched for — and it is decoded unchecked, as it was before.
	UTxOTableDigest string
	// UTxOHD indicates that the snapshot used the UTxO-HD ledger
	// state wrapper. These snapshots keep the real UTxO set in an
	// external table file and the inline UTxO field is only a
	// placeholder.
	UTxOHD bool
}

RawLedgerState holds partially-decoded ledger state data from a Cardano node snapshot file. Large sections are kept as cbor.RawMessage for deferred, streaming decoding.

func ParseSnapshot

func ParseSnapshot(path string) (*RawLedgerState, error)

ParseSnapshot reads and partially decodes a Cardano node ledger state snapshot file. The UTxO map, cert state, and stake snapshots are kept as raw CBOR for streaming decode later.

Note: The entire file is read into memory because the CBOR parsing pipeline (decodeRawArray, cbor.Decode) requires a contiguous byte slice and does not support io.Reader streaming. For legacy-format mainnet snapshots the embedded UTxO map can be hundreds of MB. A future optimization could use mmap (syscall.Mmap) to avoid copying the file contents into Go heap memory, which would keep the OS page cache as the backing store rather than allocating a separate heap buffer.

func ParseSnapshotBytes added in v0.70.0

func ParseSnapshotBytes(data []byte) (*RawLedgerState, error)

ParseSnapshotBytes parses a ledger state snapshot the caller already holds.

A caller checking a signature over the snapshot needs this rather than ParseSnapshotFile: it has to hash something and parse something, and those have to be the same bytes. Hashing a descriptor and then handing the parser the same descriptor is not the same thing — the parser re-reads, and a write through the file in between is visible to the second read. Reading once and giving both the buffer leaves nothing to change.

func ParseSnapshotFile added in v0.70.0

func ParseSnapshotFile(f *os.File) (*RawLedgerState, error)

ParseSnapshotFile parses a ledger state snapshot from an already-open file, so the bytes come from the file the caller opened rather than from a name re-resolved here. The caller closes f.

type SnapshotFiles added in v0.70.0

type SnapshotFiles struct {
	// State is the open ledger state file.
	State *os.File
	// StatePath is the slash-separated path State was found at, for messages.
	StatePath string
	// Table is the open UTxO-HD table, or nil for legacy snapshots that embed
	// their UTxO set in the state file.
	Table *os.File
	// TablePath is the slash-separated path Table was found at, for messages.
	TablePath string
}

SnapshotFiles is a ledger state snapshot opened during discovery: the files themselves, not names for them.

Handing back open files is the point. A name would be resolved again by whoever reads it, and the tree this searched is only guaranteed to be the tree that gets read if no resolution happens in between.

func OpenSnapshotAtOrBefore added in v0.70.0

func OpenSnapshotAtOrBefore(
	root *os.Root,
	maxSlot uint64,
) (*SnapshotFiles, error)

OpenSnapshotAtOrBefore is FindLedgerStateFileAtOrBefore for an untrusted tree: it searches through an open handle on the extracted snapshot directory and returns the selected files already open, together with the UTxO-HD table belonging to the same state.

Every component is verified on the way down, so a symlinked ledger directory, slot directory, state file, or table is refused rather than followed. Extraction never writes a symlink, so one here is planted.

The caller closes the result.

func (*SnapshotFiles) Close added in v0.70.0

func (s *SnapshotFiles) Close()

Close releases the open files.

type SnapshotTip

type SnapshotTip struct {
	Slot      uint64
	BlockHash []byte
}

SnapshotTip represents the chain tip recorded in the ledger state snapshot.

type UTxOCallback

type UTxOCallback func(batch []ParsedUTxO) error

UTxOCallback is called for each batch of parsed UTxOs during streaming decode.

type UTxOParseProgress added in v0.24.0

type UTxOParseProgress struct {
	EntriesProcessed int
	TotalEntries     int
	BytesProcessed   int
	TotalBytes       int
	Percent          float64
}

Jump to

Keyboard shortcuts

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