1use derive_more::Display;
2use serde::{Deserialize, Serialize};
3
4use crate::smr::smr_types::{Lock, Step};
5use crate::types::{AggregatedVote, UpdateFrom};
6use crate::Codec;
7
8#[derive(Serialize, Deserialize, Clone, Debug, Display, Eq, PartialEq)]
9#[rustfmt::skip]
10#[display(
11 fmt = "wal info height {}, round {}, step {:?}",
12 height, round, step,
13)]
14pub struct WalInfo<T: Codec> {
16 pub height: u64,
18 pub round: u64,
20 pub step: Step,
22 pub lock: Option<WalLock<T>>,
24 pub from: UpdateFrom,
26}
27
28impl<T: Codec> WalInfo<T> {
29 pub fn into_smr_base(self) -> SMRBase {
31 SMRBase {
32 height: self.height,
33 round: self.round,
34 step: self.step.clone(),
35 polc: self.lock.map(|polc| polc.to_lock()),
36 }
37 }
38}
39
40#[derive(Serialize, Deserialize, Clone, Debug, Display, PartialEq, Eq)]
41#[display(fmt = "wal lock round {}, qc {:?}", lock_round, lock_votes)]
42pub struct WalLock<T: Codec> {
43 pub lock_round: u64,
44 pub lock_votes: AggregatedVote,
45 pub content: T,
46}
47
48impl<T: Codec> WalLock<T> {
49 pub fn to_lock(&self) -> Lock {
50 Lock {
51 round: self.lock_round,
52 hash: self.lock_votes.block_hash.clone(),
53 }
54 }
55}
56
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct SMRBase {
59 pub height: u64,
60 pub round: u64,
61 pub step: Step,
62 pub polc: Option<Lock>,
63}
64
65#[cfg(test)]
66mod test {
67 use std::error::Error;
68
69 use bytes::Bytes;
70 use rand::random;
71
72 use super::*;
73 use crate::types::{AggregatedSignature, VoteType};
74
75 #[derive(Clone, Debug, PartialEq, Eq)]
76 struct Pill {
77 inner: Vec<u8>,
78 }
79
80 impl Codec for Pill {
81 fn encode(&self) -> Result<Bytes, Box<dyn Error + Send>> {
82 Ok(Bytes::from(self.inner.clone()))
83 }
84
85 fn decode(data: Bytes) -> Result<Self, Box<dyn Error + Send>> {
86 Ok(Pill {
87 inner: data.as_ref().to_vec(),
88 })
89 }
90 }
91
92 impl Pill {
93 fn new() -> Self {
94 Pill {
95 inner: (0..128).map(|_| random::<u8>()).collect::<Vec<_>>(),
96 }
97 }
98 }
99
100 fn mock_qc() -> AggregatedVote {
101 let aggregated_signature = AggregatedSignature {
102 signature: Bytes::default(),
103 address_bitmap: Bytes::default(),
104 };
105
106 AggregatedVote {
107 signature: aggregated_signature,
108 vote_type: VoteType::Precommit,
109 height: 0u64,
110 round: 0u64,
111 block_hash: Bytes::default(),
112 leader: Bytes::default(),
113 }
114 }
115
116 #[test]
117 fn test_display() {
118 let wal_lock = WalLock {
119 lock_round: 0,
120 lock_votes: mock_qc(),
121 content: Pill::new(),
122 };
123 println!("{}", wal_lock);
124
125 let wal_info = WalInfo {
126 height: 0,
127 round: 0,
128 step: Step::Propose,
129 lock: Some(wal_lock),
130 from: UpdateFrom::PrecommitQC(mock_qc()),
131 };
132
133 assert_eq!(
134 wal_info.to_string(),
135 "wal info height 0, round 0, step Propose"
136 );
137 }
138}