primitives.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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, io};
  19. use darkfi_serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
  20. use crate::{Error, Result};
  21. pub type Channel<T> = (smol::channel::Sender<T>, smol::channel::Receiver<T>);
  22. pub type Sender = (smol::channel::Sender<NetMsg>, smol::channel::Receiver<NetMsg>);
  23. #[derive(PartialEq, Eq, Debug, Clone)]
  24. pub enum Role {
  25. Follower,
  26. Candidate,
  27. Leader,
  28. }
  29. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  30. pub struct SyncRequest {
  31. pub id: u64,
  32. pub logs_len: u64,
  33. pub last_term: u64,
  34. }
  35. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  36. pub struct SyncResponse {
  37. pub id: u64,
  38. pub logs: Logs,
  39. pub commit_length: u64,
  40. pub leader_id: NodeId,
  41. pub wipe: bool,
  42. }
  43. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  44. pub struct VoteRequest {
  45. pub node_id: NodeId,
  46. pub current_term: u64,
  47. pub log_length: u64,
  48. pub last_term: u64,
  49. }
  50. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  51. pub struct VoteResponse {
  52. pub node_id: NodeId,
  53. pub current_term: u64,
  54. pub ok: bool,
  55. }
  56. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  57. pub struct LogRequest {
  58. pub leader_id: NodeId,
  59. pub current_term: u64,
  60. pub prefix_len: u64,
  61. pub prefix_term: u64,
  62. pub commit_length: u64,
  63. pub suffix: Logs,
  64. }
  65. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  66. pub struct LogResponse {
  67. pub node_id: NodeId,
  68. pub current_term: u64,
  69. pub ack: u64,
  70. pub ok: bool,
  71. }
  72. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  73. pub struct NodeIdMsg {
  74. pub id: NodeId,
  75. }
  76. impl VoteResponse {
  77. pub fn set_ok(&mut self, ok: bool) {
  78. self.ok = ok;
  79. }
  80. }
  81. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  82. pub struct BroadcastMsgRequest(pub Vec<u8>);
  83. #[derive(Clone, Debug, SerialDecodable, SerialEncodable)]
  84. pub struct Log {
  85. pub term: u64,
  86. pub msg: Vec<u8>,
  87. }
  88. #[derive(Clone, Debug, Eq, PartialEq, Hash, SerialDecodable, SerialEncodable)]
  89. pub struct NodeId(pub String);
  90. #[derive(Clone, Debug, SerialDecodable, SerialEncodable)]
  91. pub struct Logs(pub Vec<Log>);
  92. impl Logs {
  93. pub fn len(&self) -> u64 {
  94. self.0.len() as u64
  95. }
  96. pub fn is_empty(&self) -> bool {
  97. self.0.is_empty()
  98. }
  99. pub fn slice_from(&self, start: u64) -> Option<Self> {
  100. if self.len() >= start {
  101. return Some(Self(self.0[start as usize..].to_vec()))
  102. }
  103. None
  104. }
  105. pub fn slice_to(&self, end: u64) -> Self {
  106. for i in (0..end).rev() {
  107. if self.len() >= i {
  108. return Self(self.0[..i as usize].to_vec())
  109. }
  110. }
  111. Self(vec![])
  112. }
  113. pub fn get(&self, index: u64) -> Result<Log> {
  114. match self.0.get(index as usize) {
  115. Some(l) => Ok(l.clone()),
  116. None => Err(Error::RaftError("unable to indexing into vector".into())),
  117. }
  118. }
  119. pub fn to_vec(&self) -> Vec<Log> {
  120. self.0.clone()
  121. }
  122. }
  123. #[derive(Clone, Debug)]
  124. pub struct MapLength(pub HashMap<NodeId, u64>);
  125. impl MapLength {
  126. pub fn get(&self, key: &NodeId) -> Result<u64> {
  127. match self.0.get(key) {
  128. Some(v) => Ok(*v),
  129. None => Err(Error::RaftError("unable to indexing into HashMap".into())),
  130. }
  131. }
  132. pub fn insert(&mut self, key: &NodeId, value: u64) {
  133. self.0.insert(key.clone(), value);
  134. }
  135. }
  136. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  137. pub struct NetMsg {
  138. pub id: u64,
  139. pub recipient_id: Option<NodeId>,
  140. pub method: NetMsgMethod,
  141. pub payload: Vec<u8>,
  142. }
  143. #[derive(Clone, Debug, PartialEq, Eq)]
  144. #[repr(u8)]
  145. pub enum NetMsgMethod {
  146. LogResponse = 0,
  147. LogRequest = 1,
  148. VoteResponse = 2,
  149. VoteRequest = 3,
  150. BroadcastRequest = 4,
  151. NodeIdMsg = 5,
  152. }
  153. impl Encodable for NetMsgMethod {
  154. fn encode<S: io::Write>(&self, s: S) -> core::result::Result<usize, io::Error> {
  155. let len: usize = match self {
  156. Self::LogResponse => 0,
  157. Self::LogRequest => 1,
  158. Self::VoteResponse => 2,
  159. Self::VoteRequest => 3,
  160. Self::BroadcastRequest => 4,
  161. Self::NodeIdMsg => 5,
  162. };
  163. (len as u8).encode(s)
  164. }
  165. }
  166. impl Decodable for NetMsgMethod {
  167. fn decode<D: io::Read>(d: D) -> core::result::Result<Self, io::Error> {
  168. let com: u8 = Decodable::decode(d)?;
  169. Ok(match com {
  170. 0 => Self::LogResponse,
  171. 1 => Self::LogRequest,
  172. 2 => Self::VoteResponse,
  173. 3 => Self::VoteRequest,
  174. 4 => Self::BroadcastRequest,
  175. _ => Self::NodeIdMsg,
  176. })
  177. }
  178. }