node

package
v0.0.0-...-3d75ffd Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: MIT Imports: 35 Imported by: 0

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

View Source
const (
	// Mainnet
	MainnetDHTPrefix   = "/klingon"
	MainnetDiscoveryNS = "klingon-mainnet"

	// Testnet
	TestnetDHTPrefix   = "/klingon-testnet"
	TestnetDiscoveryNS = "klingon-testnet"
)

Network-specific constants for peer separation.

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

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

View Source
const ConfigFileName = "config.yaml"

ConfigFileName is the default config file name.

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

func ConfigPath(dataDir string) string

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

func LoadConfig(dataDir string) (*Config, error)

LoadConfig loads configuration from a YAML file. If the file doesn't exist, it creates one with default values.

func (*Config) DHTPrefix

func (c *Config) DHTPrefix() string

DHTPrefix returns the DHT protocol prefix for the configured network.

func (*Config) DiscoveryNamespace

func (c *Config) DiscoveryNamespace() string

DiscoveryNamespace returns the discovery namespace for the configured network.

func (*Config) GetBackendConfig

func (c *Config) GetBackendConfig(symbol string) *backend.Config

GetBackendConfig returns the backend config for a chain symbol. Returns default config if not explicitly configured.

func (*Config) GetBackendURL

func (c *Config) GetBackendURL(symbol string) string

GetBackendURL returns the appropriate backend URL for the chain and network.

func (*Config) IsTestnet

func (c *Config) IsTestnet() bool

IsTestnet returns true if running on testnet.

func (*Config) Save

func (c *Config) Save(path string) error

Save writes the configuration to a YAML file.

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

type FundingInfoPayload struct {
	TxID string `json:"txid"`
	Vout uint32 `json:"vout"`
}

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

func NewMessageEncryptor(privKey crypto.PrivKey, peerID peer.ID) (*MessageEncryptor, error)

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 New

func New(ctx context.Context, cfg *Config) (*Node, error)

New creates a new Klingon P2P node.

func (*Node) Addrs

func (n *Node) Addrs() []multiaddr.Multiaddr

Addrs returns the node's listen addresses.

func (*Node) Config

func (n *Node) Config() *Config

Config returns the node configuration.

func (*Node) Connect

func (n *Node) Connect(ctx context.Context, pi peer.AddrInfo) error

Connect connects to a peer.

func (*Node) ConnectByAddr

func (n *Node) ConnectByAddr(ctx context.Context, addr string) error

ConnectByAddr connects to a peer by multiaddr string.

func (*Node) DHT

func (n *Node) DHT() *dht.IpfsDHT

DHT returns the Kademlia DHT.

func (*Node) GetTopic

func (n *Node) GetTopic(topicName string) *pubsub.Topic

GetTopic returns a PubSub topic by name. Used by message sender to publish encrypted messages.

func (*Node) HandlePeerFound

func (n *Node) HandlePeerFound(pi peer.AddrInfo)

HandlePeerFound is called when mDNS discovers a peer.

func (*Node) Host

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

Host returns the underlying libp2p host.

func (*Node) ID

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

ID returns the node's peer ID.

func (*Node) LoadPersistedPeers

func (n *Node) LoadPersistedPeers() error

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

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

OnPeerConnected sets a callback for when a peer connects.

func (*Node) OnPeerDisconnected

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

OnPeerDisconnected sets a callback for when a peer disconnects.

func (*Node) PeerCount

func (n *Node) PeerCount() int

PeerCount returns the number of connected peers.

func (*Node) Peers

func (n *Node) Peers() []peer.ID

Peers returns the list of connected peers.

func (*Node) PubSub

func (n *Node) PubSub() *pubsub.PubSub

PubSub returns the GossipSub instance.

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

func (n *Node) SavePeerCache() error

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

func (n *Node) SetupDirectMessaging(store *storage.Storage) error

SetupDirectMessaging initializes the direct P2P messaging layer. This must be called after the node is created and before Start().

func (*Node) Start

func (n *Node) Start() error

Start starts the node and connects to bootstrap peers.

func (*Node) Stop

func (n *Node) Stop() error

Stop stops the node gracefully.

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.

func (*Node) Uptime

func (n *Node) Uptime() time.Duration

Uptime returns how long the node has been running.

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.

func (*PeerMonitor) Stop

func (m *PeerMonitor) Stop()

Stop stops the peer monitor.

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.

func (*RetryWorker) Stop

func (w *RetryWorker) Stop()

Stop stops the retry worker.

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.

func (*StreamHandler) Stop

func (h *StreamHandler) Stop()

Stop stops the stream handler.

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.

func (*SwapHandler) Stop

func (h *SwapHandler) Stop() error

Stop stops the swap handler.

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.

Jump to

Keyboard shortcuts

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