package main
import (
"bytes"
"compress/gzip"
"context"
"encoding/gob"
"encoding/json"
"fmt"
"log"
"math"
"math/rand"
"net"
"os"
"os/signal"
"sort"
"sync"
"syscall"
"time"
)
// ==========================================
// 1. Configuration & Data Structures
// ==========================================
type Config struct {
NodeID string
BindAddr string
Peers []string // Initial peer list
GossipInterval time.Duration
FanoutBase int
MaxPacketSize int
CompressionThreshold int
}
type Message struct {
Type string // "HEARTBEAT", "DATA", "NACK"
SenderID string
Timestamp int64
Payload []byte
Compressed bool
}
type PeerState struct {
Address string
LastHeartbeat time.Time
History []time.Duration // For Phi Accrual
TrustScore float64 // 0.0 to 1.0
IsAlive bool
}
// ==========================================
// 2. Trust Model
// ==========================================
type TrustManager struct {
mu sync.RWMutex
peers map[string]*PeerState
}
func NewTrustManager() *TrustManager {
return &TrustManager{peers: make(map[string]*PeerState)}
}
// RecordHeartbeat updates the history for Phi calculation and boosts trust slightly
func (tm *TrustManager) RecordHeartbeat(peerID string, latency time.Duration) {
tm.mu.Lock()
defer tm.mu.Unlock()
state, exists := tm.peers[peerID]
if !exists {
state = &PeerState{
Address: peerID,
TrustScore: 0.5, // Start neutral
IsAlive: true,
}
tm.peers[peerID] = state
}
state.LastHeartbeat = time.Now()
state.IsAlive = true
// Keep limited history for variance calculation
state.History = append(state.History, latency)
if len(state.History) > 100 {
state.History = state.History[1:]
}
// Reward good behavior
state.TrustScore = math.Min(1.0, state.TrustScore+0.01)
}
// Penalize reduces trust score (e.g., for invalid messages or timeouts)
func (tm *TrustManager) Penalize(peerID string) {
tm.mu.Lock()
defer tm.mu.Unlock()
if state, exists := tm.peers[peerID]; exists {
state.TrustScore = math.Max(0.0, state.TrustScore-0.1)
}
}
// CalculatePhi implements the Phi Accrual Failure Detector
// Returns a suspicion level. > 1.0 usually implies suspicion.
func (tm *TrustManager) CalculatePhi(peerID string) float64 {
tm.mu.RLock()
defer tm.mu.RUnlock()
state, exists := tm.peers[peerID]
if !exists || len(state.History) < 2 {
return 0.0
}
// Calculate mean and variance of heartbeat intervals
var sum, mean, variance float64
n := float64(len(state.History))
for _, d := range state.History {
sum += float64(d.Milliseconds())
}
mean = sum / n
for _, d := range state.History {
diff := float64(d.Milliseconds()) - mean
variance += diff * diff
}
variance /= n
// Standard deviation
pStdDev := math.Sqrt(variance)
if pStdDev == 0 { pStdDev = 1 } // Avoid division by zero
// Time since last heartbeat
timeSinceLast := time.Since(state.LastHeartbeat).Milliseconds()
// Probability calculation (Normal Distribution approximation)
// y = (x - mean) / std_dev
y := (float64(timeSinceLast) - mean) / pStdDev
// phi = -log10(1 - F(y)) where F is CDF
// Simplified phi calculation:
return math.Abs(y)
}
// GetTrustedPeers returns peers sorted by trust score, weighted random selection
func (tm *TrustManager) GetTrustedPeers(exclude string, count int) []string {
tm.mu.RLock()
defer tm.mu.RUnlock()
// Filter candidates
candidates := []string{}
for id, state := range tm.peers {
// Only consider peers with decent trust and low Phi (suspicion)
if id != exclude && state.TrustScore > 0.2 && tm.CalculatePhi(id) < 2.0 {
candidates = append(candidates, id)
}
}
// Sort by trust score (descending)
sort.Slice(candidates, func(i, j int) bool {
return tm.peers[candidates[i]].TrustScore > tm.peers[candidates[j]].TrustScore
})
// Select top 'count'
if len(candidates) < count {
return candidates
}
return candidates[:count]
}
// ==========================================
// 3. Network & Compression
// ==========================================
type Transport struct {
conn *net.UDPConn
compressor *CompressionEngine
}
func NewTransport(addr string) (*Transport, error) {
udpAddr, _ := net.ResolveUDPAddr("udp", addr)
conn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return nil, err
}
return &Transport{conn: conn, compressor: &CompressionEngine{}}, nil
}
func (t *Transport) Send(addr string, msg Message) error {
b, _ := t.compressor.Serialize(msg)
// Simple reliability: if packet too large, drop or fragment (omitted for brevity)
if len(b) > 1400 {
// In prod, implement fragmentation or MTU discovery
return fmt.Errorf("packet too large")
}
udpAddr, _ := net.ResolveUDPAddr("udp", addr)
_, err := t.conn.WriteToUDP(b, udpAddr)
return err
}
func (t *Transport) Receive() (Message, *net.UDPAddr, error) {
buf := make([]byte, 2048)
n, addr, err := t.conn.ReadFromUDP(buf)
if err != nil {
return Message{}, nil, err
}
var msg Message
err = t.compressor.Deserialize(buf[:n], &msg)
return msg, addr, err
}
type CompressionEngine struct{}
func (c *CompressionEngine) Serialize(msg Message) ([]byte, error) {
if !msg.Compressed {
return json.Marshal(msg)
}
// Already compressed payload, just wrap
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(msg)
return buf.Bytes(), err
}
func (c *CompressionEngine) Deserialize(data []byte, msg *Message) error {
// Try gob first (binary), then json
dec := gob.NewDecoder(bytes.NewReader(data))
if err := dec.Decode(msg); err == nil {
return nil
}
return json.Unmarshal(data, msg)
}
// ApplyCompression compresses the payload if enabled
func ApplyCompression(payload []byte) ([]byte, bool) {
if len(payload) < 500 { // Threshold
return payload, false
}
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(payload)
w.Close()
return b.Bytes(), true
}
// ==========================================
// 4. Adaptive Logic & Observability
// ==========================================
type Metrics struct {
Latency float64
Fanout int
PeersAlive int
}
type GossipNode struct {
Config
Transport *Transport
Trust *TrustManager
Metrics Metrics
stopCh chan struct{}
}
func NewGossipNode(cfg Config) (*GossipNode, error) {
t, err := NewTransport(cfg.BindAddr)
if err != nil {
return nil, err
}
tm := NewTrustManager()
// Seed initial peers
for _, p := range cfg.Peers {
tm.RecordHeartbeat(p, 10*time.Millisecond) // Initial assumption
}
return &GossipNode{
Config: cfg,
Transport: t,
Trust: tm,
stopCh: make(chan struct{}),
}, nil
}
// calculateAdaptiveFanout adjusts gossip spread based on cluster health
func (n *GossipNode) calculateAdaptiveFanout() int {
suspiciousCount := 0
total := 0
// Check health via Trust Manager
for _, peer := range n.Trust.peers {
total++
if n.Trust.CalculatePhi(peer.Address) > 1.0 {
suspiciousCount++
}
}
healthRatio := 1.0
if total > 0 {
healthRatio = 1.0 - (float64(suspiciousCount) / float64(total))
}
// Logic: If cluster is unstable (low health), increase fanout to ensure redundancy.
// If cluster is healthy, reduce fanout to save bandwidth (Low Latency).
// Base formula: Fanout = log2(N). Adaptive: Scale by (1 / health).
baseFanout := n.FanoutBase
if healthRatio < 0.8 {
// Unstable cluster: Aggressively gossip
baseFanout = int(float64(baseFanout) * 1.5)
}
// Cap at reasonable limits
if baseFanout > 6 { baseFanout = 6 }
if baseFanout < 1 { baseFanout = 1 }
return baseFanout
}
// ==========================================
// 5. Main Loops
// ==========================================
func (n *GossipNode) Start() {
// 1. Receiver Loop
go n.receiveLoop()
// 2. Gossip Loop (Heartbeats & Data)
go n.gossipLoop()
// 3. Monitoring Loop
go n.monitorLoop()
}
func (n *GossipNode) receiveLoop() {
for {
select {
case <-n.stopCh:
return
default:
msg, addr, err := n.Transport.Receive()
if err != nil {
continue
}
// 1. Trust Check (Anti-Spam)
if msg.SenderID != n.NodeID {
latency := time.Since(time.Unix(0, msg.Timestamp))
n.Trust.RecordHeartbeat(msg.SenderID, latency)
}
// 2. Handle Payload
if msg.Type == "DATA" {
// Decompress if needed
if msg.Compressed {
// Decompress logic here (omitted for brevity, inverse of ApplyCompression)
}
fmt.Printf("[%s] Received Data from %s\n", n.NodeID, msg.SenderID)
}
}
}
}
func (n *GossipNode) gossipLoop() {
ticker := time.NewTicker(n.GossipInterval)
for {
select {
case <-n.stopCh:
return
case <-ticker.C:
// Determine Adaptive Fanout
fanout := n.calculateAdaptiveFanout()
n.Metrics.Fanout = fanout
// Select targets based on Trust Score
targets := n.Trust.GetTrustedPeers(n.NodeID, fanout)
// Construct Message
msg := Message{
Type: "HEARTBEAT",
SenderID: n.NodeID,
Timestamp: time.Now().UnixNano(),
}
// Send
for _, target := range targets {
go func(t string) {
// Simulate Latency measurement start
start := time.Now()
err := n.Transport.Send(t, msg)
if err != nil {
// Failure detection integration: Penalize on send failure
n.Trust.Penalize(t)
}
// Update Metrics
n.Metrics.Latency = float64(time.Since(start).Milliseconds())
}(target)
}
}
}
}
func (n *GossipNode) monitorLoop() {
ticker := time.NewTicker(5 * time.Second)
for {
select {
case <-n.stopCh:
return
case <-ticker.C:
alive := 0
for _, p := range n.Trust.peers {
if p.IsAlive && n.Trust.CalculatePhi(p.Address) < 2.0 {
alive++
}
}
n.Metrics.PeersAlive = alive
log.Printf("[OBSERVABILITY] Node: %s | Fanout: %d | Peers: %d | Latency: %.2fms",
n.NodeID, n.Metrics.Fanout, n.Metrics.PeersAlive, n.Metrics.Latency)
}
}
}
func main() {
// Setup 3 nodes locally for simulation
cfg1 := Config{NodeID: "Node1", BindAddr: "127.0.0.1:5001", Peers: []string{"127.0.0.1:5002", "127.0.0.1:5003"}, GossipInterval: 1*time.Second, FanoutBase: 2}
cfg2 := Config{NodeID: "Node2", BindAddr: "127.0.0.1:5002", Peers: []string{"127.0.0.1:5001", "127.0.0.1:5003"}, GossipInterval: 1*time.Second, FanoutBase: 2}
cfg3 := Config{NodeID: "Node3", BindAddr: "127.0.0.1:5003", Peers: []string{"127.0.0.1:5001", "127.0.0.1:5002"}, GossipInterval: 1*time.Second, FanoutBase: 2}
n1, _ := NewGossipNode(cfg1)
n2, _ := NewGossipNode(cfg2)
n3, _ := NewGossipNode(cfg3)
n1.Start()
n2.Start()
n3.Start()
fmt.Println("Gossip Protocol Running... Press Ctrl+C to stop")
// Wait for shutdown
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh
}