saorsa-gossip 0.1.14

CLI tool for Saorsa Gossip network - demonstration and testing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Saorsa Gossip CLI Tool
//!
//! Interactive demonstration and testing tool for the Saorsa Gossip network.
//! This CLI exercises all library features for validation and demos.
//!
//! # Commands
//!
//! - `identity` - Create and manage ML-DSA identities
//! - `network` - Join network and participate in gossip
//! - `pubsub` - Publish/subscribe to topics
//! - `presence` - Manage presence beacons
//! - `groups` - Create and join groups
//! - `crdt` - Demonstrate CRDT operations
//! - `rendezvous` - Test rendezvous coordination
//!
//! # Usage
//!
//! ```bash
//! saorsa-gossip identity create --alias "Alice"
//! saorsa-gossip network join --coordinator 127.0.0.1:7000
//! saorsa-gossip pubsub publish --topic news --message "Hello World"
//! ```

use anyhow::{anyhow, Result};
use clap::{Parser, Subcommand};
use std::path::PathBuf;

mod updater;

/// Saorsa Gossip CLI - Demonstrate and test gossip network features
#[derive(Parser, Debug)]
#[command(name = "saorsa-gossip")]
#[command(version, about = "Saorsa Gossip Network CLI Tool", long_about = None)]
struct Args {
    /// Config directory (default: ~/.saorsa-gossip)
    #[arg(short, long, default_value = "~/.saorsa-gossip")]
    config_dir: PathBuf,

    /// Enable verbose logging
    #[arg(short, long)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Identity management (ML-DSA keypairs)
    Identity {
        #[command(subcommand)]
        action: IdentityAction,
    },

    /// Network operations
    Network {
        #[command(subcommand)]
        action: NetworkAction,
    },

    /// Publish/Subscribe operations
    Pubsub {
        #[command(subcommand)]
        action: PubsubAction,
    },

    /// Presence beacon management
    Presence {
        #[command(subcommand)]
        action: PresenceAction,
    },

    /// Group operations
    Groups {
        #[command(subcommand)]
        action: GroupAction,
    },

    /// CRDT synchronization demo
    Crdt {
        #[command(subcommand)]
        action: CrdtAction,
    },

    /// Rendezvous coordination
    Rendezvous {
        #[command(subcommand)]
        action: RendezvousAction,
    },

    /// Run interactive demo
    Demo {
        /// Demo scenario to run
        #[arg(short, long, default_value = "basic")]
        scenario: String,
    },

    /// Check for and install updates
    Update {
        /// Check for updates without installing
        #[arg(short, long)]
        check_only: bool,
    },
}

#[derive(Subcommand, Debug)]
enum IdentityAction {
    /// Create a new identity
    Create {
        /// Alias for the identity
        #[arg(short, long)]
        alias: String,
    },

    /// List all identities
    List,

    /// Show identity details
    Show {
        /// Alias of identity to show
        alias: String,
    },

    /// Delete an identity
    Delete {
        /// Alias of identity to delete
        alias: String,
    },
}

#[derive(Subcommand, Debug)]
enum NetworkAction {
    /// Join the network
    Join {
        /// Coordinator address (e.g., 127.0.0.1:7000)
        #[arg(short, long)]
        coordinator: String,

        /// Identity alias to use
        #[arg(short, long)]
        identity: String,

        /// Bind address (default: 0.0.0.0:0 for random port)
        #[arg(short, long, default_value = "0.0.0.0:0")]
        bind: String,
    },

    /// Show network status
    Status,

    /// List known peers
    Peers,

    /// Leave the network
    Leave,
}

#[derive(Subcommand, Debug)]
enum PubsubAction {
    /// Subscribe to a topic
    Subscribe {
        /// Topic name
        #[arg(short, long)]
        topic: String,
    },

    /// Publish to a topic
    Publish {
        /// Topic name
        #[arg(short, long)]
        topic: String,

        /// Message to publish
        #[arg(short, long)]
        message: String,
    },

    /// Unsubscribe from a topic
    Unsubscribe {
        /// Topic name
        #[arg(short, long)]
        topic: String,
    },

    /// List subscribed topics
    List,
}

#[derive(Subcommand, Debug)]
enum PresenceAction {
    /// Start broadcasting presence
    Start {
        /// Topic for presence
        #[arg(short, long)]
        topic: String,
    },

    /// Stop broadcasting presence
    Stop {
        /// Topic to stop
        #[arg(short, long)]
        topic: String,
    },

    /// Show online peers
    Online {
        /// Topic to check
        #[arg(short, long)]
        topic: String,
    },
}

#[derive(Subcommand, Debug)]
enum GroupAction {
    /// Create a new group
    Create {
        /// Group name
        #[arg(short, long)]
        name: String,
    },

    /// Join a group
    Join {
        /// Group ID
        #[arg(short, long)]
        group_id: String,
    },

    /// Leave a group
    Leave {
        /// Group ID
        #[arg(short, long)]
        group_id: String,
    },

    /// List groups
    List,
}

#[derive(Subcommand, Debug)]
enum CrdtAction {
    /// Demonstrate LWW Register
    LwwRegister {
        /// Value to set
        value: String,
    },

    /// Demonstrate OR-Set
    OrSet {
        /// Action: add or remove
        #[arg(short, long)]
        action: String,

        /// Value
        value: String,
    },

    /// Show current CRDT state
    Show,
}

#[derive(Subcommand, Debug)]
enum RendezvousAction {
    /// Register as a provider
    Register {
        /// Capability to provide
        #[arg(short, long)]
        capability: String,
    },

    /// Find providers
    Find {
        /// Capability to find
        #[arg(short, long)]
        capability: String,
    },

    /// Unregister
    Unregister,
}

#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();

    // Initialize logging
    init_logging(args.verbose)?;

    tracing::info!("Saorsa Gossip CLI v{}", env!("CARGO_PKG_VERSION"));

    // Expand config directory tilde
    let config_dir = expand_path(&args.config_dir)?;
    tracing::debug!("Config directory: {}", config_dir.display());

    // Ensure config directory exists
    tokio::fs::create_dir_all(&config_dir).await?;

    // Perform silent update check (rate-limited) for all commands except 'update'
    if !matches!(args.command, Commands::Update { .. }) {
        updater::silent_update_check(&config_dir).await;
    }

    // Route to command handlers
    match args.command {
        Commands::Identity { action } => handle_identity(action, &config_dir).await?,
        Commands::Network { action } => handle_network(action, &config_dir).await?,
        Commands::Pubsub { action } => handle_pubsub(action, &config_dir).await?,
        Commands::Presence { action } => handle_presence(action, &config_dir).await?,
        Commands::Groups { action } => handle_groups(action, &config_dir).await?,
        Commands::Crdt { action } => handle_crdt(action, &config_dir).await?,
        Commands::Rendezvous { action } => handle_rendezvous(action, &config_dir).await?,
        Commands::Demo { scenario } => handle_demo(&scenario, &config_dir).await?,
        Commands::Update { check_only } => handle_update(check_only).await?,
    }

    Ok(())
}

/// Handle identity commands
async fn handle_identity(action: IdentityAction, config_dir: &std::path::Path) -> Result<()> {
    use saorsa_gossip_identity::Identity;

    match action {
        IdentityAction::Create { alias } => {
            tracing::info!("Creating identity: {}", alias);

            let identity = Identity::new(alias.clone())?;
            let peer_id = identity.peer_id();

            // Save to keystore (using alias as four-words for now)
            let keystore = config_dir.join("keystore");
            let keystore_str = path_to_string(&keystore)?;
            identity.save_to_keystore(&alias, &keystore_str).await?;

            println!("✓ Created identity: {}", alias);
            println!("  PeerId: {}", hex::encode(peer_id.as_bytes()));
            println!("  Saved to: {}", keystore.display());
        }

        IdentityAction::List => {
            tracing::info!("Listing identities");
            let keystore = config_dir.join("keystore");

            if !keystore.exists() {
                println!("No identities found");
                return Ok(());
            }

            let mut entries = tokio::fs::read_dir(&keystore).await?;
            let mut count = 0;

            println!("Identities:");
            while let Some(entry) = entries.next_entry().await? {
                if let Some(name) = entry.file_name().to_str() {
                    if name.ends_with(".identity") {
                        let alias = name.trim_end_matches(".identity").replace('_', "-");
                        println!("  - {}", alias);
                        count += 1;
                    }
                }
            }

            if count == 0 {
                println!("  (none)");
            }
        }

        IdentityAction::Show { alias } => {
            tracing::info!("Showing identity: {}", alias);
            let keystore = config_dir.join("keystore");

            let identity =
                Identity::load_from_keystore(&alias, &path_to_string(&keystore)?).await?;

            println!("Identity: {}", alias);
            println!("  PeerId: {}", hex::encode(identity.peer_id().as_bytes()));
            println!("  Alias: {}", identity.alias());
        }

        IdentityAction::Delete { alias } => {
            tracing::info!("Deleting identity: {}", alias);
            let keystore = config_dir.join("keystore");
            let filename = alias.replace('-', "_");
            let file_path = keystore.join(format!("{}.identity", filename));

            if file_path.exists() {
                tokio::fs::remove_file(&file_path).await?;
                println!("✓ Deleted identity: {}", alias);
            } else {
                println!("Identity not found: {}", alias);
            }
        }
    }

    Ok(())
}

/// Handle network commands
async fn handle_network(action: NetworkAction, config_dir: &std::path::Path) -> Result<()> {
    use saorsa_gossip_identity::Identity;
    use saorsa_gossip_transport::AntQuicTransport;

    match action {
        NetworkAction::Join {
            coordinator,
            identity,
            bind,
        } => {
            tracing::info!("Joining network with identity: {}", identity);

            // Load identity
            let keystore = config_dir.join("keystore");
            let ident =
                Identity::load_from_keystore(&identity, &path_to_string(&keystore)?).await?;

            println!("✓ Loaded identity: {}", identity);
            println!("  PeerId: {}", hex::encode(ident.peer_id().as_bytes()));

            // Parse addresses
            let bind_addr: std::net::SocketAddr = bind.parse()?;
            let coordinator_addr: std::net::SocketAddr = coordinator.parse()?;

            println!("\n🌐 Connecting to network...");
            println!("  Coordinator: {}", coordinator);
            println!("  Local bind: {}", bind);

            // Create transport (automatically connects to known peers)
            println!("  Creating transport and establishing QUIC connection...");
            let transport = AntQuicTransport::new(bind_addr, vec![coordinator_addr]).await?;

            println!("\n✓ Transport initialized and connected!");
            println!(
                "  Transport PeerId: {}",
                hex::encode(transport.peer_id().as_bytes())
            );
            println!("  Ant PeerId: {:?}", transport.ant_peer_id());

            // Send a PING to coordinator to test message exchange
            println!("\n📡 Sending PING to coordinator...");
            use saorsa_gossip_transport::GossipTransport;
            use std::time::Instant;

            let ping_start = Instant::now();

            // Get coordinator's peer ID (we need to discover this from bootstrap)
            // For now, we'll send to the transport and handle it on coordinator side
            // TODO: Get actual coordinator peer ID from discovery

            // Try to receive a message with timeout to test connectivity
            println!("⏳ Waiting for coordinator response (5s timeout)...");

            let receive_task = tokio::spawn({
                let transport = std::sync::Arc::new(transport);
                async move {
                    match tokio::time::timeout(
                        std::time::Duration::from_secs(5),
                        transport.receive_message(),
                    )
                    .await
                    {
                        Ok(Ok((peer_id, stream_type, data))) => Some((peer_id, stream_type, data)),
                        Ok(Err(e)) => {
                            println!("❌ Error receiving: {}", e);
                            None
                        }
                        Err(_) => {
                            println!("⏱️  Timeout waiting for response");
                            None
                        }
                    }
                }
            });

            if let Ok(Some((peer_id, _stream_type, data))) = receive_task.await {
                let rtt = ping_start.elapsed();
                println!(
                    "✓ Received response from peer {}",
                    hex::encode(peer_id.as_bytes())
                );
                println!("  RTT: {:?}", rtt);
                println!("  Data: {}", String::from_utf8_lossy(&data));
            }

            println!("\n⚠️  Full network integration in progress!");
            println!("   - Address reflection (IPv4/IPv6 observation)");
            println!("   - NAT type detection");
            println!("   - Peer discovery and listing");
            println!("\nPress Ctrl+C to disconnect");

            // Keep connection alive
            tokio::signal::ctrl_c().await?;
            println!("\n👋 Disconnecting...");
        }

        NetworkAction::Status => {
            println!("Network status - Coming soon!");
            println!("This will show:");
            println!("  - Connection state");
            println!("  - Observed IPv4/IPv6 addresses");
            println!("  - NAT type");
            println!("  - Active peer count");
        }

        NetworkAction::Peers => {
            println!("Peer list - Coming soon!");
            println!("This will show:");
            println!("  - Connected peers with IPs (IPv4/IPv6)");
            println!("  - RTT to each peer");
            println!("  - Connection type (direct/relayed)");
        }

        NetworkAction::Leave => {
            println!("Leave network - Coming soon!");
        }
    }

    Ok(())
}

/// Handle pubsub commands
async fn handle_pubsub(_action: PubsubAction, _config_dir: &std::path::Path) -> Result<()> {
    println!("PubSub commands - Coming soon!");
    println!("This will demonstrate:");
    println!("  - Subscribing to topics");
    println!("  - Publishing messages");
    println!("  - Gossip-based message propagation");
    println!("  - ML-DSA signatures on messages");
    Ok(())
}

/// Handle presence commands
async fn handle_presence(_action: PresenceAction, _config_dir: &std::path::Path) -> Result<()> {
    println!("Presence commands - Coming soon!");
    println!("This will demonstrate:");
    println!("  - Periodic presence beacons");
    println!("  - Online peer discovery");
    println!("  - Presence TTL and expiration");
    Ok(())
}

/// Handle group commands
async fn handle_groups(_action: GroupAction, _config_dir: &std::path::Path) -> Result<()> {
    println!("Group commands - Coming soon!");
    println!("This will demonstrate:");
    println!("  - Creating encrypted groups");
    println!("  - Joining with shared secrets");
    println!("  - Group messaging");
    Ok(())
}

/// Handle CRDT commands
async fn handle_crdt(_action: CrdtAction, _config_dir: &std::path::Path) -> Result<()> {
    println!("CRDT commands - Coming soon!");
    println!("This will demonstrate:");
    println!("  - LWW Register operations");
    println!("  - OR-Set add/remove");
    println!("  - Anti-entropy synchronization");
    Ok(())
}

/// Handle rendezvous commands
async fn handle_rendezvous(_action: RendezvousAction, _config_dir: &std::path::Path) -> Result<()> {
    println!("Rendezvous commands - Coming soon!");
    println!("This will demonstrate:");
    println!("  - Provider registration");
    println!("  - Capability-based discovery");
    println!("  - DHT-based lookups");
    Ok(())
}

/// Handle demo scenarios
async fn handle_demo(scenario: &str, _config_dir: &std::path::Path) -> Result<()> {
    match scenario {
        "basic" => {
            println!("=== Saorsa Gossip Basic Demo ===");
            println!();
            println!("This demo will showcase:");
            println!("  1. Identity creation with ML-DSA");
            println!("  2. Network bootstrap");
            println!("  3. Peer discovery");
            println!("  4. PubSub messaging");
            println!("  5. Presence beacons");
            println!();
            println!("To run individual commands, use:");
            println!("  saorsa-gossip identity create --alias Alice");
            println!("  saorsa-gossip network join --coordinator 127.0.0.1:7000 --identity Alice");
            println!();
            println!("Demo implementation coming soon!");
        }
        _ => {
            println!("Unknown demo scenario: {}", scenario);
            println!("Available scenarios: basic");
        }
    }

    Ok(())
}

/// Initialize logging based on verbosity
fn init_logging(verbose: bool) -> Result<()> {
    use tracing_subscriber::EnvFilter;

    let filter = if verbose {
        EnvFilter::new("debug")
    } else {
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"))
    };

    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_target(false)
        .init();

    Ok(())
}

/// Expand tilde in path
fn expand_path(path: &std::path::Path) -> Result<PathBuf> {
    let expanded = shellexpand::tilde(&path.to_string_lossy()).to_string();
    Ok(PathBuf::from(expanded))
}

fn path_to_string(path: &std::path::Path) -> Result<String> {
    path.to_str()
        .map(str::to_owned)
        .ok_or_else(|| anyhow!("Path contains invalid UTF-8: {}", path.display()))
}

/// Handle update command
async fn handle_update(check_only: bool) -> Result<()> {
    if check_only {
        println!("🔍 Checking for updates...");
        match updater::check_for_update().await? {
            Some(new_version) => {
                println!("✓ Update available: {}", new_version);
                println!("  Run 'saorsa-gossip update' to install");
            }
            None => {
                println!("✓ Already on latest version: {}", env!("CARGO_PKG_VERSION"));
            }
        }
    } else {
        updater::perform_update().await?;
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_cli_parses() {
        // Verify CLI structure compiles and parses
        let _args = Args::try_parse_from(["saorsa-gossip", "demo", "--scenario", "basic"]);
    }

    #[test]
    fn test_expand_path_no_tilde() {
        let path = std::path::Path::new("/tmp/test");
        let expanded = expand_path(path).expect("expand");
        assert_eq!(expanded, path);
    }

    #[test]
    fn test_expand_path_with_tilde() {
        let path = std::path::Path::new("~/test");
        let expanded = expand_path(path).expect("expand");
        assert!(expanded.to_string_lossy().contains("test"));
        assert!(!expanded.to_string_lossy().contains('~'));
    }
}