Skip to main content

cfx_internal_common/
chain_id.rs

1/// The parameters needed to determine the chain_id based on epoch_number.
2#[derive(Clone, Debug, Eq, RlpEncodable, RlpDecodable, PartialEq, Default)]
3pub struct ChainIdParamsDeprecated {
4    /// Preconfigured chain_id.
5    pub chain_id: u32,
6}
7
8impl ChainIdParamsDeprecated {
9    /// The function return the chain_id with given parameters
10    pub fn get_chain_id(&self, _epoch_number: u64) -> u32 { self.chain_id }
11}
12
13#[derive(Clone, Debug, Default, PartialEq)]
14pub struct ChainIdParamsInnerGeneric<ChainID> {
15    heights: Vec<u64>,
16    chain_ids: Vec<ChainID>,
17}
18
19pub type ChainIdParamsInner = ChainIdParamsInnerGeneric<AllChainID>;
20pub type ChainIdParamsOneChainInner = ChainIdParamsInnerGeneric<u32>;
21pub type ChainIdParams = Arc<RwLock<ChainIdParamsInner>>;
22
23impl<T> ChainIdParamsInnerGeneric<T>
24where T: Clone + Debug + Default + PartialEq + Encodable + Decodable + Copy
25{
26    /// The function return the chain_id with given parameters
27    pub fn get_chain_id(&self, epoch_number: u64) -> T {
28        let index = self
29            .heights
30            .binary_search(&epoch_number)
31            .unwrap_or_else(|x| x - 1);
32        self.chain_ids[index]
33    }
34
35    pub fn new_inner(chain_id: T) -> Self {
36        Self {
37            heights: vec![0],
38            chain_ids: vec![chain_id],
39        }
40    }
41
42    pub fn matches(&self, other: &Self, peer_epoch_number: u64) -> bool {
43        // Sub-array check. One height to epoch id map must be a sub-array of
44        // another.
45        let min_len = min(self.heights.len(), other.heights.len());
46        let sub_array_check = other.heights[0..min_len]
47            == self.heights[0..min_len]
48            && other.chain_ids[0..min_len] == self.chain_ids[0..min_len];
49
50        if sub_array_check {
51            // Check if peer has a high epoch_number but a shorter height to
52            // epoch id map, so that the chain_id of ourselves is
53            // not a match anymore.
54            let index = self
55                .heights
56                .binary_search(&peer_epoch_number)
57                .unwrap_or_else(|x| x - 1);
58            min_len > index
59        } else {
60            return false;
61        }
62    }
63}
64
65impl ChainIdParamsOneChainInner {
66    pub fn parse_config_str(config: &str) -> std::result::Result<Self, String> {
67        let mut parsed = Self::default();
68        let value = config
69            .parse::<toml::Value>()
70            .map_err(|e| format!("{}", e))?;
71        if let toml::Value::Table(table) = &value {
72            if let Some(height_to_chain_ids) = table.get("height_to_chain_ids")
73            {
74                if let toml::Value::Array(array) = height_to_chain_ids {
75                    if array.len() == 0 {
76                        return Err(String::from("Invalid ChainIdParams config format: height_to_chain_ids is empty"));
77                    }
78                    let mut used_chain_ids = BTreeSet::new();
79                    for element in array {
80                        if let toml::Value::Array(pair) = element {
81                            if pair.len() != 2 {
82                                return Err(String::from("Invalid ChainIdParams config format: height_to_chain_ids elements is not [height, chain_id]"));
83                            }
84                            if let [toml::Value::Integer(height), toml::Value::Integer(chain_id)] =
85                                &pair[0..2]
86                            {
87                                if *height < 0 {
88                                    return Err(String::from("Invalid ChainIdParams config format: height must be positive"));
89                                }
90                                if used_chain_ids.contains(chain_id) {
91                                    return Err(String::from("Invalid ChainIdParams config format: chain_id must be pairwise different"));
92                                }
93                                if *chain_id < 0 || *chain_id > u32::MAX as i64
94                                {
95                                    return Err(String::from("Invalid ChainIdParams config format: chain_id out of range for u32"));
96                                }
97                                parsed.heights.push(*height as u64);
98                                parsed.chain_ids.push(*chain_id as u32);
99                                used_chain_ids.insert(*chain_id);
100                            }
101                        } else {
102                            return Err(String::from("Invalid ChainIdParams config format: height_to_chain_ids elements is not [height, chain_id]"));
103                        }
104                    }
105                } else {
106                    return Err(String::from("Invalid ChainIdParams config format: height_to_chain_ids is not an array"));
107                }
108            } else {
109                return Err(String::from("Invalid ChainIdParams config format: height_to_chain_ids not found"));
110            }
111            if parsed.heights[0] != 0 {
112                return Err(String::from("Invalid ChainIdParams config format: height must start from 0"));
113            }
114            Ok(parsed)
115        } else {
116            return Err(String::from(
117                "Invalid ChainIdParams config format: not a table",
118            ));
119        }
120    }
121}
122
123impl ChainIdParamsInner {
124    pub fn new_simple(chain_id: AllChainID) -> ChainIdParams {
125        Arc::new(RwLock::new(Self::new_inner(chain_id)))
126    }
127
128    pub fn new_from_inner(x: &Self) -> ChainIdParams {
129        Arc::new(RwLock::new(x.clone()))
130    }
131
132    pub fn to_native_space_params(&self) -> ChainIdParamsOneChainInner {
133        ChainIdParamsOneChainInner {
134            heights: self.heights.clone(),
135            chain_ids: self
136                .chain_ids
137                .iter()
138                .map(|x| x.in_native_space())
139                .collect(),
140        }
141    }
142}
143
144impl From<ChainIdParamsDeprecated> for ChainIdParamsOneChainInner {
145    fn from(x: ChainIdParamsDeprecated) -> Self {
146        Self {
147            heights: vec![0],
148            chain_ids: vec![x.chain_id],
149        }
150    }
151}
152
153#[cfg(test)]
154mod test {
155    use super::*;
156    use ChainIdParamsInnerGeneric as ChainIdParamsInner;
157
158    #[test]
159    fn test_parse_config_str() {
160        let config_str =
161            "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2], [30000, 3]]";
162        let config = ChainIdParamsInner::parse_config_str(config_str).unwrap();
163        assert_eq!(
164            config,
165            ChainIdParamsInner {
166                heights: vec![0, 10000, 20000, 30000],
167                chain_ids: vec![0, 1, 2, 3],
168            }
169        );
170
171        // Config can't be empty.
172        let config_str = "";
173        let config = ChainIdParamsInner::parse_config_str(config_str);
174        assert!(config.is_err());
175
176        // Height must start from 0.
177        let config_str = "height_to_chain_ids = [[10, 1024]]";
178        let config = ChainIdParamsInner::parse_config_str(config_str);
179        assert!(config.is_err());
180
181        // Must be array of array.
182        let config_str = "height_to_chain_ids = [0, 1024]";
183        let config = ChainIdParamsInner::parse_config_str(config_str);
184        assert!(config.is_err());
185
186        // Can not reuse chain_id.
187        let config_str = "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2], [30000, 1]]";
188        let config = ChainIdParamsInner::parse_config_str(config_str);
189        assert!(config.is_err());
190
191        let config_str = "height_to_chain_ids = [[0, 1024]]";
192        let config = ChainIdParamsInner::parse_config_str(config_str).unwrap();
193        assert_eq!(
194            config,
195            ChainIdParamsInner {
196                heights: vec![0],
197                chain_ids: vec![1024],
198            }
199        );
200    }
201
202    #[test]
203    fn test_chain_id_at_height() {
204        let config_str =
205            "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2], [30000, 3]]";
206        let config = ChainIdParamsInner::parse_config_str(config_str).unwrap();
207        assert_eq!(config.get_chain_id(0), 0);
208        assert_eq!(config.get_chain_id(1), 0);
209        assert_eq!(config.get_chain_id(9999), 0);
210        assert_eq!(config.get_chain_id(10000), 1);
211        assert_eq!(config.get_chain_id(10001), 1);
212        assert_eq!(config.get_chain_id(19999), 1);
213        assert_eq!(config.get_chain_id(20000), 2);
214        assert_eq!(config.get_chain_id(20001), 2);
215        assert_eq!(config.get_chain_id(29999), 2);
216        assert_eq!(config.get_chain_id(30000), 3);
217        assert_eq!(config.get_chain_id(30001), 3);
218    }
219
220    #[test]
221    fn test_chain_id_peer_compatibility() {
222        let epoch_number = 30000;
223        let config = ChainIdParamsInner::parse_config_str(
224            "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2], [30000, 3]]",
225        )
226        .unwrap();
227        let compatible_config_1 = ChainIdParamsInner::parse_config_str(
228            "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2]]",
229        )
230        .unwrap();
231        let compatible_config_2 = ChainIdParamsInner::parse_config_str(
232            "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2], [30000, 3], [40000, 4], [50000, 5]]",
233        )
234            .unwrap();
235        let incompatible_config_1 = ChainIdParamsInner::parse_config_str(
236            "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2], [30000, 4]]",
237        )
238            .unwrap();
239        let incompatible_config_2 = ChainIdParamsInner::parse_config_str(
240            "height_to_chain_ids = [[0, 0], [10000, 1], [20000, 2], [25000, 3]]",
241        )
242            .unwrap();
243        let incompatible_config_3 = ChainIdParamsInner::parse_config_str(
244            "height_to_chain_ids = [[0, 0], [10000, 1]]",
245        )
246        .unwrap();
247
248        assert!(config.matches(&compatible_config_1, epoch_number - 1));
249        assert!(!config.matches(&compatible_config_1, epoch_number));
250        assert!(config.matches(&compatible_config_2, epoch_number));
251        assert!(!config.matches(&incompatible_config_1, epoch_number));
252        assert!(!config.matches(&incompatible_config_1, epoch_number - 1));
253        assert!(!config.matches(&incompatible_config_2, epoch_number));
254        assert!(!config.matches(&incompatible_config_3, epoch_number));
255    }
256}
257
258use cfx_types::AllChainID;
259use parking_lot::RwLock;
260use rlp::{Decodable, Encodable};
261use std::{cmp::min, collections::BTreeSet, fmt::Debug, sync::Arc};