Documentation
¶
Overview ¶
Package network - Audit logging for security and compliance
Package network - Secure channel with authenticated encryption ¶
Package network - Message serialization and handling ¶
Package network provides secure P2P networking for MPC-TSS protocols ¶
Package network - Rate limiting and DoS protection ¶
Package network - Production-grade TLS 1.3 configuration ¶
Package network - TLS-based P2P transport implementation
Index ¶
- Constants
- Variables
- func DecodePayload(payload []byte, data interface{}) error
- func DefaultProductionTLSConfig(certPath, keyPath, caCertPath string) (*tls.Config, error)
- func DeriveSessionKey(sharedSecret, sessionID []byte) ([]byte, error)
- func EncodePayload(data interface{}) ([]byte, error)
- func GenerateSelfSignedCert(certPath, keyPath string, hosts []string, validFor time.Duration) error
- func GenerateSharedSecret() ([]byte, error)
- func InsecureDevTLSConfig() *tls.Config
- func NewProductionTLSConfig(params TLSConfigParams) (*tls.Config, error)
- func ValidateMessage(msg *Message, maxPayloadSize int) error
- func ValidateTLSConfig(config *tls.Config) error
- type AESGCMChannel
- func (c *AESGCMChannel) Close()
- func (c *AESGCMChannel) ComputeMAC(data []byte) []byte
- func (c *AESGCMChannel) Decrypt(ciphertext []byte) ([]byte, error)
- func (c *AESGCMChannel) Encrypt(plaintext []byte) ([]byte, error)
- func (c *AESGCMChannel) KeyVersion() uint32
- func (c *AESGCMChannel) LastRotation() time.Time
- func (c *AESGCMChannel) RotateKeys() error
- func (c *AESGCMChannel) VerifyMAC(data, expectedMAC []byte) bool
- type AdaptiveRateLimiter
- type AuditEntry
- type AuditLogger
- func (al *AuditLogger) Close() error
- func (al *AuditLogger) GetStats() (*AuditStats, error)
- func (al *AuditLogger) LogAuthenticationFailure(localParty, remoteParty int, reason string)
- func (al *AuditLogger) LogConnectionEstablished(localParty, remoteParty int, tlsVersion uint16)
- func (al *AuditLogger) LogConnectionFailed(localParty, remoteParty int, err error)
- func (al *AuditLogger) LogEncryptionError(localParty, remoteParty int, err error)
- func (al *AuditLogger) LogKeyRotation(localParty, remoteParty int, keyVersion uint32)
- func (al *AuditLogger) LogMessageReceived(msg *Message, fromParty int)
- func (al *AuditLogger) LogMessageSent(msg *Message, toParty int)
- func (al *AuditLogger) LogRateLimitExceeded(localParty, remoteParty int)
- func (al *AuditLogger) LogReplayAttackDetected(localParty, remoteParty int, sessionID []byte)
- func (al *AuditLogger) LogSecurityEvent(eventType string, partyID int, details map[string]interface{})
- func (al *AuditLogger) Rotate() error
- type AuditStats
- type ConnectionManager
- type ConnectionThrottler
- type HandlerFunc
- type Message
- type MessageHandler
- type MessageHeader
- type MessageType
- type NetworkMetrics
- type P2PNetwork
- type PeerInfo
- type RateLimitManager
- type RateLimitStats
- type SecureChannel
- type Session
- type TLSConfigParams
- type TLSTransport
- func (t *TLSTransport) Broadcast(ctx context.Context, msg *Message) error
- func (t *TLSTransport) GetMetrics() *NetworkMetrics
- func (t *TLSTransport) GetPeerInfo(partyID int) (*PeerInfo, error)
- func (t *TLSTransport) IsConnected(partyID int) bool
- func (t *TLSTransport) LocalPartyID() int
- func (t *TLSTransport) PeerCount() int
- func (t *TLSTransport) Receive(ctx context.Context) (*Message, error)
- func (t *TLSTransport) RegisterHandler(msgType MessageType, handler HandlerFunc) error
- func (t *TLSTransport) Send(ctx context.Context, partyID int, msg *Message) error
- func (t *TLSTransport) SetRateLimit(partyID int, messagesPerSecond int) error
- func (t *TLSTransport) Start(ctx context.Context) error
- func (t *TLSTransport) Stop(ctx context.Context) error
- func (t *TLSTransport) UnregisterHandler(msgType MessageType) error
- type Transport
- type TransportConfig
Constants ¶
const ( // CurrentProtocolVersion is the current protocol version CurrentProtocolVersion uint16 = 1 // HeaderSize is the fixed size of the message header HeaderSize = 2 + 1 + 4 + 4 + 8 + 8 + 2 + 4 + 2 // 35 bytes // MaxNonceSize is the maximum nonce size MaxNonceSize = 32 // MaxMACSize is the maximum MAC size MaxMACSize = 64 )
Variables ¶
var ( // ErrInvalidPartyID is returned when party ID is invalid ErrInvalidPartyID = errors.New("invalid party ID") // ErrInvalidPartyCount is returned when party count is invalid ErrInvalidPartyCount = errors.New("invalid party count") // ErrInvalidConfig is returned when configuration is invalid ErrInvalidConfig = errors.New("invalid configuration") // ErrInvalidPeerAddrs is returned when peer addresses are invalid ErrInvalidPeerAddrs = errors.New("invalid peer addresses") // ErrInvalidListenAddr is returned when listen address is invalid ErrInvalidListenAddr = errors.New("invalid listen address") // ErrInvalidPeerAddr is returned when a peer address is invalid ErrInvalidPeerAddr = errors.New("invalid peer address") // ErrSelfConnection is returned when trying to connect to self ErrSelfConnection = errors.New("cannot connect to self") // ErrNotConnected is returned when peer is not connected ErrNotConnected = errors.New("peer not connected") // ErrAlreadyConnected is returned when peer is already connected ErrAlreadyConnected = errors.New("peer already connected") // ErrConnectionFailed is returned when connection fails ErrConnectionFailed = errors.New("connection failed") // ErrSendFailed is returned when message send fails ErrSendFailed = errors.New("failed to send message") // ErrReceiveFailed is returned when message receive fails ErrReceiveFailed = errors.New("failed to receive message") // ErrMessageTooLarge is returned when message exceeds size limit ErrMessageTooLarge = errors.New("message too large") // ErrInvalidMessage is returned when message is malformed ErrInvalidMessage = errors.New("invalid message") // ErrInvalidMAC is returned when MAC verification fails ErrInvalidMAC = errors.New("invalid message authentication code") // ErrTimeout is returned when operation times out ErrTimeout = errors.New("operation timeout") // ErrRateLimited is returned when rate limit is exceeded ErrRateLimited = errors.New("rate limit exceeded") // ErrHandlerNotFound is returned when no handler is registered ErrHandlerNotFound = errors.New("handler not found for message type") // ErrHandlerAlreadyRegistered is returned when handler already exists ErrHandlerAlreadyRegistered = errors.New("handler already registered") // ErrSessionNotFound is returned when session doesn't exist ErrSessionNotFound = errors.New("session not found") // ErrSessionExpired is returned when session has expired ErrSessionExpired = errors.New("session expired") // ErrEncryptionFailed is returned when encryption fails ErrEncryptionFailed = errors.New("encryption failed") // ErrDecryptionFailed is returned when decryption fails ErrDecryptionFailed = errors.New("decryption failed") // ErrInvalidNonce is returned when nonce is invalid or reused ErrInvalidNonce = errors.New("invalid or reused nonce") // ErrInvalidSequence is returned when sequence number is invalid ErrInvalidSequence = errors.New("invalid sequence number") // ErrReplayAttack is returned when replay attack is detected ErrReplayAttack = errors.New("replay attack detected") // ErrTransportClosed is returned when transport is closed ErrTransportClosed = errors.New("transport closed") // ErrShutdown is returned when shutting down ErrShutdown = errors.New("shutting down") // ErrPeerTimeout is returned when peer doesn't respond ErrPeerTimeout = errors.New("peer timeout") // ErrTLSHandshakeFailed is returned when TLS handshake fails ErrTLSHandshakeFailed = errors.New("TLS handshake failed") // ErrInvalidCertificate is returned when certificate is invalid ErrInvalidCertificate = errors.New("invalid certificate") // ErrBufferFull is returned when message buffer is full ErrBufferFull = errors.New("message buffer full") )
Functions ¶
func DecodePayload ¶
DecodePayload decodes payload into data
func DefaultProductionTLSConfig ¶
DefaultProductionTLSConfig creates a default production TLS config with commonly used settings for MPC-TSS deployments
func DeriveSessionKey ¶
DeriveSessionKey derives a session-specific key from a shared secret
func EncodePayload ¶
EncodePayload encodes arbitrary data into payload
func GenerateSelfSignedCert ¶
GenerateSelfSignedCert generates a self-signed certificate for testing DO NOT USE IN PRODUCTION - use proper CA-signed certificates
Parameters:
- certPath: Where to save the certificate PEM file
- keyPath: Where to save the private key PEM file
- hosts: List of hostnames/IPs (e.g., []string{"localhost", "127.0.0.1"})
- validFor: Certificate validity duration (e.g., 365*24*time.Hour for 1 year)
Example:
err := GenerateSelfSignedCert("cert.pem", "key.pem",
[]string{"localhost", "127.0.0.1"}, 365*24*time.Hour)
func GenerateSharedSecret ¶
GenerateSharedSecret generates a shared secret for a session
func InsecureDevTLSConfig ¶
InsecureDevTLSConfig creates a TLS config for DEVELOPMENT/TESTING ONLY DO NOT USE IN PRODUCTION - skips certificate validation
func NewProductionTLSConfig ¶
func NewProductionTLSConfig(params TLSConfigParams) (*tls.Config, error)
NewProductionTLSConfig creates a production-grade TLS 1.3 configuration with Perfect Forward Secrecy and certificate validation
Features: - TLS 1.3 only (downgrade attacks prevented) - Perfect Forward Secrecy (PFS) cipher suites - Certificate validation with CA verification - Mutual TLS (mTLS) authentication - Session resumption with tickets - Certificate pinning support - No weak ciphers or protocols
Security: This configuration meets industry best practices for cryptographic transport security as of 2025.
func ValidateMessage ¶
ValidateMessage validates message fields
func ValidateTLSConfig ¶
ValidateTLSConfig validates a TLS configuration for security Returns an error if the configuration is insecure
Types ¶
type AESGCMChannel ¶
type AESGCMChannel struct {
// contains filtered or unexported fields
}
AESGCMChannel implements SecureChannel using AES-256-GCM
func NewAESGCMChannel ¶
func NewAESGCMChannel(masterKey []byte) (*AESGCMChannel, error)
NewAESGCMChannel creates a new AES-GCM secure channel
func (*AESGCMChannel) Close ¶
func (c *AESGCMChannel) Close()
Close securely erases all key material
func (*AESGCMChannel) ComputeMAC ¶
func (c *AESGCMChannel) ComputeMAC(data []byte) []byte
ComputeMAC computes HMAC-SHA256 for a message
func (*AESGCMChannel) Decrypt ¶
func (c *AESGCMChannel) Decrypt(ciphertext []byte) ([]byte, error)
Decrypt decrypts and verifies ciphertext
func (*AESGCMChannel) Encrypt ¶
func (c *AESGCMChannel) Encrypt(plaintext []byte) ([]byte, error)
Encrypt encrypts and authenticates plaintext Format: version(4) || nonce(12) || ciphertext || tag(16)
func (*AESGCMChannel) KeyVersion ¶
func (c *AESGCMChannel) KeyVersion() uint32
KeyVersion returns the current key version
func (*AESGCMChannel) LastRotation ¶
func (c *AESGCMChannel) LastRotation() time.Time
LastRotation returns when keys were last rotated
func (*AESGCMChannel) RotateKeys ¶
func (c *AESGCMChannel) RotateKeys() error
RotateKeys generates new encryption keys
func (*AESGCMChannel) VerifyMAC ¶
func (c *AESGCMChannel) VerifyMAC(data, expectedMAC []byte) bool
VerifyMAC verifies HMAC-SHA256 for a message
type AdaptiveRateLimiter ¶
type AdaptiveRateLimiter struct {
// contains filtered or unexported fields
}
AdaptiveRateLimiter implements adaptive rate limiting based on network conditions
func NewAdaptiveRateLimiter ¶
func NewAdaptiveRateLimiter(baseRate, minRate, maxRate int) *AdaptiveRateLimiter
NewAdaptiveRateLimiter creates a new adaptive rate limiter
func (*AdaptiveRateLimiter) CurrentRate ¶
func (arl *AdaptiveRateLimiter) CurrentRate() int
CurrentRate returns the current rate
func (*AdaptiveRateLimiter) RecordError ¶
func (arl *AdaptiveRateLimiter) RecordError()
RecordError records a failed message
func (*AdaptiveRateLimiter) RecordSuccess ¶
func (arl *AdaptiveRateLimiter) RecordSuccess()
RecordSuccess records a successful message
type AuditEntry ¶
type AuditEntry struct {
Timestamp time.Time `json:"timestamp"`
EventType string `json:"event_type"`
PartyID int `json:"party_id"`
RemoteParty int `json:"remote_party,omitempty"`
MessageType MessageType `json:"message_type,omitempty"`
SessionID string `json:"session_id,omitempty"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Details map[string]interface{} `json:"details,omitempty"`
}
AuditEntry represents a single audit log entry
type AuditLogger ¶
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger provides secure audit logging
func NewAuditLogger ¶
func NewAuditLogger(filePath string) (*AuditLogger, error)
NewAuditLogger creates a new audit logger
func (*AuditLogger) GetStats ¶
func (al *AuditLogger) GetStats() (*AuditStats, error)
GetStats returns statistics about the audit log
func (*AuditLogger) LogAuthenticationFailure ¶
func (al *AuditLogger) LogAuthenticationFailure(localParty, remoteParty int, reason string)
LogAuthenticationFailure logs an authentication failure
func (*AuditLogger) LogConnectionEstablished ¶
func (al *AuditLogger) LogConnectionEstablished(localParty, remoteParty int, tlsVersion uint16)
LogConnectionEstablished logs a new connection
func (*AuditLogger) LogConnectionFailed ¶
func (al *AuditLogger) LogConnectionFailed(localParty, remoteParty int, err error)
LogConnectionFailed logs a failed connection attempt
func (*AuditLogger) LogEncryptionError ¶
func (al *AuditLogger) LogEncryptionError(localParty, remoteParty int, err error)
LogEncryptionError logs an encryption/decryption error
func (*AuditLogger) LogKeyRotation ¶
func (al *AuditLogger) LogKeyRotation(localParty, remoteParty int, keyVersion uint32)
LogKeyRotation logs a key rotation event
func (*AuditLogger) LogMessageReceived ¶
func (al *AuditLogger) LogMessageReceived(msg *Message, fromParty int)
LogMessageReceived logs a received message
func (*AuditLogger) LogMessageSent ¶
func (al *AuditLogger) LogMessageSent(msg *Message, toParty int)
LogMessageSent logs a sent message
func (*AuditLogger) LogRateLimitExceeded ¶
func (al *AuditLogger) LogRateLimitExceeded(localParty, remoteParty int)
LogRateLimitExceeded logs a rate limit violation
func (*AuditLogger) LogReplayAttackDetected ¶
func (al *AuditLogger) LogReplayAttackDetected(localParty, remoteParty int, sessionID []byte)
LogReplayAttackDetected logs a detected replay attack
func (*AuditLogger) LogSecurityEvent ¶
func (al *AuditLogger) LogSecurityEvent(eventType string, partyID int, details map[string]interface{})
LogSecurityEvent logs a generic security event
func (*AuditLogger) Rotate ¶
func (al *AuditLogger) Rotate() error
Rotate rotates the audit log file
type AuditStats ¶
AuditStats contains audit log statistics
type ConnectionManager ¶
type ConnectionManager interface {
// Connect establishes a connection to a peer
Connect(ctx context.Context, partyID int, addr string) error
// Disconnect closes a connection to a peer
Disconnect(ctx context.Context, partyID int) error
// GetConnection returns the connection for a party
GetConnection(partyID int) (net.Conn, error)
// IsConnected checks if connected to a party
IsConnected(partyID int) bool
// ConnectedPeers returns list of connected party IDs
ConnectedPeers() []int
// WaitForPeers waits for a minimum number of peers
WaitForPeers(ctx context.Context, minPeers int) error
}
ConnectionManager manages peer connections
type ConnectionThrottler ¶
type ConnectionThrottler struct {
// contains filtered or unexported fields
}
ConnectionThrottler prevents connection flooding
func NewConnectionThrottler ¶
func NewConnectionThrottler(maxAttempts int, window time.Duration) *ConnectionThrottler
NewConnectionThrottler creates a new connection throttler
func (*ConnectionThrottler) AllowConnection ¶
func (ct *ConnectionThrottler) AllowConnection(addr string) bool
AllowConnection checks if a connection from an address is allowed
func (*ConnectionThrottler) Cleanup ¶
func (ct *ConnectionThrottler) Cleanup()
Cleanup removes old connection attempts
type HandlerFunc ¶
HandlerFunc is called when a message of a specific type is received
type Message ¶
type Message struct {
// Type identifies the message type
Type MessageType
// From is the sender party ID
From int
// To is the recipient party ID (-1 for broadcast)
To int
// SessionID uniquely identifies the protocol session
SessionID []byte
// Payload is the encrypted message payload
Payload []byte
// MAC is the message authentication code
MAC []byte
// Timestamp is when the message was created
Timestamp time.Time
// Nonce is a unique nonce for this message
Nonce []byte
// Sequence number for ordering
Sequence uint64
}
Message represents a network message
func DeserializeMessage ¶
Deserialize deserializes a message from bytes
func NewMessage ¶
func NewMessage(msgType MessageType, from, to int, sessionID, payload []byte) (*Message, error)
NewMessage creates a new message
type MessageHandler ¶
type MessageHandler interface {
// HandleMessage processes a received message
HandleMessage(ctx context.Context, msg *Message) error
// HandleError processes errors
HandleError(ctx context.Context, err error, msg *Message)
}
MessageHandler processes incoming messages
type MessageHeader ¶
type MessageHeader struct {
Version uint16
Type MessageType
From int32
To int32
Sequence uint64
Timestamp int64
NonceSize uint16
PayloadSize uint32
MACSize uint16
}
MessageHeader contains message metadata
type MessageType ¶
type MessageType uint8
MessageType identifies the type of message being sent
const ( // MessageTypeDKGRound1 is for DKG round 1 messages MessageTypeDKGRound1 MessageType = iota // MessageTypeDKGRound2 is for DKG round 2 messages MessageTypeDKGRound2 // MessageTypeDKGRound3 is for DKG round 3 messages MessageTypeDKGRound3 // MessageTypeSignRound1 is for signing round 1 messages MessageTypeSignRound1 // MessageTypeSignRound2 is for signing round 2 messages MessageTypeSignRound2 // MessageTypeSignRound3 is for signing round 3 messages MessageTypeSignRound3 // MessageTypeSignRound4 is for signing round 4 messages MessageTypeSignRound4 // MessageTypePreSignRound1 is for presigning round 1 messages MessageTypePreSignRound1 // MessageTypePreSignRound2 is for presigning round 2 messages MessageTypePreSignRound2 // MessageTypeHeartbeat is for keepalive messages MessageTypeHeartbeat // MessageTypeAck is for acknowledgments MessageTypeAck // MessageTypeError is for error notifications MessageTypeError )
func (MessageType) IsProtocolMessage ¶
func (mt MessageType) IsProtocolMessage() bool
IsProtocolMessage returns true if message is part of core protocol
func (MessageType) String ¶
func (mt MessageType) String() string
String returns a string representation of message type
type NetworkMetrics ¶
type NetworkMetrics struct {
// Total messages sent/received
MessagesSent uint64
MessagesReceived uint64
// Total bytes sent/received
BytesSent uint64
BytesReceived uint64
// Connection metrics
ActiveConnections int
TotalConnections uint64
FailedConnections uint64
// Error counters
SendErrors uint64
ReceiveErrors uint64
TimeoutErrors uint64
// Rate limiting
RateLimitedMessages uint64
// Latency statistics
AverageLatency time.Duration
MinLatency time.Duration
MaxLatency time.Duration
// Uptime
Uptime time.Duration
}
NetworkMetrics contains network performance metrics
type P2PNetwork ¶
type P2PNetwork interface {
Transport
// RegisterHandler registers a handler for a specific message type
RegisterHandler(msgType MessageType, handler HandlerFunc) error
// UnregisterHandler removes a handler for a message type
UnregisterHandler(msgType MessageType) error
// SetRateLimit sets the rate limit for a specific party
SetRateLimit(partyID int, messagesPerSecond int) error
// GetPeerInfo returns information about a peer
GetPeerInfo(partyID int) (*PeerInfo, error)
// GetMetrics returns network metrics
GetMetrics() *NetworkMetrics
}
P2PNetwork provides peer-to-peer networking functionality
type PeerInfo ¶
type PeerInfo struct {
PartyID int
Address string
Connected bool
LastSeen time.Time
MessagesSent uint64
MessagesRecv uint64
BytesSent uint64
BytesRecv uint64
Latency time.Duration
TLSVersion uint16
CipherSuite uint16
}
PeerInfo contains information about a connected peer
type RateLimitManager ¶
type RateLimitManager struct {
// contains filtered or unexported fields
}
RateLimitManager manages rate limiters for multiple peers
func NewRateLimitManager ¶
func NewRateLimitManager() *RateLimitManager
NewRateLimitManager creates a new rate limit manager
func (*RateLimitManager) CheckLimit ¶
func (rlm *RateLimitManager) CheckLimit(partyID int) bool
CheckLimit checks if a message from a party is allowed
func (*RateLimitManager) GetStats ¶
func (rlm *RateLimitManager) GetStats() map[int]*RateLimitStats
GetStats returns rate limiting statistics
func (*RateLimitManager) RemoveLimit ¶
func (rlm *RateLimitManager) RemoveLimit(partyID int)
RemoveLimit removes the rate limit for a party
func (*RateLimitManager) ResetLimit ¶
func (rlm *RateLimitManager) ResetLimit(partyID int)
ResetLimit resets the rate limiter for a party
func (*RateLimitManager) SetLimit ¶
func (rlm *RateLimitManager) SetLimit(partyID, messagesPerSecond int)
SetLimit sets the rate limit for a specific party
type RateLimitStats ¶
type RateLimitStats struct {
PartyID int
Rate int
Burst int
AvailableTokens int
LastUpdate time.Time
}
RateLimitStats contains rate limiting statistics
type SecureChannel ¶
type SecureChannel interface {
// Encrypt encrypts and authenticates a message
Encrypt(plaintext []byte) (ciphertext []byte, err error)
// Decrypt decrypts and verifies a message
Decrypt(ciphertext []byte) (plaintext []byte, err error)
// RotateKeys rotates encryption keys
RotateKeys() error
}
SecureChannel provides encrypted and authenticated communication
type Session ¶
type Session struct {
// SessionID uniquely identifies this session
SessionID []byte
// PartyID is the remote party's ID
PartyID int
// LocalPartyID is this party's ID
LocalPartyID int
SharedSecret []byte
// Created timestamp
Created time.Time
// LastActivity timestamp
LastActivity time.Time
// Sequence number for message ordering
SendSequence uint64
RecvSequence uint64
// Connection state
Conn net.Conn
// TLS connection state
TLSState *tls.ConnectionState
}
Session represents a network session with security context
type TLSConfigParams ¶
type TLSConfigParams struct {
// Certificate and key paths
CertPath string
KeyPath string
// CA certificate path for peer verification
CACertPath string
// Server name for SNI (Server Name Indication)
ServerName string
// Enable mutual TLS (both parties authenticate)
EnableMutualTLS bool
// Enable strict certificate validation
StrictValidation bool
// Minimum TLS version (default: TLS 1.3)
MinVersion uint16
// Session ticket key (32 bytes) for session resumption
// Leave nil to disable session tickets
SessionTicketKey []byte
// Enable certificate pinning (provide expected cert fingerprints)
PinnedCertificates [][]byte
}
TLSConfig parameters for secure connections
type TLSTransport ¶
type TLSTransport struct {
// contains filtered or unexported fields
}
TLSTransport implements secure P2P transport using TLS 1.3
func NewTLSTransport ¶
func NewTLSTransport(config *TransportConfig) (*TLSTransport, error)
NewTLSTransport creates a new TLS transport
func (*TLSTransport) Broadcast ¶
func (t *TLSTransport) Broadcast(ctx context.Context, msg *Message) error
Broadcast sends a message to all parties
func (*TLSTransport) GetMetrics ¶
func (t *TLSTransport) GetMetrics() *NetworkMetrics
GetMetrics returns network metrics
func (*TLSTransport) GetPeerInfo ¶
func (t *TLSTransport) GetPeerInfo(partyID int) (*PeerInfo, error)
GetPeerInfo returns information about a peer
func (*TLSTransport) IsConnected ¶
func (t *TLSTransport) IsConnected(partyID int) bool
IsConnected checks if a specific party is connected
func (*TLSTransport) LocalPartyID ¶
func (t *TLSTransport) LocalPartyID() int
LocalPartyID returns this party's ID
func (*TLSTransport) PeerCount ¶
func (t *TLSTransport) PeerCount() int
PeerCount returns the number of connected peers
func (*TLSTransport) Receive ¶
func (t *TLSTransport) Receive(ctx context.Context) (*Message, error)
Receive receives a message from any party
func (*TLSTransport) RegisterHandler ¶
func (t *TLSTransport) RegisterHandler(msgType MessageType, handler HandlerFunc) error
RegisterHandler registers a message handler
func (*TLSTransport) SetRateLimit ¶
func (t *TLSTransport) SetRateLimit(partyID int, messagesPerSecond int) error
SetRateLimit sets the rate limit for a party
func (*TLSTransport) Start ¶
func (t *TLSTransport) Start(ctx context.Context) error
Start starts the transport
func (*TLSTransport) Stop ¶
func (t *TLSTransport) Stop(ctx context.Context) error
Stop stops the transport
func (*TLSTransport) UnregisterHandler ¶
func (t *TLSTransport) UnregisterHandler(msgType MessageType) error
UnregisterHandler removes a message handler
type Transport ¶
type Transport interface {
// Start initializes and starts the transport
Start(ctx context.Context) error
// Stop gracefully shuts down the transport
Stop(ctx context.Context) error
// Send sends a message to a specific party
Send(ctx context.Context, partyID int, msg *Message) error
// Broadcast sends a message to all parties
Broadcast(ctx context.Context, msg *Message) error
// Receive receives a message from any party
Receive(ctx context.Context) (*Message, error)
// LocalPartyID returns this party's ID
LocalPartyID() int
// PeerCount returns the number of connected peers
PeerCount() int
// IsConnected checks if a specific party is connected
IsConnected(partyID int) bool
}
Transport defines the interface for network transport
type TransportConfig ¶
type TransportConfig struct {
// PartyID is this party's identifier
PartyID int
// TotalParties is the total number of parties
TotalParties int
// ListenAddr is the address to listen on
ListenAddr string
// PeerAddrs maps party IDs to their addresses
PeerAddrs map[int]string
// TLSConfig for secure connections
TLSConfig *tls.Config
// MaxMessageSize limits message size (default: 10MB)
MaxMessageSize int
// SendTimeout for send operations
SendTimeout time.Duration
// ReceiveTimeout for receive operations
ReceiveTimeout time.Duration
// ReconnectInterval for automatic reconnection
ReconnectInterval time.Duration
// MaxReconnectAttempts before giving up
MaxReconnectAttempts int
// EnableRateLimiting enables rate limiting
EnableRateLimiting bool
// DefaultRateLimit is messages per second per peer
DefaultRateLimit int
// BufferSize for message queues
BufferSize int
// EnableMetrics enables metrics collection
EnableMetrics bool
// EnableAuditLog enables audit logging
EnableAuditLog bool
// AuditLogPath is the path for audit logs
AuditLogPath string
}
TransportConfig configures the network transport
func DefaultTransportConfig ¶
func DefaultTransportConfig(partyID, totalParties int) *TransportConfig
DefaultTransportConfig returns a secure default configuration
func (*TransportConfig) Validate ¶
func (c *TransportConfig) Validate() error
Validate validates the transport configuration