Documentation
¶
Overview ¶
Package node provides the libp2p node implementation for the Klingon P2P network.
Package node - Peer-to-peer message encryption using NaCl box.
Package node - Message sender with persistence and retry support. Implements hybrid delivery: direct streams when connected, encrypted PubSub as fallback.
Package node - Monitors peer connection events for message flushing.
Package node - Background worker for retrying undelivered messages.
Package node - Direct P2P stream handler for private swap messages.
Package node - Swap message handler for P2P swap protocol.
Index ¶
- Constants
- func ConfigPath(dataDir string) string
- type AckPayload
- type Config
- type ConnMgrConfig
- type EVMClaimPayload
- type EVMFundingInfoPayload
- type EVMRefundPayload
- type EncryptedEnvelope
- type FundingInfoPayload
- type HTLCClaimPayload
- type HTLCSecretHashPayload
- type HTLCSecretRevealPayload
- type IdentityConfig
- type LoggingConfig
- type MessageEncryptor
- type MessageSender
- func (s *MessageSender) CancelPendingForTrade(tradeID string, reason string) error
- func (s *MessageSender) FlushPendingForPeer(ctx context.Context, peerID peer.ID)
- func (s *MessageSender) GetPendingCount(tradeID string) (int, error)
- func (s *MessageSender) RetryMessage(ctx context.Context, outboxMsg *storage.OutboxMessage)
- func (s *MessageSender) SendDirect(ctx context.Context, peerID peer.ID, tradeID string, swapTimeout int64, ...) error
- func (s *MessageSender) SetEncryptor(enc *MessageEncryptor)
- type MessageSenderConfig
- type NetworkConfig
- type NetworkType
- type Node
- func (n *Node) Addrs() []multiaddr.Multiaddr
- func (n *Node) Config() *Config
- func (n *Node) Connect(ctx context.Context, pi peer.AddrInfo) error
- func (n *Node) ConnectByAddr(ctx context.Context, addr string) error
- func (n *Node) DHT() *dht.IpfsDHT
- func (n *Node) GetTopic(topicName string) *pubsub.Topic
- func (n *Node) HandlePeerFound(pi peer.AddrInfo)
- func (n *Node) Host() host.Host
- func (n *Node) ID() peer.ID
- func (n *Node) LoadPersistedPeers() error
- func (n *Node) MessageSender() *MessageSender
- func (n *Node) OnPeerConnected(cb func(peer.ID))
- func (n *Node) OnPeerDisconnected(cb func(peer.ID))
- func (n *Node) PeerCount() int
- func (n *Node) Peers() []peer.ID
- func (n *Node) PubSub() *pubsub.PubSub
- func (n *Node) RegisterDirectHandler(msgType string, handler SwapMessageHandler)
- func (n *Node) SavePeerCache() error
- func (n *Node) SendDirect(ctx context.Context, peerID peer.ID, tradeID string, swapTimeout int64, ...) error
- func (n *Node) SetPeerStoreAdapter(adapter *PeerStoreAdapter)
- func (n *Node) SetupDirectMessaging(store *storage.Storage) error
- func (n *Node) Start() error
- func (n *Node) Stop() error
- func (n *Node) StreamHandler() *StreamHandler
- func (n *Node) SwapHandler() *SwapHandler
- func (n *Node) Uptime() time.Duration
- type NonceExchangePayload
- type PartialSigPayload
- type PeerMonitor
- type PeerStoreAdapter
- func (a *PeerStoreAdapter) LoadPeers(limit int) ([]*storage.PeerRecord, error)
- func (a *PeerStoreAdapter) LoadRecentPeers(since time.Duration, limit int) ([]*storage.PeerRecord, error)
- func (a *PeerStoreAdapter) PeerCount() (int, error)
- func (a *PeerStoreAdapter) SavePeer(peerID peer.ID, addrs []multiaddr.Multiaddr, isBootstrap bool) error
- func (a *PeerStoreAdapter) UpdatePeerConnected(peerID peer.ID) error
- func (a *PeerStoreAdapter) UpdatePeerSeen(peerID peer.ID) error
- type PubKeyExchangePayload
- type RetryWorker
- type RetryWorkerConfig
- type StorageConfig
- type StreamHandler
- type SwapHandler
- type SwapMessage
- func NewEVMClaimMessage(tradeID, chain string, chainID uint64, txHash, swapID, secret string) (*SwapMessage, error)
- func NewEVMFundingInfoMessage(tradeID string, payload *EVMFundingInfoPayload) (*SwapMessage, error)
- func NewEVMRefundMessage(tradeID, chain string, chainID uint64, txHash, swapID string) (*SwapMessage, error)
- func NewHTLCClaimMessage(tradeID, chain, txid, secret string) (*SwapMessage, error)
- func NewHTLCSecretHashMessage(tradeID, secretHash, pubKey, offerAddr, requestAddr string) (*SwapMessage, error)
- func NewHTLCSecretRevealMessage(tradeID string, secret string) (*SwapMessage, error)
- func NewOrderAnnounceMessage(orderID string, payload interface{}) (*SwapMessage, error)
- func NewOrderTakeMessage(orderID, tradeID string, payload interface{}) (*SwapMessage, error)
- func NewPubKeyExchangeMessage(tradeID, pubKey, offerAddr, requestAddr string) (*SwapMessage, error)
- func NewSwapMessage(msgType, tradeID string, payload interface{}) (*SwapMessage, error)
- type SwapMessageHandler
Constants ¶
const ( // Mainnet MainnetDHTPrefix = "/klingon" MainnetDiscoveryNS = "klingon-mainnet" // Testnet TestnetDHTPrefix = "/klingon-testnet" TestnetDiscoveryNS = "klingon-testnet" )
Network-specific constants for peer separation.
const ( // SwapTopic is for public swap messages (order announcements). SwapTopic = "/klingon/swap/1.0.0" // SwapEncryptedTopic is for encrypted private swap messages. // Messages are encrypted with recipient's public key, broadcast via gossip, // but only the recipient can decrypt them. SwapEncryptedTopic = "/klingon/swap/encrypted/1.0.0" )
PubSub topics for swap messages.
const ( SwapMsgOrderAnnounce = "order_announce" SwapMsgOrderCancel = "order_cancel" SwapMsgOrderTake = "order_take" SwapMsgOrderTaken = "order_taken" SwapMsgSwapInit = "swap_init" SwapMsgSwapAccept = "swap_accept" SwapMsgPubKeyExchange = "pubkey_exchange" SwapMsgNonceExchange = "nonce_exchange" SwapMsgFundingInfo = "funding_info" SwapMsgPartialSig = "partial_sig" SwapMsgComplete = "complete" SwapMsgRefund = "refund" SwapMsgAbort = "abort" // HTLC-specific message types (Bitcoin-family) SwapMsgHTLCSecretHash = "htlc_secret_hash" // Initiator sends secret hash to responder SwapMsgHTLCSecretReveal = "htlc_secret_reveal" // Initiator reveals secret for claiming SwapMsgHTLCClaim = "htlc_claim" // Notify counterparty of claim tx // EVM HTLC-specific message types SwapMsgEVMFundingInfo = "evm_funding_info" // EVM HTLC created on-chain (tx hash, swap ID) SwapMsgEVMClaimed = "evm_claimed" // EVM HTLC claimed (includes secret) SwapMsgEVMRefunded = "evm_refunded" // EVM HTLC refunded after timeout // Acknowledgment message type SwapMsgAck = "ack" // Acknowledgment of message receipt )
Swap message types
const ConfigFileName = "config.yaml"
ConfigFileName is the default config file name.
const SwapDirectProtocol protocol.ID = "/klingon/swap/direct/1.0.0"
SwapDirectProtocol is the protocol ID for direct swap messages.
Variables ¶
This section is empty.
Functions ¶
func ConfigPath ¶
ConfigPath returns the full path to the config file for the given data directory.
Types ¶
type AckPayload ¶
type AckPayload struct {
MessageID string `json:"message_id"` // Which message we're ACKing
SequenceNum uint64 `json:"sequence_num"` // Sequence number ACKed
Success bool `json:"success"` // Processing successful
Error string `json:"error,omitempty"` // Error if failed
}
AckPayload is the acknowledgment message payload.
type Config ¶
type Config struct {
// NetworkType is the network type (mainnet or testnet).
NetworkType NetworkType `yaml:"network_type"`
// Identity
Identity IdentityConfig `yaml:"identity"`
// Network settings
Network NetworkConfig `yaml:"network"`
// Storage
Storage StorageConfig `yaml:"storage"`
// Logging
Logging LoggingConfig `yaml:"logging"`
// Backends holds blockchain API configurations per chain symbol.
// If not specified, defaults to public APIs (mempool.space, etc.)
Backends map[string]*backend.Config `yaml:"backends,omitempty"`
}
Config holds all configuration for the P2P node.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with sensible defaults.
func LoadConfig ¶
LoadConfig loads configuration from a YAML file. If the file doesn't exist, it creates one with default values.
func (*Config) DiscoveryNamespace ¶
DiscoveryNamespace returns the discovery namespace for the configured network.
func (*Config) GetBackendConfig ¶
GetBackendConfig returns the backend config for a chain symbol. Returns default config if not explicitly configured.
func (*Config) GetBackendURL ¶
GetBackendURL returns the appropriate backend URL for the chain and network.
type ConnMgrConfig ¶
type ConnMgrConfig struct {
// LowWater is the minimum number of connections to maintain.
LowWater int `yaml:"low_water"`
// HighWater is the maximum number of connections before pruning.
HighWater int `yaml:"high_water"`
// GracePeriod is how long to wait before closing new connections.
GracePeriod time.Duration `yaml:"grace_period"`
}
ConnMgrConfig holds connection manager settings.
type EVMClaimPayload ¶
type EVMClaimPayload struct {
Chain string `json:"chain"` // Chain symbol (ETH, BSC, etc.)
ChainID uint64 `json:"chain_id"` // EVM chain ID
TxHash string `json:"tx_hash"` // Claim transaction hash
SwapID string `json:"swap_id"` // On-chain swap ID
Secret string `json:"secret"` // Hex-encoded secret (32 bytes)
}
EVMClaimPayload notifies the counterparty of an EVM HTLC claim. Includes the secret so counterparty can claim their side.
type EVMFundingInfoPayload ¶
type EVMFundingInfoPayload struct {
Chain string `json:"chain"` // Chain symbol (ETH, BSC, etc.)
ChainID uint64 `json:"chain_id"` // EVM chain ID
TxHash string `json:"tx_hash"` // Creation transaction hash
SwapID string `json:"swap_id"` // On-chain swap ID (keccak256 hash)
ContractAddress string `json:"contract_address"` // HTLC contract address
Sender string `json:"sender"` // Sender address (initiator)
Receiver string `json:"receiver"` // Receiver address (responder)
TokenAddress string `json:"token_address"` // Token address (0x0 for native)
Amount string `json:"amount"` // Amount in wei (string for big.Int)
SecretHash string `json:"secret_hash"` // Hex-encoded secret hash
Timelock int64 `json:"timelock"` // Unix timestamp when refund becomes available
}
EVMFundingInfoPayload contains EVM HTLC creation info. Sent when an EVM HTLC is created on-chain to notify counterparty.
type EVMRefundPayload ¶
type EVMRefundPayload struct {
Chain string `json:"chain"` // Chain symbol (ETH, BSC, etc.)
ChainID uint64 `json:"chain_id"` // EVM chain ID
TxHash string `json:"tx_hash"` // Refund transaction hash
SwapID string `json:"swap_id"` // On-chain swap ID
}
EVMRefundPayload notifies the counterparty of an EVM HTLC refund. Indicates the swap was not completed and funds were returned.
type EncryptedEnvelope ¶
type EncryptedEnvelope struct {
// RecipientPeerID is the intended recipient (only they can decrypt)
RecipientPeerID string `json:"recipient"`
// SenderPeerID identifies the sender for reply routing
SenderPeerID string `json:"sender"`
// EphemeralPubKey is the sender's ephemeral X25519 public key (32 bytes, base64)
EphemeralPubKey []byte `json:"ephemeral_key"`
// Nonce is the 24-byte nonce used for encryption (base64)
Nonce []byte `json:"nonce"`
// Ciphertext is the encrypted message (base64)
Ciphertext []byte `json:"ciphertext"`
// MessageID for deduplication and ACK matching
MessageID string `json:"message_id"`
// TradeID for routing to correct swap handler
TradeID string `json:"trade_id"`
}
EncryptedEnvelope wraps an encrypted message for PubSub delivery.
type FundingInfoPayload ¶
FundingInfoPayload contains funding transaction info.
type HTLCClaimPayload ¶
type HTLCClaimPayload struct {
Chain string `json:"chain"` // Chain symbol (BTC, LTC)
TxID string `json:"txid"` // Claim transaction ID
Secret string `json:"secret"` // Hex-encoded secret used for claim (for counterparty to use)
}
HTLCClaimPayload notifies the counterparty of a claim transaction. Allows both parties to track swap completion on-chain.
type HTLCSecretHashPayload ¶
type HTLCSecretHashPayload struct {
SecretHash string `json:"secret_hash"` // Hex-encoded SHA256 hash (32 bytes)
PubKey string `json:"pubkey"` // Initiator's hex-encoded pubkey (for HTLC script)
OfferWalletAddr string `json:"offer_wallet_addr"` // Initiator's address on offer chain for receiving
RequestWalletAddr string `json:"request_wallet_addr"` // Initiator's address on request chain for receiving
}
HTLCSecretHashPayload contains the secret hash for HTLC swaps. Sent by the initiator to the responder after swap initialization.
type HTLCSecretRevealPayload ¶
type HTLCSecretRevealPayload struct {
Secret string `json:"secret"` // Hex-encoded preimage (32 bytes)
}
HTLCSecretRevealPayload contains the secret for claiming HTLC outputs. Sent by the initiator when ready to complete the swap.
type IdentityConfig ¶
type IdentityConfig struct {
// KeyFile is the path to the node's private key file.
KeyFile string `yaml:"key_file"`
}
IdentityConfig holds identity-related settings.
type LoggingConfig ¶
type LoggingConfig struct {
// Level is the log level (debug, info, warn, error).
Level string `yaml:"level"`
// File is the log file path (empty for stdout).
File string `yaml:"file"`
}
LoggingConfig holds logging settings.
type MessageEncryptor ¶
type MessageEncryptor struct {
// contains filtered or unexported fields
}
MessageEncryptor handles encryption/decryption of P2P messages.
func NewMessageEncryptor ¶
NewMessageEncryptor creates a new encryptor using the node's identity key.
func (*MessageEncryptor) Decrypt ¶
func (e *MessageEncryptor) Decrypt(envelope *EncryptedEnvelope) (*SwapMessage, error)
Decrypt decrypts an encrypted envelope intended for us.
func (*MessageEncryptor) Encrypt ¶
func (e *MessageEncryptor) Encrypt(recipientPeerID peer.ID, msg *SwapMessage) (*EncryptedEnvelope, error)
Encrypt encrypts a message for a specific peer. Uses ephemeral key + recipient's public key for forward secrecy.
func (*MessageEncryptor) IsForUs ¶
func (e *MessageEncryptor) IsForUs(envelope *EncryptedEnvelope) bool
IsForUs checks if an encrypted envelope is intended for us.
type MessageSender ¶
type MessageSender struct {
// contains filtered or unexported fields
}
MessageSender handles outbound messages with persistence and retry. Uses hybrid delivery: tries direct stream first, falls back to encrypted PubSub.
func NewMessageSender ¶
func NewMessageSender(n *Node, store *storage.Storage, streamHandler *StreamHandler, cfg MessageSenderConfig) *MessageSender
NewMessageSender creates a new message sender.
func (*MessageSender) CancelPendingForTrade ¶
func (s *MessageSender) CancelPendingForTrade(tradeID string, reason string) error
CancelPendingForTrade marks all pending messages for a trade as failed. Used when a swap is cancelled or times out.
func (*MessageSender) FlushPendingForPeer ¶
func (s *MessageSender) FlushPendingForPeer(ctx context.Context, peerID peer.ID)
FlushPendingForPeer attempts to deliver all pending messages for a peer. Called when a peer reconnects.
func (*MessageSender) GetPendingCount ¶
func (s *MessageSender) GetPendingCount(tradeID string) (int, error)
GetPendingCount returns the number of pending messages for a trade.
func (*MessageSender) RetryMessage ¶
func (s *MessageSender) RetryMessage(ctx context.Context, outboxMsg *storage.OutboxMessage)
RetryMessage retries a pending message from the outbox.
func (*MessageSender) SendDirect ¶
func (s *MessageSender) SendDirect(ctx context.Context, peerID peer.ID, tradeID string, swapTimeout int64, msg *SwapMessage) error
SendDirect sends a message directly to a peer with persistence and guaranteed delivery. The message is persisted to the outbox first, then immediate delivery is attempted. If the peer is offline, the message will be retried automatically.
func (*MessageSender) SetEncryptor ¶
func (s *MessageSender) SetEncryptor(enc *MessageEncryptor)
SetEncryptor sets the message encryptor (for testing or late initialization).
type MessageSenderConfig ¶
type MessageSenderConfig struct {
InitialRetryInterval time.Duration // Initial retry interval (default: 10s)
MaxRetryInterval time.Duration // Maximum retry interval (default: 10m)
BackoffMultiplier float64 // Backoff multiplier (default: 2.0)
AckTimeout time.Duration // Time to wait for ACK (default: 30s)
StopBeforeExpiry time.Duration // Stop retrying this long before swap expires (default: 1h)
MaxRetries int // Maximum retry attempts before giving up (default: 50)
DHTLookupTimeout time.Duration // Timeout for DHT peer lookup (default: 30s)
ConnectTimeout time.Duration // Timeout for connecting to peer (default: 15s)
}
MessageSenderConfig configures the message sender behavior.
func DefaultMessageSenderConfig ¶
func DefaultMessageSenderConfig() MessageSenderConfig
DefaultMessageSenderConfig returns the default configuration.
type NetworkConfig ¶
type NetworkConfig struct {
// ListenAddrs are the multiaddrs to listen on.
ListenAddrs []string `yaml:"listen_addrs"`
// BootstrapPeers are the initial peers to connect to.
BootstrapPeers []string `yaml:"bootstrap_peers"`
// EnableMDNS enables local peer discovery via mDNS.
EnableMDNS bool `yaml:"enable_mdns"`
// EnableDHT enables the Kademlia DHT for peer discovery.
EnableDHT bool `yaml:"enable_dht"`
// EnableRelay enables circuit relay for NAT traversal.
EnableRelay bool `yaml:"enable_relay"`
// EnableNAT enables NAT port mapping (UPnP/NAT-PMP).
EnableNAT bool `yaml:"enable_nat"`
// EnableHolePunching enables direct connection establishment through NAT.
EnableHolePunching bool `yaml:"enable_hole_punching"`
// ConnectionManager settings
ConnMgr ConnMgrConfig `yaml:"conn_mgr"`
}
NetworkConfig holds P2P network settings.
type NetworkType ¶
type NetworkType string
NetworkType represents the network (mainnet or testnet).
const ( NetworkMainnet NetworkType = "mainnet" NetworkTestnet NetworkType = "testnet" )
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node represents a Klingon P2P node.
func (*Node) ConnectByAddr ¶
ConnectByAddr connects to a peer by multiaddr string.
func (*Node) GetTopic ¶
GetTopic returns a PubSub topic by name. Used by message sender to publish encrypted messages.
func (*Node) HandlePeerFound ¶
HandlePeerFound is called when mDNS discovers a peer.
func (*Node) LoadPersistedPeers ¶
LoadPersistedPeers loads known peers from storage into the peerstore.
func (*Node) MessageSender ¶
func (n *Node) MessageSender() *MessageSender
MessageSender returns the message sender for direct P2P messaging.
func (*Node) OnPeerConnected ¶
OnPeerConnected sets a callback for when a peer connects.
func (*Node) OnPeerDisconnected ¶
OnPeerDisconnected sets a callback for when a peer disconnects.
func (*Node) RegisterDirectHandler ¶
func (n *Node) RegisterDirectHandler(msgType string, handler SwapMessageHandler)
RegisterDirectHandler registers a handler for direct messages of a specific type.
func (*Node) SavePeerCache ¶
SavePeerCache saves the current peerstore to persistent storage.
func (*Node) SendDirect ¶
func (n *Node) SendDirect(ctx context.Context, peerID peer.ID, tradeID string, swapTimeout int64, msg *SwapMessage) error
SendDirect sends a message directly to a peer with persistence and retry. This is the primary method for sending swap protocol messages.
func (*Node) SetPeerStoreAdapter ¶
func (n *Node) SetPeerStoreAdapter(adapter *PeerStoreAdapter)
SetPeerStoreAdapter sets the peer store adapter for the node.
func (*Node) SetupDirectMessaging ¶
SetupDirectMessaging initializes the direct P2P messaging layer. This must be called after the node is created and before Start().
func (*Node) StreamHandler ¶
func (n *Node) StreamHandler() *StreamHandler
StreamHandler returns the direct stream handler.
func (*Node) SwapHandler ¶
func (n *Node) SwapHandler() *SwapHandler
SwapHandler returns the swap message handler.
type NonceExchangePayload ¶
type NonceExchangePayload struct {
OfferNonce string `json:"offer_nonce"` // Hex-encoded public nonce for offer chain (66 bytes)
RequestNonce string `json:"request_nonce"` // Hex-encoded public nonce for request chain (66 bytes)
}
NonceExchangePayload contains nonce exchange data for both chains.
type PartialSigPayload ¶
type PartialSigPayload struct {
OfferPartialSig string `json:"offer_partial_sig"` // Hex-encoded partial signature for offer chain
RequestPartialSig string `json:"request_partial_sig"` // Hex-encoded partial signature for request chain
}
PartialSigPayload contains partial signature data for both chains.
type PeerMonitor ¶
type PeerMonitor struct {
// contains filtered or unexported fields
}
PeerMonitor watches for peer connection events and triggers message flushing.
func NewPeerMonitor ¶
func NewPeerMonitor(n *Node, store *storage.Storage, sender *MessageSender) *PeerMonitor
NewPeerMonitor creates a new peer monitor.
func (*PeerMonitor) Start ¶
func (m *PeerMonitor) Start() error
Start starts the peer monitor background goroutine.
type PeerStoreAdapter ¶
type PeerStoreAdapter struct {
// contains filtered or unexported fields
}
PeerStoreAdapter provides persistent storage for peer information.
func NewPeerStoreAdapter ¶
func NewPeerStoreAdapter(store *storage.Storage) *PeerStoreAdapter
NewPeerStoreAdapter creates a new peer store adapter.
func (*PeerStoreAdapter) LoadPeers ¶
func (a *PeerStoreAdapter) LoadPeers(limit int) ([]*storage.PeerRecord, error)
LoadPeers loads all known peers from storage.
func (*PeerStoreAdapter) LoadRecentPeers ¶
func (a *PeerStoreAdapter) LoadRecentPeers(since time.Duration, limit int) ([]*storage.PeerRecord, error)
LoadRecentPeers loads peers seen within the given duration.
func (*PeerStoreAdapter) PeerCount ¶
func (a *PeerStoreAdapter) PeerCount() (int, error)
PeerCount returns the number of known peers.
func (*PeerStoreAdapter) SavePeer ¶
func (a *PeerStoreAdapter) SavePeer(peerID peer.ID, addrs []multiaddr.Multiaddr, isBootstrap bool) error
SavePeer saves a peer's information to persistent storage.
func (*PeerStoreAdapter) UpdatePeerConnected ¶
func (a *PeerStoreAdapter) UpdatePeerConnected(peerID peer.ID) error
UpdatePeerConnected updates the peer's connection timestamp.
func (*PeerStoreAdapter) UpdatePeerSeen ¶
func (a *PeerStoreAdapter) UpdatePeerSeen(peerID peer.ID) error
UpdatePeerSeen updates the peer's last seen timestamp.
type PubKeyExchangePayload ¶
type PubKeyExchangePayload struct {
PubKey string `json:"pubkey"` // Hex-encoded public key
OfferWalletAddr string `json:"offer_wallet_addr"` // Our address on offer chain for receiving
RequestWalletAddr string `json:"request_wallet_addr"` // Our address on request chain for receiving
}
PubKeyExchangePayload contains public key exchange data.
type RetryWorker ¶
type RetryWorker struct {
// contains filtered or unexported fields
}
RetryWorker periodically checks for undelivered messages and retries them.
func NewRetryWorker ¶
func NewRetryWorker(n *Node, store *storage.Storage, sender *MessageSender, cfg RetryWorkerConfig) *RetryWorker
NewRetryWorker creates a new retry worker.
func (*RetryWorker) CleanupOldMessages ¶
func (w *RetryWorker) CleanupOldMessages() (int64, error)
CleanupOldMessages removes old completed/failed messages from storage. Should be called periodically (e.g., once per day).
func (*RetryWorker) Start ¶
func (w *RetryWorker) Start()
Start starts the retry worker background goroutine.
type RetryWorkerConfig ¶
type RetryWorkerConfig struct {
PollInterval time.Duration // How often to check for messages to retry
CleanupInterval time.Duration // How often to cleanup old messages
BatchSize int // Max messages to process per poll
BufferDuration time.Duration // Stop retrying this long before swap expires
RetentionPeriod time.Duration // How long to keep completed/failed messages
}
RetryWorkerConfig configures the retry worker behavior.
func DefaultRetryWorkerConfig ¶
func DefaultRetryWorkerConfig() RetryWorkerConfig
DefaultRetryWorkerConfig returns the default configuration.
type StorageConfig ¶
type StorageConfig struct {
// DataDir is the directory for all data files.
DataDir string `yaml:"data_dir"`
}
StorageConfig holds storage settings.
type StreamHandler ¶
type StreamHandler struct {
// contains filtered or unexported fields
}
StreamHandler handles incoming direct P2P streams for swap messages.
func NewStreamHandler ¶
func NewStreamHandler(n *Node, store *storage.Storage) *StreamHandler
NewStreamHandler creates a new direct stream handler.
func (*StreamHandler) OnMessage ¶
func (h *StreamHandler) OnMessage(msgType string, handler SwapMessageHandler)
OnMessage registers a handler for a specific message type.
func (*StreamHandler) SendDirectMessage ¶
func (h *StreamHandler) SendDirectMessage(ctx context.Context, peerID peer.ID, msg *SwapMessage) error
SendDirectMessage sends a message directly to a peer and waits for ACK. This is a blocking call that returns when ACK is received or timeout occurs.
func (*StreamHandler) Start ¶
func (h *StreamHandler) Start() error
Start registers the stream handler with the libp2p host.
type SwapHandler ¶
type SwapHandler struct {
// contains filtered or unexported fields
}
SwapHandler manages swap-related PubSub messaging.
func NewSwapHandler ¶
func NewSwapHandler(n *Node) (*SwapHandler, error)
NewSwapHandler creates a new swap handler.
func (*SwapHandler) GetEncryptedTopic ¶
func (h *SwapHandler) GetEncryptedTopic() *pubsub.Topic
GetEncryptedTopic returns the encrypted topic for direct publishing.
func (*SwapHandler) OnMessage ¶
func (h *SwapHandler) OnMessage(msgType string, handler SwapMessageHandler)
OnMessage registers a handler for a specific message type.
func (*SwapHandler) SendMessage ¶
func (h *SwapHandler) SendMessage(ctx context.Context, msg *SwapMessage) error
SendMessage sends a swap message to the network.
func (*SwapHandler) Start ¶
func (h *SwapHandler) Start() error
Start starts the swap handler and joins the swap topics.
type SwapMessage ¶
type SwapMessage struct {
Type string `json:"type"` // Message type
TradeID string `json:"trade_id"` // Trade identifier
OrderID string `json:"order_id"` // Order identifier (for take messages)
FromPeer string `json:"from_peer"` // Sender peer ID
Payload json.RawMessage `json:"payload"` // Type-specific payload
Timestamp int64 `json:"timestamp"` // Unix timestamp
// Delivery guarantee fields (for direct P2P messaging)
MessageID string `json:"message_id,omitempty"` // UUID for deduplication
SequenceNum uint64 `json:"sequence_num,omitempty"` // Per-trade sequence number
RequiresAck bool `json:"requires_ack,omitempty"` // Whether sender expects ACK
SwapTimeout int64 `json:"swap_timeout,omitempty"` // When swap expires (for retry decision)
}
SwapMessage represents a swap protocol message.
func NewEVMClaimMessage ¶
func NewEVMClaimMessage(tradeID, chain string, chainID uint64, txHash, swapID, secret string) (*SwapMessage, error)
NewEVMClaimMessage creates an EVM HTLC claim notification message.
func NewEVMFundingInfoMessage ¶
func NewEVMFundingInfoMessage(tradeID string, payload *EVMFundingInfoPayload) (*SwapMessage, error)
NewEVMFundingInfoMessage creates an EVM HTLC funding info message.
func NewEVMRefundMessage ¶
func NewEVMRefundMessage(tradeID, chain string, chainID uint64, txHash, swapID string) (*SwapMessage, error)
NewEVMRefundMessage creates an EVM HTLC refund notification message.
func NewHTLCClaimMessage ¶
func NewHTLCClaimMessage(tradeID, chain, txid, secret string) (*SwapMessage, error)
NewHTLCClaimMessage creates a claim notification message for HTLC swaps.
func NewHTLCSecretHashMessage ¶
func NewHTLCSecretHashMessage(tradeID, secretHash, pubKey, offerAddr, requestAddr string) (*SwapMessage, error)
NewHTLCSecretHashMessage creates a secret hash message for HTLC swaps.
func NewHTLCSecretRevealMessage ¶
func NewHTLCSecretRevealMessage(tradeID string, secret string) (*SwapMessage, error)
NewHTLCSecretRevealMessage creates a secret reveal message for HTLC swaps.
func NewOrderAnnounceMessage ¶
func NewOrderAnnounceMessage(orderID string, payload interface{}) (*SwapMessage, error)
NewOrderAnnounceMessage creates an order announcement message.
func NewOrderTakeMessage ¶
func NewOrderTakeMessage(orderID, tradeID string, payload interface{}) (*SwapMessage, error)
NewOrderTakeMessage creates an order take message.
func NewPubKeyExchangeMessage ¶
func NewPubKeyExchangeMessage(tradeID, pubKey, offerAddr, requestAddr string) (*SwapMessage, error)
NewPubKeyExchangeMessage creates a pubkey exchange message with wallet addresses. This is used by both parties to exchange their receiving addresses.
func NewSwapMessage ¶
func NewSwapMessage(msgType, tradeID string, payload interface{}) (*SwapMessage, error)
NewSwapMessage creates a generic swap message.
type SwapMessageHandler ¶
type SwapMessageHandler func(ctx context.Context, msg *SwapMessage) error
SwapMessageHandler handles incoming swap messages.