protocol_raft.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::collections::HashMap;
  19. use async_std::sync::{Arc, Mutex};
  20. use async_trait::async_trait;
  21. use chrono::Utc;
  22. use darkfi_serial::serialize;
  23. use log::debug;
  24. use rand::{rngs::OsRng, RngCore};
  25. use smol::Executor;
  26. use super::primitives::{NetMsg, NetMsgMethod, NodeId, NodeIdMsg};
  27. use crate::{net, Result};
  28. pub struct ProtocolRaft {
  29. id: NodeId,
  30. jobsman: net::ProtocolJobsManagerPtr,
  31. notify_queue_sender: smol::channel::Sender<NetMsg>,
  32. msg_sub: net::MessageSubscription<NetMsg>,
  33. p2p: net::P2pPtr,
  34. seen_msgs: Arc<Mutex<HashMap<String, i64>>>,
  35. channel: net::ChannelPtr,
  36. }
  37. impl ProtocolRaft {
  38. pub async fn init(
  39. id: NodeId,
  40. channel: net::ChannelPtr,
  41. notify_queue_sender: smol::channel::Sender<NetMsg>,
  42. p2p: net::P2pPtr,
  43. seen_msgs: Arc<Mutex<HashMap<String, i64>>>,
  44. ) -> net::ProtocolBasePtr {
  45. let message_subsytem = channel.get_message_subsystem();
  46. message_subsytem.add_dispatch::<NetMsg>().await;
  47. let msg_sub = channel.subscribe_msg::<NetMsg>().await.expect("Missing NetMsg dispatcher!");
  48. Arc::new(Self {
  49. id,
  50. notify_queue_sender,
  51. msg_sub,
  52. jobsman: net::ProtocolJobsManager::new("ProtocolRaft", channel.clone()),
  53. p2p,
  54. seen_msgs,
  55. channel,
  56. })
  57. }
  58. async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
  59. debug!(target: "raft::protocol_raft", "ProtocolRaft::handle_receive_msg() [START]");
  60. // on initialization send a NodeIdMsg
  61. let random_id = OsRng.next_u64();
  62. let node_id_msg = serialize(&NodeIdMsg { id: self.id.clone() });
  63. let net_msg = NetMsg {
  64. id: random_id,
  65. recipient_id: None,
  66. payload: node_id_msg.to_vec(),
  67. method: NetMsgMethod::NodeIdMsg,
  68. };
  69. {
  70. self.seen_msgs.lock().await.insert(random_id.to_string(), Utc::now().timestamp());
  71. }
  72. self.channel.send(net_msg).await?;
  73. loop {
  74. let msg = self.msg_sub.receive().await?;
  75. debug!(
  76. target: "raft::protocol_raft",
  77. "ProtocolRaft::handle_receive_msg() received id: {:?} method {:?}",
  78. &msg.id, &msg.method
  79. );
  80. {
  81. let mut msgs = self.seen_msgs.lock().await;
  82. if msgs.contains_key(&msg.id.to_string()) {
  83. continue
  84. }
  85. msgs.insert(msg.id.to_string(), chrono::Utc::now().timestamp());
  86. }
  87. let msg = (*msg).clone();
  88. self.p2p.broadcast(msg.clone()).await?;
  89. // check if the local node and recipient id are equal
  90. if let Some(recipient_id) = &msg.recipient_id {
  91. if &self.id != recipient_id {
  92. continue
  93. }
  94. }
  95. self.notify_queue_sender.send(msg).await?;
  96. }
  97. }
  98. }
  99. #[async_trait]
  100. impl net::ProtocolBase for ProtocolRaft {
  101. /// Starts ping-pong keep-alive messages exchange. Runs ping-pong in the
  102. /// protocol task manager, then queues the reply. Sends out a ping and
  103. /// waits for pong reply. Waits for ping and replies with a pong.
  104. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  105. debug!(target: "raft::protocol_raft", "ProtocolRaft::start() [START]");
  106. self.jobsman.clone().start(executor.clone());
  107. self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await;
  108. debug!(target: "raft::protocol_raft", "ProtocolRaft::start() [END]");
  109. Ok(())
  110. }
  111. fn name(&self) -> &'static str {
  112. "ProtocolRaft"
  113. }
  114. }
  115. impl net::Message for NetMsg {
  116. fn name() -> &'static str {
  117. "netmsg"
  118. }
  119. }