bft_core/
core.rs

1use crate::{
2    algorithm::{Bft, INIT_HEIGHT},
3    error::BftError,
4    types::*,
5    FromCore,
6};
7
8use crossbeam_channel::{unbounded, Sender};
9
10/// Result of Bft Core.
11pub type Result<T> = ::std::result::Result<T, BftError>;
12
13/// A Bft Core
14#[derive(Clone, Debug)]
15pub struct Core {
16    sender: Sender<CoreInput>,
17    height: u64,
18}
19
20impl Core {
21    /// A function to create a new Bft Core.
22    pub fn new<T: FromCore + Send + 'static>(s: T, address: Address) -> Self {
23        let (sender, internal_receiver) = unbounded();
24        Bft::start(s, internal_receiver, address);
25        Core {
26            sender,
27            height: INIT_HEIGHT,
28        }
29    }
30
31    /// A function to send BFT message to BFT core.
32    pub fn send_bft_msg(&mut self, msg: CoreInput) -> Result<()> {
33        match msg {
34            CoreInput::Status(s) => {
35                let status_height = s.height;
36                if self.sender.send(CoreInput::Status(s)).is_ok() {
37                    if self.height <= status_height {
38                        self.height = status_height + 1;
39                    }
40                    Ok(())
41                } else {
42                    Err(BftError::SendMsgErr)
43                }
44            }
45            _ => self.sender.send(msg).map_err(|_| BftError::SendMsgErr),
46        }
47    }
48
49    /// A function to get Bft machine height.
50    pub fn get_height(&self) -> u64 {
51        self.height
52    }
53}
54
55#[cfg(test)]
56mod test {
57    use super::Core as Bft;
58    use crate::{types::*, FromCore};
59    use crossbeam_channel::{unbounded, Sender};
60
61    #[derive(Debug)]
62    enum Error {
63        SendErr,
64    }
65
66    struct SendMsg(Sender<CoreOutput>);
67
68    impl FromCore for SendMsg {
69        type error = Error;
70
71        fn send_msg(&self, msg: CoreOutput) -> Result<(), Error> {
72            self.0.send(msg).map_err(|_| Error::SendErr)?;
73            Ok(())
74        }
75    }
76
77    impl SendMsg {
78        fn new() -> Self {
79            let (s, _) = unbounded();
80            SendMsg(s)
81        }
82    }
83
84    fn create_status(height: u64) -> CoreInput {
85        CoreInput::Status(Status {
86            height,
87            interval: None,
88            authority_list: vec![],
89        })
90    }
91
92    #[test]
93    fn test_height_change() {
94        let height: Vec<(u64, u64)> = vec![(1, 2), (2, 3), (1, 3), (4, 5), (6, 7), (5, 7)];
95        let mut bft = Bft::new(SendMsg::new(), vec![1]);
96        assert_eq!(bft.get_height(), 0);
97
98        for h in height.into_iter() {
99            if let Ok(_) = bft.send_bft_msg(create_status(h.0)) {
100                assert_eq!(bft.get_height(), h.1);
101            } else {
102                panic!("Send Error!");
103            }
104        }
105    }
106}