Documentation
¶
Index ¶
- Constants
- Variables
- func AppendUtxoAddressOrBranch(ors *[]string, args *[]any, addr ledger.Address) error
- func AppendUtxoAddressOrBranchMode(ors *[]string, args *[]any, addr ledger.Address, mode UtxoAddressMatchMode) error
- func AppendUtxoAddressPatternOrBranch(ors *[]string, args *[]any, pattern UtxoAddressPattern) error
- func CredentialTagFromUint(tag uint) (uint8, error)
- func CredentialTagFromUint64(tag uint64) (uint8, error)
- func DecodeConwayBlock(raw []byte) (ledger.Block, error)
- func DrepTypeFromInt(drepType int) (uint64, error)
- func IsPhaseCompleted(checkpointPhase, queryPhase string) bool
- func MatchesUtxoAddressPatterns(addr ledger.Address, patterns []UtxoAddressPattern) (bool, error)
- func PaymentScriptFromAddress(addr ledger.Address) bool
- func RequiresExactAddressFilter(patterns []UtxoAddressPattern) bool
- func StakeCredentialTagFromAddress(addr ledger.Address) (uint8, bool)
- func ValidPoolStakeSnapshotType(snapshotType string) bool
- func ValidatePredefinedDrepTypes(drepTypes []uint64) error
- type Account
- type AccountDelegationHistoryRow
- type AccountImportRegistration
- type AccountInactivityActivation
- type AccountRegistrationHistoryRow
- type AccountRewardDelta
- type AccountSums
- type AccountTransactionAssociationRow
- type AccountWithdrawalHistoryRow
- type AccountWithdrawalWitness
- type AddressBalance
- type AddressTransaction
- type AddressTransactionPosition
- type Asset
- type AssetBalance
- type AssetMintBurn
- type AuthCommitteeHot
- type BackfillCheckpoint
- type Block
- type BlockNonce
- type Certificate
- type CommitteeMember
- type CommitteeQuorum
- type Constitution
- type Datum
- type Deregistration
- type DeregistrationDrep
- type Drep
- type DrepListRow
- type Epoch
- type EpochSummary
- type GenesisDelegation
- type GovernanceProposal
- type GovernanceVote
- type ImportCheckpoint
- type KeyWitness
- type MIREffect
- type MIRReward
- type MidnightAriadneParams
- type MidnightAriadneRollback
- type MidnightAssetCreate
- type MidnightAssetSpend
- type MidnightCommitteeCandidateRegistration
- type MidnightDeregistration
- type MidnightEpochCandidates
- type MidnightGovernanceDatum
- type MidnightRegistration
- type MoveInstantaneousRewards
- type MoveInstantaneousRewardsReward
- type NetworkState
- type OffchainMetadata
- type PParamUpdate
- type PParams
- type PlutusData
- type Pool
- type PoolOpCertSequence
- type PoolRegistration
- type PoolRegistrationOwner
- type PoolRegistrationRelay
- type PoolRetirement
- type PoolRetirementRefund
- type PoolRetiringRow
- type PoolStakeSnapshot
- type Redeemer
- type Registration
- type RegistrationDrep
- type ResignCommitteeCold
- type RewardAccountOutput
- type RewardAdaPots
- type RewardLiveStake
- type RewardPoolInput
- type RewardPoolOutput
- type RewardSnapshot
- type RewardStakeInput
- type Script
- type StakeCredentialRef
- type StakeDelegation
- type StakeDeregistration
- type StakeRegistration
- type StakeRegistrationDelegation
- type StakeVoteDelegation
- type StakeVoteRegistrationDelegation
- type SyncState
- type Tip
- type TokenRegistryEntry
- type Transaction
- type UpdateDrep
- type Utxo
- type UtxoAddressMatchMode
- type UtxoAddressPattern
- type UtxoId
- type UtxoOrderingCursor
- type UtxoSlot
- type UtxoWithOrdering
- type UtxoWithOrderingQuery
- type VoteDelegation
- type VoteRegistrationDelegation
- type WitnessScripts
Constants ¶
const ( DrepTypeAddrKeyHash uint64 = iota DrepTypeScriptHash DrepTypeAlwaysAbstain DrepTypeAlwaysNoConfidence )
const ( VoterTypeCC = 0 // Constitutional Committee member VoterTypeDRep = 1 // DRep VoterTypeSPO = 2 // Stake Pool Operator )
VoterType constants represent the type of voter casting a governance vote.
const ( VoteNo = 0 VoteYes = 1 VoteAbstain = 2 )
Vote constants represent the vote choice on a governance proposal.
const ( MidnightGovernanceDatumTypeTechnicalCommittee = "technical_committee" MidnightGovernanceDatumTypeCouncil = "council" )
const ( ImportPhaseUTxO = "utxo" ImportPhaseCertState = "certstate" ImportPhaseSnapshots = "snapshots" ImportPhasePParams = "pparams" ImportPhaseGovState = "gov_state" ImportPhaseTip = "tip" )
Import phases in execution order.
const ( OffchainMetadataSourcePool = "pool" OffchainMetadataSourceDrep = "drep" OffchainMetadataSourceDrepRegistration = "drep_registration" OffchainMetadataSourceDrepUpdate = "drep_update" OffchainMetadataSourceGovernanceProposal = "gov_proposal" OffchainMetadataSourceGovernanceVote = "gov_vote" OffchainMetadataSourceConstitution = "constitution" OffchainMetadataSourceCommitteeResign = "committee_resign" // OffchainFetchErrHashMismatch is the exact LastError recorded when // the fetched document does not match the on-chain anchor hash. The // API error classification matches on it, so the fetcher and API // must agree on the text. OffchainFetchErrHashMismatch = "metadata hash mismatch" // OffchainFetchErrBodyTooLargePrefix prefixes the LastError recorded // when the response body exceeds the fetch size limit. OffchainFetchErrBodyTooLargePrefix = "response body exceeds" // OffchainFetchErrDecodeErrorPrefix prefixes the LastError recorded // when hash-valid content fails schema validation for its off-chain // metadata source (for example, stake-pool metadata missing a // required field or violating a field length constraint). The API // error classification matches on it, so the fetcher and API must // agree on the text. OffchainFetchErrDecodeErrorPrefix = "metadata decode error" OffchainMetadataStatusPending = "pending" OffchainMetadataStatusFetched = "fetched" OffchainMetadataStatusFailed = "failed" )
const ( // PoolRewardAccountAutoVoteNone means the pool's reward account is // unset, deregistered, or delegated to anything other than the // predefined Always{Abstain,NoConfidence} DRep options. Such a // pool contributes to SPOTotalStake only and counts as implicit // no under CIP-1694. PoolRewardAccountAutoVoteNone uint8 = 0 // PoolRewardAccountAutoVoteAbstain means the pool's reward // account delegates to AlwaysAbstain at the snapshot epoch. Its // stake is bucketed into SPOAbstainStake (excluded from the // active denominator). PoolRewardAccountAutoVoteAbstain uint8 = 1 // PoolRewardAccountAutoVoteNoConfidence means the pool's reward // account delegates to AlwaysNoConfidence at the snapshot epoch. // For NoConfidence actions the pool stake is bucketed Yes; for // any other action type it is bucketed No (mirrors the // AlwaysNoConfidence DRep handling). PoolRewardAccountAutoVoteNoConfidence uint8 = 2 )
PoolRewardAccountAutoVote enumerates the CIP-1694 reward-account DRep-delegation outcomes that produce an implicit SPO vote when a pool did not cast an explicit vote on a proposal. Resolved and frozen at the epoch boundary that captures the stake snapshot so the governance tally uses snapshot-era state rather than live state.
const ( // PoolStakeSnapshotTypeMark is the epoch-boundary mark snapshot used by // governance and by the normal Praos epoch-offset rotation. PoolStakeSnapshotTypeMark = "mark" // PoolStakeSnapshotTypeSet is the mark snapshot rotated forward one // epoch, per the Shelley set/go/mark rotation. PoolStakeSnapshotTypeSet = "set" // PoolStakeSnapshotTypeGo is the set snapshot rotated forward one more // epoch; this is the row consulted for live leader-election stake. PoolStakeSnapshotTypeGo = "go" // PoolStakeSnapshotTypeActive is the active consensus pool distribution // imported from a Mithril NewEpochState.pool-distr field. TotalStake // stores the fraction numerator and StakeDenominator stores the // denominator for the same row. PoolStakeSnapshotTypeActive = "actv" )
const ( // KeyWitnessTypeVkey represents a Vkey witness KeyWitnessTypeVkey uint8 = 0 // KeyWitnessTypeBootstrap represents a Bootstrap witness KeyWitnessTypeBootstrap uint8 = 1 )
const AccountCreatedSlotUnset = uint64(math.MaxInt64)
AccountCreatedSlotUnset is the sentinel the account create helpers stamp on a freshly built (not-yet-persisted) account so the save helpers can resolve Account.CreatedSlot to the account's AddedSlot at insert time without overwriting the immutable CreatedSlot of an existing row (which is loaded from the database and is never equal to this sentinel). It is math.MaxInt64 rather than ^uint64(0) because database/sql cannot bind a uint64 with the high bit set, and no real slot ever reaches it.
const RewardStakeCalculationVersion uint = 1
RewardStakeCalculationVersion identifies the stake-accounting algorithm used to produce persisted live stake and consensus snapshots. Bump it when changing that calculation so upgrades cannot trust older values.
Variables ¶
var ( ErrAccountNotFound = errors.New("account not found") // ErrRewardWithdrawalExceedsBalance identifies a transaction whose // withdrawal cannot be satisfied by the node's persisted reward account. ErrRewardWithdrawalExceedsBalance = errors.New( "reward withdrawal exceeds account balance", ) )
var ( ErrDrepNotFound = errors.New("drep not found") // ErrDrepActivityNotUpdated is returned when an // UpdateDRepActivity call matches no DRep record. ErrDrepActivityNotUpdated = errors.New( "drep activity not updated: no matching record", ) )
var ( ErrNilUtxoWithOrderingQuery = errors.New( "nil UtxoWithOrderingQuery", ) ErrEmptyAssetPolicyID = errors.New("empty asset policy id") ErrEmptyUtxoAddressPattern = errors.New("empty UTxO address pattern") ErrExactAddressRequiresCbor = errors.New( "exact address matching requires output CBOR", ) ErrDescendingKeysetUnsupported = errors.New( "keyset pagination (After) does not support Descending", ) ErrOffsetKeysetUnsupported = errors.New( "keyset pagination (After) does not support Offset", ) ErrOffsetRequiresCoarseMatch = errors.New( "offset requires address patterns that do not need exact-address CBOR filtering", ) )
Sentinel errors for UtxoWithOrderingQuery validation.
var ErrBlockNotFound = errors.New("block not found")
var ErrCommitteeMemberNotFound = errors.New("committee member not found")
var ErrGovernanceProposalNotFound = errors.New("governance proposal not found")
var ErrPoolNotFound = errors.New("pool not found")
var ImportPhaseOrder = []string{ ImportPhaseUTxO, ImportPhaseCertState, ImportPhaseSnapshots, ImportPhasePParams, ImportPhaseGovState, ImportPhaseTip, }
ImportPhaseOrder defines the sequential order of import phases.
Functions ¶
func AppendUtxoAddressOrBranch ¶ added in v0.34.0
AppendUtxoAddressOrBranch appends an OR branch for the given address to the ors/args slices. It uses standard anonymous placeholders; the shared SQL dialect may rebind them. Payment-only addresses use payment-credential matching; see AppendUtxoAddressOrBranchMode for exact full-address semantics.
func AppendUtxoAddressOrBranchMode ¶ added in v0.68.0
func AppendUtxoAddressOrBranchMode( ors *[]string, args *[]any, addr ledger.Address, mode UtxoAddressMatchMode, ) error
AppendUtxoAddressOrBranchMode appends an OR branch for the given address with an explicit match mode.
func AppendUtxoAddressPatternOrBranch ¶ added in v0.68.0
func AppendUtxoAddressPatternOrBranch( ors *[]string, args *[]any, pattern UtxoAddressPattern, ) error
AppendUtxoAddressPatternOrBranch appends one coarse SQL branch. Exact addresses are narrowed by their stored credentials and later compared by complete serialized bytes after CBOR resolution.
func CredentialTagFromUint ¶ added in v0.55.0
func CredentialTagFromUint64 ¶ added in v0.55.0
func DecodeConwayBlock ¶ added in v0.62.0
DecodeConwayBlock decodes a Conway block, transparently accepting the Musashi/Leios prototype header extension. The respun Musashi network (network magic 164) tags its early chain as Conway (NtN block type 7) but its block headers carry a 12-field header body — the 10 standard Babbage fields plus leios_certified and leios_announcement — which gouroboros' strict Conway decoder rejects. Standard Conway blocks decode via gouroboros unchanged; only a strict-decode failure triggers the Leios-extended reconstruct, so real Conway networks (mainnet/preprod/preview) pay no cost and are unaffected.
func DrepTypeFromInt ¶ added in v0.37.0
func IsPhaseCompleted ¶ added in v0.22.0
IsPhaseCompleted returns true if the given phase was completed in a previous import run (i.e., the checkpoint phase is at or past the given phase).
func MatchesUtxoAddressPatterns ¶ added in v0.68.0
func MatchesUtxoAddressPatterns( addr ledger.Address, patterns []UtxoAddressPattern, ) (bool, error)
MatchesUtxoAddressPatterns applies the full address-pattern contract to a decoded output address.
func PaymentScriptFromAddress ¶ added in v0.55.0
func RequiresExactAddressFilter ¶ added in v0.68.0
func RequiresExactAddressFilter(patterns []UtxoAddressPattern) bool
RequiresExactAddressFilter reports whether candidate rows must be checked against decoded output CBOR after the coarse SQL credential predicate.
func StakeCredentialTagFromAddress ¶ added in v0.55.0
func ValidPoolStakeSnapshotType ¶ added in v0.63.0
ValidPoolStakeSnapshotType reports whether snapshotType is one of the known pool_stake_snapshot.snapshot_type values. Callers that accept a snapshotType from outside the package should validate with this before querying, so a typo or stale value fails fast instead of silently returning zero rows.
func ValidatePredefinedDrepTypes ¶ added in v0.37.0
ValidatePredefinedDrepTypes rejects credential-backed DRep delegation types. GetDRepVotingPowerByType is only for predefined, credentialless DRep options.
Types ¶
type Account ¶
type Account struct {
StakingKey []byte
CredentialTag uint8
Pool []byte
Drep []byte
ID uint
AddedSlot uint64
// CreatedSlot is the slot at which this account row was first created
// (0 for Shelley-genesis delegated accounts). Unlike AddedSlot it is
// immutable after creation — never bumped by later delegation/registration
// changes. See AccountCreatedSlotUnset for the sentinel used by the
// create/save helpers.
CreatedSlot uint64
CertificateID uint
Reward types.Uint64
// ImportDeposit is the stake-key deposit carried by a ledger-state
// snapshot. It is only used when ImportAccount records the rollback
// baseline; nil means the import source could not establish the deposit.
ImportDeposit *types.Uint64
// DrepType is the DRep delegation type code, an internal enum
// matching the Cardano ledger CBOR sum-type tag:
// 0 = key credential, 1 = script credential,
// 2 = AlwaysAbstain, 3 = AlwaysNoConfidence.
// A zero value (0) means either "key credential" or "no delegation set",
// disambiguated by whether Drep is nil.
DrepType uint64
Active bool
// ExpirationEpoch is the CIP-0163 reward-account inactivity expiry: the
// last epoch in which the account remains active unless it
// witnesses again. 0 means unset (treated as active). Mirrors
// Drep.ExpiryEpoch. Set/bumped by RenewAccountExpirations and the one-time
// activation stamp; only read when the delegator-inactivity gate is on.
ExpirationEpoch uint64
}
type AccountDelegationHistoryRow ¶ added in v0.46.0
type AccountDelegationHistoryRow struct {
AddedSlot uint64
BlockIndex uint32
CertIndex uint32
TxHash []byte
PoolKeyHash []byte
// TxSlot is the slot of the transaction containing the
// delegation certificate.
TxSlot uint64
// BlockHash is the hash of the block containing the
// delegation certificate's transaction. The block height is
// resolved from the block store, which is not part of the
// metadata SQL schema.
BlockHash []byte
}
AccountDelegationHistoryRow holds delegation history query results for a stake account.
type AccountImportRegistration ¶ added in v0.70.4
AccountImportRegistration is the virtual registration state established by a snapshot import or Shelley genesis delegation. No registration certificate exists in local history, so AddedSlot is the baseline boundary and Deposit may be nil for a legacy baseline whose import discarded the historical value.
type AccountInactivityActivation ¶ added in v0.67.0
AccountInactivityActivation records the exact reward-account credentials stamped by the one-time CIP-0163 activation. Membership cannot be inferred from CreatedSlot alone because an account may have existed but been inactive at the activation boundary.
type AccountRegistrationHistoryRow ¶ added in v0.46.0
type AccountRegistrationHistoryRow struct {
AddedSlot uint64
BlockIndex uint32
CertIndex uint32
TxHash []byte
Action string
// Deposit is the registration deposit (or refund, for
// deregistrations) in lovelace. Zero for certificate types
// that do not record an explicit deposit.
Deposit uint64
// TxSlot is the slot of the transaction containing the
// (de)registration certificate.
TxSlot uint64
// BlockHash is the hash of the block containing the
// (de)registration certificate's transaction. The block
// height is resolved from the block store, which is not part
// of the metadata SQL schema.
BlockHash []byte
}
AccountRegistrationHistoryRow holds registration history query results for a stake account.
type AccountRewardDelta ¶ added in v0.37.0
type AccountRewardDelta struct {
StakingKey []byte
CredentialTag uint8
TxHash []byte
Amount types.Uint64
PreviousReward types.Uint64
ID uint
AddedSlot uint64
Withdrawal bool
// PostSnapshot marks a credit that cardano-ledger applies AFTER the
// epoch-boundary stake snapshot (the SNAP rule): POOLREAP deposit refunds,
// enacted treasury withdrawals and governance proposal-deposit refunds.
// Two boundary credits precede SNAP and leave this false: the delayed reward
// update (applyRUpd / applyStakeRewards) and the Shelley-era MIR rule, which
// NEWEPOCH embeds between applyRUpd and EPOCH.
//
// Every boundary credit lands at the same added_slot (the boundary slot), so
// slot alone cannot separate the pre-SNAP reward update from the post-SNAP
// credits. The epoch-boundary stake reconstruction
// (stakequery.historicalDelegatorStakeCTE with a nonzero boundary slot)
// needs exactly that separation to reproduce the authoritative SNAP-point
// capture, which observes the reward update and none of the rest.
//
// Not indexed: it is only ever read alongside added_slot for a single
// boundary slot, which idx_account_reward_delta_credential/added_slot
// already narrow.
PostSnapshot bool
}
AccountRewardDelta records reward-account balance changes that are not otherwise represented by a rollback-aware certificate row. Credits store the credited Amount. Withdrawals store the withdrawal Amount, PreviousReward, and TxHash so rollback can restore the cleared reward balance.
The unique index idx_account_reward_delta_w_tx_s_slot includes AddedSlot. Withdrawal writers use TxHash and the credential as their logical replay key, regardless of slot. Credit deltas (deposit refunds, MIR, POOLREAP) use an event discriminator in TxHash when one is available and otherwise use the normalized empty value. Without AddedSlot, repeated per-epoch credits to a given account could still collapse onto a single row — colliding across epochs even on a clean first pass and breaking per-row rollback accounting in DeleteAccountRewardsAfterSlot. Including AddedSlot makes each per-epoch credit a distinct row while keeping a replayed epoch-rollover credit (same account, same event discriminator, same boundary slot) mapped to the same row so it can be skipped idempotently instead of erroring.
type AccountSums ¶ added in v0.59.0
type AccountSums struct {
// WithdrawalsSum is the total of all reward withdrawals
// made by the account.
WithdrawalsSum uint64
// ReservesSum is the total of all MIR transfers to the
// account sourced from the reserves pot.
ReservesSum uint64
// TreasurySum is the total of all MIR transfers to the
// account sourced from the treasury pot.
TreasurySum uint64
}
AccountSums holds aggregated lovelace totals for a stake account, summed from persisted withdrawal and MIR state.
type AccountTransactionAssociationRow ¶ added in v0.69.0
type AccountTransactionAssociationRow struct {
PaymentKey []byte
TxHash []byte
// TxSlot and TxIndex are the transaction's position, used for
// ordering and from/to range filtering.
TxSlot uint64
TxIndex uint32
// BlockHash is the hash of the block containing the transaction. The
// block height is resolved from the block store, which is not part
// of the metadata SQL schema.
BlockHash []byte
}
AccountTransactionAssociationRow holds one (payment address, transaction) association row for a stake credential, backing the Blockfrost account transactions endpoint. It is the direct, final page of results: ordering, the from/to range filter, and LIMIT/OFFSET are all applied in SQL, so building a response from these rows does not require any further application-level fan-out or filtering.
type AccountWithdrawalHistoryRow ¶ added in v0.69.0
type AccountWithdrawalHistoryRow struct {
TxHash []byte
Amount uint64
// TxSlot is the slot of the transaction containing the
// withdrawal.
TxSlot uint64
// BlockIndex is the withdrawal transaction's position within
// its containing block, used as an ordering tie-break for
// transactions sharing a slot.
BlockIndex uint32
// BlockHash is the hash of the block containing the
// withdrawal transaction. The block height is resolved from
// the block store, which is not part of the metadata SQL
// schema.
BlockHash []byte
}
AccountWithdrawalHistoryRow holds withdrawal history query results for a stake account.
type AccountWithdrawalWitness ¶ added in v0.67.0
type AccountWithdrawalWitness struct {
StakingKey []byte
CredentialTag uint8
TxHash []byte
ID uint
AddedSlot uint64
}
AccountWithdrawalWitness records every valid reward-withdrawal map entry, including zero-amount withdrawals. It is separate from balance deltas because CIP-0163 treats the credential witness as activity even when no reward moves.
type AddressBalance ¶ added in v0.68.0
type AddressBalance struct {
Lovelace uint64
UtxoCount int64
// Assets is ordered by (policy id, name) so callers emit
// deterministic unit ordering without re-sorting.
Assets []AssetBalance
}
AddressBalance holds SQL-aggregated live-UTxO balances for an address.
type AddressTransaction ¶ added in v0.22.0
type AddressTransaction struct {
ID uint
// PaymentKey backs bare payment-credential lookups and provides the final
// deterministic tie-break in the stake-position index.
PaymentKey []byte
StakingKey []byte
CredentialTag uint8
TransactionID uint
// Slot retains its standalone rollback index in addition to participating
// in the stake-position index.
Slot uint64
// TxIndex is queried as part of the stake-position ordering.
TxIndex uint32
}
AddressTransaction maps an address (payment and/or staking key) to a transaction that references it as an input/output participant.
type AddressTransactionPosition ¶ added in v0.69.0
AddressTransactionPosition is an inclusive (slot, tx_index) boundary used to filter address_transaction rows for the Blockfrost account transactions endpoint's from/to block-range query. Both fields are compared as one tuple: a row qualifies as a lower bound when its (slot, tx_index) is greater than or equal to this position, and as an upper bound when it is less than or equal to it.
type Asset ¶
type Asset struct {
Name []byte
NameHex []byte
PolicyId []byte
Fingerprint []byte
ID uint
UtxoID uint
Amount types.Uint64
}
func ConvertMultiAssetToModels ¶
func ConvertMultiAssetToModels( multiAsset *lcommon.MultiAsset[lcommon.MultiAssetTypeOutput], ) ([]Asset, error)
ConvertMultiAssetToModels converts a MultiAsset structure into a slice of Asset models. Each asset is populated with its name, hex-encoded name, policy ID, fingerprint, and amount. Returns an empty slice if multiAsset is nil or contains no assets.
type AssetBalance ¶ added in v0.68.0
AssetBalance is one aggregated native-asset balance.
type AssetMintBurn ¶ added in v0.63.1
type AssetMintBurn struct {
ID uint
TxHash []byte
PolicyId []byte
Name []byte
Fingerprint []byte
Slot uint64
Quantity string
TxIndex uint32
}
AssetMintBurn records a single asset mint or burn event: one row per (transaction, asset) pair for every transaction that mints or burns the asset. Quantity is a signed decimal string (positive for a mint, negative for a burn). Only populated in API storage mode.
Unlike Asset (which tracks live UTxO holdings), this table preserves the full mint/burn history so the Blockfrost API can derive an asset's initial_mint_tx_hash (earliest event) and mint_or_burn_count (row count).
func ConvertMintToAssetMintBurnModels ¶ added in v0.63.1
func ConvertMintToAssetMintBurnModels( mint *lcommon.MultiAsset[lcommon.MultiAssetTypeMint], txHash []byte, slot uint64, txIndex uint32, ) []AssetMintBurn
ConvertMintToAssetMintBurnModels converts a transaction's mint field into a slice of AssetMintBurn models, one per (policy, asset name) pair with a non-zero net quantity. Returns nil when there is nothing minted or burned.
type AuthCommitteeHot ¶
type AuthCommitteeHot struct {
ColdCredential []byte
// Column is "host_credential" for backward compatibility with
// existing databases; the Go field uses the canonical Cardano
// terminology ("hot credential" for committee voting keys).
HotCredential []byte
ID uint
CertificateID uint
AddedSlot uint64
}
type BackfillCheckpoint ¶ added in v0.22.0
type BackfillCheckpoint struct {
ID uint
Phase string // "metadata"
LastSlot uint64 // Last successfully processed slot
TotalSlots uint64 // Total slots to process (for progress)
StartedAt time.Time
UpdatedAt time.Time
Completed bool
}
BackfillCheckpoint tracks progress of automatic historical metadata backfill. After a Mithril bootstrap in API storage mode, stored blocks are replayed to populate transaction metadata. The checkpoint enables resumable progress if the process is interrupted.
type Block ¶
type BlockNonce ¶
type Certificate ¶
type Certificate struct {
BlockHash []byte
ID uint
TransactionID uint
CertificateID uint // Polymorphic FK to certificate table based on CertType. Not DB-enforced.
Slot uint64
CertIndex uint
CertType uint
}
Certificate maps transaction certificates to their specialized table records. Provides unified indexing across all certificate types without requiring joins.
All certificate types now have dedicated specialized models. The CertificateID field references the ID of the specific certificate record based on CertType.
func (Certificate) Type ¶
func (c Certificate) Type() uint
type CommitteeMember ¶ added in v0.22.0
type CommitteeMember struct {
ID uint
ColdCredHash []byte // 28-byte credential hash
ExpiresEpoch uint64
AddedSlot uint64 // Slot when imported/registered
DeletedSlot *uint64 // For rollback support
}
CommitteeMember represents a Constitutional Committee member imported from a Mithril snapshot. This is separate from the certificate-based AuthCommitteeHot/ResignCommitteeCold tables, which track committee membership changes from on-chain certificates. This table captures the committee composition at the time of the snapshot.
type CommitteeQuorum ¶ added in v0.37.0
CommitteeQuorum records the quorum threshold enacted with a committee.
type Constitution ¶ added in v0.22.0
type Constitution struct {
ID uint
AnchorURL string
AnchorHash []byte
PolicyHash []byte
AddedSlot uint64
DeletedSlot *uint64
}
Constitution represents the on-chain constitution document reference. The constitution is established via governance action and contains a URL and hash pointing to the full document, plus an optional guardrails script.
type Deregistration ¶
type DeregistrationDrep ¶
type DrepListRow ¶ added in v0.68.0
type DrepListRow struct {
AnchorURL string
Credential []byte
AnchorHash []byte
ID uint
AddedSlot uint64
CredentialTag uint8
LastActivityEpoch uint64
ExpiryEpoch uint64
Active bool
FirstSeenSlot uint64
// LastRegistrationSlot is the added_slot of the most recent
// registration certificate, 0 when no cert history exists.
LastRegistrationSlot uint64
}
DrepListRow is a Drep row extended with the credential's first on-chain appearance slot, as returned by GetDreps for registration-order listings.
type Epoch ¶
type Epoch struct {
Nonce []byte
EvolvingNonce []byte
// CandidateNonce holds the frozen candidate nonce from the end
// of the previous epoch (psCandidateNonce in Haskell). In
// Ouroboros Praos, the candidate nonce tracks the evolving
// nonce until the randomness stabilisation window cutoff
// (4k/f slots before the end of the epoch), then freezes.
// When 4k/f >= epochLength (e.g., devnets with short epochs),
// the candidate nonce is never updated and stays at its
// initial value (genesis hash). This field carries the
// candidate nonce across epochs so it can seed the next
// epoch's computation correctly.
CandidateNonce []byte
// LastEpochBlockNonce holds the Praos lab carried at this epoch's
// boundary: the parent hash (PrevHash) of the previous epoch's last
// block, or the previously carried lab when that epoch had no blocks.
// In Ouroboros Praos, the epoch nonce formula mixes CandidateNonce with
// this value. This field is nil for epoch 0 (equivalent to NeutralNonce /
// identity).
LastEpochBlockNonce []byte
ID uint
// EpochId is a ledger identifier where zero is valid, so the SQL schema
// uses the separate surrogate ID as its primary key.
EpochId uint64
StartSlot uint64
EraId uint
SlotLength uint
LengthInSlots uint
}
type EpochSummary ¶ added in v0.21.0
type EpochSummary struct {
ID uint
Epoch uint64
TotalActiveStake types.Uint64
TotalPoolCount uint64
TotalDelegators uint64
EpochNonce []byte
BoundarySlot uint64
SnapshotReady bool
}
EpochSummary captures network-wide aggregate statistics at epoch boundary.
type GenesisDelegation ¶ added in v0.63.0
type GenesisDelegation struct {
ID uint
GenesisHash []byte
GenesisDelegateHash []byte
VrfKeyHash []byte
AddedSlot uint64
BlockIndex uint32
CertIndex uint
CertificateID uint
}
GenesisDelegation records Shelley genesis-key delegation certificates. Header verification uses the latest row for a genesis key before a block slot to validate overlay-slot genesis delegate headers against active ledger state.
type GovernanceProposal ¶ added in v0.22.0
type GovernanceProposal struct {
ID uint
TxHash []byte
ActionIndex uint32
ActionType uint8 // GovActionType enum
ProposedEpoch uint64
ExpiresEpoch uint64
ParentTxHash []byte
ParentActionIdx *uint32
EnactedEpoch *uint64
EnactedSlot *uint64 // Slot when enacted (for rollback safety)
RatifiedEpoch *uint64
RatifiedSlot *uint64 // Slot when ratified (for rollback safety)
PolicyHash []byte
AnchorURL string
AnchorHash []byte
Deposit uint64
ReturnAddress []byte // Reward account for deposit return (1 byte header + 28 bytes hash)
// GovActionCbor holds the CBOR-encoded GovAction needed at enactment
// time to extract type-specific fields (ParamUpdate, ProtocolVersion,
// Withdrawals, Committee changes, Constitution). Populated on proposal
// submission so enactment does not need to re-fetch the transaction.
GovActionCbor []byte
ExpiredEpoch *uint64
ExpiredSlot *uint64 // Slot when expired (for rollback safety)
AddedSlot uint64
DeletedSlot *uint64
}
GovernanceProposal represents a governance action submitted to the chain. Proposals have a lifecycle: submitted -> (ratified) -> (enacted) or expired.
type GovernanceVote ¶ added in v0.22.0
type GovernanceVote struct {
ID uint
ProposalID uint
VoterType uint8 // 0=CC, 1=DRep, 2=SPO
VoterCredentialTag uint8
VoterCredential []byte
Vote uint8 // 0=No, 1=Yes, 2=Abstain
AnchorURL string
AnchorHash []byte
AddedSlot uint64
// Slot when vote was last changed (for rollback safety).
VoteUpdatedSlot *uint64
DeletedSlot *uint64
}
GovernanceVote represents a vote cast by a Constitutional Committee member, DRep, or Stake Pool Operator on a governance proposal.
type ImportCheckpoint ¶ added in v0.22.0
type ImportCheckpoint struct {
ID uint
ImportKey string // "{digest}:{slot}"
Phase string // last completed phase
}
ImportCheckpoint tracks the progress of a Mithril snapshot import so that it can be resumed after a failure without re-importing already completed phases.
type KeyWitness ¶
type KeyWitness struct {
Vkey []byte
Signature []byte
PublicKey []byte
ChainCode []byte
Attributes []byte
ID uint
TransactionID uint
Type uint8
}
KeyWitness represents a key witness entry (Vkey or Bootstrap) Type: KeyWitnessTypeVkey = VkeyWitness, KeyWitnessTypeBootstrap = BootstrapWitness
type MIREffect ¶ added in v0.55.0
type MIREffect struct {
// ID is the move_instantaneous_rewards row ID. It is used as the stable
// per-MIR reward-credit discriminator when applying epoch-boundary effects.
ID uint
// Pot is the source Ada pot: 0 = Reserves, 1 = Treasury.
Pot uint
// OtherPot is the amount for a pot-to-pot transfer (0 when distributing).
OtherPot uint64
// Rewards lists credential→amount pairs for a distribution MIR.
Rewards []MIRReward
}
MIREffect is the processed form of a single MIR certificate used by the epoch-boundary application logic. One of OtherPot > 0 (pot-to-pot transfer) or len(Rewards) > 0 (credential distribution) will be non-empty.
type MIRReward ¶ added in v0.55.0
MIRReward is a single credential→amount entry from a distribution MIR cert.
type MidnightAriadneParams ¶ added in v0.55.0
MidnightAriadneParams stores Ariadne parameters per epoch when changed.
type MidnightAriadneRollback ¶ added in v0.61.0
type MidnightAriadneRollback struct {
ID uint
BlockNumber uint64
Epoch uint64
PreviousExists bool
PreviousDatum []byte
}
MidnightAriadneRollback stores the previous Ariadne row for a block upsert, so a later rollback can restore state even after process restart.
type MidnightAssetCreate ¶ added in v0.55.0
type MidnightAssetCreate struct {
ID uint
Address []byte
Quantity uint64
TxHash []byte
OutputIndex uint32
BlockNumber uint64
BlockHash []byte
TxIndex uint32
BlockTimestampMs uint64
}
MidnightAssetCreate stores cNIGHT UTxO creations for the Midnight indexer.
func (MidnightAssetCreate) BlockTxPosition ¶ added in v0.63.0
func (r MidnightAssetCreate) BlockTxPosition() (blockNumber uint64, txIndex uint32)
BlockTxPosition implements pagination.BlockTxPositioned.
type MidnightAssetSpend ¶ added in v0.55.0
type MidnightAssetSpend struct {
ID uint
Address []byte
Quantity uint64
SpendingTxHash []byte
UtxoTxHash []byte
UtxoIndex uint32
BlockNumber uint64
BlockHash []byte
TxIndex uint32
BlockTimestampMs uint64
}
MidnightAssetSpend stores cNIGHT UTxO spends for the Midnight indexer.
func (MidnightAssetSpend) BlockTxPosition ¶ added in v0.63.0
func (r MidnightAssetSpend) BlockTxPosition() (blockNumber uint64, txIndex uint32)
BlockTxPosition implements pagination.BlockTxPositioned.
type MidnightCommitteeCandidateRegistration ¶ added in v0.63.0
type MidnightCommitteeCandidateRegistration struct {
ID uint
TxHash []byte
OutputIndex uint32
BlockNumber uint64
SlotNumber uint64
TxIndex uint32
TxInputsCbor []byte
}
MidnightCommitteeCandidateRegistration stores full on-chain provenance for a committee-candidate UTxO the first time it is observed as a transaction output: which block/slot/transaction created it and which UTxOs its creating transaction consumed. MidnightEpochCandidates.CandidatesCbor records only (tx_hash, output_index, datum) membership at each epoch boundary — this table is the durable side-store GetEpochCandidates joins against to fill in tx_inputs/slot_number/tx_index/block_number, since the in-memory candidate set is rebuilt on restart from the generic UTXO index (GetMidnightCandidates), which carries only tx_hash/output_index/datum.
type MidnightDeregistration ¶ added in v0.55.0
type MidnightDeregistration struct {
ID uint
FullDatum []byte
TxHash []byte
UtxoTxHash []byte
UtxoIndex uint32
BlockNumber uint64
BlockHash []byte
TxIndex uint32
BlockTimestampMs uint64
}
MidnightDeregistration stores mapping validator deregistration events.
func (MidnightDeregistration) BlockTxPosition ¶ added in v0.63.0
func (r MidnightDeregistration) BlockTxPosition() (blockNumber uint64, txIndex uint32)
BlockTxPosition implements pagination.BlockTxPositioned.
type MidnightEpochCandidates ¶ added in v0.55.0
type MidnightEpochCandidates struct {
ID uint
Epoch uint64
BlockNumber uint64
CandidatesCbor []byte
}
MidnightEpochCandidates stores candidate snapshots at epoch boundaries.
type MidnightGovernanceDatum ¶ added in v0.55.0
type MidnightGovernanceDatum struct {
ID uint
DatumType string
TxHash []byte
OutputIndex uint32
Datum []byte
BlockNumber uint64
}
MidnightGovernanceDatum stores latest Technical Committee and Council datums.
type MidnightRegistration ¶ added in v0.55.0
type MidnightRegistration struct {
ID uint
FullDatum []byte
TxHash []byte
OutputIndex uint32
BlockNumber uint64
BlockHash []byte
TxIndex uint32
BlockTimestampMs uint64
}
MidnightRegistration stores mapping validator registration events.
func (MidnightRegistration) BlockTxPosition ¶ added in v0.63.0
func (r MidnightRegistration) BlockTxPosition() (blockNumber uint64, txIndex uint32)
BlockTxPosition implements pagination.BlockTxPositioned.
type MoveInstantaneousRewards ¶
type MoveInstantaneousRewards struct {
Rewards []MoveInstantaneousRewardsReward
Pot uint
CertificateID uint
ID uint
AddedSlot uint64
// OtherPot holds the lovelace amount for a pot-to-pot transfer (non-zero
// only when the cert moves coins between treasury and reserves rather than
// distributing to staking credentials).
OtherPot types.Uint64
}
type NetworkState ¶ added in v0.22.0
NetworkState stores treasury and reserves balances at a given slot.
type OffchainMetadata ¶ added in v0.54.0
type OffchainMetadata struct {
FetchedAt *time.Time
NextFetchAfter *time.Time
CreatedAt time.Time
UpdatedAt time.Time
URL string
SourceType string
Status string
ContentType string
LastError string
Hash []byte
BodyHash []byte
Content []byte
ID uint
FetchAttempts uint
LastHTTPStatus uint
}
OffchainMetadata stores a fetched copy of content referenced by on-chain metadata and governance anchors. The on-chain URL/hash pair remains authoritative; this table is a best-effort API cache.
type PParamUpdate ¶
type PlutusData ¶
type PlutusData struct {
Transaction *Transaction
Data []byte
ID uint
TransactionID uint
}
PlutusData represents a Plutus data value in the witness set
type Pool ¶
type Pool struct {
Margin *types.Rat
PoolKeyHash []byte
VrfKeyHash []byte
RewardAccount []byte
LatestOpCertSequence uint64
// RewardAccountCredentialTag is the stake credential type of the pool's
// reward account: 0 = key hash, 1 = script hash. The on-chain pool cert
// encodes the reward_account as a 29-byte reward address (header + 28-byte
// hash). The gouroboros library stores only the first 28 bytes in
// RewardAccount (AddrKeyHash), discarding the header. We decode the raw
// cert CBOR to preserve the credential type here.
RewardAccountCredentialTag uint8
// LeiosKeyPublic and LeiosKeyPossessionProof are the pool's registered
// Dijkstra/Leios BLS voting key (96-byte compressed G2 public key) and
// its proof of possession (48-byte compressed G1 signature), as decoded
// from the on-chain leios_key pool-cert field. Both are nil only when
// the pool has no leios_key. This is raw registration data -- the proof
// is not checked here or anywhere in this package; a key with an
// invalid proof is still stored as-is, and only excluded when read back
// out for committee construction in ledger/leios, matching upstream's
// "invalid proofs are treated as absent" rule.
LeiosKeyPublic []byte
LeiosKeyPossessionProof []byte
// Owners and Relays are query-only associations (no CASCADE).
// The actual parent-child relationship is PoolRegistration -> Owners/Relays.
// When Pool is deleted, PoolRegistrations cascade, which then cascade to Owners/Relays.
Owners []PoolRegistrationOwner
Relays []PoolRegistrationRelay
Registration []PoolRegistration
Retirement []PoolRetirement
ID uint
Pledge types.Uint64
Cost types.Uint64
}
Error 1170 (42000): BLOB/TEXT column 'staking_key' used in key specification without a key length
type PoolOpCertSequence ¶ added in v0.46.0
PoolOpCertSequence records the operational-certificate issue number a pool minted each of its blocks under. It takes a row per block for the life of the chain and is pruned only by rollback, so reads over the whole table have to be served from an index rather than from its rows.
idx_pool_opcert_sequence_pool_sequence exists for one of those: the highest-sequence-per-pool fold behind GetChainDepState's counters, which has no slot bound to narrow it because every row it holds is at or below the tip. Carrying the sequence beside the pool key hash lets that fold run without reading a single row, and in the index's own order, so the GROUP BY needs no sort.
It does not make the fold sublinear everywhere. MySQL 8 can skip through the index a pool at a time; SQLite has no loose index scan and reads it end to end, so there the win is dropping the row fetches rather than dropping the scan. Worth the write cost for a one-shot query behind `leadership-schedule`; it would not be for something on a hot path.
Migration v1 declares it; the schema lives in SQL rather than in tags on this struct.
type PoolRegistration ¶
type PoolRegistration struct {
Margin *types.Rat
Pool *Pool // Belongs-to relationship; CASCADE is defined on Pool.Registration
MetadataUrl string
VrfKeyHash []byte
PoolKeyHash []byte
RewardAccount []byte
RewardAccountCredentialTag uint8
MetadataHash []byte
LeiosKeyPublic []byte
LeiosKeyPossessionProof []byte
Owners []PoolRegistrationOwner
Relays []PoolRegistrationRelay
Pledge types.Uint64
Cost types.Uint64
CertificateID uint
ID uint
PoolID uint
AddedSlot uint64
DepositAmount types.Uint64
}
type PoolRegistrationOwner ¶
type PoolRegistrationRelay ¶
type PoolRetirement ¶
type PoolRetirementRefund ¶ added in v0.55.0
type PoolRetirementRefund struct {
PoolKeyHash []byte
RewardAccount []byte
RewardAccountCredentialTag uint8
DepositAmount types.Uint64
}
PoolRetirementRefund identifies a pool retiring at an epoch boundary along with the reward account and deposit needed to refund its POOLREAP deposit. It is a query result, not a persisted table.
type PoolRetiringRow ¶ added in v0.69.0
PoolRetiringRow is one pending-retirement entry returned by GetRetiringPools: the latest retirement certificate for a pool that has not been cancelled by a later registration and whose epoch is still in the future.
type PoolStakeSnapshot ¶ added in v0.21.0
type PoolStakeSnapshot struct {
ID uint
Epoch uint64
SnapshotType string // "mark", "set", "go", "actv"
PoolKeyHash []byte
TotalStake types.Uint64
StakeDenominator types.Uint64
DelegatorCount uint64
CapturedSlot uint64
// LeiosKeyPublic and LeiosKeyPossessionProof freeze the pool's optional
// Dijkstra/Leios voting key at the same boundary as its stake. Both are
// nil for a keyless seat and for legacy snapshots captured before the key
// was stored here. Consumers must verify the proof of possession before
// using the key.
LeiosKeyPublic []byte
LeiosKeyPossessionProof []byte
// CalculationVersion identifies the stake-accounting algorithm used to
// produce Mark/Set/Go rows. Zero denotes a pre-provenance snapshot.
CalculationVersion uint
// RewardAccountAutoVote captures the CIP-1694 SPO auto-vote
// outcome implied by the pool's reward-account DRep delegation at
// the snapshot epoch. Values come from PoolRewardAccountAutoVote*.
// This field is only meaningful when RewardAccountAutoVoteResolved
// is true; otherwise its value is undefined and must not be read
// by the tally.
RewardAccountAutoVote uint8
// RewardAccountAutoVoteResolved disambiguates "resolved as none"
// from "never resolved". The resolver sets this to true after it
// has computed RewardAccountAutoVote against snapshot-era state.
// Rows imported by Mithril for set/go rotations (which only have
// live state available at import time and cannot be faithfully
// resolved against historical boundaries) intentionally leave this
// false; the tally treats them as PoolRewardAccountAutoVoteNone,
// matching pre-CIP-1694 behaviour for those rows. Pre-CIP-1694
// rows in upgraded databases also remain false until re-resolved.
RewardAccountAutoVoteResolved bool
}
PoolStakeSnapshot captures pool stake for an epoch snapshot. Mark rows store lovelace totals at an epoch boundary. Active rows imported from Mithril store a consensus stake fraction as TotalStake/StakeDenominator.
type Redeemer ¶
type Redeemer struct {
Data []byte
ID uint
TransactionID uint
ExUnitsMemory uint64
ExUnitsCPU uint64
Index uint32
Tag uint8
}
Redeemer represents a redeemer in the witness set
type Registration ¶
type RegistrationDrep ¶
type ResignCommitteeCold ¶
type ResignCommitteeCold struct {
AnchorURL string
ColdCredential []byte
AnchorHash []byte
ID uint
CertificateID uint
AddedSlot uint64
}
ResignCommitteeCold represents a resignation certificate for a Constitutional Committee cold credential.
type RewardAccountOutput ¶ added in v0.66.0
type RewardAccountOutput struct {
StakingKey []byte
PoolKeyHash []byte
RewardType string
ID uint
Epoch uint64
CredentialTag uint8
Amount types.Uint64
Spendable bool
// Guarded records that CIP-0163 account expiry prevented this otherwise
// spendable reward from being credited.
Guarded bool
CapturedSlot uint64
BoundarySlot uint64
}
RewardAccountOutput captures per-account reward calculation output.
type RewardAdaPots ¶ added in v0.49.0
type RewardAdaPots struct {
ID uint
Epoch uint64
Treasury types.Uint64
Reserves types.Uint64
Fees types.Uint64
Rewards types.Uint64
CapturedSlot uint64
}
RewardAdaPots captures the reward-related ADA pots at an epoch boundary.
type RewardLiveStake ¶ added in v0.65.0
type RewardLiveStake struct {
PoolKeyHash []byte
StakingKey []byte
ID uint
CredentialTag uint8
UtxoStake types.Uint64
RewardStake types.Uint64
TotalStake types.Uint64
Registered bool
// PoolDelegation* records the certificate order used to derive PoolKeyHash.
// It is rollback/rebuild bookkeeping; snapshot consumers select eligible
// pools independently at the requested slot.
PoolDelegationSlot uint64
PoolDelegationBlockIndex uint64
PoolDelegationCertIndex uint32
UpdatedSlot uint64
// CalculationVersion is set by every rebuild and incremental update. Zero
// denotes rows created before calculation provenance was introduced.
CalculationVersion uint
}
RewardLiveStake is the live per-stake-credential aggregate maintained for a reward and leader-election snapshot consumers. UtxoStake and RewardStake are stored separately so rollback/account-reward repair can refresh only the affected credential while TotalStake remains directly queryable.
type RewardPoolInput ¶ added in v0.49.0
type RewardPoolInput struct {
Margin *types.Rat
PoolKeyHash []byte
RewardAccount []byte
BlocksProduced *uint64
TotalBlocksInEpoch *uint64
ID uint
Epoch uint64
Pledge types.Uint64
DelegatedStake types.Uint64
OwnerStake types.Uint64
Cost types.Uint64
DelegatorCount uint64
RewardAccountCredentialTag uint8
CapturedSlot uint64
BoundarySlot uint64
}
RewardPoolInput captures per-pool inputs needed by reward calculation.
type RewardPoolOutput ¶ added in v0.66.0
type RewardPoolOutput struct {
ApparentPerformance *types.Rat
PoolKeyHash []byte
ID uint
Epoch uint64
OptimalReward types.Uint64
TotalReward types.Uint64
LeaderReward types.Uint64
MemberRewardTotal types.Uint64
OwnerStake types.Uint64
Undistributed types.Uint64
Unspendable types.Uint64
CapturedSlot uint64
BoundarySlot uint64
}
RewardPoolOutput captures per-pool reward calculation output for an epoch.
type RewardSnapshot ¶ added in v0.49.0
type RewardSnapshot struct {
ID uint
Epoch uint64
SnapshotType string
TotalActiveStake types.Uint64
TotalPoolCount uint64
TotalDelegators uint64
CapturedSlot uint64
BoundarySlot uint64
EpochNonce []byte
ProtocolVersion uint
// Authoritative marks a snapshot captured inside the ledger epoch-rollover
// write transaction at the SNAP point (CaptureEpochBoundarySnapshot). The
// event-driven fallback capture (captureMarkSnapshot) never overwrites an
// authoritative row: it either claims a fresh row or is superseded. Defaults
// to false, so pre-existing rows and fallback captures read as provisional.
Authoritative bool
// CalculationVersion ties authoritative Mark metadata to the stake
// calculation that produced its accompanying pool snapshots.
CalculationVersion uint
}
RewardSnapshot captures reward-calculation snapshot metadata for an epoch.
type RewardStakeInput ¶ added in v0.66.0
type RewardStakeInput struct {
PoolKeyHash []byte
StakingKey []byte
ID uint
Epoch uint64
CredentialTag uint8
Stake types.Uint64
Owner bool
Registered bool
CapturedSlot uint64
BoundarySlot uint64
}
RewardStakeInput captures per-credential stake at the reward snapshot.
type Script ¶
Script represents the content of a script, indexed by its hash This avoids storing duplicate script data when the same script appears in multiple transactions
type StakeCredentialRef ¶ added in v0.55.0
func NewStakeCredentialRef ¶ added in v0.55.0
func NewStakeCredentialRef(tag uint8, key []byte) StakeCredentialRef
func (StakeCredentialRef) MapKey ¶ added in v0.55.0
func (r StakeCredentialRef) MapKey() string
type StakeDelegation ¶
type StakeDeregistration ¶
type StakeRegistration ¶
type StakeVoteDelegation ¶
type SyncState ¶ added in v0.22.0
SyncState stores ephemeral key-value pairs used during one-time sync/load operations. Cleaned up after completion.
type TokenRegistryEntry ¶ added in v0.70.1
type TokenRegistryEntry struct {
// Decimals is nil when the registry declares no decimals for the
// subject. Zero is a meaningful declared value distinct from absent, so
// this cannot collapse to a bare int.
Decimals *int
CreatedAt time.Time
UpdatedAt time.Time
Subject string
Name string
Ticker string
Description string
URL string
// Logo is the base64 payload as published by the registry. Logos are
// roughly 90% of registry bytes, so the syncer drops them unless the
// operator opts in; an empty Logo means "not stored", never "the
// registry published an empty logo".
Logo string
ID uint
}
TokenRegistryEntry holds the CIP-26 off-chain token registry properties for a single asset, keyed by the registry subject (hex policy ID followed by the hex-encoded asset name). It backs the `metadata` field of the Blockfrost GET /assets/{asset} response, which is distinct from `onchain_metadata` (CIP-25/CIP-68 mint metadata read from the chain itself).
Rows are a best-effort cache of a periodically synced upstream registry, not consensus data: the node serves whatever the last successful sync produced and an absent subject simply yields a null `metadata` field. Only populated in API storage mode, and only when the token registry sync is enabled.
func (*TokenRegistryEntry) IsEmpty ¶ added in v0.70.1
func (e *TokenRegistryEntry) IsEmpty() bool
IsEmpty reports whether the entry carries no property worth persisting. A subject with no properties tells a consumer nothing the asset ID did not already, so the syncer skips it rather than writing an all-null row.
type Transaction ¶
type Transaction struct {
// CollateralReturn uses a separate FK (CollateralReturnForTxID) to
// distinguish it from regular Outputs, which use TransactionID.
CollateralReturn *Utxo
PlutusData []PlutusData
Certificates []Certificate
Outputs []Utxo
Hash []byte
Collateral []Utxo
BlockHash []byte
KeyWitnesses []KeyWitness
WitnessScripts []WitnessScripts
Inputs []Utxo
Redeemers []Redeemer
ReferenceInputs []Utxo
Metadata []byte
Slot uint64
Type int
ID uint
Fee types.Uint64
// CollateralFee is the lovelace consumed into the fee pot by a
// phase-2-invalid transaction (collateral inputs minus collateral
// return, per the Alonzo/Babbage UTXOS rule). Zero for valid
// transactions; Fee keeps the declared body fee in both cases.
CollateralFee types.Uint64
TTL types.Uint64
BlockIndex uint32
Valid bool
}
Transaction represents a transaction record
type UpdateDrep ¶
type Utxo ¶
type Utxo struct {
TransactionID *uint
CollateralReturnForTxID *uint // Unique: a transaction has at most one collateral return output
TxId []byte
PaymentKey []byte
StakingKey []byte
CredentialTag uint8
Assets []Asset
Cbor []byte // This is here for convenience but not represented in the metadata DB
DatumHash []byte // Optional datum hash (32 bytes)
Datum []byte // Inline datum CBOR, not stored in metadata DB
ScriptRef []byte // Reference script bytes, not stored in metadata DB
// SpentAtTxId, ReferencedByTxId, and CollateralByTxId are nullable FKs to
// transaction(hash); they are unset until a UTxO is spent/referenced.
// They use types.NullableHash so an empty value serializes to SQL NULL
// (not an empty blob), which is required for the FK to be skipped — see
// the type docs for the FOREIGN KEY constraint failed (787) issue.
SpentAtTxId types.NullableHash
ReferencedByTxId types.NullableHash
CollateralByTxId types.NullableHash
ID uint
AddedSlot uint64
DeletedSlot uint64
Amount types.Uint64
OutputIdx uint32
// PaymentScript is true when the output's payment credential is a
// script hash (as opposed to a key hash). It is derived from the
// address type at index time and used to compute the network's
// script-locked supply (see GetScriptLockedSupply). The composite
// index (deleted_slot, payment_script, amount) lets the supply sum
// scan only live script UTxOs.
PaymentScript bool
}
Utxo represents an unspent transaction output
type UtxoAddressMatchMode ¶ added in v0.68.0
type UtxoAddressMatchMode int
UtxoAddressMatchMode selects how an address matches utxo rows.
const ( // UtxoAddressMatchExact requests full-address identity. Metadata-only // aggregate queries reject this mode because exact identity requires // output CBOR; use UtxoAddressPattern through the coordinated Database. UtxoAddressMatchExact UtxoAddressMatchMode = iota // UtxoAddressMatchPaymentCred aggregates across every address // form sharing the payment credential, mirroring Blockfrost's // bare-credential (addr_vkh/script) lookups. UtxoAddressMatchPaymentCred )
type UtxoAddressPattern ¶ added in v0.68.0
UtxoAddressPattern carries explicit address-match intent through the shared query API. Fields within one pattern are ANDed; multiple patterns are ORed. ExactAddress is the complete serialized address, while PaymentPart and DelegationPart deliberately match credentials across address forms.
func ExactUtxoAddressPattern ¶ added in v0.68.0
func ExactUtxoAddressPattern(addr ledger.Address) (UtxoAddressPattern, error)
ExactUtxoAddressPattern builds an exact pattern from a decoded address.
type UtxoId ¶ added in v0.19.0
UtxoId uniquely identifies a UTxO by transaction hash and output index.
type UtxoOrderingCursor ¶ added in v0.32.0
UtxoOrderingCursor is the keyset position for SearchUtxos.
Text form (non-empty): slot:block_index:output_idx:tx_id. GetUtxosByAddressWithOrdering uses the producing transaction position for ordering. Snapshot-imported UTxOs without a producing transaction use AddedSlot and block index zero. TxId makes the cursor unique when those fallback fields collide.
type UtxoWithOrdering ¶ added in v0.27.5
UtxoWithOrdering includes UTxO with transaction ordering metadata
type UtxoWithOrderingQuery ¶ added in v0.32.0
type UtxoWithOrderingQuery struct {
MatchAllAddresses bool
AddressPatterns []UtxoAddressPattern
After *UtxoOrderingCursor
Limit int
Offset int
Descending bool
SkipAssets bool
FilterByAsset bool
AssetPolicyID []byte
AssetName []byte
}
UtxoWithOrderingQuery drives GetUtxosByAddressWithOrdering (single MetadataStore entry).
Address matching (exactly one of these applies):
- MatchAllAddresses true: do not filter by payment/stake keys (all live UTxOs, subject to asset filter if set). SearchUtxos sets this when the predicate is nil or is asset-only (no address pattern).
- MatchAllAddresses false and len(AddressPatterns) == 0: match no rows (caller uses this when a predicate was given but no Cardano address parts could be decoded).
- MatchAllAddresses false and len(AddressPatterns) > 0: match UTxOs that satisfy any pattern. Fields within a pattern are ANDed; patterns are ORed.
After + Limit: keyset pagination; Limit <= 0 means no SQL LIMIT. SearchUtxos sets Limit to effective page size + 1. Mutually exclusive with Offset and Descending (both page-number pagination controls); GetUtxosByAddressWithOrdering errors if After is combined with either one.
Offset: page-number pagination; > 0 means SQL OFFSET. Only valid when the address patterns do not require CBOR-based exact-address filtering (see RequiresExactAddressFilter): the coarse SQL predicate over-matches address forms sharing a payment/delegation credential (for example pointer addresses), so skipping rows in SQL would skip a different set of rows than skipping exact matches. Combine with Limit for a bounded page; GetUtxosByAddressWithOrdering errors if Offset is set on a query that requires exact-address filtering.
Descending: reverses SQL ORDER BY direction (newest first) instead of the default ascending (oldest first) producing-transaction-position order.
SkipAssets: when true, GetUtxosByAddressWithOrdering does not load each row's native assets. Set this for a candidate scan whose rows are discarded or only used to confirm an exact-address match (see RequiresExactAddressFilter) and never returned to a caller that reads Utxo.Assets, to avoid materializing asset data that is thrown away.
FilterByAsset: when true, AssetPolicyID is required; AssetName nil matches any name under the policy (same semantics as GetUtxosByAssets).
type VoteDelegation ¶
type WitnessScripts ¶
WitnessScripts represents a reference to a script in the witness set Type corresponds to ScriptRefType constants from gouroboros/ledger/common: 0=NativeScript (ScriptRefTypeNativeScript) 1=PlutusV1 (ScriptRefTypePlutusV1) 2=PlutusV2 (ScriptRefTypePlutusV2) 3=PlutusV3 (ScriptRefTypePlutusV3)
To avoid storing duplicate script data for the same script used in multiple transactions, we store only the script hash here. The actual script content is stored separately in Script table, indexed by hash.
Source Files
¶
- account.go
- account_history.go
- address_transaction.go
- asset.go
- auth_committee_hot.go
- backfill_checkpoint.go
- block.go
- block_nonce.go
- certs.go
- committee_member.go
- datum.go
- drep.go
- epoch.go
- genesis_delegation.go
- governance.go
- leios_block.go
- midnight.go
- mir.go
- models.go
- network_state.go
- offchain_metadata.go
- pool.go
- pparams.go
- redeemer.go
- reward_state.go
- script.go
- stake_snapshot.go
- tip.go
- token_registry.go
- transaction.go
- utxo.go
- utxoid.go
- witness.go
- witness_script.go