mithril

package
v0.27.2 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AggregatorURLForNetwork

func AggregatorURLForNetwork(network string) (string, error)

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

func AncillaryVerificationKeyURLForNetwork(network string) (string, error)

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

func GenesisVerificationKeyURLForNetwork(network string) (string, error)

GenesisVerificationKeyURLForNetwork returns the default Mithril genesis verification key URL for the given network.

func HumanBytes added in v0.26.0

func HumanBytes(b int64) string

HumanBytes formats a byte count in a human-readable form.

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
	// 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
}

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:

  1. Fetch the latest snapshot from the aggregator
  2. Download the snapshot archive
  3. Extract the archive to obtain the ImmutableDB files
  4. 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 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) 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

func (c *Client) GetCertificate(
	ctx context.Context,
	hash string,
) (*Certificate, error)

GetCertificate retrieves a certificate by its hash. Corresponds to GET /certificate/{hash}.

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

func (c *Client) GetSnapshot(
	ctx context.Context,
	digest string,
) (*SnapshotListItem, error)

GetSnapshot retrieves the details of a specific snapshot by its digest. Corresponds to GET /artifact/snapshot/{digest}.

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
}

DownloadConfig holds configuration for downloading a snapshot archive.

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

type ProtocolMessage struct {
	MessageParts map[string]string `json:"message_parts"`
}

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) 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

type StakeDistributionParty struct {
	PartyID string `json:"party_id"`
	Stake   uint64 `json:"stake"`
}

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 VerificationKey added in v0.26.0

type VerificationKey struct {
	Type        string
	Description string
	CborHex     string
	RawKeyBytes []byte
}

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
)

Jump to

Keyboard shortcuts

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