builder

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: 6 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Default configuration values
	DefaultWorkerCount        = 4
	DefaultCacheSize          = 1000
	DefaultBlockTime          = 10 // seconds
	DefaultDifficulty         = 4
	DefaultMinStake           = 1000
	DefaultSlashingPenalty    = 0.1
	DefaultMaxPeers           = 50
	DefaultElectionTimeout    = 150 // milliseconds
	DefaultHeartbeatInterval  = 50  // milliseconds
	DefaultMaxLogEntries      = 10000
	DefaultEpochLength        = 100
	DefaultCheckpointInterval = 10

	// Plugin types
	PluginTypeMonitoring = "monitoring"
	PluginTypeAlerting   = "alerting"
	PluginTypeBackup     = "backup"
	PluginTypeDebug      = "debug"
	PluginTypeTrace      = "trace"
	PluginTypeMetrics    = "metrics"
	PluginTypeLogging    = "logging"
	PluginTypeSecurity   = "security"

	// Error messages
	ErrConsensusTypeNotSpecified   = "consensus type not specified"
	ErrInvalidWorkerCount          = "invalid worker count: %d"
	ErrInvalidValidationMode       = "invalid validation mode: %s"
	ErrUnsupportedConsensusType    = "unsupported consensus type: %s"
	ErrValidatorRegistrationFailed = "failed to register validator: %w"
	ErrWorkerRegistrationFailed    = "failed to register worker: %w"
	ErrPluginRegistrationFailed    = "failed to register plugin: %w"
	ErrBuildValidationFailed       = "validation failed: %w"

	// Security feature flags
	SecurityFeatureSlashing                  = "slashing"
	SecurityFeatureCheckpointing             = "checkpointing"
	SecurityFeatureFraudProofs               = "fraud_proofs"
	SecurityFeatureLongRangeAttackProtection = "long_range_attack_protection"
	SecurityFeatureDoubleSpendProtection     = "double_spend_protection"
	SecurityFeatureReplayProtection          = "replay_protection"

	// Optimization flags
	OptimizationSIMD     = "simd"
	OptimizationParallel = "parallel"
	OptimizationCache    = "cache"
	OptimizationGPU      = "gpu"
	OptimizationASM      = "asm"

	// Parameter names for consensus configuration
	// Common parameters
	ParamAlgorithm     = "algorithm"
	ParamDifficulty    = "difficulty"
	ParamBlockTime     = "blockTime"
	ParamMode          = "mode"
	ParamOptimizations = "optimizations"

	// PoS specific parameters
	ParamMinStake           = "minStake"
	ParamSlashingPenalty    = "slashingPenalty"
	ParamValidatorSetSize   = "validatorSetSize"
	ParamEpochLength        = "epochLength"
	ParamCheckpointInterval = "checkpointInterval"
	ParamSecurityFeatures   = "securityFeatures"

	// PBFT specific parameters
	ParamMinNodes          = "minNodes"
	ParamFaultTolerance    = "faultTolerance"
	ParamTimeout           = "timeout"
	ParamViewChangeTimeout = "viewChangeTimeout"

	// Raft specific parameters
	ParamElectionTimeout   = "electionTimeout"
	ParamHeartbeatInterval = "heartbeatInterval"
	ParamMaxLogEntries     = "maxLogEntries"

	// Hybrid consensus parameters
	ParamPrimaryConsensus   = "primaryConsensus"
	ParamSecondaryConsensus = "secondaryConsensus"
	ParamSwitchThreshold    = "switchThreshold"
	ParamPoWDifficulty      = "powDifficulty"
	ParamPoSMinStake        = "posMinStake"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// General settings
	ConsensusType string         `json:"consensus_type"`
	Parameters    map[string]any `json:"parameters"`

	// Worker settings
	WorkerCount int    `json:"worker_count"`
	WorkerType  string `json:"worker_type"`

	// Validation settings
	ValidationMode   string `json:"validation_mode"` // "sequential", "parallel"
	StopOnFirstError bool   `json:"stop_on_first_error"`

	// Network settings
	NetworkType   string         `json:"network_type"`
	NetworkConfig map[string]any `json:"network_config"`

	// Storage settings
	StorageType   string         `json:"storage_type"`
	StorageConfig map[string]any `json:"storage_config"`

	// Plugin settings
	EnabledPlugins []string       `json:"enabled_plugins"`
	PluginConfigs  map[string]any `json:"plugin_configs"`

	// Performance settings
	CacheSize       int  `json:"cache_size"`
	EnableMetrics   bool `json:"enable_metrics"`
	EnableProfiling bool `json:"enable_profiling"`
}

Config holds configuration for consensus building

type ConsensusBuilder

type ConsensusBuilder struct {
	// contains filtered or unexported fields
}

ConsensusBuilder provides a fluent API for configuring consensus implementations As a framework, Forge does not provide implementations - users must provide their own

func NewConsensusBuilder

func NewConsensusBuilder(consensus interfaces.Consensus) *ConsensusBuilder

NewConsensusBuilder creates a new builder with the user-provided consensus implementation

func (*ConsensusBuilder) Build

Build configures and returns the consensus implementation This method wires up validators and workers with the consensus Use BuildWithContext() if you need workers started and plugins initialized

func (*ConsensusBuilder) BuildWithContext

func (b *ConsensusBuilder) BuildWithContext(ctx context.Context) (interfaces.Consensus, error)

BuildWithContext builds the consensus AND starts components that need initialization This method: 1. Calls Build() to wire up all dependencies 2. Starts workers (they have Start methods) 3. Initializes and starts plugins (if any exist) Use this instead of Build() when you need to start workers or initialize plugins

func (*ConsensusBuilder) Clone

func (b *ConsensusBuilder) Clone() *ConsensusBuilder

Clone creates a copy of the builder with the same configuration

func (*ConsensusBuilder) GetConfig

func (b *ConsensusBuilder) GetConfig() *Config

GetConfig returns the current configuration

func (*ConsensusBuilder) GetEventBus

func (b *ConsensusBuilder) GetEventBus() *plugin.EventBus

GetEventBus returns the event bus for event handling

func (*ConsensusBuilder) GetHookManager

func (b *ConsensusBuilder) GetHookManager() *plugin.HookManager

GetHookManager returns the hook manager for hook execution

func (*ConsensusBuilder) GetRegistry

func (b *ConsensusBuilder) GetRegistry() *plugin.Registry

GetRegistry returns the plugin registry

func (*ConsensusBuilder) Reset

func (b *ConsensusBuilder) Reset() *ConsensusBuilder

Reset resets the builder to initial state but keeps the consensus implementation

func (*ConsensusBuilder) Validate

func (b *ConsensusBuilder) Validate() error

Validate checks if the configuration is valid

func (*ConsensusBuilder) WithCacheSize

func (b *ConsensusBuilder) WithCacheSize(size int) *ConsensusBuilder

WithCacheSize sets the cache size for consensus operations

func (*ConsensusBuilder) WithConfig

func (b *ConsensusBuilder) WithConfig(config *Config) *ConsensusBuilder

WithConfig applies a complete configuration

func (*ConsensusBuilder) WithHook

WithHook adds a hook at a specific point with priority support

func (*ConsensusBuilder) WithMetrics

func (b *ConsensusBuilder) WithMetrics(enabled bool) *ConsensusBuilder

WithMetrics enables metrics collection

func (*ConsensusBuilder) WithNetwork

func (b *ConsensusBuilder) WithNetwork(networkType string, config map[string]any) *ConsensusBuilder

WithNetwork sets the network configuration

func (*ConsensusBuilder) WithParameter

func (b *ConsensusBuilder) WithParameter(key string, value any) *ConsensusBuilder

WithParameter sets a consensus-specific parameter

func (*ConsensusBuilder) WithParameters

func (b *ConsensusBuilder) WithParameters(params map[string]any) *ConsensusBuilder

WithParameters sets multiple parameters

func (*ConsensusBuilder) WithPlugin

WithPlugin adds a plugin to the consensus

func (*ConsensusBuilder) WithProfiling

func (b *ConsensusBuilder) WithProfiling(enabled bool) *ConsensusBuilder

WithProfiling enables performance profiling

func (*ConsensusBuilder) WithStopOnFirstError

func (b *ConsensusBuilder) WithStopOnFirstError(stop bool) *ConsensusBuilder

WithStopOnFirstError sets whether to stop validation on first error

func (*ConsensusBuilder) WithStorage

func (b *ConsensusBuilder) WithStorage(storageType string, config map[string]any) *ConsensusBuilder

WithStorage sets the storage configuration

func (*ConsensusBuilder) WithValidationMode

func (b *ConsensusBuilder) WithValidationMode(mode string) *ConsensusBuilder

WithValidationMode sets the validation mode ("sequential" or "parallel")

func (*ConsensusBuilder) WithValidator

func (b *ConsensusBuilder) WithValidator(validator interfaces.Validator) *ConsensusBuilder

WithValidator adds a validator to the consensus

func (*ConsensusBuilder) WithValidators

func (b *ConsensusBuilder) WithValidators(validators ...interfaces.Validator) *ConsensusBuilder

WithValidators adds multiple validators

func (*ConsensusBuilder) WithWorker

func (b *ConsensusBuilder) WithWorker(worker interfaces.Worker) *ConsensusBuilder

WithWorker adds a worker to the consensus

func (*ConsensusBuilder) WithWorkerCount

func (b *ConsensusBuilder) WithWorkerCount(count int) *ConsensusBuilder

WithWorkerCount sets the number of workers to create

func (*ConsensusBuilder) WithWorkers

func (b *ConsensusBuilder) WithWorkers(workers ...interfaces.Worker) *ConsensusBuilder

WithWorkers adds multiple workers

type ConsensusType

type ConsensusType string

ConsensusType represents the type of consensus mechanism

const (
	// Core consensus types
	ConsensusTypePoW    ConsensusType = "pow"    // Proof of Work
	ConsensusTypePoS    ConsensusType = "pos"    // Proof of Stake
	ConsensusTypePBFT   ConsensusType = "pbft"   // Practical Byzantine Fault Tolerance
	ConsensusTypeRaft   ConsensusType = "raft"   // Raft consensus
	ConsensusTypeCustom ConsensusType = "custom" // Custom consensus implementation

	// Extended consensus types
	ConsensusTypeDPoS       ConsensusType = "dpos"       // Delegated Proof of Stake
	ConsensusTypePoA        ConsensusType = "poa"        // Proof of Authority
	ConsensusTypePoET       ConsensusType = "poet"       // Proof of Elapsed Time
	ConsensusTypePoB        ConsensusType = "pob"        // Proof of Burn
	ConsensusTypePoC        ConsensusType = "poc"        // Proof of Capacity
	ConsensusTypeHybrid     ConsensusType = "hybrid"     // Hybrid consensus
	ConsensusTypeTendermint ConsensusType = "tendermint" // Tendermint consensus
	ConsensusTypeHotStuff   ConsensusType = "hotstuff"   // HotStuff consensus

	// Special types
	ConsensusTypeTest        ConsensusType = "test"        // Test consensus for testing
	ConsensusTypeLightweight ConsensusType = "lightweight" // Lightweight consensus for resource-constrained environments
)

type Factory

type Factory struct{}

Factory provides pre-configured builders for common consensus setups As a framework, Forge doesn't provide consensus implementations - users must provide their own

func NewFactory

func NewFactory() *Factory

NewFactory creates a new factory instance

func (*Factory) BuildComplete

func (f *Factory) BuildComplete(
	consensus interfaces.Consensus,
	config *Config,
	validators []interfaces.Validator,
	workers []interfaces.Worker,
	plugins []interfaces.Plugin,
	hooks map[plugin.HookPoint][]interfaces.Hook,
) (*ConsensusBuilder, error)

BuildComplete creates a fully configured consensus with all components

func (*Factory) BuildWithHooks

func (f *Factory) BuildWithHooks(consensus interfaces.Consensus, hooks map[plugin.HookPoint][]interfaces.Hook) (*ConsensusBuilder, error)

BuildWithHooks creates a consensus with pre-configured hooks

func (*Factory) BuildWithPlugins

func (f *Factory) BuildWithPlugins(consensus interfaces.Consensus, plugins ...interfaces.Plugin) (*ConsensusBuilder, error)

BuildWithPlugins creates a consensus with plugins

func (*Factory) CreateCustomBuilder

func (f *Factory) CreateCustomBuilder(customConsensus interfaces.Consensus, config *Config) *ConsensusBuilder

CreateCustomBuilder creates a builder for custom consensus implementations Users provide both the implementation and configuration

func (*Factory) CreatePBFTBuilder

func (f *Factory) CreatePBFTBuilder(pbftConsensus interfaces.Consensus) *ConsensusBuilder

CreatePBFTBuilder creates a pre-configured builder for PBFT Users must provide their own PBFT implementation

func (*Factory) CreatePoSBuilder

func (f *Factory) CreatePoSBuilder(posConsensus interfaces.Consensus) *ConsensusBuilder

CreatePoSBuilder creates a pre-configured builder for Proof of Stake Users must provide their own PoS implementation

func (*Factory) CreatePoWBuilder

func (f *Factory) CreatePoWBuilder(powConsensus interfaces.Consensus) *ConsensusBuilder

CreatePoWBuilder creates a pre-configured builder for Proof of Work Users must provide their own PoW implementation

func (*Factory) CreateRaftBuilder

func (f *Factory) CreateRaftBuilder(raftConsensus interfaces.Consensus) *ConsensusBuilder

CreateRaftBuilder creates a pre-configured builder for Raft consensus Users must provide their own Raft implementation

func (*Factory) StartConsensus

func (f *Factory) StartConsensus(ctx context.Context, builder *ConsensusBuilder) (interfaces.Consensus, error)

StartConsensus is a convenience method to build and start consensus in one call

type HashAlgorithm

type HashAlgorithm string

HashAlgorithm represents the hash algorithm to use

const (
	HashAlgorithmSHA256      HashAlgorithm = "sha256"      // SHA-256
	HashAlgorithmSHA3        HashAlgorithm = "sha3"        // SHA-3 (Keccak)
	HashAlgorithmBlake2b     HashAlgorithm = "blake2b"     // Blake2b
	HashAlgorithmBlake2s     HashAlgorithm = "blake2s"     // Blake2s
	HashAlgorithmBlake3      HashAlgorithm = "blake3"      // Blake3
	HashAlgorithmScrypt      HashAlgorithm = "scrypt"      // Scrypt
	HashAlgorithmArgon2      HashAlgorithm = "argon2"      // Argon2
	HashAlgorithmEthash      HashAlgorithm = "ethash"      // Ethash (Ethereum)
	HashAlgorithmRandomX     HashAlgorithm = "randomx"     // RandomX (Monero)
	HashAlgorithmCryptonight HashAlgorithm = "cryptonight" // Cryptonight
	HashAlgorithmCustom      HashAlgorithm = "custom"      // Custom hash algorithm
)

type NetworkType

type NetworkType string

NetworkType represents the type of network protocol

const (
	NetworkTypeP2P    NetworkType = "p2p"    // Peer-to-peer network
	NetworkTypeLocal  NetworkType = "local"  // Local/in-process network
	NetworkTypeMemory NetworkType = "memory" // In-memory network for testing
	NetworkTypeCustom NetworkType = "custom" // Custom network implementation
)

type PresetConfiguration

type PresetConfiguration string

PresetConfiguration represents predefined configuration presets

const (
	PresetPoW         PresetConfiguration = "pow"         // Default PoW configuration
	PresetPoS         PresetConfiguration = "pos"         // Default PoS configuration
	PresetProduction  PresetConfiguration = "production"  // Production-ready configuration
	PresetDevelopment PresetConfiguration = "development" // Development configuration
	PresetTesting     PresetConfiguration = "testing"     // Testing configuration
	PresetBenchmark   PresetConfiguration = "benchmark"   // Benchmarking configuration
)

type StorageType

type StorageType string

StorageType represents the type of storage backend

const (
	StorageTypeMemory     StorageType = "memory"     // In-memory storage
	StorageTypePersistent StorageType = "persistent" // Persistent disk storage
	StorageTypeLevelDB    StorageType = "leveldb"    // LevelDB storage
	StorageTypeBadgerDB   StorageType = "badgerdb"   // BadgerDB storage
	StorageTypeRocksDB    StorageType = "rocksdb"    // RocksDB storage
	StorageTypeCustom     StorageType = "custom"     // Custom storage implementation
)

type ValidationMode

type ValidationMode string

ValidationMode represents the validation execution mode

const (
	ValidationModeSequential ValidationMode = "sequential" // Validators run one after another
	ValidationModeParallel   ValidationMode = "parallel"   // Validators run concurrently
)

type WorkerType

type WorkerType string

WorkerType represents the type of worker implementation

const (
	WorkerTypeCPU         WorkerType = "cpu"         // CPU-based worker
	WorkerTypeGPU         WorkerType = "gpu"         // GPU-based worker
	WorkerTypeASIC        WorkerType = "asic"        // ASIC-based worker
	WorkerTypeFPGA        WorkerType = "fpga"        // FPGA-based worker
	WorkerTypeDistributed WorkerType = "distributed" // Distributed worker
	WorkerTypeCustom      WorkerType = "custom"      // Custom worker implementation
)

Jump to

Keyboard shortcuts

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