Mesh Network

v3.5.10

WebSocket-based peer-to-peer mesh infrastructure

The YAKMESH mesh network provides the communication backbone for all peer-to-peer operations. Built on WebSockets with quantum-resistant cryptography, gossip protocols, and onion routing.

"Your packets travel like yak caravans through hidden mountain paths"

The mesh network is designed for resilience, privacy, and decentralization. No central servers, no single points of failure — just nodes cooperating through cryptographic trust.

Quick Start

Create and start a mesh network node:

import { MeshNetwork, MessageTypes } from './mesh/network.js';

// Create mesh network with your node identity
const mesh = new MeshNetwork(identity, {
  wsPort: 9080,           // WebSocket port (auto-fallback if in use)
  maxConcurrentHandshakes: 50,  // Sybil gate on HELLO/WELCOME (peers unbounded)
  pingInterval: 30000,    // Keep-alive ping interval (ms)
  portRetries: 10,        // Try up to 10 sequential ports
  networkId: 'yakmesh',   // Network identifier
  networkFingerprint: fingerprint,  // Code proof verification
});

// Start listening for connections
await mesh.start();

// Connect to a peer
await mesh.connect('ws://peer-node:9001');

// Broadcast to all peers (gossip)
mesh.broadcast({ type: 'custom', data: 'hello mesh!' });

// Send to specific peer
mesh.sendTo(nodeId, { action: 'sync', payload: data });

// Listen for messages
mesh.on(MessageTypes.GOSSIP, (msg, ws, nodeId) => {
  console.log(`Gossip from ${nodeId}:`, msg.payload);
});

// Get connected peers
const peers = mesh.getPeers();
console.log(`Connected to ${peers.length} peers`);

// Stop mesh server
await mesh.stop();

Message Types

The mesh protocol uses these message types for peer communication:

Type Constant Description
hello MessageTypes.HELLO Handshake with identity, network fingerprint, and signed proof-of-possession (nodeId + timestamp + Tribhuj ratchet key + persistentId)
welcome MessageTypes.WELCOME Response with peer list and reciprocal proof-of-possession binding nodeId to the responder's identity key
ping MessageTypes.PING Keep-alive ping
pong MessageTypes.PONG Keep-alive response
peers MessageTypes.PEERS Share known peer endpoints
sync_request MessageTypes.SYNC_REQUEST Request data synchronization
sync_response MessageTypes.SYNC_RESPONSE Data sync response
replicate MessageTypes.REPLICATE Push new data to peers
gossip MessageTypes.GOSSIP Broadcast message with deduplication

Mesh Modules

The mesh subsystem is composed of specialized modules, each handling a critical aspect of network communication.

MeshNetwork

network.js

Core mesh network manager handling peer connections, message routing, and WebSocket server. Features automatic port fallback, code proof verification, and gossip with deduplication.

import { MeshNetwork, MessageTypes } from './mesh/network.js';

const mesh = new MeshNetwork(identity, { wsPort: 9080 });
await mesh.start();
mesh.broadcast({ type: 'announce', data: myData });
WebSocket Gossip Protocol Port Fallback Code Proof

ANNEX

annex.js — Autonomous Network Negotiated Encrypted eXchange

End-to-end encrypted point-to-point channels using ML-KEM768 (Kyber) for quantum-resistant key exchange and AES-256-GCM for authenticated encryption. Perfect forward secrecy via ephemeral keys.

import { Annex } from 'yakmesh/mesh/annex';

const annex = new Annex({ identity: myIdentity, mesh: meshNetwork });
await annex.send(peerNodeId, { secret: 'data' });  // E2E encrypted, session auto-established
ML-KEM768 AES-256-GCM ML-DSA-65 PFS

Beacon Broadcast

beacon-broadcast.js — Broadcast Emergency Alert Channel Over Network

Priority message propagation with guaranteed delivery. Flood-based protocol with intelligent deduplication, proof-of-receipt, and emergency priority levels (ROUTINE → CRITICAL).

import { StupaBroadcast, STUPA_CONFIG } from 'yakmesh/mesh/beacon-broadcast';

const stupa = new StupaBroadcast({ nodeId: myNodeId });
stupa.addPeer(peerId);
const message = stupa.broadcast(payload, {
  priority: STUPA_CONFIG.priorities.IMMEDIATE,
  ttl: 10,  // hop count
});
Priority Levels Proof-of-Receipt TTL Control

SHERPA Discovery

sherpa-discovery.js — Secure Hidden Endpoint Resolution Path Architecture

Decentralized peer discovery using public web endpoints as a DHT. Nodes expose /.well-known/yakmesh/beacon for self-organizing peer registry. No central bootstrap nodes required.

import { SherpaDiscovery } from './mesh/sherpa-discovery.js';

const sherpa = new SherpaDiscovery(identity, {
  maxCrawlDepth: 3,
  crawlInterval: 300000,  // 5 minutes
});
const peers = await sherpa.discover(seedEndpoints);
Web DHT Peer Scoring Geo-Proof v2.5

NAKPAK Routing

nakpak-routing.js — Nested Anonymous Kernel for Private Authenticated Komms

Post-quantum secure onion routing with ML-DSA-65 signatures at every layer and ML-KEM key encapsulation. Multi-layer encryption with timing attack resistance through temporal padding.

import { NakpakRouter } from './mesh/nakpak-routing.js';

const router = new NakpakRouter(identity, mesh);
const circuit = await router.buildCircuit(3);  // 3 hops
await router.sendAnonymous(circuit, payload);
Onion Routing ML-KEM768 Decoy Traffic Fixed-Size Packets

Pulse Sync

pulse-sync.js — Precision Universal Latency Sync Engine

The heartbeat of the mesh network. Distributed liveness detection with temporal proofs, cryptographic heartbeat chains, and partition detection through gap analysis.

import { PulseSync } from './mesh/pulse-sync.js';

const pulse = new PulseSync(identity, mesh, {
  heartbeatIntervalMs: 1000,
  missedBeatsThreshold: 5,
});
pulse.on('partition', (nodes) => handlePartition(nodes));
Heartbeat Chains Partition Detection Leader Election

Echo Ranging

echo-ranging.js — Encrypted Coordinate Heuristic Oracle

Privacy-preserving network cartography. Maps mesh topology using encrypted timing probes without exposing node positions. Builds virtual coordinate space from RTT measurements.

import { EchoRanging } from './mesh/echo-ranging.js';

const echo = new EchoRanging(identity, mesh);
const rtt = await echo.measureLatency(peerId);
const coords = echo.getVirtualCoordinates();
RTT Measurement Virtual Coords Encrypted Probes

Temporal Encoder

temporal-encoder.js — Temporal Mesh Encoding

Novel packet resilience through temporal encoding. Instead of erasure coding across space, TME encodes data across TIME using synchronized clocks as the redundancy dimension.

import { TemporalMeshEncoder } from 'yakmesh/mesh/temporal-encoder';

const encoder = new TemporalMeshEncoder({
  nodeId: myNodeId,
  meshPosition: [1, 2, 3],
});
const { streamId, slices, metadata } = encoder.encode(data);
Temporal Slicing Hash Chains Path Diversity

v3.3.0 Hardening Protocols

Three new protocols introduced in v3.3.0 strengthen the mesh against resource exhaustion, sybil attacks, and internal component compromise.

Security Modules

Defense-in-depth protection against network attacks:

Rate Limiter

rate-limiter.js

Sliding window rate limiter protecting against connection floods, handshake spam, and gossip storms. Per-IP and per-node tracking with automatic banning.

import { ConnectionRateLimiter } from './mesh/rate-limiter.js';

const limiter = new ConnectionRateLimiter({
  maxConnectionsPerMinute: 10,
  maxMessagesPerSecond: 50,
  maxHandshakesPerMinute: 5,
  banThreshold: 5,
  banDuration: 300000,  // 5 minutes
});

if (!limiter.checkConnection(ip).allowed) {
  ws.close(1008, 'Rate limited');
}
Sliding Window Auto-Ban Per-IP Tracking

Message Validator

message-validator.js

Validates message size and structure to prevent amplification attacks. Enforces payload limits by type: gossip (64KB), handshake (8KB), listing (128KB), data (512KB).

import { MessageValidator, SafeJsonParser } from './mesh/message-validator.js';

const validator = new MessageValidator();
const parser = new SafeJsonParser();

const sizeCheck = validator.validateRaw(rawMessage, 'gossip');
if (!sizeCheck.valid) reject(sizeCheck.reason);

const parsed = parser.parse(rawMessage);
if (!parsed.success) reject(parsed.error);

const structCheck = validator.validateStructure(parsed.data, 'gossip');
if (!structCheck.valid) reject(structCheck.reason);
Size Limits Depth Check Safe JSON

Replay Defense

replay-defense.js

Multi-layer replay attack protection with nonce registry, timestamp validation, and sequence tracking. Automatically detects and rejects duplicate or out-of-window messages.

import { NonceRegistry, TimestampValidator, SequenceTracker } 
  from './mesh/replay-defense.js';

const nonces = new NonceRegistry({ maxAge: 3600000 });
const timestamps = new TimestampValidator({ maxAge: 600000 });
const sequences = new SequenceTracker();

// Generate nonce for outgoing message
const nonce = nonces.generate();

// Validate incoming message
const nonceOk = nonces.validate(msg.nonce);
const timeOk = timestamps.validate(msg.timestamp);
const seqOk = sequences.validate(msg.senderId, msg.sequence);
Nonce Registry Timestamp Sequence Window

Sybil Defense

sybil-defense.js

Protection against Sybil attacks through NAVR (proof-of-work challenges), reputation tracking, and subnet diversity enforcement.

import { NAVR, ReputationTracker, SubnetDiversity } 
  from 'yakmesh/mesh/sybil-defense';

const navr = new NAVR({ difficulty: 16 });
const reputation = new ReputationTracker();
const subnets = new SubnetDiversity({ maxPerSubnet: 3 });

// Challenge new peer
const challenge = navr.createChallenge(peerId);
// Peer solves and returns solution
const verified = navr.verify(challenge, solution);

// Track reputation
reputation.registerNode(peerId, solution);
reputation.reportGoodBehavior(peerId);
const trust = reputation.getTrustLevel(peerId);  // 'trusted'|'normal'|'suspicious'|'banned'

// Check subnet diversity
if (!subnets.allowConnection(peerIp).allowed) {
  reject('Too many connections from this subnet');
}
NAVR PoW Reputation Subnet Diversity

Key Features

Automatic Port Fallback

If the configured WebSocket port is in use, automatically tries sequential ports up to portRetries times.

Code Proof Verification

Network fingerprint exchanged during handshake. Nodes running different codebases are automatically rejected.

Gossip Deduplication

Messages include unique IDs tracked in seenMessages set. Prevents infinite broadcast loops.

Signed Messages

All outgoing messages are signed with the node's identity using ML-DSA-65. Receivers verify authenticity.

Handshake Proof-of-Possession v3.5.10

HELLO/WELCOME carry ML-DSA-65 signatures binding nodeId, timestamp, the Tribhuj ratchet public key, and — since v3.5.10 — the persistentId. The claimed nodeId must derive from the claimed key, and a 5-minute freshness window rejects replays. Peers presenting the legacy 3-field proof are accepted during rolling upgrades but marked persistentIdBound: false.

Pinned Ratchet Keys v3.5.10

Peer Tribhuj keys are pinned through the authenticated handshake — messages verify only against pinned keys. Rotation requires a signed certificate from the pinned identity key. Unknown keys fail closed.

Persistent Identity v3.5.10

Each node carries a 162-trit persistentId that survives code upgrades and re-keying. 162T routing derives addresses from it (summit IDs map verbatim; lower tiers via SHA3 domain separation), the routing table deduplicates re-keyed machines by address, and KARMA evidence keys on persistentId so reputation follows the machine.

Configuration

MeshNetwork constructor options:

Option Default Description
wsPort 9001 WebSocket server port (the packaged node config defaults to 9080)
maxPeers 10 Maximum concurrent peer connections
pingInterval 30000 Keep-alive ping interval (ms)
portRetries 10 Number of sequential ports to try if base port is in use
networkId null Network identifier for code proof
networkFingerprint null Codebase hash for peer verification
publicHost null Public hostname for endpoint advertisement
rateLimiter {} Rate limiter configuration object

MeshNetwork API

Method Description
start() Start WebSocket server with automatic port fallback
connect(endpoint) Connect to a peer node, returns identity on WELCOME
broadcast(message) Send gossip message to all connected peers
sendTo(nodeId, message) Send direct message to specific peer
on(type, handler) Register message handler for type
off(type, handler) Remove message handler
emit(type, ...args) Emit event to registered handlers
isConnectedTo(nodeId) Check if connected to a specific node
getPeers() Get list of connected peers with metadata
getPublicEndpoint() Get this node's public WebSocket endpoint
stop() Stop server and close all connections

Related Documentation

  • SHERPA — Detailed peer discovery documentation
  • NAKPAK — Onion routing deep dive
  • ANNEX — Encrypted P2P channels
  • TATTVA — Code proof and validation
  • SURAKSHA — Trust scoring and verification
  • Configuration — Full configuration reference

Provenance full version history →

Introduced in v1.0.2 — Mesh core.

  • v3.3.0 — ARCH-RESONANCE mesh hardening
  • v3.5.10 — persistentId-bound handshakes + upgrade grace