Documentation
¶
Index ¶
- Constants
- Variables
- func AggregatorURLForNetwork(network string) (string, error)
- func AncillaryVerificationKeyURLForNetwork(network string) (string, error)
- func DownloadSnapshot(ctx context.Context, cfg DownloadConfig) (string, error)
- func ExtractArchive(ctx context.Context, archivePath string, destDir string, logger *slog.Logger) (string, error)
- func GenesisVerificationKeyURLForNetwork(network string) (string, error)
- func HumanBytes(b int64) string
- func NeedsSync(cfg SyncConfig) (bool, error)
- func ValidateVerificationMaterial(material *VerificationMaterial) error
- func VerifyCertificateChain(ctx context.Context, client *Client, certificateHash string, ...) error
- func VerifyGenesisCertificateSignature(cert *Certificate, verificationKeyText string) error
- type Beacon
- type BootstrapConfig
- type BootstrapResult
- type CardanoDatabaseAncillary
- type CardanoDatabaseDigestEntry
- type CardanoDatabaseDigests
- type CardanoDatabaseImmutables
- type CardanoDatabaseLocation
- type CardanoDatabaseSnapshot
- type CardanoDatabaseSnapshotListItem
- type CardanoStakeDistribution
- type CardanoStakeDistributionListItem
- type CardanoStakeDistributionParty
- type CardanoTransactionsBeacon
- type Certificate
- type CertificateChainVerificationResult
- type CertificateMetadata
- type Client
- func (c *Client) GetCardanoDatabaseDigests(ctx context.Context) ([]CardanoDatabaseDigestEntry, error)
- func (c *Client) GetCardanoDatabaseSnapshot(ctx context.Context, hash string) (*CardanoDatabaseSnapshot, error)
- func (c *Client) GetCardanoStakeDistribution(ctx context.Context, identifier string) (*CardanoStakeDistribution, error)
- func (c *Client) GetCertificate(ctx context.Context, hash string) (*Certificate, error)
- func (c *Client) GetLatestCardanoDatabaseSnapshot(ctx context.Context) (*CardanoDatabaseSnapshot, error)
- func (c *Client) GetLatestSnapshot(ctx context.Context) (*SnapshotListItem, error)
- func (c *Client) GetMithrilStakeDistribution(ctx context.Context, hash string) (*MithrilStakeDistribution, error)
- func (c *Client) GetSnapshot(ctx context.Context, digest string) (*SnapshotListItem, error)
- func (c *Client) ListCardanoDatabaseSnapshots(ctx context.Context) ([]CardanoDatabaseSnapshotListItem, error)
- func (c *Client) ListCardanoStakeDistributions(ctx context.Context) ([]CardanoStakeDistributionListItem, error)
- func (c *Client) ListMithrilStakeDistributions(ctx context.Context) ([]MithrilStakeDistributionListItem, error)
- func (c *Client) ListSnapshots(ctx context.Context) ([]SnapshotListItem, error)
- type ClientOption
- type DownloadConfig
- type DownloadProgress
- type MithrilStakeDistribution
- type MithrilStakeDistributionListItem
- type MithrilStakeDistributionParty
- type NetworkConfig
- type ProgressFunc
- type ProtocolMessage
- type ProtocolParameters
- type ResolvedStakeDistribution
- type SignedEntityType
- func (s *SignedEntityType) CardanoDatabase() *Beacon
- func (s *SignedEntityType) CardanoImmutableFilesFull() *Beacon
- func (s *SignedEntityType) CardanoStakeDistribution() *Beacon
- func (s *SignedEntityType) CardanoTransactions() *CardanoTransactionsBeacon
- func (s *SignedEntityType) Kind() (string, error)
- func (s SignedEntityType) MarshalJSON() ([]byte, error)
- func (s *SignedEntityType) MithrilStakeDistribution() *Beacon
- func (s *SignedEntityType) Raw() json.RawMessage
- func (s *SignedEntityType) UnmarshalJSON(data []byte) error
- type SnapshotBase
- type SnapshotListItem
- type StakeDistributionParty
- type SyncConfig
- type SyncPhase
- type SyncProgress
- type SyncProgressFunc
- type SyncResult
- type VerificationKey
- type VerificationMaterial
- type VerificationMode
Constants ¶
const ( // BackendV1 restores from the legacy full-database snapshot // archives (CardanoImmutableFilesFull, /artifact/snapshots). // Upstream Mithril is phasing this artifact type out. BackendV1 = "v1" // BackendV2 restores from incremental Cardano database artifacts // (CardanoDatabase, /artifact/cardano-database): per-immutable // archives verified against the certified merkle root. BackendV2 = "v2" )
Mithril artifact backends.
Variables ¶
var ErrNoSnapshotsAvailable = errors.New(
"no snapshots available from aggregator",
)
ErrNoSnapshotsAvailable indicates that the aggregator responded successfully but currently has no snapshots to serve.
Functions ¶
func AggregatorURLForNetwork ¶
AggregatorURLForNetwork returns the default aggregator URL for the given network name, or an error if the network is not recognized.
func AncillaryVerificationKeyURLForNetwork ¶ added in v0.26.0
AncillaryVerificationKeyURLForNetwork returns the default Mithril ancillary verification key URL for the given network.
func DownloadSnapshot ¶
func DownloadSnapshot( ctx context.Context, cfg DownloadConfig, ) (string, error)
DownloadSnapshot downloads a snapshot archive from the given URL to the specified destination directory. It returns the path to the downloaded file.
func ExtractArchive ¶
func ExtractArchive( ctx context.Context, archivePath string, destDir string, logger *slog.Logger, ) (string, error)
ExtractArchive extracts a zstd-compressed tar archive to the specified destination directory. It returns the path to the directory where files were extracted. The context is checked between files so that long-running extractions can be cancelled.
func GenesisVerificationKeyURLForNetwork ¶ added in v0.26.0
GenesisVerificationKeyURLForNetwork returns the default Mithril genesis verification key URL for the given network.
func HumanBytes ¶ added in v0.26.0
HumanBytes formats a byte count in a human-readable form.
func NeedsSync ¶ added in v0.53.0
func NeedsSync(cfg SyncConfig) (bool, error)
NeedsSync reports whether the database at cfg.DataDir requires a (re)sync — i.e. it is empty or its sync_status indicates an incomplete sync.
func ValidateVerificationMaterial ¶ added in v0.26.0
func ValidateVerificationMaterial(material *VerificationMaterial) error
ValidateVerificationMaterial checks that the certificate's active signer metadata is consistent with the certified Mithril stake distribution used for the same epoch.
func VerifyCertificateChain ¶
func VerifyCertificateChain( ctx context.Context, client *Client, certificateHash string, snapshotDigest string, ) error
VerifyCertificateChain walks the Mithril certificate chain from the given hash back to the genesis certificate. This verifies the chain is unbroken and, if snapshotDigest is non-empty, that the leaf certificate's protocol message binds to it. It does not verify STM cryptographic signatures (Phase 2).
func VerifyGenesisCertificateSignature ¶ added in v0.26.0
func VerifyGenesisCertificateSignature( cert *Certificate, verificationKeyText string, ) error
VerifyGenesisCertificateSignature verifies a genesis certificate signature with the configured Mithril genesis verification key.
Types ¶
type Beacon ¶
type Beacon struct {
Epoch uint64 `json:"epoch"`
ImmutableFileNumber uint64 `json:"immutable_file_number"`
}
Beacon represents a Cardano chain position at a specific epoch and immutable file number.
type BootstrapConfig ¶
type BootstrapConfig struct {
// Network is the Cardano network name (e.g., "mainnet",
// "preprod", "preview").
Network string
// Backend selects the Mithril artifact backend: BackendV1
// downloads the legacy full-database tarball, BackendV2 restores
// per-immutable archives verified against the certified merkle
// root. Empty selects BackendV2.
Backend string
// AggregatorURL overrides the default aggregator URL for the
// network. If empty, the default URL for the network is used.
AggregatorURL string
// DownloadDir is the directory where the snapshot archive will
// be downloaded. If empty, a temporary directory is created.
DownloadDir string
// CleanupAfterLoad controls whether temporary files are removed
// after loading completes.
CleanupAfterLoad bool
// VerifyCertificateChain enables certificate chain verification
// against the aggregator. When true, the bootstrap process
// walks the certificate chain from the snapshot back to the
// genesis certificate to verify the chain is unbroken.
VerifyCertificateChain bool
// GenesisVerificationKey is the Mithril genesis verification key loaded
// from Cardano network config. It is validated for parseability now and
// will be used by full STM verification.
GenesisVerificationKey string
// AncillaryVerificationKey is the Mithril ancillary verification key loaded
// from Cardano network config. It is validated for parseability now and
// will be used when ancillary artifacts are verified cryptographically.
AncillaryVerificationKey string
// Logger is used for structured logging.
Logger *slog.Logger
// OnProgress is called during download with progress updates.
OnProgress ProgressFunc
// DownloadIdleTimeout is the maximum time to wait for download
// response headers or body bytes before retrying. Zero uses the
// downloader default; negative disables idle detection.
DownloadIdleTimeout time.Duration
// DownloadMaxIdleRetries is the number of consecutive idle retries
// allowed without additional bytes. Zero uses the downloader default.
DownloadMaxIdleRetries int
// DownloadMaxTransientRetries is the maximum number of retry attempts
// for transient network errors (TLS handshake failures, connection
// resets, HTTP 429, HTTP 5xx) per download. Zero uses the downloader
// default. Negative disables transient retries.
DownloadMaxTransientRetries int
// StartImmutable is the lowest immutable file number to download and
// extract. Files below it are assumed already present (a Mithril v2
// catch-up sets this to the immutable-import marker so it only fetches the
// archives missing from the existing blob store). Zero downloads the full
// 0..N range, the normal bootstrap behaviour.
StartImmutable uint64
// OnChunkContiguous, when set, enables download<->processing
// pipelining: chunks are fetched in parallel (out of order) but this
// callback is invoked for each immutable file number in strict
// contiguous order (0,1,2,...) as soon as that prefix is fully
// downloaded. immutableDir is the directory the chunks are extracted
// into. It lets the caller copy blocks into the blob store while later
// chunks are still downloading. When nil, downloads run to completion
// before any processing (legacy behaviour). The callback runs on a
// single consumer goroutine and serializes processing, so it needs no
// internal locking.
OnChunkContiguous func(immutableDir string, num uint64) error
// contains filtered or unexported fields
}
BootstrapConfig holds configuration for the Mithril bootstrap process.
type BootstrapResult ¶
type BootstrapResult struct {
// Snapshot is the snapshot that was downloaded and extracted.
Snapshot *SnapshotListItem
// ImmutableDir is the path to the extracted ImmutableDB
// directory.
ImmutableDir string
// ExtractDir is the root directory where the archive was
// extracted. Contains db/immutable/, db/ledger/, etc.
ExtractDir string
// AncillaryDir is the root directory where the ancillary
// archive was extracted. Contains ledger/<slot>/{meta,state,
// tables/tvar}. Empty if no ancillary data was downloaded.
AncillaryDir string
// AncillaryArchivePath is the path to the downloaded ancillary
// archive file. Empty if no ancillary data was downloaded.
AncillaryArchivePath string
// ArchivePath is the path to the downloaded archive file.
ArchivePath string
// TempDir is the auto-created temporary directory that holds
// all downloaded and extracted files. Set only when
// BootstrapConfig.DownloadDir was empty. Cleanup() removes it
// after removing its children.
TempDir string
}
BootstrapResult contains the result of a bootstrap operation.
func Bootstrap ¶
func Bootstrap( ctx context.Context, cfg BootstrapConfig, ) (*BootstrapResult, error)
Bootstrap orchestrates the full Mithril bootstrap flow:
- Fetch the latest snapshot from the aggregator
- Download the snapshot archive
- Extract the archive to obtain the ImmutableDB files
- Return the path for loading with existing immutable DB logic
The caller is responsible for invoking the immutable DB load using the returned ImmutableDir path. If CleanupAfterLoad is true, the caller should call Cleanup() on the result after loading.
func (*BootstrapResult) Cleanup ¶
func (r *BootstrapResult) Cleanup(logger *slog.Logger)
Cleanup removes the temporary files created during bootstrap. It removes the archive, extract directory, and ancillary directory individually rather than the entire parent directory, to avoid deleting user-specified download directories.
type CardanoDatabaseAncillary ¶ added in v0.54.0
type CardanoDatabaseAncillary struct {
SizeUncompressed int64 `json:"size_uncompressed"`
Locations []CardanoDatabaseLocation `json:"locations"`
}
CardanoDatabaseAncillary describes the ancillary component (ledger state plus the next in-progress immutable trio) of a v2 artifact.
type CardanoDatabaseDigestEntry ¶ added in v0.54.0
type CardanoDatabaseDigestEntry struct {
ImmutableFileName string `json:"immutable_file_name"`
Digest string `json:"digest"`
}
CardanoDatabaseDigestEntry is one immutable-file digest from the v2 digest list.
type CardanoDatabaseDigests ¶ added in v0.54.0
type CardanoDatabaseDigests struct {
SizeUncompressed int64 `json:"size_uncompressed"`
Locations []CardanoDatabaseLocation `json:"locations"`
}
CardanoDatabaseDigests describes the digest-list component of a v2 artifact.
type CardanoDatabaseImmutables ¶ added in v0.54.0
type CardanoDatabaseImmutables struct {
AverageSizeUncompressed int64 `json:"average_size_uncompressed"`
Locations []CardanoDatabaseLocation `json:"locations"`
}
CardanoDatabaseImmutables describes the immutable-archives component of a v2 artifact.
type CardanoDatabaseLocation ¶ added in v0.54.0
type CardanoDatabaseLocation struct {
Type string
URI string
URITemplate string
CompressionAlgorithm string
}
CardanoDatabaseLocation is one download location for a component of a Cardano database (v2) artifact. The JSON representation is internally tagged by "type"; the uri field is either a plain string or, for immutable archives, a {"Template": "..."} object whose template contains the {immutable_file_number} placeholder. Unknown location types and uri shapes are tolerated so new aggregator location kinds do not break parsing; such locations are simply skipped during download.
func (*CardanoDatabaseLocation) ImmutableArchiveURI ¶ added in v0.54.0
func (l *CardanoDatabaseLocation) ImmutableArchiveURI(num uint64) string
ImmutableArchiveURI resolves the location's URI template for the given immutable file number (zero-padded to 5 digits). Returns an empty string if the location has no URI template.
func (CardanoDatabaseLocation) MarshalJSON ¶ added in v0.54.0
func (l CardanoDatabaseLocation) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for CardanoDatabaseLocation, producing the aggregator wire format (uri as a plain string, or as a {"Template": ...} object for templated locations).
func (*CardanoDatabaseLocation) UnmarshalJSON ¶ added in v0.54.0
func (l *CardanoDatabaseLocation) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for CardanoDatabaseLocation.
type CardanoDatabaseSnapshot ¶ added in v0.54.0
type CardanoDatabaseSnapshot struct {
Hash string `json:"hash"`
MerkleRoot string `json:"merkle_root"`
Network string `json:"network"`
Beacon Beacon `json:"beacon"`
CertificateHash string `json:"certificate_hash"`
TotalDbSizeUncompressed int64 `json:"total_db_size_uncompressed"`
Digests CardanoDatabaseDigests `json:"digests"`
Immutables CardanoDatabaseImmutables `json:"immutables"`
Ancillary CardanoDatabaseAncillary `json:"ancillary"`
CardanoNodeVersion string `json:"cardano_node_version"`
CreatedAt string `json:"created_at"`
}
CardanoDatabaseSnapshot represents the detail response for a v2 artifact (GET /artifact/cardano-database/{hash}).
func (*CardanoDatabaseSnapshot) ComputeHash ¶ added in v0.54.0
func (s *CardanoDatabaseSnapshot) ComputeHash() string
ComputeHash matches the upstream Mithril Cardano database artifact hash: hex(sha256(beacon.epoch as 8-byte big-endian || merkle_root ASCII bytes)).
type CardanoDatabaseSnapshotListItem ¶ added in v0.54.0
type CardanoDatabaseSnapshotListItem struct {
Hash string `json:"hash"`
MerkleRoot string `json:"merkle_root"`
Beacon Beacon `json:"beacon"`
CertificateHash string `json:"certificate_hash"`
TotalDbSizeUncompressed int64 `json:"total_db_size_uncompressed"`
CardanoNodeVersion string `json:"cardano_node_version"`
CreatedAt string `json:"created_at"`
}
CardanoDatabaseSnapshotListItem represents one entry returned by the aggregator's v2 artifact list endpoint (GET /artifact/cardano-database).
type CardanoStakeDistribution ¶ added in v0.26.0
type CardanoStakeDistribution struct {
Hash string `json:"hash"`
CertificateHash string `json:"certificate_hash"`
Epoch uint64 `json:"epoch"`
Pools []CardanoStakeDistributionParty `json:"pools"`
}
CardanoStakeDistribution represents a downloaded Cardano stake distribution artifact.
type CardanoStakeDistributionListItem ¶ added in v0.26.0
type CardanoStakeDistributionListItem struct {
Hash string `json:"hash"`
CertificateHash string `json:"certificate_hash"`
CreatedAt string `json:"created_at"`
Locations []string `json:"locations"`
CompressionAlgorithm string `json:"compression_algorithm"`
Epoch uint64 `json:"epoch"`
}
CardanoStakeDistributionListItem represents a Cardano stake distribution artifact entry returned by the aggregator.
type CardanoStakeDistributionParty ¶ added in v0.26.0
type CardanoStakeDistributionParty struct {
PoolID string `json:"pool_id"`
Stake uint64 `json:"stake"`
}
CardanoStakeDistributionParty represents a stake pool and stake value in a certified Cardano stake distribution artifact.
type CardanoTransactionsBeacon ¶ added in v0.26.0
type CardanoTransactionsBeacon struct {
Epoch uint64 `json:"epoch"`
BlockNumber uint64 `json:"block_number"`
}
CardanoTransactionsBeacon represents a Cardano chain position at a specific epoch and block number, used by the CardanoTransactions signed entity type.
type Certificate ¶
type Certificate struct {
Hash string `json:"hash"`
PreviousHash string `json:"previous_hash"`
Epoch uint64 `json:"epoch"`
SignedEntityType SignedEntityType `json:"signed_entity_type"`
Metadata CertificateMetadata `json:"metadata"`
ProtocolMessage ProtocolMessage `json:"protocol_message"`
SignedMessage string `json:"signed_message"`
AggregateVerificationKey string `json:"aggregate_verification_key"`
MultiSignature string `json:"multi_signature"`
GenesisSignature string `json:"genesis_signature"`
}
Certificate represents a Mithril certificate as returned by the aggregator's certificate endpoint (GET /certificate/{hash}).
func (*Certificate) AggregateVerificationKeyBytes ¶ added in v0.26.0
func (c *Certificate) AggregateVerificationKeyBytes() ([]byte, error)
AggregateVerificationKeyBytes decodes the aggregate verification key from its encoded string representation.
func (*Certificate) ComputeHash ¶ added in v0.26.0
func (c *Certificate) ComputeHash() (string, error)
ComputeHash matches the upstream Mithril certificate hash.
func (*Certificate) IsChainingToItself ¶
func (c *Certificate) IsChainingToItself() bool
IsChainingToItself returns true if this certificate's hash equals its previous hash (i.e., it is the root of the chain). Returns false if either hash is empty to avoid treating malformed certificates as root.
func (*Certificate) IsGenesis ¶
func (c *Certificate) IsGenesis() bool
IsGenesis returns true if the certificate was signed with a genesis signature rather than a multi-signature.
func (*Certificate) MultiSignatureBytes ¶ added in v0.26.0
func (c *Certificate) MultiSignatureBytes() ([]byte, error)
MultiSignatureBytes decodes the multi-signature from its encoded string representation.
type CertificateChainVerificationResult ¶ added in v0.26.0
type CertificateChainVerificationResult struct {
Certificates []*Certificate
LeafCertificate *Certificate
GenesisCertificate *Certificate
SignedEntityKind string
SnapshotDigest string
}
CertificateChainVerificationResult captures the parsed certificate chain and derived leaf/root metadata that higher verification modes can build on.
func VerifyCertificateChainWithMode ¶ added in v0.26.0
func VerifyCertificateChainWithMode( ctx context.Context, client *Client, certificateHash string, snapshotDigest string, mode VerificationMode, ) (*CertificateChainVerificationResult, error)
VerifyCertificateChainWithMode verifies the Mithril certificate chain using the requested verification mode.
type CertificateMetadata ¶
type CertificateMetadata struct {
Network string `json:"network"`
Version string `json:"version"`
Parameters ProtocolParameters `json:"parameters"`
InitiatedAt string `json:"initiated_at"`
SealedAt string `json:"sealed_at"`
Signers []StakeDistributionParty `json:"signers"`
}
CertificateMetadata holds the metadata section of a certificate.
func (CertificateMetadata) ComputeHash ¶ added in v0.26.0
func (m CertificateMetadata) ComputeHash() (string, error)
ComputeHash matches the upstream Mithril certificate-metadata hash.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client for the Mithril aggregator REST API.
func NewClient ¶
func NewClient( aggregatorURL string, opts ...ClientOption, ) *Client
NewClient creates a new Mithril aggregator API client. The aggregatorURL should be the base URL of the aggregator (e.g., "https://aggregator.release-preprod.api.mithril.network/aggregator").
func (*Client) GetCardanoDatabaseDigests ¶ added in v0.54.0
func (c *Client) GetCardanoDatabaseDigests( ctx context.Context, ) ([]CardanoDatabaseDigestEntry, error)
GetCardanoDatabaseDigests retrieves the immutable-file digest list for the latest v2 snapshot directly from the aggregator. Corresponds to GET /artifact/cardano-database/digests.
func (*Client) GetCardanoDatabaseSnapshot ¶ added in v0.54.0
func (c *Client) GetCardanoDatabaseSnapshot( ctx context.Context, hash string, ) (*CardanoDatabaseSnapshot, error)
GetCardanoDatabaseSnapshot retrieves the details of a specific v2 Cardano database snapshot by its hash. Corresponds to GET /artifact/cardano-database/{hash}.
func (*Client) GetCardanoStakeDistribution ¶ added in v0.26.0
func (c *Client) GetCardanoStakeDistribution( ctx context.Context, identifier string, ) (*CardanoStakeDistribution, error)
GetCardanoStakeDistribution retrieves a Cardano stake distribution by hash or unique identifier.
func (*Client) GetCertificate ¶
GetCertificate retrieves a certificate by its hash. Corresponds to GET /certificate/{hash}.
func (*Client) GetLatestCardanoDatabaseSnapshot ¶ added in v0.54.0
func (c *Client) GetLatestCardanoDatabaseSnapshot( ctx context.Context, ) (*CardanoDatabaseSnapshot, error)
GetLatestCardanoDatabaseSnapshot returns the most recent v2 Cardano database snapshot from the aggregator, sorted by epoch (descending) with immutable file number as tie-breaker.
func (*Client) GetLatestSnapshot ¶
func (c *Client) GetLatestSnapshot( ctx context.Context, ) (*SnapshotListItem, error)
GetLatestSnapshot returns the most recent snapshot from the aggregator, sorted by epoch (descending) with immutable file number as tie-breaker.
func (*Client) GetMithrilStakeDistribution ¶ added in v0.26.0
func (c *Client) GetMithrilStakeDistribution( ctx context.Context, hash string, ) (*MithrilStakeDistribution, error)
GetMithrilStakeDistribution retrieves a Mithril stake distribution by hash.
func (*Client) GetSnapshot ¶
GetSnapshot retrieves the details of a specific snapshot by its digest. Corresponds to GET /artifact/snapshot/{digest}.
func (*Client) ListCardanoDatabaseSnapshots ¶ added in v0.54.0
func (c *Client) ListCardanoDatabaseSnapshots( ctx context.Context, ) ([]CardanoDatabaseSnapshotListItem, error)
ListCardanoDatabaseSnapshots retrieves the list of available v2 Cardano database snapshots from the aggregator. Corresponds to GET /artifact/cardano-database.
func (*Client) ListCardanoStakeDistributions ¶ added in v0.26.0
func (c *Client) ListCardanoStakeDistributions( ctx context.Context, ) ([]CardanoStakeDistributionListItem, error)
ListCardanoStakeDistributions retrieves available Cardano stake distributions from the aggregator.
func (*Client) ListMithrilStakeDistributions ¶ added in v0.26.0
func (c *Client) ListMithrilStakeDistributions( ctx context.Context, ) ([]MithrilStakeDistributionListItem, error)
ListMithrilStakeDistributions retrieves available Mithril stake distributions from the aggregator.
func (*Client) ListSnapshots ¶
func (c *Client) ListSnapshots( ctx context.Context, ) ([]SnapshotListItem, error)
ListSnapshots retrieves the list of available snapshots from the aggregator. Corresponds to GET /artifact/snapshots.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption is a functional option for configuring a Client.
func WithHTTPClient ¶
func WithHTTPClient(hc *http.Client) ClientOption
WithHTTPClient sets a custom *http.Client for the Mithril client. Note: the default client enforces HTTPS-only redirects via httpsOnlyRedirect. A custom client bypasses this protection, so callers should configure their own redirect policy if needed.
type DownloadConfig ¶
type DownloadConfig struct {
// URL is the download URL for the snapshot archive.
URL string
// DestDir is the directory where the archive will be saved.
DestDir string
// Filename is the name of the downloaded file. If empty, a
// default name is generated from the snapshot digest.
Filename string
// ExpectedSize is the expected file size in bytes. When > 0,
// the downloaded file size is verified after download. A
// mismatch returns an error.
ExpectedSize int64
// Logger is used for logging download progress.
Logger *slog.Logger
// OnProgress is called periodically with download progress.
OnProgress ProgressFunc
// IdleTimeout is the maximum time to wait for response headers
// or body bytes before retrying. If zero, a conservative default
// is used. If negative, idle detection is disabled.
IdleTimeout time.Duration
// MaxIdleRetries is the number of consecutive retry attempts
// after idle timeouts that make no additional download progress.
// If zero, a conservative default is used.
MaxIdleRetries int
// MaxTransientRetries is the maximum number of retry attempts for
// transient network errors (TLS handshake failures, connection
// resets, unexpected EOF, HTTP 429, HTTP 5xx). If zero, a
// conservative default is used. If negative, transient retries
// are disabled.
MaxTransientRetries int
// HTTPClient, when non-nil, is reused for the download instead of
// constructing a fresh client per call. Callers that fetch many
// files (the v2 immutable pool) pass one shared keep-alive client so
// connections are pooled across files. When nil, a per-call client
// with keep-alives disabled is used (single-archive downloads).
HTTPClient *http.Client
}
DownloadConfig holds configuration for downloading a snapshot archive.
func (DownloadConfig) Validate ¶ added in v0.47.0
func (cfg DownloadConfig) Validate() error
Validate checks DownloadConfig values before use.
type DownloadProgress ¶
type DownloadProgress struct {
BytesDownloaded int64
TotalBytes int64
Percent float64
BytesPerSecond float64
}
DownloadProgress reports download progress to a callback.
type MithrilStakeDistribution ¶ added in v0.26.0
type MithrilStakeDistribution struct {
Hash string `json:"hash"`
CertificateHash string `json:"certificate_hash"`
Epoch uint64 `json:"epoch"`
Signers []MithrilStakeDistributionParty `json:"signers"`
}
MithrilStakeDistribution represents a downloaded Mithril stake distribution artifact.
type MithrilStakeDistributionListItem ¶ added in v0.26.0
type MithrilStakeDistributionListItem struct {
Hash string `json:"hash"`
CertificateHash string `json:"certificate_hash"`
CreatedAt string `json:"created_at"`
Locations []string `json:"locations"`
CompressionAlgorithm string `json:"compression_algorithm"`
Epoch uint64 `json:"epoch"`
}
MithrilStakeDistributionListItem represents a Mithril stake distribution artifact entry returned by the aggregator.
type MithrilStakeDistributionParty ¶ added in v0.26.0
type MithrilStakeDistributionParty struct {
PartyID string `json:"party_id"`
Stake uint64 `json:"stake"`
VerificationKey string `json:"verification_key"`
}
MithrilStakeDistributionParty represents a Mithril signer and its associated stake and verification key in the certified stake distribution.
func (*MithrilStakeDistributionParty) VerificationKeyBytes ¶ added in v0.26.0
func (p *MithrilStakeDistributionParty) VerificationKeyBytes() ([]byte, error)
VerificationKeyBytes decodes the signer's verification key from its encoded string representation.
type NetworkConfig ¶ added in v0.26.0
type NetworkConfig struct {
AggregatorURL string
GenesisVerificationKeyURL string
AncillaryVerificationKeyURL string
}
NetworkConfig describes the Mithril trust endpoints for a specific Cardano network.
func NetworkConfigForNetwork ¶ added in v0.26.0
func NetworkConfigForNetwork(network string) (NetworkConfig, error)
NetworkConfigForNetwork returns the default Mithril network configuration for the given network name, or an error if the network is not recognized.
type ProgressFunc ¶
type ProgressFunc func(DownloadProgress)
ProgressFunc is a callback invoked periodically during download to report progress.
type ProtocolMessage ¶
ProtocolMessage represents the protocol message included in a certificate.
func (ProtocolMessage) ComputeHash ¶ added in v0.26.0
func (p ProtocolMessage) ComputeHash() string
ComputeHash matches the upstream Mithril protocol-message hash.
type ProtocolParameters ¶
type ProtocolParameters struct {
K uint64 `json:"k"`
M uint64 `json:"m"`
PhiF float64 `json:"phi_f"`
}
ProtocolParameters represents the Mithril protocol parameters used during signing.
func (ProtocolParameters) ComputeHash ¶ added in v0.26.0
func (p ProtocolParameters) ComputeHash() string
ComputeHash matches the upstream Mithril protocol-parameters hash.
type ResolvedStakeDistribution ¶ added in v0.26.0
type ResolvedStakeDistribution struct {
Kind string
MithrilStakeDistribution *MithrilStakeDistribution
CardanoStakeDistribution *CardanoStakeDistribution
}
ResolvedStakeDistribution bundles the stake-distribution artifact selected for a certificate verification flow.
func ResolveStakeDistributionForCertificate ¶ added in v0.26.0
func ResolveStakeDistributionForCertificate( ctx context.Context, client *Client, verification *CertificateChainVerificationResult, ) (*ResolvedStakeDistribution, error)
ResolveStakeDistributionForCertificate locates the stake-distribution artifact referenced by a verified certificate chain result.
type SignedEntityType ¶
type SignedEntityType struct {
// contains filtered or unexported fields
}
SignedEntityType represents the type and parameters of the signed entity in a certificate. The JSON representation uses a tagged union where the key is the entity type name.
func (*SignedEntityType) CardanoDatabase ¶ added in v0.54.0
func (s *SignedEntityType) CardanoDatabase() *Beacon
CardanoDatabase attempts to parse the signed entity as a CardanoDatabase beacon. Returns nil if the entity type does not match.
func (*SignedEntityType) CardanoImmutableFilesFull ¶
func (s *SignedEntityType) CardanoImmutableFilesFull() *Beacon
CardanoImmutableFilesFull attempts to parse the signed entity as a CardanoImmutableFilesFull beacon. Returns nil if the entity type does not match.
func (*SignedEntityType) CardanoStakeDistribution ¶ added in v0.26.0
func (s *SignedEntityType) CardanoStakeDistribution() *Beacon
CardanoStakeDistribution attempts to parse the signed entity as a CardanoStakeDistribution beacon. Returns nil if the entity type does not match.
func (*SignedEntityType) CardanoTransactions ¶ added in v0.26.0
func (s *SignedEntityType) CardanoTransactions() *CardanoTransactionsBeacon
CardanoTransactions attempts to parse the signed entity as a CardanoTransactions beacon containing epoch and block_number. Returns nil if the entity type does not match.
func (*SignedEntityType) Kind ¶ added in v0.26.0
func (s *SignedEntityType) Kind() (string, error)
Kind returns the tagged union key for the signed entity type.
func (SignedEntityType) MarshalJSON ¶
func (s SignedEntityType) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for SignedEntityType.
func (*SignedEntityType) MithrilStakeDistribution ¶ added in v0.26.0
func (s *SignedEntityType) MithrilStakeDistribution() *Beacon
MithrilStakeDistribution attempts to parse the signed entity as a MithrilStakeDistribution beacon. Returns nil if the entity type does not match.
func (*SignedEntityType) Raw ¶
func (s *SignedEntityType) Raw() json.RawMessage
Raw returns the raw JSON of the signed entity type.
func (*SignedEntityType) UnmarshalJSON ¶
func (s *SignedEntityType) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for SignedEntityType.
type SnapshotBase ¶
type SnapshotBase struct {
Digest string `json:"digest"`
Network string `json:"network"`
Beacon Beacon `json:"beacon"`
CertificateHash string `json:"certificate_hash"`
Size int64 `json:"size"`
AncillarySize int64 `json:"ancillary_size"`
CreatedAt string `json:"created_at"`
Locations []string `json:"locations"`
AncillaryLocations []string `json:"ancillary_locations"`
CompressionAlgorithm string `json:"compression_algorithm"`
CardanoNodeVersion string `json:"cardano_node_version"`
}
SnapshotBase contains the fields shared by both the list and detail snapshot responses from the Mithril aggregator.
func (*SnapshotBase) CreatedAtTime ¶
func (s *SnapshotBase) CreatedAtTime() (time.Time, error)
CreatedAtTime parses the CreatedAt string into a time.Time value.
type SnapshotListItem ¶
type SnapshotListItem struct {
SnapshotBase
}
SnapshotListItem represents a snapshot entry returned by the aggregator's list endpoint (GET /artifact/snapshots).
type StakeDistributionParty ¶
StakeDistributionParty represents a signer in the certificate metadata with their party ID and stake.
func (StakeDistributionParty) ComputeHash ¶ added in v0.26.0
func (p StakeDistributionParty) ComputeHash() string
ComputeHash matches the upstream Mithril signer hash used in certificate metadata hashing.
type SyncConfig ¶ added in v0.53.0
type SyncConfig struct {
Network string // "mainnet" | "preprod" | "preview"
DataDir string // node database path
StorageMode string // "api" | "core"
CardanoNodeConfig *cardano.CardanoNodeConfig // genesis + Mithril verification keys; if nil, loaded from EmbeddedConfigFS for Network
CardanoConfigPath string // optional explicit config.json path (else "<network>/config.json")
Backend string // Mithril artifact backend; same semantics as BootstrapConfig.Backend (empty selects v2)
AggregatorURL string // optional; defaults per-network
DownloadDir string // optional; defaults to <DataDir>/.mithril-cache
DownloadIdleTimeout string // optional; passed to BootstrapConfig
DownloadMaxIdleRetries int // must be >= 0
VerifyCertChain bool
CleanupAfterLoad bool
BlobPlugin string // database plugin selection (match the node's)
MetadataPlugin string
RunMode string
BackfillBatchSize int
DatabaseWorkers int
Logger *slog.Logger // optional; defaults to slog.Default()
OnProgress SyncProgressFunc // optional
}
SyncConfig is the input to a full Mithril bootstrap of a node database.
type SyncPhase ¶ added in v0.53.0
type SyncPhase string
SyncPhase identifies a stage of a Mithril bootstrap.
const ( PhaseBootstrap SyncPhase = "bootstrap" PhaseLedgerImport SyncPhase = "ledger_import" PhaseImmutableCopy SyncPhase = "immutable_copy" PhaseGapBlocks SyncPhase = "gap_blocks" PhasePostLedger SyncPhase = "post_ledger_state" PhaseBackfill SyncPhase = "backfill" PhaseIndexRebuild SyncPhase = "index_rebuild" PhaseComplete SyncPhase = "complete" )
type SyncProgress ¶ added in v0.53.0
type SyncProgress struct {
Phase SyncPhase
Active bool // true while the phase is active (begin + every mid-phase tick); false only marks the phase end
BytesDownloaded int64 // download phase
TotalBytes int64 // download phase
BytesPerSecond float64 // download/copy/backfill rate
CurrentSlot uint64
TipSlot uint64
Percent float64
Count int // generic counter (gap blocks, blocks copied)
Total int // Total complements Count for non-byte progress (e.g. ledger-import items).
Description string // free-form (era/stage label)
}
SyncProgress is a flat, dependency-free progress report emitted during Sync. It deliberately exposes no internal/node or ledgerstate types so external embedders can consume it without importing dingo internals.
type SyncProgressFunc ¶ added in v0.53.0
type SyncProgressFunc func(SyncProgress)
SyncProgressFunc receives progress updates. It must be fast and non-blocking.
type SyncResult ¶ added in v0.53.0
type SyncResult struct {
Snapshot *SnapshotListItem
LedgerSlot uint64
}
SyncResult summarises a completed bootstrap.
func Sync ¶ added in v0.53.0
func Sync(ctx context.Context, cfg SyncConfig) (SyncResult, error)
Sync performs a full Mithril bootstrap of the database at cfg.DataDir: download + verify + extract a snapshot, import ledger state and immutable blocks, close the volatile gap, backfill metadata, and mark the sync complete. The resulting database is servable by dingo.Node.Run.
type VerificationKey ¶ added in v0.26.0
VerificationKey is a parsed Mithril/Cardano verification key file.
func ParseVerificationKey ¶ added in v0.26.0
func ParseVerificationKey(data string) (*VerificationKey, error)
ParseVerificationKey parses a verification key from either Cardano text envelope JSON or a raw hex-encoded key string.
func (*VerificationKey) RawKeyBytesHex ¶ added in v0.26.0
func (v *VerificationKey) RawKeyBytesHex() string
RawKeyBytesHex returns the raw key bytes as a hex-encoded string.
type VerificationMaterial ¶ added in v0.26.0
type VerificationMaterial struct {
CertificateChain *CertificateChainVerificationResult
MithrilCertificate *Certificate
CardanoCertificate *Certificate
MithrilStakeDistribution *MithrilStakeDistribution
CardanoStakeDistribution *CardanoStakeDistribution
}
VerificationMaterial bundles the non-cryptographic inputs needed for full Mithril STM certificate verification.
func BuildVerificationMaterial ¶ added in v0.26.0
func BuildVerificationMaterial( ctx context.Context, client *Client, verification *CertificateChainVerificationResult, ) (*VerificationMaterial, error)
BuildVerificationMaterial assembles the current verification inputs for a certificate chain. This does not perform aggregate signature verification; it only prepares the inputs required for that future step.
type VerificationMode ¶ added in v0.26.0
type VerificationMode uint8
VerificationMode selects the level of Mithril certificate verification.
const ( // VerificationModeStructural verifies certificate chain linkage and leaf // binding to the requested snapshot digest. VerificationModeStructural VerificationMode = iota + 1 // VerificationModeSTM verifies the structural certificate chain and the // aggregate multi-signature of each non-genesis certificate. VerificationModeSTM )