sync

package
v0.0.0-...-a9b9656 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2025 License: MIT Imports: 28 Imported by: 0

README

Clipman Sync Package

This package provides clipboard synchronization capabilities for Clipman, allowing content to be synced across multiple devices using libp2p for peer-to-peer communication.

Architecture

The sync package follows a node-centric architecture leveraging libp2p for all networking capabilities:

                           ┌───────────────────┐
                           │    Application    │
                           └─────────┬─────────┘
                                     │
                                     ▼
                           ┌───────────────────┐
                           │      sync.go      │
                           └─────────┬─────────┘
                                     │
                                     ▼
                           ┌───────────────────┐
                           │      node.go      │
                           └─────────┬─────────┘
                                     │
                    ┌────────────────┼────────────────┐
                    │                │                │
          ┌─────────▼─────────┐ ┌────▼──────────┐ ┌───▼────────────┐
          │   protocols.go    │ │ discovery.go  │ │  clipboard.go  │
          └───────────────────┘ └───────────────┘ └────────────────┘
                   │                                      │
                   │                                ┌─────▼─────┐
                   │                                │  file.go  │
                   ▼                                └───────────┘
          ┌────────────────┐
          │   pairing.go   │
          └────────────────┘
Key Components
  1. sync.go: The primary entry point and orchestrator for synchronization. Provides high-level API for applications.
  2. node.go: Core libp2p node setup, managing the host, identity, and connections.
  3. protocols.go: Defines and manages custom protocols for clipboard and file synchronization.
  4. discovery.go: Handles peer discovery using multiple methods (mDNS, DHT, and manual).
  5. pairing.go: Implements secure device pairing protocol and management.
  6. clipboard.go: Implements clipboard content synchronization logic.
  7. file.go: Implements file transfer functionality.
  8. types.go: Common types and interfaces used throughout the package.

libp2p Integration

The sync package leverages libp2p for all networking capabilities:

  1. Direct P2P Communication: Content is transferred directly between peers without central servers
  2. Multiple Transport Support: Uses libp2p's transport layer (TCP, QUIC, WebRTC)
  3. NAT Traversal: Automatic NAT hole punching and relay support for connectivity
  4. Secure Communication: End-to-end encryption with libp2p's secure transports
  5. PubSub: Group messaging using libp2p's GossipSub
  6. DHT: Distributed peer discovery for wide-area networking
  7. mDNS: Local network discovery
  8. Custom Protocols: Application-specific protocols for pairing and sync

Directory Structure

internal/sync/
├── sync.go             # High-level sync manager API (entrypoint)
├── node.go             # Core libp2p node setup (host, discovery, routing)
├── protocols.go        # Define custom protocols (e.g., clipboard, file)
├── discovery.go        # mDNS / DHT / Manual discovery logic
├── pairing.go          # Secure device pairing implementation
├── clipboard.go        # Clipboard sync handler
├── file.go             # File transfer logic
├── config.go           # Configuration handling
└── types.go            # Common structs/enums

Usage

Basic Usage
import (
    "github.com/berrythewa/clipman-daemon/internal/config"
    "github.com/berrythewa/clipman-daemon/internal/sync"
    "github.com/berrythewa/clipman-daemon/internal/types"
    "go.uber.org/zap"
)

func main() {
    // Get configuration and logger
    cfg := config.Load("/path/to/config.json")
    logger := zap.NewExample()

    // Create sync manager
    syncManager, err := sync.New(context.Background(), cfg, logger)
    if err != nil {
        logger.Fatal("Failed to create sync manager", zap.Error(err))
    }

    // Start sync manager
    if err := syncManager.Start(); err != nil {
        logger.Fatal("Failed to start sync manager", zap.Error(err))
    }
    defer syncManager.Stop()

    // Join a sync group
    if err := syncManager.JoinGroup("my-group"); err != nil {
        logger.Error("Failed to join group", zap.Error(err))
    }

    // Handle incoming content
    syncManager.SetContentHandler(func(content *types.ClipboardContent, peer types.PeerInfo) {
        logger.Info("Received content",
            zap.String("content_type", string(content.Type)),
            zap.Int("content_size", len(content.Data)),
            zap.String("from_peer", peer.ID))
        
        // Process the content...
    })

    // Send content
    content := &types.ClipboardContent{
        Type: types.TypeText,
        Data: []byte("Hello, world!"),
    }
    
    if err := syncManager.SendContent(content, "my-group"); err != nil {
        logger.Error("Failed to send content", zap.Error(err))
    }
    
    // Manually add a peer
    peerAddr := "/ip4/192.168.1.100/tcp/45678/p2p/QmHashOfThePeer"
    if err := syncManager.AddPeer(peerAddr); err != nil {
        logger.Error("Failed to add peer", zap.Error(err))
    }
}
Secure Device Pairing
// Enter pairing mode on Device A
address, err := syncManager.EnablePairing(func(request types.PairingRequest, remotePeerId string) (bool, error) {
    // This callback will be called when a pairing request is received
    // Here you would typically ask the user if they want to accept the pairing
    // For CLI usage, you could print the request info and read user input
    
    fmt.Printf("Pairing request from %s (%s)\n", request.DeviceName, remotePeerId)
    fmt.Printf("Accept? [y/n]: ")
    
    var response string
    fmt.Scanln(&response)
    
    return strings.ToLower(response) == "y", nil
})

if err != nil {
    log.Fatal("Failed to enable pairing mode:", err)
}

fmt.Println("Share this address with the device you want to pair with:")
fmt.Println(address)

// On Device B, request pairing with the address from Device A
response, err := syncManager.RequestPairing(address)
if err != nil {
    log.Fatal("Pairing request failed:", err)
}

if response.Accepted {
    fmt.Println("Pairing successful!")
    fmt.Println("Verification code:", response.PairingCode)
    
    // The same code should be displayed on both devices
    // Users can visually verify they match for enhanced security
} else {
    fmt.Println("Pairing rejected:", response.ErrorMessage)
}

// After pairing is done on Device A
syncManager.DisablePairing()

Protocol Details

Pairing Protocol

The pairing protocol enables secure device-to-device authentication:

  • Protocol Path: /clipman/1.0.0/pairing
  • Security Model:
    • Manual approval of pairing requests
    • Verification codes derived from both peer IDs
    • End-to-end encryption via libp2p
    • Persistent storage of paired devices
  • Pairing Flow:
    1. Device A enters pairing mode and gets an address to share
    2. Device B connects to Device A using the address
    3. Device A prompts for confirmation
    4. Both devices display a verification code for visual confirmation
    5. Both devices store each other's information permanently
Clipboard Protocol

The clipboard protocol allows sharing clipboard content between peers:

  • Protocol Path: /clipman/1.0.0/clipboard
  • Content Types: Text, Image, Files, HTML, and more
  • Metadata: Content type, size, timestamp, source device
  • Delivery: Direct to peer for 1:1 or via pubsub for groups
File Transfer Protocol

The file transfer protocol enables transferring larger files:

  • Protocol Path: /clipman/1.0.0/file
  • Features:
    • Resume support
    • Progress tracking
    • Integrity verification
    • Selective sync

Configuration

The sync functionality is configured through a comprehensive configuration structure:

// SyncConfig holds all sync-related configuration
type SyncConfig struct {
    // Core Sync Settings
    Enabled           bool     `json:"enable_sync"`
    SyncOverInternet  bool     `json:"sync_over_internet"`
    UseRelayNodes     bool     `json:"use_relay_nodes"`
    ListenPort        int      `json:"listen_port"`
    PeerIdentity      string   `json:"peer_identity"`
    DiscoveryMethod   string   `json:"discovery_method"` // "mdns", "dht", "manual", or "paired"
    DHTBootstrapPeers []string `json:"dht_bootstrap_peers"` // Bootstrap peers for DHT
    
    // Device Information
    DeviceName        string   `json:"device_name"`      // Human-readable device name
    DeviceType        string   `json:"device_type"`      // Type of device (desktop, mobile, etc.)
    
    // Peer Persistence
    PersistDiscoveredPeers bool   `json:"persist_discovered_peers"` // Whether to save discovered peers to disk
    DiscoveredPeersPath    string `json:"discovered_peers_path"`    // Path to store discovered peers
    AutoReconnectToPeers   bool   `json:"auto_reconnect_to_peers"`  // Whether to auto-reconnect to known peers
    MaxStoredPeers         int    `json:"max_stored_peers"`         // Maximum number of peers to store
    
    // Pairing
    PairingEnabled      bool     `json:"pairing_enabled"`       // Whether pairing functionality is enabled
    PairingTimeout      int      `json:"pairing_timeout"`       // Seconds before pairing mode times out (0 for no timeout)
    RequireVerification bool     `json:"require_verification"`  // Whether verification code must be confirmed
    
    // Clipboard Sync Options
    ClipboardTypes         []string `json:"clipboard_types"`         // "text", "image", "files"
    AutoCopyFromPeers      bool     `json:"auto_copy_from_peers"`
    MaxClipboardSizeKB     int      `json:"max_clipboard_size_kb"`
    ClipboardHistorySize   int      `json:"clipboard_history_size"`
    ClipboardBlacklistApps []string `json:"clipboard_blacklist_apps"`
    
    // File Transfer Options
    EnableFileSharing       bool     `json:"enable_file_sharing"`
    RequireFileConfirmation bool     `json:"require_file_confirmation"`
    DefaultDownloadFolder   string   `json:"default_download_folder"`
    AutoAcceptFromPeers     []string `json:"auto_accept_from_peers"`
    MaxFileSizeMB           int      `json:"max_file_size_mb"`
    
    // Privacy & Security
    AllowOnlyKnownPeers bool     `json:"allow_only_known_peers"`
    TrustedPeers        []string `json:"trusted_peers"`
    RequireApprovalPin  bool     `json:"require_approval_pin"`
    LogPeerActivity     bool     `json:"log_peer_activity"`
    
    // Developer & Debug Options
    DebugLogging              bool `json:"debug_logging"`
    ShowPeerDebugInfo         bool `json:"show_peer_debug_info"`
    DisableMultiplexing       bool `json:"disable_multiplexing"`
    ForceDirectConnectionOnly bool `json:"force_direct_connection_only"`
    
    // DHT Discovery Options
    DHTPersistentStorage bool   `json:"dht_persistent_storage"` // Whether to store DHT data on disk
    DHTStoragePath       string `json:"dht_storage_path"`       // Path to store DHT data
    DHTServerMode        bool   `json:"dht_server_mode"`        // Whether to run DHT in server mode
}

Configuration in JSON format:

{
  "sync": {
    "enable_sync": true,
    "sync_over_internet": true,
    "use_relay_nodes": true,
    "listen_port": 0,
    "discovery_method": "paired",
    "dht_bootstrap_peers": [],
    
    "device_name": "My Laptop",
    "device_type": "desktop",
    
    "persist_discovered_peers": true,
    "discovered_peers_path": "~/.clipman/peers.json",
    "auto_reconnect_to_peers": true,
    "max_stored_peers": 100,
    
    "pairing_enabled": true,
    "pairing_timeout": 300,
    "require_verification": true,
    
    "clipboard_types": ["text", "image"],
    "auto_copy_from_peers": true,
    "max_clipboard_size_kb": 512,
    "clipboard_history_size": 50,
    "clipboard_blacklist_apps": [],
    
    "enable_file_sharing": true,
    "require_file_confirmation": true,
    "default_download_folder": "~/Downloads/Clipman",
    "auto_accept_from_peers": [],
    "max_file_size_mb": 100,
    
    "allow_only_known_peers": true,
    "trusted_peers": [],
    "require_approval_pin": false,
    "log_peer_activity": true,
    
    "debug_logging": false,
    "show_peer_debug_info": false,
    "disable_multiplexing": false,
    "force_direct_connection_only": false,
    
    "dht_persistent_storage": false,
    "dht_storage_path": "~/.clipman/dht",
    "dht_server_mode": false
  }
}

Discovery Mechanisms

Clipman supports four complementary discovery mechanisms:

The most secure option for connecting devices:

  • Manual, user-initiated pairing process
  • Verification codes to confirm the correct devices are being paired
  • Persistent connections between paired devices
  • Highest security and reliability
  • Implementation in PairingManager class
2. Local Discovery (mDNS)

mDNS discovery automatically finds peers on the local network:

  • Zero configuration required
  • Low latency for local connections
  • Automatic discovery without manual setup
  • Implementation in MDNSDiscovery class
3. Wide-area Discovery (DHT)

DHT discovery finds peers across the internet using the Kademlia Distributed Hash Table:

  • Discover peers outside your local network
  • Bootstrap from known peers
  • Uses rendezvous points for application-specific discovery
  • Persistent peer routing
  • Customizable bootstrap peers
  • Optional server mode to improve network health
  • Implementation in DHTDiscovery and RendezvousDHT classes
4. Manual Discovery

Manual discovery allows direct connection to known peers:

  • Add peers by their multiaddress
  • Useful for known/fixed peers
  • Connect across network boundaries
  • Implementation in ManualDiscovery class

Security Model

Clipman's synchronization has multiple layers of security:

  1. Transport Security: libp2p provides encryption for all communications using the Noise protocol
  2. Identity: Each device has a unique peer ID derived from a cryptographic key pair
  3. Pairing: Manual confirmation for all device-to-device connections
  4. Verification: Visual verification codes ensure correct device pairing
  5. Trust Levels: Different trust for paired vs. discovered peers
  6. Persistence: Paired devices are stored for future reconnection
  7. Control: Users can disable discovery methods or limit to only paired devices

Peer Persistence

Clipman supports persisting discovered peers between sessions:

  • Saves peer information to disk
  • Automatically reconnects to previously discovered peers
  • Configurable storage path
  • Maximum peer storage limit
  • Peer aging/pruning mechanism

PubSub Groups

Groups in Clipman are implemented using libp2p's GossipSub:

  • Topic-based messaging
  • Message signing and verification
  • Efficient message propagation
  • Message deduplication

Future Enhancements

Planned enhancements include:

  1. Multiple Device Profiles: Different sync profiles for different devices or use cases
  2. Conflict Resolution: Smart handling of concurrent edits
  3. Bandwidth Controls: Limiting sync based on network conditions
  4. Search: Searching across synced content
  5. End-to-End Encryption: Additional encryption layer for content
  6. History and Versioning: Content history and version management
  7. Advanced DHT: Custom validators and providers
  8. NAT Traversal Improvements: Better connectivity across NATs
  9. Offline Mode: Queue changes when offline for later sync
  10. Selective Sync: Choose what content to sync between specific peers

License

Same as the main project.

Documentation

Overview

Package sync provides clipboard synchronization using libp2p

Package sync provides clipboard synchronization using libp2p

Package sync provides clipboard synchronization using libp2p

Package sync provides clipboard synchronization using libp2p

Package sync provides clipboard synchronization using libp2p

Package sync provides clipboard synchronization using libp2p

Index

Constants

View Source
const (
	// PairingRequestTimeout is the timeout for pairing requests
	PairingRequestTimeout = 5 * time.Minute

	// AuthCodeLength is the length of the verification code in bytes
	AuthCodeLength = 4
)
View Source
const (
	// Protocol versions
	ProtocolVersion = "1.0.0"

	// Base protocol path
	BaseProtocolPath = "/clipman/"

	// Full protocol paths
	PairingProtocolPath   = BaseProtocolPath + ProtocolVersion + "/pairing"
	ClipboardProtocolPath = BaseProtocolPath + ProtocolVersion + "/clipboard"
	FileProtocolPath      = BaseProtocolPath + ProtocolVersion + "/file"
)

Protocol paths

Variables

This section is empty.

Functions

func ClipboardTypesToContentTypes

func ClipboardTypesToContentTypes(types []string) []string

ClipboardTypesToContentTypes converts string type names to ContentType values

func ConvertToDiscoveryConfig

func ConvertToDiscoveryConfig(cfg *SyncConfig) *discovery.Config

GetDiscoveryConfig converts SyncConfig to discovery.Config

func ExpandPath

func ExpandPath(path string) string

ExpandPath expands paths like ~ to absolute paths

func GetConfigFromGlobal

func GetConfigFromGlobal(cfg *config.Config) *types.SyncConfig

GetConfigFromGlobal extracts sync configuration from the global config

func MapToLibp2pOptions

func MapToLibp2pOptions(cfg *SyncConfig, nodeCfg NodeConfig, logger *zap.Logger) ([]libp2p.Option, error)

MapToLibp2pOptions converts sync config to libp2p options

func SaveIdentityToString

func SaveIdentityToString(privKey crypto.PrivKey) (string, error)

SaveIdentityToString converts a private key to a storable string format

func ValidateSyncConfig

func ValidateSyncConfig(cfg *SyncConfig) error

ValidateSyncConfig validates the sync configuration

Types

type DiscoveryConfig

type DiscoveryConfig struct {
	Method         string
	EnableMDNS     bool
	EnableDHT      bool
	BootstrapPeers []string
}

DiscoveryConfig contains discovery-specific configuration

func GetDiscoveryConfig

func GetDiscoveryConfig(cfg *SyncConfig) DiscoveryConfig

GetDiscoveryConfig extracts discovery-specific configuration

type FileInfo

type FileInfo struct {
	Name        string    // Filename
	Size        int64     // File size in bytes
	ModTime     time.Time // Modification time
	ContentType string    // MIME type
	Hash        string    // File hash for verification
}

FileInfo provides information about a file being transferred

type InternalPeerInfo

type InternalPeerInfo struct {
	ID           string            // Peer ID (string representation of peer.ID)
	Name         string            // Human-readable name
	Addrs        []string          // Multiaddrs for connecting to the peer
	Groups       []string          // Groups the peer is a member of
	LastSeen     time.Time         // When the peer was last seen
	Capabilities map[string]string // Peer capabilities
	Version      string            // Software version
	DeviceType   string            // Type of device (desktop, mobile, etc.)
}

InternalPeerInfo contains detailed information about a discovered peer Used internally by the sync package

func FromExternalPeerInfo

func FromExternalPeerInfo(p types.PeerInfo) InternalPeerInfo

FromExternalPeerInfo creates an internal peer info from the external type

func (InternalPeerInfo) ToExternalPeerInfo

func (p InternalPeerInfo) ToExternalPeerInfo() types.PeerInfo

ToExternalPeerInfo converts an internal peer info to the external type

type Manager

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

Manager implements the types.SyncManager interface It orchestrates the libp2p node, protocols, and discovery

func New

func New(ctx context.Context, cfg *config.Config, logger *zap.Logger) (*Manager, error)

New creates a new sync manager

func (*Manager) AddPeer

func (m *Manager) AddPeer(address string) error

AddPeer adds a peer by its multiaddress string

func (*Manager) DisablePairing

func (m *Manager) DisablePairing()

DisablePairing disables pairing mode

func (*Manager) DisconnectPeer

func (m *Manager) DisconnectPeer(peerID string) error

DisconnectPeer disconnects from a peer but keeps it in the peerstore

func (*Manager) EnablePairing

func (m *Manager) EnablePairing(handler types.PairingRequestCallback) (string, error)

EnablePairing enables pairing mode

func (*Manager) GetConfig

func (m *Manager) GetConfig() *types.SyncConfig

GetConfig returns the sync configuration for application use

func (*Manager) GetConnectedPeers

func (m *Manager) GetConnectedPeers() []types.PeerInfo

GetConnectedPeers returns a list of currently connected peers

func (*Manager) GetDiscoveredPeers

func (m *Manager) GetDiscoveredPeers() []types.PeerInfo

GetDiscoveredPeers returns the list of discovered peers

func (*Manager) GetPairedDevices

func (m *Manager) GetPairedDevices() []types.PairedDevice

GetPairedDevices returns a list of paired devices

func (*Manager) IsConnected

func (m *Manager) IsConnected() bool

IsConnected checks if connected to the network

func (*Manager) IsPaired

func (m *Manager) IsPaired(peerID string) bool

IsPaired checks if a peer is paired

func (*Manager) IsPairingEnabled

func (m *Manager) IsPairingEnabled() bool

IsPairingEnabled checks if pairing mode is enabled

func (*Manager) JoinGroup

func (m *Manager) JoinGroup(group string) error

JoinGroup joins a group

func (*Manager) LeaveGroup

func (m *Manager) LeaveGroup(group string) error

LeaveGroup leaves a group

func (*Manager) ListGroups

func (m *Manager) ListGroups() ([]string, error)

ListGroups lists the joined groups

func (*Manager) RemovePairedDevice

func (m *Manager) RemovePairedDevice(peerID string) error

RemovePairedDevice removes a paired device

func (*Manager) RemovePeer

func (m *Manager) RemovePeer(peerID string) error

RemovePeer removes a peer by its ID

func (*Manager) RequestPairing

func (m *Manager) RequestPairing(address string) (*types.PairingResponse, error)

RequestPairing requests pairing with a device at the given address

func (*Manager) SendContent

func (m *Manager) SendContent(content *types.ClipboardContent, group string) error

SendContent sends content to a group

func (*Manager) SetContentHandler

func (m *Manager) SetContentHandler(handler types.ContentCallback)

SetContentHandler sets the handler for incoming content

func (*Manager) Start

func (m *Manager) Start() error

Start starts the sync manager

func (*Manager) Stop

func (m *Manager) Stop() error

Stop stops the sync manager

type Node

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

Node manages the libp2p host and core networking functionality

func NewNode

func NewNode(ctx context.Context, cfg *config.Config, logger *zap.Logger, opts ...NodeOption) (*Node, error)

NewNode creates a new libp2p node using the provided configuration

func (*Node) AddPeer

func (n *Node) AddPeer(pi InternalPeerInfo)

AddPeer adds a peer to the internal peer store

func (*Node) AddPeerByAddress

func (n *Node) AddPeerByAddress(addrStr string) error

AddPeerByAddress adds a peer by its multiaddress string

func (*Node) Close

func (n *Node) Close() error

Close closes the node

func (*Node) DisconnectPeer

func (n *Node) DisconnectPeer(peerID string) error

DisconnectPeer disconnects from a peer but keeps it in the peerstore

func (*Node) GetConfig

func (n *Node) GetConfig() *SyncConfig

GetConfig returns the node's configuration

func (*Node) GetConnectedPeers

func (n *Node) GetConnectedPeers() []InternalPeerInfo

GetConnectedPeers returns a list of connected peers

func (*Node) GetManualDiscoveryService

func (n *Node) GetManualDiscoveryService() (*discovery.ManualDiscovery, error)

GetManualDiscoveryService returns the manual discovery service

func (*Node) GetPeers

func (n *Node) GetPeers() []InternalPeerInfo

GetPeers returns all peers in the internal store

func (*Node) Host

func (n *Node) Host() host.Host

Host returns the libp2p host

func (*Node) ID

func (n *Node) ID() peer.ID

ID returns the node's peer ID

func (*Node) JoinTopic

func (n *Node) JoinTopic(group string) (*pubsub.Topic, *pubsub.Subscription, error)

JoinTopic joins a pubsub topic for a group

func (*Node) LeaveTopic

func (n *Node) LeaveTopic(group string) error

LeaveTopic leaves a pubsub topic for a group

func (*Node) Pairing

func (n *Node) Pairing() *PairingManager

Pairing returns the pairing manager

func (*Node) Protocols

func (n *Node) Protocols() *ProtocolManager

Protocols returns the protocol manager

func (*Node) PublishToTopic

func (n *Node) PublishToTopic(group string, data []byte) error

PublishToTopic publishes data to a topic

func (*Node) RemovePeer

func (n *Node) RemovePeer(id peer.ID)

RemovePeer removes a peer from the internal store

func (*Node) RemovePeerByID

func (n *Node) RemovePeerByID(peerID string) error

RemovePeerByID removes a peer by its ID string

func (*Node) Start

func (n *Node) Start() error

Start starts the node and all its services

func (*Node) Stop

func (n *Node) Stop() error

Stop stops the node and all its services

type NodeConfig

type NodeConfig struct {
	ListenAddresses []string
	EnableNAT       bool
	EnableRelay     bool
	PeerIdentity    string
}

NodeConfig contains configuration specific to the libp2p node

func GetNodeConfig

func GetNodeConfig(cfg *SyncConfig) NodeConfig

GetNodeConfig extracts node-specific configuration

type NodeOption

type NodeOption func(*Node) error

NodeOption is a functional option for configuring the Node

type PairedDevice

type PairedDevice struct {
	PeerID       string            `json:"peer_id"`      // Peer ID of the paired device
	DeviceName   string            `json:"device_name"`  // Human-readable name
	DeviceType   string            `json:"device_type"`  // Type of device (desktop, mobile, etc.)
	LastSeen     time.Time         `json:"last_seen"`    // When this device was last seen
	PairedAt     time.Time         `json:"paired_at"`    // When the pairing was established
	Addresses    []string          `json:"addresses"`    // Known addresses for this device
	Metadata     map[string]string `json:"metadata"`     // Additional device metadata
	Capabilities []string          `json:"capabilities"` // Device capabilities
}

PairedDevice represents a device that has been paired

type PairingDiscoveryService

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

CreatePairingDiscoveryService creates a discovery service for paired devices

func NewPairingDiscoveryService

func NewPairingDiscoveryService(manager *PairingManager, host host.Host) *PairingDiscoveryService

NewPairingDiscoveryService creates a new pairing discovery service

func (*PairingDiscoveryService) Name

func (p *PairingDiscoveryService) Name() string

Name returns the name of the discovery service

func (*PairingDiscoveryService) Start

func (p *PairingDiscoveryService) Start() error

Start starts the pairing discovery service

func (*PairingDiscoveryService) Stop

func (p *PairingDiscoveryService) Stop() error

Stop stops the pairing discovery service

type PairingManager

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

PairingManager implements the pairing protocol

func NewPairingManager

func NewPairingManager(ctx context.Context, host host.Host, pm *ProtocolManager, config *SyncConfig, logger *zap.Logger) *PairingManager

NewPairingManager creates a new pairing manager

func (*PairingManager) DisablePairing

func (pm *PairingManager) DisablePairing()

DisablePairing disables pairing mode

func (*PairingManager) EnablePairing

func (pm *PairingManager) EnablePairing(handler PairingRequestCallback) (string, error)

EnablePairing enables pairing mode for the device

func (*PairingManager) GetPairedDevices

func (pm *PairingManager) GetPairedDevices() []PairedDevice

GetPairedDevices returns all paired devices

func (*PairingManager) Handle

func (pm *PairingManager) Handle(stream network.Stream)

Handle processes incoming pairing streams

func (*PairingManager) ID

func (pm *PairingManager) ID() protocol.ID

ID returns the protocol ID

func (*PairingManager) IsPaired

func (pm *PairingManager) IsPaired(peerID string) bool

IsPaired checks if a device is paired

func (*PairingManager) IsPairingEnabled

func (pm *PairingManager) IsPairingEnabled() bool

IsPairingEnabled returns whether pairing is enabled

func (*PairingManager) RemovePairedDevice

func (pm *PairingManager) RemovePairedDevice(peerID string) error

RemovePairedDevice removes a paired device

func (*PairingManager) RequestPairing

func (pm *PairingManager) RequestPairing(address string) (*PairingResponse, error)

RequestPairing sends a pairing request to a device

func (*PairingManager) Start

func (pm *PairingManager) Start() error

Start initializes the pairing manager

func (*PairingManager) Stop

func (pm *PairingManager) Stop() error

Stop shuts down the pairing manager

func (*PairingManager) UpdatePairedDevice

func (pm *PairingManager) UpdatePairedDevice(device PairedDevice) error

UpdatePairedDevice updates a paired device's information

type PairingRequest

type PairingRequest struct {
	DeviceName string            `json:"device_name"`
	DeviceType string            `json:"device_type"`
	Timestamp  time.Time         `json:"timestamp"`
	RandomData string            `json:"random_data"` // Used for verification code generation
	PeerID     string            `json:"peer_id"`     // Requester's peer ID
	Nonce      string            `json:"nonce"`       // Random nonce for this request
	Metadata   map[string]string `json:"metadata"`    // Additional device metadata
}

PairingRequest contains information about a device requesting pairing

type PairingRequestCallback

type PairingRequestCallback func(request PairingRequest, remotePeerId string) (bool, error)

PairingRequestCallback is the callback for handling pairing requests

type PairingResponse

type PairingResponse struct {
	Accepted     bool              `json:"accepted"`      // Whether the pairing was accepted
	ErrorMessage string            `json:"error_message"` // Error message if rejected
	PairingCode  string            `json:"pairing_code"`  // Verification code
	DeviceName   string            `json:"device_name"`   // Responder's device name
	DeviceType   string            `json:"device_type"`   // Responder's device type
	Timestamp    time.Time         `json:"timestamp"`     // Time of response
	RandomData   string            `json:"random_data"`   // Used for verification code generation
	PeerID       string            `json:"peer_id"`       // Responder's peer ID
	Metadata     map[string]string `json:"metadata"`      // Additional device metadata
	ValidUntil   time.Time         `json:"valid_until"`   // When this pairing expires (0 = never)
}

PairingResponse is the response to a pairing request

type ProtocolConfig

type ProtocolConfig struct {
	EnablePubSub  bool
	SignMessages  bool
	StrictSigning bool
}

ProtocolConfig contains protocol-specific configuration

func GetProtocolConfig

func GetProtocolConfig(cfg *SyncConfig) ProtocolConfig

GetProtocolConfig extracts protocol-specific configuration

type ProtocolHandler

type ProtocolHandler interface {
	// ID returns the protocol ID
	ID() protocol.ID

	// Handle processes an incoming stream
	Handle(stream network.Stream)

	// Start initializes and starts the protocol handler
	Start() error

	// Stop stops the protocol handler
	Stop() error
}

ProtocolHandler defines the interface for protocol-specific handlers

type ProtocolManager

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

ProtocolManager manages the various protocols used for peer communication

func NewProtocolManager

func NewProtocolManager(ctx context.Context, host host.Host, config *SyncConfig, logger *zap.Logger) *ProtocolManager

NewProtocolManager creates a new protocol manager

func (*ProtocolManager) AddHandler

func (pm *ProtocolManager) AddHandler(handler ProtocolHandler)

AddHandler adds a protocol handler

func (*ProtocolManager) GetHandler

func (pm *ProtocolManager) GetHandler(id protocol.ID) (ProtocolHandler, error)

GetHandler returns the handler for a specific protocol

func (*ProtocolManager) OpenStream

func (pm *ProtocolManager) OpenStream(peerID peer.ID, protocolID protocol.ID) (network.Stream, error)

OpenStream opens a stream to a peer using a specific protocol

func (*ProtocolManager) Start

func (pm *ProtocolManager) Start() error

Start starts all protocol handlers

func (*ProtocolManager) Stop

func (pm *ProtocolManager) Stop() error

Stop stops all protocol handlers

type SyncConfig

type SyncConfig struct {
	// Core Sync Settings
	Enabled           bool     `json:"enable_sync"`
	SyncOverInternet  bool     `json:"sync_over_internet"`
	UseRelayNodes     bool     `json:"use_relay_nodes"`
	ListenPort        int      `json:"listen_port"`
	PeerIdentity      string   `json:"peer_identity"`
	DiscoveryMethod   string   `json:"discovery_method"`    // "mdns", "dht", or "manual"
	DHTBootstrapPeers []string `json:"dht_bootstrap_peers"` // Bootstrap peers for DHT
	BootstrapPeers    []string `json:"bootstrap_peers"`     // Bootstrap peers for the network

	// Peer Persistence
	PersistDiscoveredPeers bool   `json:"persist_discovered_peers"` // Whether to save discovered peers to disk
	DiscoveredPeersPath    string `json:"discovered_peers_path"`    // Path to store discovered peers
	AutoReconnectToPeers   bool   `json:"auto_reconnect_to_peers"`  // Whether to auto-reconnect to known peers
	MaxStoredPeers         int    `json:"max_stored_peers"`         // Maximum number of peers to store

	// Clipboard Sync Options
	ClipboardTypes         []string `json:"clipboard_types"` // "text", "image", "files"
	AutoCopyFromPeers      bool     `json:"auto_copy_from_peers"`
	MaxClipboardSizeKB     int      `json:"max_clipboard_size_kb"`
	ClipboardHistorySize   int      `json:"clipboard_history_size"`
	ClipboardBlacklistApps []string `json:"clipboard_blacklist_apps"`

	// File Transfer Options
	EnableFileSharing       bool     `json:"enable_file_sharing"`
	RequireFileConfirmation bool     `json:"require_file_confirmation"`
	DefaultDownloadFolder   string   `json:"default_download_folder"`
	AutoAcceptFromPeers     []string `json:"auto_accept_from_peers"`
	MaxFileSizeMB           int      `json:"max_file_size_mb"`

	// Privacy & Security
	AllowOnlyKnownPeers bool     `json:"allow_only_known_peers"`
	TrustedPeers        []string `json:"trusted_peers"`
	RequireApprovalPin  bool     `json:"require_approval_pin"`
	LogPeerActivity     bool     `json:"log_peer_activity"`

	// Developer & Debug Options
	DebugLogging              bool `json:"debug_logging"`
	ShowPeerDebugInfo         bool `json:"show_peer_debug_info"`
	DisableMultiplexing       bool `json:"disable_multiplexing"`
	ForceDirectConnectionOnly bool `json:"force_direct_connection_only"`

	// DHT Discovery Options
	DHTPersistentStorage bool   `json:"dht_persistent_storage"` // Whether to store DHT data on disk
	DHTStoragePath       string `json:"dht_storage_path"`       // Path to store DHT data
	DHTServerMode        bool   `json:"dht_server_mode"`        // Whether to run DHT in server mode
	UseAsRelay           bool   `json:"use_as_relay"`           // Whether to act as a relay for other peers
	PersistDHTData       bool   `json:"persist_dht_data"`       // Whether to persist DHT data

	// Pairing Options
	PairingEnabled bool   `json:"pairing_enabled"`
	DeviceName     string `json:"device_name"`
	DeviceType     string `json:"device_type"`
	PairingTimeout int    `json:"pairing_timeout"`
}

SyncConfig holds all sync-related configuration

func LoadSyncConfig

func LoadSyncConfig(cfg *config.Config) *SyncConfig

LoadSyncConfig extracts sync config from the global config

type SyncError

type SyncError struct {
	Code    int    // Error code
	Message string // Error message
	Err     error  // Original error
}

SyncError wraps errors from the sync package

func NewSyncError

func NewSyncError(code int, message string, err error) *SyncError

NewSyncError creates a new SyncError

func (*SyncError) Error

func (e *SyncError) Error() string

Error implements the error interface

func (*SyncError) Unwrap

func (e *SyncError) Unwrap() error

Unwrap returns the wrapped error

type SyncMessage

type SyncMessage struct {
	Type        string            // Message type (content, control, etc.)
	Source      peer.ID           // Source peer ID
	Destination peer.ID           // Destination peer ID (empty for broadcast)
	Group       string            // Target group (if applicable)
	Timestamp   time.Time         // Message timestamp
	ID          string            // Unique message ID
	Payload     []byte            // Message payload
	Headers     map[string]string // Message headers/metadata
}

SyncMessage represents a message exchanged between peers

type TransferInfo

type TransferInfo struct {
	ID         string    // Unique transfer ID
	FileName   string    // Name of the file
	FileSize   int64     // Size of the file in bytes
	Sender     string    // Sender peer ID
	Recipient  string    // Recipient peer ID
	Group      string    // Group context (if applicable)
	StartTime  time.Time // When the transfer started
	IsIncoming bool      // Whether this is an incoming or outgoing transfer
	Status     string    // "pending", "in_progress", "completed", "failed", "cancelled"
}

TransferInfo provides information about a file transfer

Directories

Path Synopsis
Package discovery provides peer discovery mechanisms for the sync package
Package discovery provides peer discovery mechanisms for the sync package

Jump to

Keyboard shortcuts

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