Просмотр исходного кода

dchat: hardcode inbound/ outbound settings as Alice + Bob

add command line switch
lunar-mining 4 лет назад
Родитель
Сommit
3cd20de425
2 измененных файлов с 81 добавлено и 102 удалено
  1. 75 66
      example/dchat/src/main.rs
  2. 6 36
      example/dchat/src/protocol_dchat.rs

+ 75 - 66
example/dchat/src/main.rs

@@ -1,4 +1,3 @@
-use async_channel::{Receiver, Sender};
 use async_executor::Executor;
 use async_std::sync::Arc;
 use easy_parallel::Parallel;
@@ -7,34 +6,24 @@ use simplelog::WriteLogger;
 use std::{
     fs::File,
     io::{self, Read, Write},
-    path::PathBuf,
 };
-use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
 use termion::{async_stdin, event::Key, input::TermRead};
-use toml::Value;
 use url::Url;
 
 use darkfi::{
     net,
     net::Settings,
-    util::{
-        cli::{get_log_config, get_log_level, spawn_config},
-        path::join_config_path,
-    },
-    Result,
+    util::cli::{get_log_config, get_log_level},
+    Error, Result,
 };
 
 use crate::{dchatmsg::Dchatmsg, protocol_dchat::ProtocolDchat};
-use darkfi::net::settings::SettingsOpt;
 
 pub mod dchatmsg;
 pub mod protocol_dchat;
 
-const CONFIG_FILE_CONTENTS: &str = include_str!("../dchat_config.toml");
-
 struct Dchat {
     p2p: net::P2pPtr,
-    //msg_sub: net::MessageSubscription<Dchatmsg>,
 }
 
 impl Dchat {
@@ -42,7 +31,7 @@ impl Dchat {
         Arc::new(Self { p2p })
     }
 
-    async fn render(&self, ex: Arc<Executor<'_>>) -> Result<()> {
+    async fn render(&self) -> Result<()> {
         info!(target: "dchat", "DCHAT::render()::start");
         let mut stdout = io::stdout().lock();
         let mut stdin = async_stdin();
@@ -83,13 +72,12 @@ impl Dchat {
         return Ok(input)
     }
 
-    async fn register_protocol(&self, p2p_send_channel: Sender<Dchatmsg>) -> Result<()> {
+    async fn register_protocol(&self) -> Result<()> {
         info!(target: "dchat", "dchat::register_protocol()::start");
         let registry = self.p2p.protocol_registry();
         registry
-            .register(net::SESSION_ALL, move |channel, p2p| {
-                let sender = p2p_send_channel.clone();
-                async move { ProtocolDchat::init(channel, p2p, sender).await }
+            .register(net::SESSION_ALL, move |channel, p2p| async move {
+                ProtocolDchat::init(channel, p2p).await
             })
             .await;
         info!(target: "dchat", "DCHAT::register_protocol()::stop");
@@ -99,45 +87,19 @@ impl Dchat {
     async fn start(&self, ex: Arc<Executor<'_>>) -> Result<()> {
         info!(target: "dchat", "DCHAT::start()::start");
 
-        //let sub = net::MessageSubscription::new();
-        let (p2p_send_channel, p2p_recv_channel) = async_channel::unbounded::<Dchatmsg>();
-
         let ex2 = ex.clone();
-        let ex3 = ex.clone();
 
         let dchat = Dchat::new(self.p2p.clone());
 
-        dchat.register_protocol(p2p_send_channel).await?;
+        dchat.register_protocol().await?;
 
         self.p2p.clone().start(ex.clone()).await?;
         ex2.spawn(self.p2p.clone().run(ex.clone())).detach();
-        self.start_p2p_receive_loop(ex3, p2p_recv_channel);
 
         info!(target: "dchat", "DCHAT::start()::stop");
         Ok(())
     }
 
-    fn start_p2p_receive_loop(
-        &self,
-        executor: Arc<Executor<'_>>,
-        p2p_receiver: Receiver<Dchatmsg>,
-    ) {
-        //let senders = self.senders.clone();
-        executor
-            .spawn(async move {
-                while let Ok(msg) = p2p_receiver.recv().await {
-                    info!(target: "dchat", "START P2P RECEIVE LOOP:: RECEIVED MSG {:?}", msg);
-                    //senders.notify(msg).await;
-                }
-            })
-            .detach();
-    }
-    //async fn send_loop(&self) -> Result<()> {
-    //    let dchatmsg = Dchatmsg { message };
-    //    loop {
-
-    //    }
-    //}
     async fn send(&self, message: String) -> Result<()> {
         let mut stdout = io::stdout().lock();
         stdout.write_all(b"sending: ")?;
@@ -155,13 +117,51 @@ impl Dchat {
     }
 }
 
-fn get_settings_from_config(flag: String) -> Result<SettingsOpt> {
-    let name = format!("dchat_{}.toml", flag);
-    let cfg_path = join_config_path(&PathBuf::from(name))?;
-    spawn_config(&cfg_path, CONFIG_FILE_CONTENTS.as_bytes())?;
-    let config: SettingsOpt =
-        SettingsOpt::from_args_with_toml(&std::fs::read_to_string(cfg_path)?).unwrap();
-    Ok(config)
+// inbound
+fn alice() -> Result<Settings> {
+    let seed = Url::parse("tcp://127.0.0.1:55555").unwrap();
+    let inbound = Url::parse("tcp://127.0.0.1:55554").unwrap();
+    let ext_addr = Url::parse("tcp://127.0.0.1:55554").unwrap();
+
+    let settings = Settings {
+        inbound: Some(inbound),
+        outbound_connections: 0,
+        manual_attempt_limit: 0,
+        seed_query_timeout_seconds: 8,
+        connect_timeout_seconds: 10,
+        channel_handshake_seconds: 4,
+        channel_heartbeat_seconds: 10,
+        outbound_retry_seconds: 1200,
+        external_addr: Some(ext_addr),
+        peers: Vec::new(),
+        seeds: vec![seed],
+        node_id: String::new(),
+    };
+
+    Ok(settings)
+}
+
+// outbound
+fn bob() -> Result<Settings> {
+    let seed = Url::parse("tcp://127.0.0.1:55555").unwrap();
+    let oc = 5;
+
+    let settings = Settings {
+        inbound: None,
+        outbound_connections: oc,
+        manual_attempt_limit: 0,
+        seed_query_timeout_seconds: 8,
+        connect_timeout_seconds: 10,
+        channel_handshake_seconds: 4,
+        channel_heartbeat_seconds: 10,
+        outbound_retry_seconds: 1200,
+        external_addr: None,
+        peers: Vec::new(),
+        seeds: vec![seed],
+        node_id: String::new(),
+    };
+
+    Ok(settings)
 }
 
 #[async_std::main]
@@ -173,19 +173,29 @@ async fn main() -> Result<()> {
     let file = File::create(log_path).unwrap();
     WriteLogger::init(log_level, log_config, file)?;
 
-    let seed = Url::parse("tcp://127.0.0.1:55555").unwrap();
-    let inbound = Url::parse("tcp://127.0.0.1:55554").unwrap();
-    let ext_addr = Url::parse("tcp://127.0.0.1:55544").unwrap();
-
-    // TODO: error
-    let settings: SettingsOpt = match std::env::args()
-        .nth(1)
-        .expect("string identifier missing: please pass a string to name your dchat instance")
-    {
-        flag => get_settings_from_config(flag)?,
+    // TODO:: proper error handling
+    let settings: Result<Settings> = match std::env::args().nth(1) {
+        Some(id) => match id.as_str() {
+            "a" => {
+                println!("alice selected");
+                alice()
+            }
+            "b" => {
+                println!("bob selected");
+                bob()
+            }
+            _ => {
+                println!("you must specify either a or b");
+                Err(Error::ConfigInvalid)
+            }
+        },
+        None => {
+            println!("you must specify either a or b");
+            Err(Error::ConfigInvalid)
+        }
     };
 
-    let p2p = net::P2p::new(settings.into()).await;
+    let p2p = net::P2p::new(settings?.into()).await;
 
     let p2p = p2p.clone();
 
@@ -194,7 +204,6 @@ async fn main() -> Result<()> {
 
     let ex = Arc::new(Executor::new());
     let ex2 = ex.clone();
-    let ex3 = ex.clone();
 
     let dchat = Dchat::new(p2p.clone());
 
@@ -202,8 +211,8 @@ async fn main() -> Result<()> {
         .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
         .finish(|| {
             smol::future::block_on(async move {
-                dchat.start(ex3).await?;
-                dchat.render(ex2).await?;
+                dchat.start(ex2).await?;
+                dchat.render().await?;
                 drop(signal);
                 Ok(())
             })

+ 6 - 36
example/dchat/src/protocol_dchat.rs

@@ -2,7 +2,7 @@ use async_executor::Executor;
 use async_std::sync::Arc;
 use async_trait::async_trait;
 use darkfi::{net, Result};
-use log::{error, info};
+use log::info;
 
 use crate::dchatmsg::Dchatmsg;
 
@@ -10,15 +10,10 @@ pub struct ProtocolDchat {
     jobsman: net::ProtocolJobsManagerPtr,
     msg_sub: net::MessageSubscription<Dchatmsg>,
     p2p: net::P2pPtr,
-    p2p_send_channel: async_channel::Sender<Dchatmsg>,
 }
 
 impl ProtocolDchat {
-    pub async fn init(
-        channel: net::ChannelPtr,
-        p2p: net::P2pPtr,
-        p2p_send_channel: async_channel::Sender<Dchatmsg>,
-    ) -> net::ProtocolBasePtr {
+    pub async fn init(channel: net::ChannelPtr, p2p: net::P2pPtr) -> net::ProtocolBasePtr {
         info!(target: "dchat", "ProtocolDchat::init() [START]");
 
         let message_subsytem = channel.get_message_subsystem();
@@ -31,42 +26,17 @@ impl ProtocolDchat {
             jobsman: net::ProtocolJobsManager::new("ProtocolDchat", channel.clone()),
             msg_sub,
             p2p,
-            p2p_send_channel,
         })
     }
 
     async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
         info!(target: "dchat", "ProtocolDchat::handle_receive_msg() [START]");
+
         loop {
-            match self.msg_sub.receive().await {
-                Ok(msg) => {
-                    info!(target: "dchat", "RECEIVED HANDLE_RECEIVE_MSG {:?}", msg);
-                    let msg = (*msg).to_owned();
-                    match self.p2p_send_channel.send(msg.clone()).await {
-                        Ok(o) => {
-                            info!(target: "dchat", "SENT MSG ACROSS p2p CHANNEL");
-                        }
-                        Err(e) => {
-                            error!(target: "dchat", "MSG SEND FAILED {}", e);
-                        }
-                    }
-                    info!(target: "dchat", "BROADCASTING MSG {:?}", msg);
-                    self.p2p.broadcast(msg).await?;
-                }
-                Err(e) => {
-                    error!(target: "dchat", "ERROR HANDLE_RECEIVE_MSG {:?}", e);
-                }
-            }
+            let msg = self.msg_sub.receive().await?;
+            let msg = (*msg).to_owned();
+            self.p2p.broadcast(msg).await?;
         }
-
-        //loop {
-
-        //    //let msg = (*msg).to_owned();
-
-        //    //self.sender.send(msg.clone()).await?;
-
-        //    //self.p2p.broadcast(msg).await?;
-        //}
     }
 }