Skip to main content

zigbee_host/
backup.rs

1//! Network backups in the open coordinator backup format (version 1), the
2//! JSON format several Zigbee hosts share, so a backup names everything a
3//! replacement coordinator needs: the network key and its frame counter,
4//! the PAN ids and channel, the coordinator's IEEE address and the trust
5//! center's link keys.
6
7use serde::{Deserialize, Serialize};
8use zigbee_primitives::{ExtPanId, Ieee, Key, PanId};
9
10/// The format name in `metadata.format`.
11pub const FORMAT: &str = "zigpy/open-coordinator-backup";
12
13/// How far the network frame counter is advanced on restore, so that the
14/// restored coordinator never reuses a counter the old one sent after the
15/// backup was taken.
16pub const RESTORE_FRAME_COUNTER_MARGIN: u32 = 100_000;
17
18/// A network backup.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Backup {
21    /// Format, version and producer.
22    pub metadata: Metadata,
23    /// Stack-specific data needed to restore onto the same NCP family.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub stack_specific: Option<StackSpecific>,
26    /// The coordinator's IEEE address.
27    pub coordinator_ieee: Ieee,
28    /// PAN id, as four hex digits.
29    #[serde(with = "pan_hex")]
30    pub pan_id: PanId,
31    /// Extended PAN id.
32    pub extended_pan_id: ExtPanId,
33    /// Network update id.
34    pub nwk_update_id: u8,
35    /// Security level (5).
36    pub security_level: u8,
37    /// Channel.
38    pub channel: u8,
39    /// Channels the network may use.
40    pub channel_mask: Vec<u8>,
41    /// The network key.
42    pub network_key: NetworkKey,
43    /// Devices and their link keys.
44    pub devices: Vec<BackupDevice>,
45}
46
47/// Backup metadata.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct Metadata {
50    /// [`FORMAT`].
51    pub format: String,
52    /// 1.
53    pub version: u32,
54    /// The producer, `name@version`.
55    pub source: String,
56    /// Producer-specific details.
57    #[serde(default)]
58    pub internal: Internal,
59}
60
61/// Producer-specific metadata.
62#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
63pub struct Internal {
64    /// When the backup was taken, seconds since the Unix epoch.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub created_unix: Option<u64>,
67    /// The NCP's EZSP protocol version.
68    #[serde(
69        default,
70        rename = "ezspVersion",
71        skip_serializing_if = "Option::is_none"
72    )]
73    pub ezsp_version: Option<u8>,
74    /// The NCP's firmware version.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub firmware: Option<String>,
77}
78
79/// Stack-specific data.
80#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
81pub struct StackSpecific {
82    /// For EmberZNet.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub ezsp: Option<EzspSpecific>,
85    /// For Z-Stack.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub zstack: Option<ZstackSpecific>,
88}
89
90/// Z-Stack-specific data.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct ZstackSpecific {
93    /// The seed Z-Stack derives each device's unique link key from.
94    pub tclk_seed: Key,
95}
96
97/// EmberZNet-specific data.
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99pub struct EzspSpecific {
100    /// The trust center's root key, from which it derives each device's
101    /// unique link key (hashed link keys).
102    pub hashed_tclk: Key,
103}
104
105/// The network key.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct NetworkKey {
108    /// The key.
109    pub key: Key,
110    /// Its sequence number.
111    pub sequence_number: u8,
112    /// The coordinator's outgoing frame counter.
113    pub frame_counter: u32,
114}
115
116/// One device in a backup.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct BackupDevice {
119    /// Network address, four hex digits, if known.
120    #[serde(default, with = "opt_pan_hex")]
121    pub nwk_address: Option<u16>,
122    /// IEEE address.
123    pub ieee_address: Ieee,
124    /// A child of the coordinator.
125    #[serde(default)]
126    pub is_child: bool,
127    /// Its trust center link key, if the trust center keeps one.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub link_key: Option<LinkKey>,
130}
131
132/// A device's link key and frame counters.
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134pub struct LinkKey {
135    /// The key.
136    pub key: Key,
137    /// Outgoing APS frame counter.
138    pub tx_counter: u32,
139    /// Incoming APS frame counter.
140    pub rx_counter: u32,
141}
142
143/// A backup failed validation.
144#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
145pub enum BackupError {
146    /// Not the open coordinator backup format.
147    #[error("not an open coordinator backup (format {0:?})")]
148    Format(String),
149    /// An unsupported format version.
150    #[error("unsupported backup format version {0}")]
151    Version(u32),
152    /// The channel is not 11 to 26.
153    #[error("channel {0} is not a 2.4 GHz Zigbee channel")]
154    Channel(u8),
155    /// The JSON did not parse.
156    #[error("backup JSON: {0}")]
157    Json(String),
158}
159
160impl Backup {
161    /// Parse and validate a backup.
162    pub fn from_json(text: &str) -> Result<Backup, BackupError> {
163        let backup: Backup =
164            serde_json::from_str(text).map_err(|e| BackupError::Json(e.to_string()))?;
165        backup.validate()?;
166        Ok(backup)
167    }
168
169    /// Check the fields a restore relies on.
170    pub fn validate(&self) -> Result<(), BackupError> {
171        if self.metadata.format != FORMAT {
172            return Err(BackupError::Format(self.metadata.format.clone()));
173        }
174        if self.metadata.version != 1 {
175            return Err(BackupError::Version(self.metadata.version));
176        }
177        if !(11..=26).contains(&self.channel) {
178            return Err(BackupError::Channel(self.channel));
179        }
180        Ok(())
181    }
182
183    /// The JSON text.
184    pub fn to_json(&self) -> String {
185        serde_json::to_string_pretty(self).unwrap_or_default()
186    }
187
188    /// The frame counter a restored coordinator should start from.
189    pub fn restore_frame_counter(&self) -> u32 {
190        self.network_key
191            .frame_counter
192            .saturating_add(RESTORE_FRAME_COUNTER_MARGIN)
193    }
194}
195
196mod pan_hex {
197    use serde::{de::Error, Deserialize, Deserializer, Serializer};
198
199    pub fn serialize<S: Serializer>(v: &u16, s: S) -> Result<S::Ok, S::Error> {
200        s.serialize_str(&format!("{v:04x}"))
201    }
202
203    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u16, D::Error> {
204        let text = String::deserialize(d)?;
205        u16::from_str_radix(text.trim_start_matches("0x"), 16).map_err(D::Error::custom)
206    }
207}
208
209mod opt_pan_hex {
210    use serde::{de::Error, Deserialize, Deserializer, Serializer};
211
212    pub fn serialize<S: Serializer>(v: &Option<u16>, s: S) -> Result<S::Ok, S::Error> {
213        match v {
214            Some(v) => s.serialize_str(&format!("{v:04x}")),
215            None => s.serialize_none(),
216        }
217    }
218
219    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u16>, D::Error> {
220        match Option::<String>::deserialize(d)? {
221            None => Ok(None),
222            Some(text) => u16::from_str_radix(text.trim_start_matches("0x"), 16)
223                .map(Some)
224                .map_err(D::Error::custom),
225        }
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn round_trips_and_validates() {
235        let backup = Backup {
236            metadata: Metadata {
237                format: FORMAT.into(),
238                version: 1,
239                source: "zigbee-bridge@0.1.0".into(),
240                internal: Internal {
241                    created_unix: Some(1),
242                    ezsp_version: Some(13),
243                    firmware: Some("7.4.4.0".into()),
244                },
245            },
246            stack_specific: Some(StackSpecific {
247                ezsp: Some(EzspSpecific {
248                    hashed_tclk: Key([1; 16]),
249                }),
250                zstack: None,
251            }),
252            coordinator_ieee: Ieee(0x00124B0001020304),
253            pan_id: 0x1A62,
254            extended_pan_id: ExtPanId(0xDDDDDDDDDDDDDDDD),
255            nwk_update_id: 0,
256            security_level: 5,
257            channel: 15,
258            channel_mask: vec![15],
259            network_key: NetworkKey {
260                key: Key([2; 16]),
261                sequence_number: 0,
262                frame_counter: 4242,
263            },
264            devices: vec![BackupDevice {
265                nwk_address: Some(0x1234),
266                ieee_address: Ieee(5),
267                is_child: true,
268                link_key: Some(LinkKey {
269                    key: Key([3; 16]),
270                    tx_counter: 1,
271                    rx_counter: 2,
272                }),
273            }],
274        };
275        let json = backup.to_json();
276        assert!(json.contains("\"pan_id\": \"1a62\""));
277        assert!(json.contains("\"coordinator_ieee\": \"00124b0001020304\""));
278        assert_eq!(Backup::from_json(&json).unwrap(), backup);
279        assert_eq!(
280            backup.restore_frame_counter(),
281            4242 + RESTORE_FRAME_COUNTER_MARGIN
282        );
283        let bad = json.replace("\"channel\": 15", "\"channel\": 30");
284        assert_eq!(Backup::from_json(&bad), Err(BackupError::Channel(30)));
285    }
286
287    #[test]
288    fn reads_backups_from_other_hosts() {
289        // The shape other open-coordinator-backup producers write: a Z-Stack
290        // seed, unknown internal fields, devices with and without keys.
291        let text = r#"{
292          "metadata": {"format": "zigpy/open-coordinator-backup", "version": 1,
293                       "source": "another-host@1.2.3",
294                       "internal": {"date": "2026-01-02T03:04:05Z", "znpVersion": 1}},
295          "stack_specific": {"zstack": {"tclk_seed": "0102030405060708090a0b0c0d0e0f10"}},
296          "coordinator_ieee": "00124b0012345678",
297          "pan_id": "1a62",
298          "extended_pan_id": "dddddddddddddddd",
299          "nwk_update_id": 3,
300          "security_level": 5,
301          "channel": 15,
302          "channel_mask": [15],
303          "network_key": {"key": "01030507090b0d0f00020406080a0c0d",
304                          "sequence_number": 1, "frame_counter": 123456},
305          "devices": [
306            {"nwk_address": "ddb4", "ieee_address": "00158d0001020304", "is_child": true,
307             "link_key": {"key": "f1f2f3f4f5f6f7f8f9fafbfcfdfeff00", "rx_counter": 7, "tx_counter": 9}},
308            {"nwk_address": null, "ieee_address": "00158d0001020305", "is_child": false}
309          ]
310        }"#;
311        let b = Backup::from_json(text).unwrap();
312        assert_eq!(b.coordinator_ieee, Ieee(0x00124B0012345678));
313        assert_eq!((b.pan_id, b.channel, b.nwk_update_id), (0x1A62, 15, 3));
314        assert_eq!(b.network_key.frame_counter, 123_456);
315        let seed = b
316            .stack_specific
317            .as_ref()
318            .and_then(|s| s.zstack.as_ref())
319            .unwrap();
320        assert_eq!(seed.tclk_seed.0[0], 0x01);
321        assert_eq!(b.devices.len(), 2);
322        assert_eq!(b.devices[0].nwk_address, Some(0xDDB4));
323        assert_eq!(
324            b.devices[0].link_key.as_ref().map(|k| k.tx_counter),
325            Some(9)
326        );
327        assert_eq!(b.devices[1].nwk_address, None);
328        // And it writes back in the same shape.
329        let again = Backup::from_json(&b.to_json()).unwrap();
330        assert_eq!(again, b);
331    }
332}