# Ring Network - Two Ring Topology with WebRTC A decentralized peer-to-peer network implementation using WebRTC for communication in a double ring topology with optional Oracle nodes for enhanced network services. ## ๐ŸŒŸ Features ### Core Network Features - **Double Ring Topology**: Inner and outer rings for redundancy and efficient routing - **WebRTC Peer-to-Peer**: Direct browser-to-browser/node-to-node communication - **Automatic Discovery**: Nodes can discover and connect to each other - **Message Routing**: Efficient message propagation through ring structures - **Network Resilience**: Automatic adaptation to node connections/disconnections ### Oracle Node Capabilities - **Network Analysis**: Topology analysis and health monitoring - **Distributed Data Storage**: Replicated data storage across Oracle nodes - **Consensus Mechanisms**: Distributed decision making - **Advanced Routing**: Sophisticated routing strategies - **Health Monitoring**: Continuous network health assessment - **Metrics Collection**: Network performance and usage statistics ## ๐Ÿ—๏ธ Architecture ``` Inner Ring: A โ†’ B โ†’ C โ†’ A Outer Ring: A โ† B โ† C โ† A Where: - A, B, C are network nodes - โ†’ indicates message flow direction - Each node maintains connections to its neighbors in both rings ``` ### Node Types 1. **Regular Nodes**: Basic network participants that route messages 2. **Oracle Nodes**: Enhanced nodes providing additional services ## ๐Ÿš€ Quick Start ### Installation ```bash # Clone or create the project directory cd ringnet # Install dependencies npm install ``` ### Running the Network 1. **Start the first node (Oracle) as bootstrap:** ```bash npm run start:oracle -- --port 8080 ``` 2. **Start additional nodes:** ```bash # Regular node npm run start:node -- --port 8081 --bootstrap localhost:8080 # Another Oracle node npm run start:oracle -- --port 8082 --bootstrap localhost:8080 ``` 3. **Start more nodes:** ```bash npm run start:node -- --port 8083 --bootstrap localhost:8080 ``` ## ๐Ÿ“– Usage ### Command Line Options ```bash --port # Port to listen on (default: random) --id # Node ID (default: auto-generated UUID) --bootstrap # Bootstrap node address (host:port) --ice-servers # ICE servers configuration (JSON array) --config # Load configuration from JSON file --help # Show help message ``` **Note**: Ring positions are now assigned automatically for optimal network topology. The system calculates the best position for each node to ensure even distribution around the ring. ### WebRTC ICE Servers Configuration The Ring Network uses WebRTC for peer-to-peer connections. You can configure custom ICE servers (STUN/TURN) for better connectivity: #### Using Command Line ```bash # With custom STUN servers node node.js --ice-servers '[{"urls":"stun:your-stun-server.com:19302"}]' # With TURN server for NAT traversal node node.js --ice-servers '[{"urls":"stun:stun.l.google.com:19302"},{"urls":"turn:your-turn-server.com:3478","username":"user","credential":"pass"}]' ``` #### Using Configuration Files ```bash # Load from config file node node.js --config config/ice-servers-with-turn.json # For Oracle nodes node oracle.js --config config/ice-servers-public-turn.json ``` #### Available Configuration Examples - `config/ice-servers-default.json` - Default Google STUN servers - `config/ice-servers-with-turn.json` - Template with TURN server - `config/ice-servers-public-turn.json` - Public TURN servers for testing #### ICE Server Configuration Format ```json { "iceServers": [ { "urls": "stun:stun.l.google.com:19302" }, { "urls": "turn:turnserver.example.com:3478", "username": "your_username", "credential": "your_password" } ] } ``` --help # Show help message ``` ### Interactive Commands Once a node is running, you can use these commands: #### Regular Node Commands - `send ` - Send a message through the ring - `info` - Show network information - `peers` - List connected peers - `connections` - Show persistent connection status - `topology` - Show ring topology and node positions - `help` - Show available commands - `quit` - Exit the node #### Oracle Node Commands (additional) - `health` - Perform network health check - `metrics` - Show network metrics - `analyze` - Analyze network topology - `store ` - Store data in distributed storage - `get ` - Retrieve data from storage - `propose ` - Create a consensus proposal - `vote ` - Vote on a proposal - `topology` - Show ring topology and node positions ## ๐Ÿ”ฎ Oracle Services Oracle nodes provide enhanced services to the network: ### 1. Network Analysis (`network-analysis`) - Topology mapping and analysis - Network health assessment - Performance recommendations ### 2. Data Storage (`data-storage`) - Distributed key-value storage - Automatic replication across Oracles - TTL (Time-To-Live) support ### 3. Consensus (`consensus`) - Proposal creation and voting - Majority-based decision making - Distributed agreement protocols ### 4. Routing (`routing`) - Advanced routing strategies - Shortest path calculation - Multi-path routing options ### 5. Health Monitoring (`health-check`) - Continuous network monitoring - Failure detection and reporting - Recovery recommendations ### 6. Network Metrics (`network-metrics`) - Performance statistics - Usage analytics - Historical data tracking ## ๐ŸŽฏ Automatic Ring Positioning The Ring Network now features **automatic node positioning** that optimizes network topology without manual configuration: ### Key Features - **Optimal Placement**: New nodes are automatically positioned in the largest gap between existing nodes - **Even Distribution**: Nodes are distributed evenly around the virtual ring for balanced load - **Dynamic Rebalancing**: Network topology adjusts automatically when nodes join or leave - **No Manual Configuration**: Eliminates the need to manually specify ring positions ### How It Works 1. **Virtual Ring**: The network uses a virtual ring of 1000 positions 2. **Gap Analysis**: When a new node joins, the system finds the largest gap between existing nodes 3. **Optimal Insertion**: The new node is placed in the middle of the largest gap 4. **Topology Update**: All nodes update their neighbor connections based on the new topology 5. **Automatic Rebalancing**: The system can redistribute nodes evenly when needed ### Benefits - **Simplified Setup**: No need to calculate or specify positions manually - **Better Performance**: Optimal positioning improves routing efficiency - **Self-Healing**: Network automatically adapts to node changes - **Scalability**: Easy to add new nodes without topology planning Use the `topology` command in any node to view the current ring structure and positions. ## ๐Ÿงช Testing Run the test suite to verify network functionality: ```bash npm test ``` The test suite covers: - Node initialization - Peer connections - Ring topology formation - Oracle services - Message routing - Network resilience ## ๐Ÿ“ API Reference ### RingNode Class ```javascript import { RingNode } from './src/ring-node.js'; const node = new RingNode({ id: 'optional-id', port: 8080, ringPosition: 0, isOracle: false }); // Events node.on('peerConnected', (peerId) => { }); node.on('peerDisconnected', (peerId) => { }); node.on('ringMessage', ({ from, payload }) => { }); node.on('networkUpdate', ({ from, payload }) => { }); // Methods node.sendRingMessage(payload, ring); node.joinRing(bootstrapNode); node.getNetworkInfo(); node.destroy(); ``` ### OracleNode Class ```javascript import { OracleNode } from './src/oracle-node.js'; const oracle = new OracleNode({ id: 'oracle-1', port: 8080 }); // Oracle-specific methods oracle.analyzeNetwork(); oracle.handleDataStorage({ operation: 'set', key: 'test', value: 'data' }); oracle.handleConsensus({ proposalId: 'prop1', proposal: 'Upgrade network' }); oracle.performHealthCheck(); oracle.getNetworkMetrics(); ``` ## ๐Ÿ”ง Configuration ### WebRTC Configuration The nodes use public STUN servers by default: - `stun:stun.l.google.com:19302` - `stun:stun1.l.google.com:19302` For production use, consider setting up your own TURN servers. ### Network Parameters - **Message History Size**: 1000 messages (prevents loops) - **Data TTL**: 1 hour default (configurable) - **Health Check Interval**: 30 seconds - **Metrics Collection**: 10 seconds - **Cleanup Interval**: 5 minutes ## ๐Ÿ›ก๏ธ Security Considerations - **Message Integrity**: All messages should be signed in production - **Node Authentication**: Implement proper node authentication - **Data Encryption**: Encrypt sensitive data in storage - **Rate Limiting**: Implement rate limiting for message propagation - **Access Control**: Restrict Oracle services to authorized nodes ## ๐Ÿ› Troubleshooting ### Common Issues 1. **Connection Failures** - Check firewall settings - Verify port availability - Ensure WebRTC support 2. **Bootstrap Node Unreachable** - Verify bootstrap node is running - Check network connectivity - Confirm port and address 3. **Ring Formation Issues** - Allow time for topology stabilization - Check node discovery process - Verify peer connections ### Debug Mode Enable debug logging by setting environment variable: ```bash DEBUG=ringnet:* npm start ``` ## ๐Ÿค Contributing 1. Fork the repository 2. Create a feature branch 3. Implement your changes 4. Add tests for new functionality 5. Run the test suite 6. Submit a pull request ## ๐Ÿ“„ License MIT License - see LICENSE file for details. ## ๐Ÿ”— Related Projects - [WebRTC](https://webrtc.org/) - Real-time communication - [Node.js WebRTC](https://github.com/node-webrtc/node-webrtc) - WebRTC for Node.js - [Chord DHT](https://en.wikipedia.org/wiki/Chord_(peer-to-peer)) - Distributed hash table - [Kademlia](https://en.wikipedia.org/wiki/Kademlia) - Distributed hash table protocol ## ๐Ÿ“š Further Reading - [Peer-to-Peer Networks](https://en.wikipedia.org/wiki/Peer-to-peer) - [Distributed Systems](https://en.wikipedia.org/wiki/Distributed_computing) - [WebRTC Documentation](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API) - [Consensus Algorithms](https://en.wikipedia.org/wiki/Consensus_(computer_science)) ### Connection Persistence The Ring Network now includes connection persistence features: #### Persistent Connection Management - **Automatic Connection Maintenance**: Nodes automatically maintain persistent WebRTC connections with other nodes - **Heartbeat System**: Regular heartbeat messages keep connections alive and detect failures - **Connection Monitoring**: Built-in monitoring of connection health and status - **Automatic Reconnection**: Failed connections are automatically retried with exponential backoff #### Connection Status Use the `connections` command to view: - Total active connections - Persistent connection count - Connection health status - Last seen timestamps for each peer - Reconnection attempt counts #### Bootstrap Connections When joining via a bootstrap node: - Initial WebSocket connection for joining the network - Automatic establishment of persistent WebRTC connection - Bootstrap node maintains connection with new nodes - Connection health monitoring and automatic recovery #### Features - โœ… **Heartbeat Messages**: 30-second intervals to maintain connections - โœ… **Connection Health Checks**: Monitor connection state every 30 seconds - โœ… **Automatic Reconnection**: Up to 3 attempts before giving up - โœ… **Connection Status Monitoring**: Real-time connection status display - โœ… **Graceful Shutdown**: Proper cleanup of connections and intervals