1use serde::{Deserialize, Serialize};
8use zigbee_primitives::{ExtPanId, Ieee, Key, PanId};
9
10pub const FORMAT: &str = "zigpy/open-coordinator-backup";
12
13pub const RESTORE_FRAME_COUNTER_MARGIN: u32 = 100_000;
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Backup {
21 pub metadata: Metadata,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
25 pub stack_specific: Option<StackSpecific>,
26 pub coordinator_ieee: Ieee,
28 #[serde(with = "pan_hex")]
30 pub pan_id: PanId,
31 pub extended_pan_id: ExtPanId,
33 pub nwk_update_id: u8,
35 pub security_level: u8,
37 pub channel: u8,
39 pub channel_mask: Vec<u8>,
41 pub network_key: NetworkKey,
43 pub devices: Vec<BackupDevice>,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct Metadata {
50 pub format: String,
52 pub version: u32,
54 pub source: String,
56 #[serde(default)]
58 pub internal: Internal,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
63pub struct Internal {
64 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub created_unix: Option<u64>,
67 #[serde(
69 default,
70 rename = "ezspVersion",
71 skip_serializing_if = "Option::is_none"
72 )]
73 pub ezsp_version: Option<u8>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub firmware: Option<String>,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
81pub struct StackSpecific {
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub ezsp: Option<EzspSpecific>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub zstack: Option<ZstackSpecific>,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct ZstackSpecific {
93 pub tclk_seed: Key,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99pub struct EzspSpecific {
100 pub hashed_tclk: Key,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct NetworkKey {
108 pub key: Key,
110 pub sequence_number: u8,
112 pub frame_counter: u32,
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct BackupDevice {
119 #[serde(default, with = "opt_pan_hex")]
121 pub nwk_address: Option<u16>,
122 pub ieee_address: Ieee,
124 #[serde(default)]
126 pub is_child: bool,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub link_key: Option<LinkKey>,
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134pub struct LinkKey {
135 pub key: Key,
137 pub tx_counter: u32,
139 pub rx_counter: u32,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
145pub enum BackupError {
146 #[error("not an open coordinator backup (format {0:?})")]
148 Format(String),
149 #[error("unsupported backup format version {0}")]
151 Version(u32),
152 #[error("channel {0} is not a 2.4 GHz Zigbee channel")]
154 Channel(u8),
155 #[error("backup JSON: {0}")]
157 Json(String),
158}
159
160impl Backup {
161 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 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 pub fn to_json(&self) -> String {
185 serde_json::to_string_pretty(self).unwrap_or_default()
186 }
187
188 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 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 let again = Backup::from_json(&b.to_json()).unwrap();
330 assert_eq!(again, b);
331 }
332}