Documentation
¶
Index ¶
- Constants
- Variables
- func IsRetryable(err error) bool
- func IsTemporary(err error) bool
- type AntiAbuseConfig
- type BlobManager
- func (bm *BlobManager) Close()
- func (bm *BlobManager) DeleteBlob(c cid.Cid)
- func (bm *BlobManager) GetBlob(ctx context.Context, c cid.Cid) ([]byte, error)
- func (bm *BlobManager) GetBlobStats() map[string]interface{}
- func (bm *BlobManager) HasBlob(c cid.Cid) bool
- func (bm *BlobManager) StoreBlob(ctx context.Context, data []byte) (cid.Cid, error)
- type BlobRequest
- type BlobResponse
- type CIDGenerator
- type CacheConfig
- type CacheEntry
- type Config
- type DHTConfig
- type GossipsubConfig
- type HTTPBridge
- type LRUCache
- func (c *LRUCache) Clear()
- func (c *LRUCache) Close()
- func (c *LRUCache) Delete(key string)
- func (c *LRUCache) Get(key string) ([]byte, bool)
- func (c *LRUCache) Has(key string) bool
- func (c *LRUCache) Set(key string, value []byte)
- func (c *LRUCache) Size() int
- func (c *LRUCache) Stats() map[string]interface{}
- type LogLevel
- type Logger
- func (l *Logger) Debug(msg string, fields ...map[string]interface{})
- func (l *Logger) Error(msg string, fields ...map[string]interface{})
- func (l *Logger) Fatal(msg string, fields ...map[string]interface{})
- func (l *Logger) Info(msg string, fields ...map[string]interface{})
- func (l *Logger) Warn(msg string, fields ...map[string]interface{})
- func (l *Logger) WithFields(fields map[string]interface{}) *LoggerContext
- func (l *Logger) WithPeer(peerID peer.ID) *LoggerContext
- func (l *Logger) WithTopic(topic string) *LoggerContext
- type LoggerContext
- func (lc *LoggerContext) Debug(msg string, fields ...map[string]interface{})
- func (lc *LoggerContext) Error(msg string, fields ...map[string]interface{})
- func (lc *LoggerContext) Fatal(msg string, fields ...map[string]interface{})
- func (lc *LoggerContext) Info(msg string, fields ...map[string]interface{})
- func (lc *LoggerContext) Warn(msg string, fields ...map[string]interface{})
- type NetworkStatusResponse
- type P2PError
- type P2PHost
- func (p *P2PHost) ConnectToPeer(ctx context.Context, addr multiaddr.Multiaddr) error
- func (p *P2PHost) FindProviders(ctx context.Context, c cid.Cid) ([]peer.AddrInfo, error)
- func (p *P2PHost) GetNetworkInfo() map[string]interface{}
- func (p *P2PHost) Provide(ctx context.Context, c cid.Cid) error
- func (p *P2PHost) Publish(ctx context.Context, topic string, data []byte) error
- func (p *P2PHost) Start(ctx context.Context) error
- func (p *P2PHost) Stop(ctx context.Context) error
- func (p *P2PHost) Subscribe(ctx context.Context, topic string) error
- type PeerLimit
- type ProvidersResponse
- type PublishRequest
- type PublishResponse
- type RateLimitConfig
- type RateLimiter
- type RequestQueue
- type TopicManager
- func (tm *TopicManager) GetCoreTopics() []string
- func (tm *TopicManager) GetEventTopics() []string
- func (tm *TopicManager) GetTopicPriority(topic string) int
- func (tm *TopicManager) GetTopicType(topic string) string
- func (tm *TopicManager) IsValidTopic(topic string) bool
- func (tm *TopicManager) ValidateTopicMessage(topic string, data []byte) error
Constants ¶
const ( // Event topics TopicEventVouch = "events/vouch" TopicEventReport = "events/report" TopicEventAppeal = "events/appeal" // Revocation topics (pattern-based) TopicRevocationPrefix = "revocations/" // Rules topics TopicRulesActive = "rules/active" // Checkpoint topics TopicCheckpointsEpoch = "checkpoints/epoch" // Blob topics (pattern-based) TopicBlobPrefix = "blobs/" )
Topic names as defined in the architecture
Variables ¶
var ( // ErrNodeNotStarted indicates the P2P node is not started ErrNodeNotStarted = errors.New("p2p node not started") // ErrNodeAlreadyStarted indicates the P2P node is already started ErrNodeAlreadyStarted = errors.New("p2p node already started") // ErrInvalidTopic indicates an invalid topic name ErrInvalidTopic = errors.New("invalid topic name") // ErrTopicNotSubscribed indicates not subscribed to the topic ErrTopicNotSubscribed = errors.New("not subscribed to topic") // ErrMessageTooLarge indicates the message exceeds size limits ErrMessageTooLarge = errors.New("message too large") // ErrPeerNotFound indicates the peer was not found ErrPeerNotFound = errors.New("peer not found") // ErrRateLimited indicates the operation is rate limited ErrRateLimited = errors.New("rate limited") // ErrPeerGreylisted indicates the peer is greylisted ErrPeerGreylisted = errors.New("peer greylisted") // ErrInvalidMessage indicates the message format is invalid ErrInvalidMessage = errors.New("invalid message format") // ErrProviderNotFound indicates no providers found for CID ErrProviderNotFound = errors.New("no providers found for CID") // ErrDHTNotReady indicates the DHT is not ready ErrDHTNotReady = errors.New("DHT not ready") // ErrConnectionFailed indicates connection to peer failed ErrConnectionFailed = errors.New("connection to peer failed") // ErrCacheMiss indicates requested item not found in cache ErrCacheMiss = errors.New("cache miss") // ErrInvalidCID indicates invalid content identifier ErrInvalidCID = errors.New("invalid CID") // ErrSubscriptionClosed indicates pubsub subscription was closed ErrSubscriptionClosed = errors.New("subscription closed") // ErrBlobFetchTimeout indicates blob fetch operation timed out ErrBlobFetchTimeout = errors.New("blob fetch timeout") // ErrValidationFailed indicates message validation failed ErrValidationFailed = errors.New("message validation failed") // ErrNetworkNotReady indicates the network is not ready ErrNetworkNotReady = errors.New("network not ready") )
Functions ¶
Types ¶
type AntiAbuseConfig ¶
type AntiAbuseConfig struct {
// Greylist settings
GreylistDuration time.Duration `json:"greylist_duration"` // default: 10m
GreylistThreshold int `json:"greylist_threshold"` // default: 10 violations
// Message validation
MaxMessageSize int `json:"max_message_size"` // default: 16KB
// Proof-of-work for reports (optional)
EnablePoW bool `json:"enable_pow"` // default: false
PoWDifficulty int `json:"pow_difficulty"` // default: 20 (bits)
}
AntiAbuseConfig contains anti-abuse settings
type BlobManager ¶
type BlobManager struct {
// contains filtered or unexported fields
}
BlobManager handles blob storage, retrieval, and caching via DHT
func NewBlobManager ¶
func NewBlobManager(p2pHost *P2PHost, cacheSize int, cacheTTL time.Duration) *BlobManager
NewBlobManager creates a new blob manager
func (*BlobManager) DeleteBlob ¶
func (bm *BlobManager) DeleteBlob(c cid.Cid)
DeleteBlob removes a blob from local cache
func (*BlobManager) GetBlobStats ¶
func (bm *BlobManager) GetBlobStats() map[string]interface{}
GetBlobStats returns blob cache statistics
type BlobRequest ¶
type BlobRequest struct {
CID cid.Cid `json:"cid"`
Requester peer.ID `json:"requester"`
Priority int `json:"priority"`
Timestamp time.Time `json:"timestamp"`
}
BlobRequest represents a request for blob content
type BlobResponse ¶
type BlobResponse struct {
CID cid.Cid `json:"cid"`
Data []byte `json:"data"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
BlobResponse represents a response with blob content
type CIDGenerator ¶
type CIDGenerator struct{}
CIDGenerator is a placeholder for the CID generator from internal/cid
func (*CIDGenerator) GenerateFromBytes ¶
func (g *CIDGenerator) GenerateFromBytes(data []byte) (cid.Cid, error)
GenerateFromBytes generates a CID from bytes (placeholder implementation)
type CacheConfig ¶
type CacheConfig struct {
// Blob cache
BlobCacheSize int `json:"blob_cache_size"` // default: 1000
BlobCacheTTL time.Duration `json:"blob_cache_ttl"` // default: 10m
// Checkpoint cache
CheckpointCacheSize int `json:"checkpoint_cache_size"` // default: 100
CheckpointCacheTTL time.Duration `json:"checkpoint_cache_ttl"` // default: 1h
// Peer info cache
PeerCacheSize int `json:"peer_cache_size"` // default: 10000
PeerCacheTTL time.Duration `json:"peer_cache_ttl"` // default: 30m
}
CacheConfig contains caching settings
type CacheEntry ¶
CacheEntry represents a cached item with TTL
func (*CacheEntry) IsExpired ¶
func (e *CacheEntry) IsExpired() bool
IsExpired checks if the cache entry has expired
type Config ¶
type Config struct {
// Host configuration
ListenAddrs []multiaddr.Multiaddr `json:"listen_addrs"`
BootstrapPeers []multiaddr.Multiaddr `json:"bootstrap_peers"`
// Gossipsub parameters (v1.1)
GossipsubConfig GossipsubConfig `json:"gossipsub"`
// DHT configuration
DHTConfig DHTConfig `json:"dht"`
// Rate limiting
RateLimit RateLimitConfig `json:"rate_limit"`
// Cache configuration
CacheConfig CacheConfig `json:"cache"`
// Anti-abuse settings
AntiAbuse AntiAbuseConfig `json:"anti_abuse"`
}
Config represents P2P node configuration
type DHTConfig ¶
type DHTConfig struct {
BootstrapTimeout time.Duration `json:"bootstrap_timeout"` // default: 30s
Mode string `json:"mode"` // "client", "server", "auto"
ProtocolPrefix string `json:"protocol_prefix"` // default: "/credence"
}
DHTConfig contains DHT-specific settings
type GossipsubConfig ¶
type GossipsubConfig struct {
// Mesh parameters
MeshN int `json:"mesh_n"` // Target mesh size (default: 8)
MeshNLow int `json:"mesh_n_low"` // Low watermark (default: 5)
MeshNHigh int `json:"mesh_n_high"` // High watermark (default: 12)
// Timing parameters
HeartbeatInterval time.Duration `json:"heartbeat_interval"` // default: 1s
// Score parameters
EnableScoring bool `json:"enable_scoring"` // default: true
}
GossipsubConfig contains gossipsub-specific settings
type HTTPBridge ¶
type HTTPBridge struct {
// contains filtered or unexported fields
}
HTTPBridge provides HTTP endpoints for internal services to interact with P2P
func NewHTTPBridge ¶
func NewHTTPBridge(p2pHost *P2PHost, listenAddr string) *HTTPBridge
NewHTTPBridge creates a new HTTP bridge
type LRUCache ¶
type LRUCache struct {
// contains filtered or unexported fields
}
LRUCache is a simple LRU cache with TTL support
func NewLRUCache ¶
NewLRUCache creates a new LRU cache
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger provides structured logging for P2P components
func (*Logger) WithFields ¶
func (l *Logger) WithFields(fields map[string]interface{}) *LoggerContext
WithFields creates logger context with default fields
func (*Logger) WithPeer ¶
func (l *Logger) WithPeer(peerID peer.ID) *LoggerContext
WithPeer creates logger context with peer information
func (*Logger) WithTopic ¶
func (l *Logger) WithTopic(topic string) *LoggerContext
WithTopic creates logger context with topic information
type LoggerContext ¶
type LoggerContext struct {
// contains filtered or unexported fields
}
LoggerContext provides logging with predefined fields
func (*LoggerContext) Debug ¶
func (lc *LoggerContext) Debug(msg string, fields ...map[string]interface{})
Debug logs debug message with context fields
func (*LoggerContext) Error ¶
func (lc *LoggerContext) Error(msg string, fields ...map[string]interface{})
Error logs error message with context fields
func (*LoggerContext) Fatal ¶
func (lc *LoggerContext) Fatal(msg string, fields ...map[string]interface{})
Fatal logs fatal message with context fields and exits
func (*LoggerContext) Info ¶
func (lc *LoggerContext) Info(msg string, fields ...map[string]interface{})
Info logs info message with context fields
func (*LoggerContext) Warn ¶
func (lc *LoggerContext) Warn(msg string, fields ...map[string]interface{})
Warn logs warning message with context fields
type NetworkStatusResponse ¶
type NetworkStatusResponse struct {
Status string `json:"status"`
PeerID string `json:"peer_id"`
ConnectedPeers int `json:"connected_peers"`
ListenAddrs []string `json:"listen_addrs"`
Topics []string `json:"topics"`
RateLimitStats map[string]interface{} `json:"rate_limit_stats"`
CacheStats map[string]interface{} `json:"cache_stats"`
}
NetworkStatusResponse represents network status information
type P2PError ¶
type P2PError struct {
Op string // Operation that failed
Err error // Underlying error
PeerID *peer.ID // Associated peer ID (if any)
Topic string // Associated topic (if any)
Context map[string]interface{} // Additional context
}
P2PError represents a P2P-specific error with context
func NewP2PError ¶
NewP2PError creates a new P2P error
func (*P2PError) WithContext ¶
WithContext adds arbitrary context to the error
type P2PHost ¶
type P2PHost struct {
// contains filtered or unexported fields
}
P2PHost manages the libp2p host and associated services
func (*P2PHost) ConnectToPeer ¶
ConnectToPeer connects to a specific peer
func (*P2PHost) FindProviders ¶
FindProviders finds providers for a CID using the DHT
func (*P2PHost) GetNetworkInfo ¶
GetNetworkInfo returns information about the network state
type PeerLimit ¶
type PeerLimit struct {
// Message count tracking
MessageCount int
ByteCount int64
ResetTime time.Time
// Violation tracking
Violations int
LastViolation time.Time
// Greylist status
IsGreylisted bool
GreylistUntil time.Time
}
PeerLimit tracks rate limiting data for a peer
type ProvidersResponse ¶
ProvidersResponse represents the response for provider queries
type PublishRequest ¶
type PublishRequest struct {
Topic string `json:"topic" validate:"required"`
Data []byte `json:"data" validate:"required"`
}
PublishRequest represents a message publish request
type PublishResponse ¶
type PublishResponse struct {
Success bool `json:"success"`
MessageID string `json:"message_id,omitempty"`
Error string `json:"error,omitempty"`
}
PublishResponse represents a message publish response
type RateLimitConfig ¶
type RateLimitConfig struct {
// Per-peer limits
PeerMsgPerMin int `json:"peer_msg_per_min"` // default: 60
PeerBytesPerSec int `json:"peer_bytes_per_sec"` // default: 1024
// Global limits
GlobalMsgPerSec int `json:"global_msg_per_sec"` // default: 1000
// Burst allowance
BurstMultiplier float64 `json:"burst_multiplier"` // default: 2.0
// Cleanup interval
CleanupInterval time.Duration `json:"cleanup_interval"` // default: 1m
}
RateLimitConfig contains rate limiting settings
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter manages rate limiting for peers and topics
func NewRateLimiter ¶
func NewRateLimiter(config *RateLimitConfig, antiAbuse *AntiAbuseConfig) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) AllowMessage ¶
AllowMessage checks if a message from a peer should be allowed
func (*RateLimiter) GetPeerStats ¶
func (rl *RateLimiter) GetPeerStats(peerID peer.ID) *PeerLimit
GetPeerStats returns rate limiting stats for a peer
func (*RateLimiter) GetStats ¶
func (rl *RateLimiter) GetStats() map[string]interface{}
GetStats returns overall rate limiting statistics
func (*RateLimiter) IsGreylisted ¶
func (rl *RateLimiter) IsGreylisted(peerID peer.ID) bool
IsGreylisted checks if a peer is greylisted
type RequestQueue ¶
type RequestQueue struct {
// contains filtered or unexported fields
}
RequestQueue manages queued blob requests
func NewRequestQueue ¶
func NewRequestQueue(maxSize int) *RequestQueue
NewRequestQueue creates a new request queue
func (*RequestQueue) Add ¶
func (rq *RequestQueue) Add(req BlobRequest)
Add adds a request to the queue
func (*RequestQueue) GetNext ¶
func (rq *RequestQueue) GetNext() *BlobRequest
GetNext returns the next request to process
type TopicManager ¶
type TopicManager struct {
// contains filtered or unexported fields
}
TopicManager manages topic subscriptions and validation
func NewTopicManager ¶
func NewTopicManager() *TopicManager
NewTopicManager creates a new topic manager
func (*TopicManager) GetCoreTopics ¶
func (tm *TopicManager) GetCoreTopics() []string
GetCoreTopics returns the core system topics
func (*TopicManager) GetEventTopics ¶
func (tm *TopicManager) GetEventTopics() []string
GetEventTopics returns all event-related topics
func (*TopicManager) GetTopicPriority ¶
func (tm *TopicManager) GetTopicPriority(topic string) int
GetTopicPriority returns the priority level for a topic (higher = more important)
func (*TopicManager) GetTopicType ¶
func (tm *TopicManager) GetTopicType(topic string) string
GetTopicType returns the category of a topic
func (*TopicManager) IsValidTopic ¶
func (tm *TopicManager) IsValidTopic(topic string) bool
IsValidTopic checks if a topic name is valid
func (*TopicManager) ValidateTopicMessage ¶
func (tm *TopicManager) ValidateTopicMessage(topic string, data []byte) error
ValidateTopicMessage performs basic validation on a topic message