#!/usr/bin/env node import { RingNode } from '../src/ring-node.js'; import { OracleNode } from '../src/oracle-node.js'; import chalk from 'chalk'; /** * Example script demonstrating Ring Network usage * This creates a simple network and shows basic operations */ console.log(chalk.blue.bold('๐Ÿ”— Ring Network Example\n')); class NetworkExample { constructor() { this.nodes = []; this.isRunning = false; } async delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async createNetwork() { console.log(chalk.cyan('๐Ÿ—๏ธ Creating example network...')); // Create Oracle node (bootstrap) const oracle = new OracleNode({ id: 'oracle-example', port: 9000 }); this.nodes.push(oracle); // Create regular nodes const node1 = new RingNode({ id: 'node-1-example', port: 9001 }); this.nodes.push(node1); const node2 = new RingNode({ id: 'node-2-example', port: 9002 }); this.nodes.push(node2); console.log(chalk.green('โœ… Created 3 nodes: 1 Oracle + 2 Regular')); // Set up event handlers this.setupEventHandlers(); // Allow nodes to initialize await this.delay(2000); return { oracle, node1, node2 }; } setupEventHandlers() { this.nodes.forEach((node, index) => { const nodeType = node.isOracle ? 'Oracle' : 'Node'; const nodeColor = node.isOracle ? chalk.yellow : chalk.blue; node.on('peerConnected', (peerId) => { // Peer connected }); node.on('peerDisconnected', (peerId) => { // Peer disconnected }); node.on('ringMessage', ({ from, payload }) => { // Message received }); }); } async demonstrateBasicMessaging() { console.log(chalk.magenta('\n๐Ÿ“จ Demonstrating basic messaging...')); const [oracle, node1, node2] = this.nodes; // Simulate ring connections for demonstration // In real usage, these would be established via WebRTC oracle.rings.inner.right = node1.id; node1.rings.inner.right = node2.id; node2.rings.inner.right = oracle.id; // Simulate message sending oracle.emit('ringMessage', { from: oracle.id, payload: { type: 'greeting', message: 'Hello from Oracle!' } }); node1.emit('ringMessage', { from: node1.id, payload: { type: 'response', message: 'Node 1 received the message!' } }); await this.delay(1000); console.log(chalk.green('โœ… Basic messaging demonstration complete')); } async demonstrateOracleServices() { console.log(chalk.yellow('\n๐Ÿ”ฎ Demonstrating Oracle services...')); const oracle = this.nodes[0]; // Network Analysis console.log(chalk.cyan('\n1. Network Analysis:')); const analysis = oracle.analyzeNetwork(); console.log(` - Network size: ${analysis.networkSize}`); console.log(` - Network health: ${analysis.networkHealth.overall}%`); console.log(` - Recommendations: ${analysis.recommendations.length}`); // Data Storage console.log(chalk.cyan('\n2. Data Storage:')); const storeResult = oracle.handleDataStorage({ operation: 'set', key: 'example-key', value: { message: 'Hello World!', timestamp: Date.now() } }); console.log(` - Data stored: ${storeResult.success}`); const retrieveResult = oracle.handleDataStorage({ operation: 'get', key: 'example-key' }); console.log(` - Data retrieved: ${retrieveResult.success}`); console.log(` - Value: ${JSON.stringify(retrieveResult.value)}`); // Consensus console.log(chalk.cyan('\n3. Consensus:')); const proposalId = 'example-proposal-' + Date.now(); const consensusResult = oracle.handleConsensus({ proposalId, proposal: 'Upgrade network protocol to v2.0' }); console.log(` - Proposal created: ${consensusResult.success}`); console.log(` - Proposal ID: ${proposalId}`); // Health Check console.log(chalk.cyan('\n4. Health Check:')); const health = oracle.performHealthCheck(); console.log(` - Network healthy: ${health.healthy}`); console.log(` - Connected peers: ${health.checks.webrtc}`); console.log(` - Uptime: ${Math.round(health.checks.uptime / 1000)}s`); // Metrics console.log(chalk.cyan('\n5. Network Metrics:')); const metrics = oracle.getNetworkMetrics(); console.log(` - Messages processed: ${metrics.messagesProcessed}`); console.log(` - Queries answered: ${metrics.queriesAnswered}`); console.log(` - Data store size: ${metrics.dataStoreSize}`); console.log(chalk.green('โœ… Oracle services demonstration complete')); } async demonstrateNetworkTopology() { console.log(chalk.blue('\n๐Ÿ”— Demonstrating network topology...')); const [oracle, node1, node2] = this.nodes; // Show network information for each node this.nodes.forEach((node, index) => { const info = node.getNetworkInfo(); const nodeType = node.isOracle ? 'Oracle' : 'Node'; console.log(chalk.cyan(`\n${nodeType} ${index} (${info.nodeId.substring(0, 8)}):`)); console.log(` - Port: ${info.port}`); console.log(` - Known nodes: ${info.knownNodes.length}`); console.log(` - Oracle nodes: ${info.oracleNodes.length}`); console.log(` - Inner ring: L=${info.rings.inner.left?.substring(0, 8) || 'none'} R=${info.rings.inner.right?.substring(0, 8) || 'none'}`); console.log(` - Outer ring: L=${info.rings.outer.left?.substring(0, 8) || 'none'} R=${info.rings.outer.right?.substring(0, 8) || 'none'}`); }); console.log(chalk.green('\nโœ… Network topology demonstration complete')); } async demonstrateAdvancedFeatures() { console.log(chalk.magenta('\nโšก Demonstrating advanced features...')); const oracle = this.nodes[0]; // Routing strategies console.log(chalk.cyan('\n1. Routing Strategies:')); const routingResult = oracle.handleRouting({ destination: 'target-node', message: { type: 'test', data: 'routing test' }, strategy: 'ring-flood' }); console.log(` - Ring flood routing: ${routingResult.success}`); // Advanced consensus console.log(chalk.cyan('\n2. Advanced Consensus:')); const advancedProposal = 'proposal-' + Date.now(); oracle.handleConsensus({ proposalId: advancedProposal, proposal: 'Implement new security protocol' }); // Simulate vote oracle.handleConsensus({ proposalId: advancedProposal, vote: 'yes' }); console.log(` - Proposal "${advancedProposal}" created and voted on`); // Network monitoring console.log(chalk.cyan('\n3. Network Monitoring:')); oracle.monitorNetworkHealth(); const recentEvents = oracle.networkMetrics.networkEvents.slice(-3); console.log(` - Recent network events: ${recentEvents.length}`); recentEvents.forEach(event => { console.log(` * ${event.type} at ${new Date(event.timestamp).toLocaleTimeString()}`); }); console.log(chalk.green('โœ… Advanced features demonstration complete')); } async simulateNetworkActivity() { console.log(chalk.blue('\n๐ŸŽญ Simulating network activity...')); const oracle = this.nodes[0]; // Simulate periodic activity for (let i = 0; i < 5; i++) { // Random data storage oracle.handleDataStorage({ operation: 'set', key: `activity-${i}`, value: { activity: `Simulated activity ${i}`, timestamp: Date.now() } }); // Simulate message processing oracle.networkMetrics.messagesProcessed++; oracle.networkMetrics.queriesAnswered++; await this.delay(500); if (i % 2 === 0) { console.log(chalk.blue(` - Activity ${i + 1}/5: Data stored and metrics updated`)); } } console.log(chalk.green('โœ… Network activity simulation complete')); } async cleanup() { console.log(chalk.red('\n๐Ÿงน Cleaning up example network...')); for (const node of this.nodes) { try { await node.destroy(); } catch (error) { console.log(chalk.yellow(`Warning: ${error.message}`)); } } this.nodes = []; console.log(chalk.green('โœ… Cleanup complete')); } async runExample() { try { this.isRunning = true; // Create network await this.createNetwork(); // Run demonstrations await this.demonstrateBasicMessaging(); await this.demonstrateOracleServices(); await this.demonstrateNetworkTopology(); await this.demonstrateAdvancedFeatures(); await this.simulateNetworkActivity(); console.log(chalk.green.bold('\n๐ŸŽ‰ Example completed successfully!')); console.log(chalk.blue('\nThis example demonstrated:')); console.log(' โœ… Network creation and initialization'); console.log(' โœ… Basic messaging between nodes'); console.log(' โœ… Oracle services (analysis, storage, consensus, health)'); console.log(' โœ… Network topology visualization'); console.log(' โœ… Advanced features (routing, monitoring)'); console.log(' โœ… Simulated network activity'); console.log(chalk.cyan('\nTo start a real network:')); console.log(' npm run start:oracle -- --port 8080'); console.log(' npm run start:node -- --port 8081 --bootstrap localhost:8080'); } catch (error) { console.error(chalk.red.bold(`\n๐Ÿ’ฅ Example failed: ${error.message}`)); console.error(error.stack); } finally { await this.cleanup(); this.isRunning = false; } } } // Handle graceful shutdown process.on('SIGINT', async () => { console.log(chalk.yellow('\n๐Ÿ›‘ Shutting down example...')); process.exit(0); }); // Run example if this file is executed directly if (import.meta.url === `file://${process.argv[1]}`) { const example = new NetworkExample(); example.runExample() .then(() => { console.log(chalk.blue('\n๐Ÿ‘‹ Example finished. Goodbye!')); process.exit(0); }) .catch(error => { console.error(chalk.red.bold(`\n๐Ÿ’ฅ Example crashed: ${error.message}`)); process.exit(1); }); } export { NetworkExample };