p2p

package
v0.0.0-...-21e1f9a Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
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

func IsRetryable

func IsRetryable(err error) bool

IsRetryable determines if an error is retryable

func IsTemporary

func IsTemporary(err error) bool

IsTemporary determines if an error is temporary

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

func (bm *BlobManager) Close()

Close closes the blob manager

func (*BlobManager) DeleteBlob

func (bm *BlobManager) DeleteBlob(c cid.Cid)

DeleteBlob removes a blob from local cache

func (*BlobManager) GetBlob

func (bm *BlobManager) GetBlob(ctx context.Context, c cid.Cid) ([]byte, error)

GetBlob retrieves a blob by CID, first from cache, then from DHT

func (*BlobManager) GetBlobStats

func (bm *BlobManager) GetBlobStats() map[string]interface{}

GetBlobStats returns blob cache statistics

func (*BlobManager) HasBlob

func (bm *BlobManager) HasBlob(c cid.Cid) bool

HasBlob checks if a blob is available locally

func (*BlobManager) StoreBlob

func (bm *BlobManager) StoreBlob(ctx context.Context, data []byte) (cid.Cid, error)

StoreBlob stores a blob locally and announces it to the DHT

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

type CacheEntry struct {
	Value     []byte
	ExpiresAt time.Time
}

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

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default 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

func (*HTTPBridge) Start

func (b *HTTPBridge) Start(ctx context.Context) error

Start starts the HTTP bridge server

func (*HTTPBridge) Stop

func (b *HTTPBridge) Stop(ctx context.Context) error

Stop stops the HTTP bridge server

type LRUCache

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

LRUCache is a simple LRU cache with TTL support

func NewLRUCache

func NewLRUCache(maxSize int, ttl time.Duration) *LRUCache

NewLRUCache creates a new LRU cache

func (*LRUCache) Clear

func (c *LRUCache) Clear()

Clear removes all cache entries

func (*LRUCache) Close

func (c *LRUCache) Close()

Close stops the cache cleanup routine

func (*LRUCache) Delete

func (c *LRUCache) Delete(key string)

Delete removes a cache entry

func (*LRUCache) Get

func (c *LRUCache) Get(key string) ([]byte, bool)

Get retrieves a cache entry

func (*LRUCache) Has

func (c *LRUCache) Has(key string) bool

Has checks if a key exists in the cache

func (*LRUCache) Set

func (c *LRUCache) Set(key string, value []byte)

Set adds or updates a cache entry

func (*LRUCache) Size

func (c *LRUCache) Size() int

Size returns the current cache size

func (*LRUCache) Stats

func (c *LRUCache) Stats() map[string]interface{}

Stats returns cache statistics

type LogLevel

type LogLevel int

LogLevel represents logging levels

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
	LogLevelFatal
)

func (LogLevel) String

func (l LogLevel) String() string

String returns string representation of log level

type Logger

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

Logger provides structured logging for P2P components

func NewLogger

func NewLogger(component string, level LogLevel) *Logger

NewLogger creates a new logger for a component

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...map[string]interface{})

Debug logs debug message with optional fields

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...map[string]interface{})

Error logs error message with optional fields

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, fields ...map[string]interface{})

Fatal logs fatal message and exits

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...map[string]interface{})

Info logs info message with optional fields

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...map[string]interface{})

Warn logs warning message with optional fields

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

func NewP2PError(op string, err error) *P2PError

NewP2PError creates a new P2P error

func (*P2PError) Error

func (e *P2PError) Error() string

Error implements the error interface

func (*P2PError) Unwrap

func (e *P2PError) Unwrap() error

Unwrap returns the underlying error

func (*P2PError) WithContext

func (e *P2PError) WithContext(key string, value interface{}) *P2PError

WithContext adds arbitrary context to the error

func (*P2PError) WithPeer

func (e *P2PError) WithPeer(peerID peer.ID) *P2PError

WithPeer adds peer context to the error

func (*P2PError) WithTopic

func (e *P2PError) WithTopic(topic string) *P2PError

WithTopic adds topic context to the error

type P2PHost

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

P2PHost manages the libp2p host and associated services

func NewP2PHost

func NewP2PHost(config *Config) *P2PHost

NewP2PHost creates a new P2P host

func (*P2PHost) ConnectToPeer

func (p *P2PHost) ConnectToPeer(ctx context.Context, addr multiaddr.Multiaddr) error

ConnectToPeer connects to a specific peer

func (*P2PHost) FindProviders

func (p *P2PHost) FindProviders(ctx context.Context, c cid.Cid) ([]peer.AddrInfo, error)

FindProviders finds providers for a CID using the DHT

func (*P2PHost) GetNetworkInfo

func (p *P2PHost) GetNetworkInfo() map[string]interface{}

GetNetworkInfo returns information about the network state

func (*P2PHost) Provide

func (p *P2PHost) Provide(ctx context.Context, c cid.Cid) error

Provide announces that this node can provide content for a CID

func (*P2PHost) Publish

func (p *P2PHost) Publish(ctx context.Context, topic string, data []byte) error

Publish publishes a message to a topic

func (*P2PHost) Start

func (p *P2PHost) Start(ctx context.Context) error

Start initializes and starts the P2P host

func (*P2PHost) Stop

func (p *P2PHost) Stop(ctx context.Context) error

Stop shuts down the P2P host

func (*P2PHost) Subscribe

func (p *P2PHost) Subscribe(ctx context.Context, topic string) error

Subscribe subscribes to a topic

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

type ProvidersResponse struct {
	Providers []string `json:"providers"`
	Count     int      `json:"count"`
}

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

func (rl *RateLimiter) AllowMessage(peerID peer.ID, topic string, size int) bool

AllowMessage checks if a message from a peer should be allowed

func (*RateLimiter) Close

func (rl *RateLimiter) Close()

Close stops the rate limiter

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

func (*RequestQueue) Size

func (rq *RequestQueue) Size() int

Size returns the queue size

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

Jump to

Keyboard shortcuts

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