nil_zonefile/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Copyright (c) 2025 New Internet Labs Limited
// SPDX-License-Identifier: MIT

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use ciborium;
use zstd;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SubDomain {
    pub owner: String,
    pub general: String,
    pub twitter: String,
    pub url: String,
    pub nostr: String,
    pub lightning: String,
    pub btc: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "v")]
pub enum ZoneFile {
    #[serde(rename = "0")]
    V0 {
        owner: String,
        general: String,
        twitter: String,
        url: String,
        nostr: String,
        lightning: String,
        btc: String,
        subdomains: HashMap<String, SubDomain>,
    },
    #[serde(rename = "1")]
    V1 {
        default: String,
    }
}

impl ZoneFile {
    /// Parse a zonefile from a JSON string
    pub fn from_str(zonefile_str: &str) -> Result<Self, serde_json::Error> {
        // First try to parse as V1
        if let Ok(v1) = serde_json::from_str::<Self>(zonefile_str) {
            return Ok(v1);
        }

        // If that fails, try to parse as legacy V0 without version field
        let legacy: Result<LegacyZoneFile, _> = serde_json::from_str(zonefile_str);
        match legacy {
            Ok(v0) => {
                // Convert legacy V0 to a proper V0 with version tag
                let v0_json = serde_json::json!({
                    "v": "0",
                    "owner": v0.owner,
                    "general": v0.general,
                    "twitter": v0.twitter,
                    "url": v0.url,
                    "nostr": v0.nostr,
                    "lightning": v0.lightning,
                    "btc": v0.btc,
                    "subdomains": v0.subdomains,
                });
                serde_json::from_value(v0_json)
            },
            Err(e) => Err(e)
        }
    }

    /// Convert the zonefile to a JSON string
    pub fn to_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Create a new V1 zonefile
    pub fn new_v1(default: String) -> Self {
        ZoneFile::V1 { default }
    }

    /// Create a new V0 zonefile
    pub fn new_v0(
        owner: String,
        general: String,
        twitter: String,
        url: String,
        nostr: String,
        lightning: String,
        btc: String,
        subdomains: HashMap<String, SubDomain>,
    ) -> Self {
        ZoneFile::V0 {
            owner,
            general,
            twitter,
            url,
            nostr,
            lightning,
            btc,
            subdomains,
        }
    }

    /// Parse a zonefile from a Clarity Buffer Hex String
    pub fn from_clarity_buffer_hex_string(hex_string: &str) -> Result<Self, serde_json::Error> {
        let bytes = ZoneFile::clarity_buffer_to_uint8_array(hex_string);
        let zonefile = ZoneFile::from_bytes(&bytes)?;
        Ok(zonefile)
    }

    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        // Try decompressing as zstd first
        let decompressed_result = zstd::decode_all(bytes);
        
        let processed_bytes = match decompressed_result {
            Ok(decompressed) => decompressed,
            Err(_) => bytes.to_vec(), // If not compressed, use original bytes
        };

        // Try parsing as CBOR
        match ZoneFile::from_cbor(&processed_bytes) {
            Ok(zonefile) => Ok(zonefile),
            Err(_) => {
                // If CBOR parsing fails, try parsing as JSON string
                match std::str::from_utf8(&processed_bytes) {
                    Ok(str_data) => ZoneFile::from_str(str_data),
                    Err(e) => Err(serde_json::Error::io(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Invalid UTF-8: {}", e)
                    )))
                }
            }
        }
    }

    /// Parse a zonefile from CBOR bytes
    pub fn from_cbor(cbor_bytes: &[u8]) -> Result<Self, ciborium::de::Error<std::io::Error>> {
        ciborium::de::from_reader(cbor_bytes)
    }

    /// Convert the zonefile to CBOR bytes
    pub fn to_cbor(&self) -> Result<Vec<u8>, ciborium::ser::Error<std::io::Error>> {
        let mut bytes = Vec::new();
        ciborium::ser::into_writer(self, &mut bytes)?;
        Ok(bytes)
    }

    /// Convert the zonefile to compressed CBOR bytes using zstd
    pub fn to_compressed_cbor(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let cbor_bytes = self.to_cbor()?;
        // Compress with highest compression level (22)
        let compressed = zstd::encode_all(&cbor_bytes[..], 22)?;
        Ok(compressed)
    }

    fn clarity_buffer_to_uint8_array(hex_string: &str) -> Vec<u8> {
        // Remove '0x' prefix if present
        let hex = hex_string.strip_prefix("0x").unwrap_or(hex_string);
        
        // Convert hex string to bytes
        (0..hex.len())
            .step_by(2)
            .filter_map(|i| {
                if i + 2 <= hex.len() {
                    u8::from_str_radix(&hex[i..i + 2], 16).ok()
                } else {
                    None
                }
            })
            .collect()
    }
}

// Internal struct for parsing legacy V0 zonefiles
#[derive(Debug, Serialize, Deserialize)]
struct LegacyZoneFile {
    owner: String,
    general: String,
    twitter: String,
    url: String,
    nostr: String,
    lightning: String,
    btc: String,
    subdomains: HashMap<String, SubDomain>,
}

// Wrap the entire WASM module in a feature flag
#[cfg(feature = "wasm")]
pub mod wasm {
    use super::*;
    use wasm_bindgen::prelude::*;

    #[wasm_bindgen]
    pub fn parse_zonefile_from_clarity_buffer_hex_string(hex_string: &str) -> Result<Vec<u8>, JsValue> {
        ZoneFile::from_clarity_buffer_hex_string(hex_string)
            .and_then(|zf| zf.to_cbor().map_err(|e| serde_json::Error::io(std::io::Error::new(
                std::io::ErrorKind::Other,
                e.to_string()
            ))))
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    #[wasm_bindgen(js_name = "generate_zonefile")]
    pub fn generate_zonefile(val: JsValue, compress: bool) -> Result<Vec<u8>, JsValue> {
        let zonefile: ZoneFile = serde_wasm_bindgen::from_value(val)
            .map_err(|e| JsValue::from_str(&format!("Failed to parse zonefile: {}", e)))?;

        if compress {
            zonefile.to_compressed_cbor()
                .map_err(|e| JsValue::from_str(&format!("Failed to compress zonefile: {}", e)))
        } else {
            zonefile.to_cbor()
                .map_err(|e| JsValue::from_str(&format!("Failed to generate CBOR: {}", e)))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SAMPLE_ZONEFILE: &str = r#"{"owner":"SP3D03X5BHMNSAAW71NN7BQRMV4DW2G4JB3MZAGJ8","general":"Pato Gómez","twitter":"@setpato","url":"pato.locker","nostr":"","lightning":"","btc":"bc1q4x98c6gwjj34lqs97zdvfyv2j0fcjhhw7hj0pc","subdomains":{"test":{"owner":"SP3D03X5BHMNSAAW71NN7BQRMV4DW2G4JB3MZAGJ8","general":"test","twitter":"setpato","url":"testurl","nostr":"","lightning":"","btc":"bc1q4x98c6gwjj34lqs97zdvfyv2j0fcjhhw7hj0pc"}}}"#;
    const SAMPLE_ZONEFILE_EMPTY_SUBDOMAINS: &str = r#"{"owner":"SP3D03X5BHMNSAAW71NN7BQRMV4DW2G4JB3MZAGJ8","general":"Pato Gómez","twitter":"@setpato","url":"pato.locker","nostr":"","lightning":"","btc":"bc1q4x98c6gwjj34lqs97zdvfyv2j0fcjhhw7hj0pc","subdomains":{}}"#;
    const SAMPLE_ZONEFILE_HEX_STRING_LARRY_ID: &str = "7b226f776e6572223a2253503252374358454244474248374d374b3052484347514750593659364b524a314d37444541414d57222c2267656e6572616c223a22222c2274776974746572223a226c6172727973616c69627261222c2275726c223a22222c226e6f737472223a22222c226c696768746e696e67223a22222c22627463223a22222c22737562646f6d61696e73223a7b7d7d";
    #[test]
    fn test_parse_zonefile_valid() {
        let result = ZoneFile::from_str(SAMPLE_ZONEFILE);
        assert!(result.is_ok());
        
        let zonefile = result.unwrap();
        match zonefile {
            ZoneFile::V0 { owner, general, twitter, .. } => {
                assert_eq!(&owner, "SP3D03X5BHMNSAAW71NN7BQRMV4DW2G4JB3MZAGJ8");
                assert_eq!(&general, "Pato Gómez");
                assert_eq!(&twitter, "@setpato");
            },
            _ => panic!("Expected V0 zonefile"),
        }
    }

    #[test]
    fn test_parse_zonefile_invalid() {
        let result = ZoneFile::from_str("{invalid json}");
        assert!(result.is_err());
    }

    #[test]
    fn test_zonefile_roundtrip() {
        let zonefile = ZoneFile::from_str(SAMPLE_ZONEFILE).unwrap();
        let json = zonefile.to_string().unwrap();
        let parsed_again = ZoneFile::from_str(&json).unwrap();
        
        match (&zonefile, &parsed_again) {
            (ZoneFile::V0 { owner: orig_owner, general: orig_general, subdomains: orig_subdomains, .. },
             ZoneFile::V0 { owner: parsed_owner, general: parsed_general, subdomains: parsed_subdomains, .. }) => {
                assert_eq!(orig_owner, parsed_owner);
                assert_eq!(orig_general, parsed_general);
                
                let orig_subdomain = orig_subdomains.get("test").unwrap();
                let parsed_subdomain = parsed_subdomains.get("test").unwrap();
                assert_eq!(orig_subdomain.general, parsed_subdomain.general);
                assert_eq!(orig_subdomain.twitter, parsed_subdomain.twitter);
            },
            _ => panic!("Expected V0 zonefile"),
        }
    }

    #[test]
    fn test_cbor_roundtrip() {
        let zonefile = ZoneFile::from_str(SAMPLE_ZONEFILE).unwrap();
        
        // Test regular CBOR still works
        let cbor_bytes = zonefile.to_cbor().unwrap();
        let parsed_from_cbor = ZoneFile::from_bytes(&cbor_bytes).unwrap();
        match (&zonefile, &parsed_from_cbor) {
            (ZoneFile::V0 { owner: orig_owner, .. }, ZoneFile::V0 { owner: parsed_owner, .. }) => {
                assert_eq!(orig_owner, parsed_owner);
            },
            _ => panic!("Expected V0 zonefile"),
        }
        
        // Test compressed CBOR
        let compressed_bytes = zonefile.to_compressed_cbor().unwrap();
        let parsed_from_compressed = ZoneFile::from_bytes(&compressed_bytes).unwrap();
        match (&zonefile, &parsed_from_compressed) {
            (ZoneFile::V0 { owner: orig_owner, .. }, ZoneFile::V0 { owner: parsed_owner, .. }) => {
                assert_eq!(orig_owner, parsed_owner);
            },
            _ => panic!("Expected V0 zonefile"),
        }

        // Verify compression actually reduces size
        assert!(compressed_bytes.len() < cbor_bytes.len());
        println!("CBOR size: {}, Compressed size: {}", cbor_bytes.len(), compressed_bytes.len());
    }

    #[test]
    fn test_cbor_invalid_input() {
        assert!(ZoneFile::from_cbor(&[]).is_err());
        assert!(ZoneFile::from_cbor(&[0xFF, 0xFF, 0xFF]).is_err());
    }

    #[test]
    fn test_cbor_size() {
        let zonefile = ZoneFile::from_str(SAMPLE_ZONEFILE).unwrap();
        let json_size = SAMPLE_ZONEFILE.len();
        let cbor_size = zonefile.to_cbor().unwrap().len();
        assert!(cbor_size < json_size);
        println!("JSON size: {}, CBOR size: {}", json_size, cbor_size);
    }

    #[test]
    fn test_cbor_empty_fields() {
        let zonefile = ZoneFile::from_str(SAMPLE_ZONEFILE_EMPTY_SUBDOMAINS).unwrap();

        let cbor_bytes = zonefile.to_cbor().unwrap();
        let parsed_zonefile = ZoneFile::from_cbor(&cbor_bytes).unwrap();

        match parsed_zonefile {
            ZoneFile::V0 { nostr, lightning, subdomains, .. } => {
                assert_eq!(nostr, "");
                assert_eq!(lightning, "");
                assert!(subdomains.is_empty());
            },
            _ => panic!("Expected V0 zonefile"),
        }
    }

    #[test]
    fn test_clarity_buffer_conversion() {
        // Test with '0x' prefix
        let hex = "0x5361746f736869"; // "Satoshi" in hex
        let bytes = ZoneFile::clarity_buffer_to_uint8_array(hex);
        assert_eq!(bytes, b"Satoshi");

        // Test without '0x' prefix
        let hex = "5361746f736869"; // "Satoshi" in hex
        let bytes = ZoneFile::clarity_buffer_to_uint8_array(hex);
        assert_eq!(bytes, b"Satoshi");

        // Test empty string
        let hex = "";
        let bytes = ZoneFile::clarity_buffer_to_uint8_array(hex);
        assert_eq!(bytes, Vec::<u8>::new());

        // Test invalid hex (odd length)
        let hex = "5361746f73686"; // Odd length
        let bytes = ZoneFile::clarity_buffer_to_uint8_array(hex);
        assert_eq!(bytes, vec![0x53, 0x61, 0x74, 0x6f, 0x73, 0x68]); // Should ignore last character

        // Test invalid hex characters
        let hex = "0xZZ";
        let bytes = ZoneFile::clarity_buffer_to_uint8_array(hex);
        assert_eq!(bytes, Vec::<u8>::new()); // Should return empty vec for invalid hex
    }

    #[test]
    fn test_from_clarity_buffer_hex_string() {
        // Create a valid zonefile JSON and convert to hex
        let hex = format!("0x{}", hex::encode(SAMPLE_ZONEFILE));
        println!("Hex: {}", hex);
        
        let result = ZoneFile::from_clarity_buffer_hex_string(&hex);
        assert!(result.is_ok());
        let zonefile = result.unwrap();
        match zonefile {
            ZoneFile::V0 { owner, general, .. } => {
                assert_eq!(&owner, "SP3D03X5BHMNSAAW71NN7BQRMV4DW2G4JB3MZAGJ8");
                assert_eq!(&general, "Pato Gómez");
            },
            _ => panic!("Expected V0 zonefile"),
        }

        // Test invalid hex string
        let result = ZoneFile::from_clarity_buffer_hex_string("0xZZ");
        assert!(result.is_err());

        // Test empty hex string
        let result = ZoneFile::from_clarity_buffer_hex_string("");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_hex_string_sample() {
        let result = ZoneFile::from_clarity_buffer_hex_string(SAMPLE_ZONEFILE_HEX_STRING_LARRY_ID);
        assert!(result.is_ok());
        
        let zonefile = result.unwrap();
        match zonefile {
            ZoneFile::V0 { owner, general, twitter, url, nostr, lightning, btc, subdomains } => {
                assert_eq!(owner, "SP2R7CXEBDGBH7M7K0RHCGQGPY6Y6KRJ1M7DEAAMW");
                assert_eq!(general, "");
                assert_eq!(twitter, "larrysalibra");
                assert_eq!(url, "");
                assert_eq!(nostr, "");
                assert_eq!(lightning, "");
                assert_eq!(btc, "");
                assert!(subdomains.is_empty());
            },
            _ => panic!("Expected V0 zonefile"),
        }
    }

    #[test]
    fn test_version_handling() {
        // Test parsing legacy V0 zonefile without version
        let json = r#"{"owner":"SP123","general":"Test","twitter":"@test","url":"test.url","nostr":"","lightning":"","btc":"","subdomains":{}}"#;
        let zonefile = ZoneFile::from_str(json).unwrap();
        
        // Verify that serializing adds the version tag
        let serialized = zonefile.to_string().unwrap();
        println!("Serialized V0 from legacy: {}", serialized);
        assert!(serialized.contains(r#""v":"0""#), "Serialized output should contain version tag");
        
        // Test parsing explicit V0 zonefile
        let json_v0 = r#"{"v":"0","owner":"SP123","general":"Test","twitter":"@test","url":"test.url","nostr":"","lightning":"","btc":"","subdomains":{}}"#;
        let zonefile = ZoneFile::from_str(json_v0).unwrap();
        let serialized = zonefile.to_string().unwrap();
        println!("Serialized V0 from explicit: {}", serialized);
        assert!(serialized.contains(r#""v":"0""#), "Serialized output should contain version tag");

        // Test that CBOR serialization includes version tag
        let cbor_bytes = zonefile.to_cbor().unwrap();
        let parsed_from_cbor = ZoneFile::from_cbor(&cbor_bytes).unwrap();
        let serialized_from_cbor = parsed_from_cbor.to_string().unwrap();
        println!("Serialized from CBOR: {}", serialized_from_cbor);
        assert!(serialized_from_cbor.contains(r#""v":"0""#), "CBOR roundtrip should preserve version tag");

        // Test parsing V1 zonefile
        let json_v1 = r#"{"v":"1","default":"test.btc"}"#;
        let zonefile = ZoneFile::from_str(json_v1).unwrap();
        match zonefile {
            ZoneFile::V1 { default } => assert_eq!(default, "test.btc"),
            _ => panic!("Expected V1 zonefile"),
        }

        // Test creating and serializing V1 zonefile
        let v1 = ZoneFile::new_v1("test.btc".to_string());
        let serialized = v1.to_string().unwrap();
        println!("Serialized V1: {}", serialized);
        assert!(serialized.contains(r#""v":"1""#), "Serialized V1 output should contain version tag");

        // Test creating and serializing V0 zonefile
        let v0 = ZoneFile::new_v0(
            "SP123".to_string(),
            "Test".to_string(),
            "@test".to_string(),
            "test.url".to_string(),
            "".to_string(),
            "".to_string(),
            "".to_string(),
            HashMap::new(),
        );
        let serialized = v0.to_string().unwrap();
        println!("Serialized V0 from new: {}", serialized);
        assert!(serialized.contains(r#""v":"0""#), "Serialized V0 output should contain version tag");
    }

    #[test]
    fn test_version_tag_simple() {
        // Test V0
        let v0 = ZoneFile::new_v0(
            "SP123".to_string(),
            "Test".to_string(),
            "@test".to_string(),
            "test.url".to_string(),
            "".to_string(),
            "".to_string(),
            "".to_string(),
            HashMap::new(),
        );
        let serialized = serde_json::to_string(&v0).unwrap();
        println!("Direct V0 serialization: {}", serialized);
        assert!(serialized.contains(r#""v":"0""#), "Direct V0 serialization should contain version tag");

        // Test V1
        let v1 = ZoneFile::new_v1("test.btc".to_string());
        let serialized = serde_json::to_string(&v1).unwrap();
        println!("Direct V1 serialization: {}", serialized);
        assert!(serialized.contains(r#""v":"1""#), "Direct V1 serialization should contain version tag");
    }
}