interfaces

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2025 License: MIT Imports: 2 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Block

type Block interface {
	// Embed Hashable to provide standardized hashing with caching
	Hashable

	// GetIndex returns the block's position in the chain
	GetIndex() uint64

	// GetTimestamp returns when the block was created
	GetTimestamp() time.Time

	// GetPreviousHash returns the hash of the previous block
	GetPreviousHash() string

	// GetData returns the block's payload data
	GetData() []byte

	// SetData sets the block's payload data
	SetData(data []byte)

	// GetNonce returns the nonce (for PoW consensus)
	GetNonce() uint64

	// SetNonce sets the nonce value
	SetNonce(nonce uint64)

	// GetDifficulty returns the block's difficulty/target
	GetDifficulty() any

	// SetDifficulty sets the block's difficulty
	SetDifficulty(difficulty any)

	// GetProof returns the consensus proof (PoW hash, PoS signature, etc.)
	GetProof() []byte

	// SetProof sets the consensus proof
	SetProof(proof []byte)

	// GetProposer returns the identity of who proposed this block
	GetProposer() string

	// SetProposer sets who proposed this block
	SetProposer(proposer string)

	// Validate performs basic validation on the block structure
	Validate() error

	// Clone creates a deep copy of the block
	Clone() Block

	// Serialize converts the block to bytes for storage/transmission
	Serialize() ([]byte, error)

	// GetSize returns the size of the block in bytes
	GetSize() int

	// GetMetadata returns additional block metadata
	GetMetadata() map[string]any

	// SetMetadata sets additional block metadata
	SetMetadata(metadata map[string]any)
}

Block defines the interface for a block in any consensus mechanism. This abstraction allows different block implementations while maintaining a consistent interface for consensus operations.

type Capability

type Capability string

Capability represents a specific capability a plugin provides

const (
	// CapabilityValidator indicates the plugin provides validation
	CapabilityValidator Capability = "validator"

	// CapabilityWorker indicates the plugin provides consensus work processing
	CapabilityWorker Capability = "worker"

	// CapabilityHasher indicates the plugin provides hashing
	CapabilityHasher Capability = "hasher"

	// CapabilityMonitor indicates the plugin provides monitoring
	CapabilityMonitor Capability = "monitor"

	// CapabilityStorage indicates the plugin provides storage
	CapabilityStorage Capability = "storage"

	// CapabilityNetwork indicates the plugin provides networking
	CapabilityNetwork Capability = "network"
)

type Collector

type Collector interface {
	// Counter operations
	IncrementCounter(name string, labels map[string]string)
	AddCounter(name string, value float64, labels map[string]string)
	GetCounter(name string, labels map[string]string) float64

	// Gauge operations
	SetGauge(name string, value float64, labels map[string]string)
	IncrementGauge(name string, labels map[string]string)
	DecrementGauge(name string, labels map[string]string)
	AddGauge(name string, value float64, labels map[string]string)
	GetGauge(name string, labels map[string]string) float64

	// Histogram operations
	ObserveHistogram(name string, value float64, labels map[string]string)
	GetHistogram(name string, labels map[string]string) *HistogramData

	// Summary operations
	ObserveSummary(name string, value float64, labels map[string]string)
	GetSummary(name string, labels map[string]string) *SummaryData

	// Timing helpers
	RecordDuration(name string, duration time.Duration, labels map[string]string)
	StartTimer(name string, labels map[string]string) func()

	// Metrics retrieval
	GetAllMetrics() map[string]Metric
	Reset()
}

Collector defines the interface for metrics collection

type Consensus

type Consensus interface {
	// Start begins the consensus mechanism operations
	Start(ctx context.Context) error

	// Stop gracefully shuts down the consensus mechanism
	Stop() error

	// ValidateBlock checks if a block meets the consensus rules
	ValidateBlock(block Block) error

	// ProposeBlock creates a new block proposal according to consensus rules
	ProposeBlock(data []byte) (Block, error)

	// GetDifficulty returns the current consensus difficulty/threshold
	GetDifficulty() any

	// AdjustDifficulty recalculates difficulty based on consensus rules
	AdjustDifficulty(blocks []Block) error

	// GetConsensusType returns the type of consensus (e.g., "PoW", "PoS")
	GetConsensusType() string

	// GetStatus returns the current status of the consensus mechanism
	GetStatus() ConsensusStatus

	// RegisterValidator adds a validator to the consensus mechanism
	RegisterValidator(validator Validator) error

	// RegisterWorker adds a worker to the consensus mechanism
	// Workers process consensus tasks (mining in PoW, validating in PoS, etc.)
	RegisterWorker(worker Worker) error

	// OnBlockAccepted is called when a block is accepted by the network
	OnBlockAccepted(block Block) error

	// OnBlockRejected is called when a block is rejected
	OnBlockRejected(block Block, reason error) error

	// GetMetrics returns consensus-related metrics for monitoring
	GetMetrics() ConsensusMetrics
}

Consensus defines the core interface for any consensus mechanism. This is the main interface that allows different consensus algorithms (PoW, PoS, etc.) to be plugged into a system.

type ConsensusMetrics

type ConsensusMetrics struct {
	// BlocksProposed is the total number of blocks proposed
	BlocksProposed uint64 `json:"blocks_proposed"`

	// BlocksAccepted is the total number of blocks accepted
	BlocksAccepted uint64 `json:"blocks_accepted"`

	// BlocksRejected is the total number of blocks rejected
	BlocksRejected uint64 `json:"blocks_rejected"`

	// AverageBlockTime is the average time between blocks
	AverageBlockTime time.Duration `json:"average_block_time"`

	// LastBlockTime is the timestamp of the last block
	LastBlockTime time.Time `json:"last_block_time"`

	// ConsensusRounds is the number of consensus rounds completed
	ConsensusRounds uint64 `json:"consensus_rounds"`

	// FailedRounds is the number of failed consensus rounds
	FailedRounds uint64 `json:"failed_rounds"`

	// Additional metrics specific to consensus type
	CustomMetrics map[string]any `json:"custom_metrics,omitempty"`
}

ConsensusMetrics contains metrics for monitoring consensus performance

type ConsensusRule

type ConsensusRule interface {
	// GetName returns the rule's unique identifier
	GetName() string

	// GetDescription returns a human-readable description of the rule
	GetDescription() string

	// GetPriority returns the execution priority (higher = executed first)
	GetPriority() int

	// Validate checks if a block satisfies this rule
	Validate(ctx context.Context, block Block) RuleResult

	// IsEnabled returns whether this rule is currently active
	IsEnabled() bool

	// Enable activates this rule
	Enable()

	// Disable deactivates this rule
	Disable()
}

ConsensusRule defines a rule that blocks must follow for a specific consensus mechanism

type ConsensusStatus

type ConsensusStatus struct {
	// Active indicates if consensus is currently running
	Active bool `json:"active"`

	// CurrentHeight is the current blockchain height
	CurrentHeight uint64 `json:"current_height"`

	// LastBlockTime is when the last block was produced
	LastBlockTime time.Time `json:"last_block_time"`

	// Participants is the number of active consensus participants
	Participants int `json:"participants"`

	// Health indicates the health status of consensus
	Health HealthStatus `json:"health"`

	// Additional status information
	Details map[string]any `json:"details,omitempty"`
}

ConsensusStatus represents the current state of the consensus mechanism

type DifficultyAdjustmentConfig

type DifficultyAdjustmentConfig struct {
	// TargetBlockTime is the desired time between blocks
	TargetBlockTime time.Duration

	// AdjustmentInterval is how often difficulty is adjusted (in blocks)
	AdjustmentInterval uint64

	// MinDifficulty is the minimum allowed difficulty
	MinDifficulty uint64

	// MaxDifficulty is the maximum allowed difficulty
	MaxDifficulty uint64

	// MaxAdjustmentFactor is the maximum multiplier for adjustment (e.g., 4.0 means difficulty can at most quadruple)
	MaxAdjustmentFactor float64

	// LookbackWindow is how many blocks to consider for adjustment
	LookbackWindow uint64
}

DifficultyAdjustmentConfig contains configuration for difficulty adjustment

type DifficultyCalculator

type DifficultyCalculator interface {
	// CalculateNextDifficulty computes the difficulty for the next block
	// based on historical data
	CalculateNextDifficulty(currentDifficulty uint64, blocks []Block) (uint64, error)

	// GetMinDifficulty returns the minimum allowed difficulty
	GetMinDifficulty() uint64

	// GetMaxDifficulty returns the maximum allowed difficulty
	GetMaxDifficulty() uint64

	// ValidateDifficulty checks if a difficulty value is valid
	ValidateDifficulty(difficulty uint64) error

	// GetAlgorithmName returns the name of the difficulty algorithm
	GetAlgorithmName() string

	// GetTargetBlockTime returns the desired time between blocks
	GetTargetBlockTime() time.Duration

	// EstimateNextDifficulty provides an estimate without committing
	EstimateNextDifficulty(currentDifficulty uint64, blocks []Block) uint64
}

DifficultyCalculator defines the interface for difficulty adjustment algorithms

type DistributionStrategy

type DistributionStrategy string

DistributionStrategy defines how work is distributed among workers

const (
	// StrategyRoundRobin distributes work in round-robin fashion
	StrategyRoundRobin DistributionStrategy = "round_robin"

	// StrategyLeastBusy distributes work to the least busy worker
	StrategyLeastBusy DistributionStrategy = "least_busy"

	// StrategyRandom distributes randomly
	StrategyRandom DistributionStrategy = "random"

	// StrategyBroadcast sends work to all workers
	StrategyBroadcast DistributionStrategy = "broadcast"

	// StrategyLoadBalanced distributes based on worker load
	StrategyLoadBalanced DistributionStrategy = "load_balanced"

	// StrategyPriority distributes based on worker priority/performance
	StrategyPriority DistributionStrategy = "priority"
)

type ErrorReporter

type ErrorReporter interface {
	// ReportError reports an error
	ReportError(err error)

	// ReportErrorWithContext reports an error with additional context
	ReportErrorWithContext(err error, context map[string]any)

	// GetErrors returns all reported errors
	GetErrors() []error

	// GetErrorCount returns the number of reported errors
	GetErrorCount() int

	// Clear clears all reported errors
	Clear()
}

ErrorReporter defines the interface for error reporting

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity indicates how critical a validation error is

const (
	// SeverityCritical indicates a critical error that must be fixed
	SeverityCritical ErrorSeverity = "critical"

	// SeverityHigh indicates a high-priority error
	SeverityHigh ErrorSeverity = "high"

	// SeverityMedium indicates a medium-priority error
	SeverityMedium ErrorSeverity = "medium"

	// SeverityLow indicates a low-priority error
	SeverityLow ErrorSeverity = "low"
)

type Extension

type Extension interface {
	// GetName returns the extension name
	GetName() string

	// GetType returns the extension type
	GetType() ExtensionType

	// Execute runs the extension logic
	Execute(ctx context.Context, input ExtensionInput) (ExtensionOutput, error)

	// Validate checks if the extension can handle the input
	Validate(input ExtensionInput) error

	// GetMetadata returns extension metadata
	GetMetadata() ExtensionMetadata
}

Extension represents an extension point where custom logic can be added

type ExtensionInput

type ExtensionInput struct {
	Type    ExtensionType  `json:"type"`
	Data    any            `json:"data"`
	Context map[string]any `json:"context,omitempty"`
}

ExtensionInput contains input data for an extension

type ExtensionMetadata

type ExtensionMetadata struct {
	Name         string         `json:"name"`
	Version      string         `json:"version"`
	Description  string         `json:"description"`
	Author       string         `json:"author,omitempty"`
	License      string         `json:"license,omitempty"`
	Capabilities []string       `json:"capabilities,omitempty"`
	Config       map[string]any `json:"config,omitempty"`
}

ExtensionMetadata describes an extension

type ExtensionOutput

type ExtensionOutput struct {
	Success  bool           `json:"success"`
	Result   any            `json:"result,omitempty"`
	Error    string         `json:"error,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

ExtensionOutput contains output from an extension

type ExtensionPoint

type ExtensionPoint struct {
	Name        string
	Type        ExtensionType
	Description string
	Required    bool
	Multiple    bool // Allow multiple extensions at this point
}

ExtensionPoint defines where extensions can be plugged in

type ExtensionType

type ExtensionType string

ExtensionType categorizes extensions

const (
	// ExtensionTypeValidator adds custom validation logic
	ExtensionTypeValidator ExtensionType = "validator"

	// ExtensionTypeWorker adds custom worker strategies
	ExtensionTypeWorker ExtensionType = "worker"

	// ExtensionTypeHasher adds custom hash algorithms
	ExtensionTypeHasher ExtensionType = "hasher"

	// ExtensionTypeDifficulty adds custom difficulty algorithms
	ExtensionTypeDifficulty ExtensionType = "difficulty"

	// ExtensionTypeRule adds custom consensus rules
	ExtensionTypeRule ExtensionType = "rule"

	// ExtensionTypeMetric adds custom metrics collection
	ExtensionTypeMetric ExtensionType = "metric"

	// ExtensionTypeStorage adds custom storage backends
	ExtensionTypeStorage ExtensionType = "storage"

	// ExtensionTypeNetwork adds custom network protocols
	ExtensionTypeNetwork ExtensionType = "network"

	// ExtensionTypeTransform adds data transformation logic
	ExtensionTypeTransform ExtensionType = "transform"

	// ExtensionTypeSerializer adds custom serialization
	ExtensionTypeSerializer ExtensionType = "serializer"

	// ExtensionTypeCompressor adds custom compression
	ExtensionTypeCompressor ExtensionType = "compressor"

	// ExtensionTypeCrypto adds custom cryptography
	ExtensionTypeCrypto ExtensionType = "crypto"

	// ExtensionTypeMiddleware adds middleware processing
	ExtensionTypeMiddleware ExtensionType = "middleware"
)

type Hashable

type Hashable interface {
	// GetHashableBytes returns the byte representation for hashing.
	// The implementation must ensure consistent ordering of fields
	// to produce deterministic hashes.
	GetHashableBytes() ([]byte, error)

	// GetHashAlgorithm returns the preferred hash algorithm for this data.
	// Examples: "SHA256", "SHA3-256", "BLAKE2b", etc.
	// Returns empty string to use the default algorithm.
	GetHashAlgorithm() string

	// ComputeHash calculates and returns the hash of the data.
	// This may use caching to avoid recomputation.
	ComputeHash() ([]byte, error)

	// GetCachedHash returns the cached hash if available, nil otherwise.
	// This allows for performance optimization by avoiding recomputation.
	GetCachedHash() []byte

	// InvalidateCache clears any cached hash value.
	// Should be called when the underlying data changes.
	InvalidateCache()

	// Verify checks if a given hash matches this data's hash.
	Verify(hash []byte) (bool, error)
}

Hashable defines the interface for any data that can be hashed. This allows flexible hashing of different data types in the consensus mechanism.

type Hasher

type Hasher interface {
	// Hash computes the hash of the given data
	Hash(data []byte) ([]byte, error)

	// HashMultiple computes the hash of multiple data pieces concatenated
	HashMultiple(data ...[]byte) ([]byte, error)

	// GetAlgorithm returns the name of the hash algorithm
	GetAlgorithm() string

	// GetHashSize returns the size of the hash in bytes
	GetHashSize() int

	// IsSecure indicates if this hasher is cryptographically secure
	IsSecure() bool

	// Reset resets the hasher to its initial state
	Reset()

	// Clone creates a copy of the hasher in its current state
	Clone() Hasher
}

Hasher defines the interface for hash function implementations. This allows pluggable hash algorithms in the consensus mechanism.

type HealthStatus

type HealthStatus string

HealthStatus represents the health state of the consensus mechanism

const (
	// HealthHealthy indicates consensus is operating normally
	HealthHealthy HealthStatus = "healthy"

	// HealthDegraded indicates consensus is operational but with issues
	HealthDegraded HealthStatus = "degraded"

	// HealthUnhealthy indicates consensus has critical issues
	HealthUnhealthy HealthStatus = "unhealthy"
)

type HistogramData

type HistogramData struct {
	Count   uint64
	Sum     float64
	Min     float64
	Max     float64
	Mean    float64
	Stddev  float64
	Buckets map[float64]uint64
}

HistogramData contains histogram statistics

type Hook

type Hook interface {
	// GetName returns the hook's name for identification
	GetName() string

	// GetPriority returns execution priority (lower executes first)
	GetPriority() int

	// Execute runs the hook with the provided data
	Execute(ctx context.Context, data any) error

	// ContinueOnError indicates if other hooks should run if this fails
	ContinueOnError() bool

	// IsEnabled checks if the hook is currently enabled
	IsEnabled() bool

	// SetEnabled enables or disables the hook
	SetEnabled(enabled bool)
}

Hook represents a function that can be executed at specific points in the consensus flow

type Iterator

type Iterator interface {
	Next() bool
	Key() []byte
	Value() []byte
	Error() error
	Release()
	Seek(key []byte) bool
}

Iterator defines the interface for iterating over storage entries

type Logger

type Logger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
	Fatal(msg string, args ...any)
	WithField(key string, value any) Logger
	WithFields(fields map[string]any) Logger
}

Logger defines the interface for logging

type Metric

type Metric struct {
	Name   string
	Type   MetricType
	Value  float64
	Labels map[string]string
	Data   any
}

Metric represents a single metric

type MetricType

type MetricType string

MetricType represents the type of metric

const (
	MetricTypeCounter   MetricType = "counter"
	MetricTypeGauge     MetricType = "gauge"
	MetricTypeHistogram MetricType = "histogram"
	MetricTypeSummary   MetricType = "summary"
)

type Plugin

type Plugin interface {
	// GetName returns the unique name of the plugin
	GetName() string

	// GetVersion returns the plugin version
	GetVersion() string

	// Initialize is called when the plugin is registered
	Initialize(ctx context.Context, config map[string]any) error

	// Start begins plugin operations
	Start(ctx context.Context) error

	// Stop halts plugin operations
	Stop() error

	// GetDependencies returns plugin names this plugin depends on
	GetDependencies() []string

	// GetCapabilities returns what capabilities this plugin provides
	GetCapabilities() []Capability

	// GetStatus returns the current plugin status
	GetStatus() PluginStatus
}

Plugin represents a pluggable component that can extend consensus functionality

type PluginState

type PluginState string

PluginState represents the plugin's lifecycle state

const (
	// PluginStateUninitialized means the plugin hasn't been initialized
	PluginStateUninitialized PluginState = "uninitialized"

	// PluginStateInitialized means the plugin is initialized but not started
	PluginStateInitialized PluginState = "initialized"

	// PluginStateRunning means the plugin is actively running
	PluginStateRunning PluginState = "running"

	// PluginStateStopped means the plugin has been stopped
	PluginStateStopped PluginState = "stopped"

	// PluginStateError means the plugin encountered an error
	PluginStateError PluginState = "error"
)

type PluginStatus

type PluginStatus struct {
	State   PluginState    `json:"state"`
	Message string         `json:"message,omitempty"`
	Error   error          `json:"error,omitempty"`
	Metrics map[string]any `json:"metrics,omitempty"`
}

PluginStatus represents the current state of a plugin

type RuleMetric

type RuleMetric struct {
	// Executions is how many times this rule was executed
	Executions uint64 `json:"executions"`

	// Failures is how many times this rule failed
	Failures uint64 `json:"failures"`

	// AverageTime is the average execution time in nanoseconds
	AverageTime int64 `json:"average_time_ns"`
}

RuleMetric contains metrics for a specific validation rule

type RuleResult

type RuleResult struct {
	// Passed indicates if the rule validation passed
	Passed bool

	// RuleName is the name of the rule that was validated
	RuleName string

	// Violation contains details if the rule was violated
	Violation *RuleViolation

	// Metadata contains additional context about the validation
	Metadata map[string]any
}

RuleResult represents the outcome of a rule validation

type RuleViolation

type RuleViolation struct {
	// RuleName is the name of the violated rule
	RuleName string

	// Severity indicates how severe the violation is
	Severity ViolationSeverity

	// Message is a human-readable description of the violation
	Message string

	// Code is a machine-readable violation code
	Code string

	// Details contains additional violation context
	Details map[string]any

	// Remedy suggests how to fix the violation (if applicable)
	Remedy string
}

RuleViolation represents a violation of a consensus rule

type StateChange

type StateChange struct {
	Key      string `json:"key"`
	OldValue any    `json:"old_value"`
	NewValue any    `json:"new_value"`
	Applied  bool   `json:"applied"`
}

StateChange represents a single state change

type StateManager

type StateManager interface {
	// State operations
	GetState(key string) (any, error)
	SetState(key string, value any) error
	DeleteState(key string) error

	// Snapshot operations
	CreateSnapshot() (string, error)
	RestoreSnapshot(snapshotID string) error
	ListSnapshots() ([]string, error)
	DeleteSnapshot(snapshotID string) error

	// State transitions
	BeginStateTransition() StateTransition
	ApplyStateTransition(transition StateTransition) error

	// State validation
	ValidateState() error
	GetStateHash() ([]byte, error)
}

StateManager defines the interface for managing consensus state

type StateTransition

type StateTransition interface {
	AddChange(key string, oldValue, newValue any)
	GetChanges() map[string]StateChange
	Validate() error
	Apply() error
	Rollback() error
}

StateTransition represents a state transition

type Storage

type Storage interface {
	// Basic operations
	Put(key []byte, value []byte) error
	Get(key []byte) ([]byte, error)
	Delete(key []byte) error
	Has(key []byte) (bool, error)

	// Batch operations
	BatchPut(items map[string][]byte) error
	BatchGet(keys [][]byte) (map[string][]byte, error)
	BatchDelete(keys [][]byte) error

	// Iterator
	NewIterator(prefix []byte) Iterator

	// Transaction support
	BeginTransaction() Transaction

	// Management
	Close() error
	Compact() error
	GetStats() StorageStats
}

Storage defines the interface for data persistence

type StorageStats

type StorageStats struct {
	Keys        int64 `json:"keys"`
	Size        int64 `json:"size"`
	Reads       int64 `json:"reads"`
	Writes      int64 `json:"writes"`
	Deletes     int64 `json:"deletes"`
	Compactions int64 `json:"compactions"`
}

StorageStats contains storage statistics

type SubWorkerMetric

type SubWorkerMetric struct {
	// ID is the sub-worker identifier
	ID string `json:"id"`

	// Throughput is this sub-worker's processing rate
	Throughput float64 `json:"throughput"`

	// Iterations is the total iterations by this sub-worker
	Iterations uint64 `json:"iterations"`

	// Status is the sub-worker's current status
	Status WorkerStatus `json:"status"`

	// LastUpdate is when this sub-worker last reported
	LastUpdate time.Time `json:"last_update"`
}

SubWorkerMetric contains metrics for a single sub-worker/thread

type SummaryData

type SummaryData struct {
	Count     uint64
	Sum       float64
	Min       float64
	Max       float64
	Mean      float64
	Quantiles map[float64]float64 // e.g., 0.5 -> median, 0.95 -> 95th percentile
}

SummaryData contains summary statistics

type Transaction

type Transaction interface {
	Put(key []byte, value []byte) error
	Get(key []byte) ([]byte, error)
	Delete(key []byte) error
	Commit() error
	Rollback() error
	Discard()
}

Transaction defines the interface for storage transactions

type ValidationError

type ValidationError struct {
	// Code is a machine-readable error code
	Code string `json:"code"`

	// Message is a human-readable error message
	Message string `json:"message"`

	// Field identifies which field failed validation
	Field string `json:"field,omitempty"`

	// Severity indicates how critical this error is
	Severity ErrorSeverity `json:"severity"`

	// Context provides additional error context
	Context map[string]any `json:"context,omitempty"`
}

ValidationError represents a validation failure

type ValidationPipeline

type ValidationPipeline interface {
	// AddValidator adds a validator to the pipeline
	AddValidator(validator Validator) error

	// RemoveValidator removes a validator from the pipeline
	RemoveValidator(name string) error

	// GetValidators returns all validators in execution order
	GetValidators() []Validator

	// Execute runs the validation pipeline on a block
	Execute(ctx context.Context, block Block) ValidationResult

	// ExecuteParallel runs validators in parallel where possible
	ExecuteParallel(ctx context.Context, block Block) ValidationResult

	// SetStopOnFirstError configures whether to stop on first validation error
	SetStopOnFirstError(stop bool)

	// GetMetrics returns pipeline-wide metrics
	GetMetrics() ValidatorMetrics
}

ValidationPipeline defines a pipeline of validators

type ValidationResult

type ValidationResult struct {
	// Valid indicates if validation passed
	Valid bool `json:"valid"`

	// Errors contains any validation errors
	Errors []ValidationError `json:"errors,omitempty"`

	// Warnings contains non-critical validation warnings
	Warnings []ValidationWarning `json:"warnings,omitempty"`

	// Score represents a validation score (0-100, where 100 is perfect)
	Score float64 `json:"score"`

	// Details contains additional validation details
	Details map[string]any `json:"details,omitempty"`

	// ValidatorName identifies which validator produced this result
	ValidatorName string `json:"validator_name"`

	// Duration is how long validation took
	Duration int64 `json:"duration_ns"`
}

ValidationResult represents the outcome of a validation

type ValidationRule

type ValidationRule struct {
	// ID uniquely identifies this rule
	ID string `json:"id"`

	// Name is the human-readable rule name
	Name string `json:"name"`

	// Description explains what this rule validates
	Description string `json:"description"`

	// Category groups related rules together
	Category string `json:"category"`

	// Enabled indicates if this rule is active
	Enabled bool `json:"enabled"`

	// Config contains rule-specific configuration
	Config map[string]any `json:"config,omitempty"`
}

ValidationRule represents a single validation rule

type ValidationWarning

type ValidationWarning struct {
	// Code is a machine-readable warning code
	Code string `json:"code"`

	// Message is a human-readable warning message
	Message string `json:"message"`

	// Field identifies which field triggered the warning
	Field string `json:"field,omitempty"`

	// Recommendation suggests how to address the warning
	Recommendation string `json:"recommendation,omitempty"`
}

ValidationWarning represents a non-critical validation issue

type Validator

type Validator interface {
	// Validate performs validation on a block
	Validate(ctx context.Context, block Block) ValidationResult

	// ValidateChain validates a sequence of blocks
	ValidateChain(ctx context.Context, blocks []Block) ValidationResult

	// GetName returns the name of this validator
	GetName() string

	// GetPriority returns the execution priority (lower executes first)
	GetPriority() int

	// IsEnabled checks if this validator is currently enabled
	IsEnabled() bool

	// SetEnabled enables or disables this validator
	SetEnabled(enabled bool)

	// GetValidationRules returns the list of rules this validator enforces
	GetValidationRules() []ValidationRule

	// GetMetrics returns validation metrics
	GetMetrics() ValidatorMetrics
}

Validator defines the interface for validation logic in the consensus mechanism. Validators can be chained and composed to create complex validation rules.

type ValidatorMetrics

type ValidatorMetrics struct {
	// TotalValidations is the total number of validations performed
	TotalValidations uint64 `json:"total_validations"`

	// PassedValidations is the number of successful validations
	PassedValidations uint64 `json:"passed_validations"`

	// FailedValidations is the number of failed validations
	FailedValidations uint64 `json:"failed_validations"`

	// AverageValidationTime is the average validation duration in nanoseconds
	AverageValidationTime int64 `json:"average_validation_time_ns"`

	// LastValidationTime is when the last validation occurred
	LastValidationTime int64 `json:"last_validation_time"`

	// RuleMetrics contains per-rule metrics
	RuleMetrics map[string]*RuleMetric `json:"rule_metrics,omitempty"`
}

ValidatorMetrics contains metrics for a validator

type ViolationAction

type ViolationAction string

ViolationAction defines actions to take on rule violations

const (
	// ActionReject rejects the block entirely
	ActionReject ViolationAction = "reject"

	// ActionWarn logs a warning but accepts the block
	ActionWarn ViolationAction = "warn"

	// ActionIgnore ignores the violation
	ActionIgnore ViolationAction = "ignore"

	// ActionRetry allows retrying with different parameters
	ActionRetry ViolationAction = "retry"

	// ActionPenalize penalizes the block proposer
	ActionPenalize ViolationAction = "penalize"
)

type ViolationResponse

type ViolationResponse struct {
	// Action specifies what action to take
	Action ViolationAction

	// RejectBlock indicates if the block should be rejected
	RejectBlock bool

	// PenalizeProposer indicates if the block proposer should be penalized
	PenalizeProposer bool

	// Message is a response message
	Message string

	// Metadata contains additional response context
	Metadata map[string]any
}

ViolationResponse defines how to respond to a rule violation

type ViolationSeverity

type ViolationSeverity string

ViolationSeverity indicates the severity of a rule violation

const (
	// ViolationSeverityCritical means the block is completely invalid
	ViolationSeverityCritical ViolationSeverity = "critical"

	// ViolationSeverityError means the block has serious issues
	ViolationSeverityError ViolationSeverity = "error"

	// ViolationSeverityWarning means the block has minor issues
	ViolationSeverityWarning ViolationSeverity = "warning"

	// ViolationSeverityInfo is informational only
	ViolationSeverityInfo ViolationSeverity = "info"
)

type WorkPackage

type WorkPackage interface {
	// GetBlockTemplate returns the block template to process
	GetBlockTemplate() Block

	// GetTarget returns the target/threshold to meet (consensus-specific)
	GetTarget() []byte

	// GetDifficulty returns the difficulty value (consensus-specific)
	GetDifficulty() uint64

	// GetParameters returns consensus-specific parameters
	GetParameters() map[string]any

	// SetParameters sets consensus-specific parameters
	SetParameters(params map[string]any)

	// GetTimeout returns the processing timeout duration
	GetTimeout() time.Duration

	// GetJobID returns a unique identifier for this work
	GetJobID() string

	// GetCreatedAt returns when this work package was created
	GetCreatedAt() time.Time

	// IsStale checks if this work package is outdated
	IsStale() bool

	// Validate checks if the work package is valid
	Validate() error
}

WorkPackage defines the work to be processed by consensus workers

type WorkResult

type WorkResult interface {
	// GetBlock returns the processed block
	GetBlock() Block

	// GetProof returns the consensus proof (nonce for PoW, signature for PoS, etc.)
	GetProof() []byte

	// GetMetadata returns result metadata (attempts, iterations, etc.)
	GetMetadata() map[string]any

	// GetDuration returns how long processing took
	GetDuration() time.Duration

	// GetThroughput returns the throughput achieved during processing
	GetThroughput() float64

	// GetWorkerID returns the ID of the worker who found the solution
	GetWorkerID() string

	// GetJobID returns the ID of the work package
	GetJobID() string

	// GetTimestamp returns when the solution was found
	GetTimestamp() time.Time

	// Verify checks if the result is valid
	Verify() error
}

WorkResult represents the result of successful work processing

type Worker

type Worker interface {
	// Start begins worker operations
	Start(ctx context.Context) error

	// Stop halts worker operations
	Stop() error

	// Process attempts to process a work package according to consensus rules
	Process(ctx context.Context, work WorkPackage) (WorkResult, error)

	// GetThroughput returns the current work throughput (e.g., hashes/sec for PoW)
	GetThroughput() float64

	// GetWorkerCount returns the number of concurrent workers/threads
	GetWorkerCount() int

	// SetWorkerCount adjusts the number of concurrent workers
	SetWorkerCount(count int) error

	// GetID returns the worker's unique identifier
	GetID() string

	// GetAddress returns the worker's reward address (if applicable)
	GetAddress() string

	// SetAddress sets the worker's reward address
	SetAddress(address string) error

	// GetMetrics returns worker performance metrics
	GetMetrics() WorkerMetrics

	// IsRunning checks if the worker is currently active
	IsRunning() bool

	// RegisterListener registers a listener for worker events
	RegisterListener(listener WorkerListener)

	// UnregisterListener removes a worker event listener
	UnregisterListener(listener WorkerListener)
}

Worker defines the interface for consensus workers. Workers perform the computational work required by the consensus mechanism: - Mining (finding nonces) in Proof of Work - Validating and proposing in Proof of Stake - Voting and consensus in PBFT/BFT systems

type WorkerEvent

type WorkerEvent struct {
	// Type is the event type
	Type WorkerEventType

	// WorkerID is the ID of the worker that triggered the event
	WorkerID string

	// Timestamp is when the event occurred
	Timestamp time.Time

	// Data contains event-specific data
	Data any
}

WorkerEvent represents an event from a worker

type WorkerEventType

type WorkerEventType string

WorkerEventType represents the type of worker event

const (
	// WorkerEventStarted is triggered when work begins
	WorkerEventStarted WorkerEventType = "work_started"

	// WorkerEventProgress is triggered for progress updates
	WorkerEventProgress WorkerEventType = "work_progress"

	// WorkerEventCompleted is triggered when work completes successfully
	WorkerEventCompleted WorkerEventType = "work_completed"

	// WorkerEventFailed is triggered when work fails
	WorkerEventFailed WorkerEventType = "work_failed"

	// WorkerEventCancelled is triggered when work is cancelled
	WorkerEventCancelled WorkerEventType = "work_cancelled"

	// WorkerEventThroughputUpdated is triggered when throughput changes
	WorkerEventThroughputUpdated WorkerEventType = "throughput_updated"

	// WorkerEventCountChanged is triggered when worker count changes
	WorkerEventCountChanged WorkerEventType = "worker_count_changed"
)

type WorkerListener

type WorkerListener interface {
	// OnWorkStarted is called when work begins
	// workerID identifies the worker, work is the package being processed
	OnWorkStarted(workerID string, work WorkPackage)

	// OnWorkProgress is called periodically with progress updates
	// workerID identifies the worker, progress is a float64 representing progress percentage
	OnWorkProgress(workerID string, progress float64)

	// OnWorkCompleted is called when valid result is found
	// workerID identifies the worker, result is the completed work result
	OnWorkCompleted(workerID string, result WorkResult)

	// OnWorkFailed is called when work fails
	// workerID identifies the worker, err is the error that occurred
	OnWorkFailed(workerID string, err error)

	// OnWorkCancelled is called when work is cancelled
	// workerID identifies the worker that had work cancelled
	OnWorkCancelled(workerID string)

	// OnThroughputUpdated is called when worker throughput changes
	// workerID identifies the worker, throughput is the new throughput value
	OnThroughputUpdated(workerID string, throughput float64)
}

WorkerListener defines callbacks for worker events

type WorkerMetrics

type WorkerMetrics struct {
	// TotalIterations is the total number of iterations performed
	TotalIterations uint64 `json:"total_iterations"`

	// SuccessfulResults is the number of valid results found
	SuccessfulResults uint64 `json:"successful_results"`

	// FailedAttempts is the number of failed attempts
	FailedAttempts uint64 `json:"failed_attempts"`

	// CurrentThroughput is the current processing rate
	CurrentThroughput float64 `json:"current_throughput"`

	// AverageThroughput is the average processing rate since start
	AverageThroughput float64 `json:"average_throughput"`

	// PeakThroughput is the highest processing rate achieved
	PeakThroughput float64 `json:"peak_throughput"`

	// Uptime is how long the worker has been running
	Uptime time.Duration `json:"uptime"`

	// LastResultFound is when the last valid result was found
	LastResultFound *time.Time `json:"last_result_found,omitempty"`

	// SubWorkerMetrics contains per-subworker statistics
	SubWorkerMetrics []SubWorkerMetric `json:"sub_worker_metrics,omitempty"`
}

WorkerMetrics contains performance metrics for a worker

type WorkerPool

type WorkerPool interface {
	// Start starts the worker pool
	Start(ctx context.Context) error

	// Stop stops the worker pool
	Stop(ctx context.Context) error

	// AddWorker adds a worker to the pool
	AddWorker(worker Worker) error

	// RemoveWorker removes a worker from the pool
	RemoveWorker(workerID string) error

	// GetWorkers returns all workers in the pool
	GetWorkers() []Worker

	// Submit submits work to the pool
	Submit(work WorkPackage) error

	// GetResult retrieves a work result from the pool
	GetResult(ctx context.Context) (WorkResult, error)

	// IsRunning returns whether the pool is running
	IsRunning() bool
}

WorkerPool defines the interface for managing multiple workers

type WorkerStatus

type WorkerStatus string

WorkerStatus represents the state of a worker

const (
	// WorkerStatusActive indicates the worker is actively processing
	WorkerStatusActive WorkerStatus = "active"

	// WorkerStatusIdle indicates the worker is idle
	WorkerStatusIdle WorkerStatus = "idle"

	// WorkerStatusError indicates the worker has encountered an error
	WorkerStatusError WorkerStatus = "error"

	// WorkerStatusStopped indicates the worker is stopped
	WorkerStatusStopped WorkerStatus = "stopped"
)

Jump to

Keyboard shortcuts

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