nil-zonefile 0.3.0

A library for parsing and creating zonefiles on the new internet.
Documentation
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
// Copyright (c) 2025 New Internet Labs Limited
// SPDX-License-Identifier: MIT
#![doc = include_str!("../README.md")]
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use ciborium;
use brotli::{BrotliCompress, BrotliDecompress};
use brotli::enc::BrotliEncoderParams;
use log::{debug, error};

mod id;
pub use id::Id;

mod resource;
pub use resource::{Resource, ResourceValue};

mod wallet;
pub use wallet::{Wallet, WalletType};

mod dns;
pub use dns::Dns;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
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)]
// pub struct Dns {
//     pub zone: String,
//     pub version: String,
// }

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Wallets {
    pub wallets: HashMap<WalletType, String> // key is the SLIP44 ID, value is the address
}

#[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 {
        #[serde(skip_serializing_if = "Option::is_none")]
        default: Option<String>,

        // #[serde(skip_serializing_if = "Option::is_none")]
        // app: Option<String>,

        // #[serde(skip_serializing_if = "Option::is_none")]
        // service: Option<Service>,
        
        #[serde(skip_serializing_if = "Option::is_none")]
        id: Option<Id>,
        
        #[serde(skip_serializing_if = "Option::is_none")]
        resources: Option<HashMap<String, Resource>>,

        #[serde(skip_serializing_if = "Option::is_none")]
        wallets: Option<HashMap<WalletType, String>>,

        #[serde(skip_serializing_if = "crate::dns::is_dns_none")]
        dns: Option<Dns>,
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Service {
    pub name: String,
    pub proof: String,
}

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

        // If that fails, try to parse as legacy V0 without version field
        debug!("V1 parsing failed, attempting to parse as legacy V0");
        let legacy: Result<LegacyZoneFile, _> = serde_json::from_str(zonefile_str);
        match legacy {
            Ok(v0) => {
                debug!("Converting legacy V0 to proper V0 with version tag");
                // 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,
                });
                let result = serde_json::from_value(v0_json);
                if result.is_ok() {
                    debug!("Successfully parsed and converted legacy V0 zonefile");
                } else {
                    error!("Failed to convert legacy V0 to proper V0 format");
                }
                result
            },
            Err(e) => {
                error!("Failed to parse zonefile: {}", e);
                Err(e)
            }
        }
    }

    /// Convert the zonefile to a JSON string
    pub fn to_string(&self) -> Result<String, serde_json::Error> {
        debug!("Converting zonefile to JSON string");
        let result = serde_json::to_string(self);
        if let Err(ref e) = result {
            error!("Failed to convert zonefile to string: {}", e);
        } else {
            debug!("Successfully converted zonefile to string");
        }
        result
    }

    /// Create a new V1 zonefile
    pub fn new_v1(default: &str) -> Self {
        debug!("Creating new V1 zonefile with default: {}", default);
        ZoneFile::V1 { default: Some(default.to_string()), id: None, resources: None, wallets: None, dns: None }
    }

    /// 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 {
        debug!("Creating new V0 zonefile for owner: {}", owner);
        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> {
        debug!("Parsing zonefile from clarity buffer hex string");
        let bytes = ZoneFile::clarity_buffer_to_uint8_array(hex_string);
        let zonefile = ZoneFile::from_bytes(&bytes)?;
        debug!("Successfully parsed zonefile from clarity buffer");
        Ok(zonefile)
    }

    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        debug!("Attempting to parse zonefile from {} bytes", bytes.len());
        
        // Try decompressing as brotli first
        let mut decompressed = Vec::new();
        let decompressed_result = {
            let mut reader = bytes;
            let mut writer = &mut decompressed;
            BrotliDecompress(&mut reader, &mut writer)
        };
        
        let processed_bytes = match decompressed_result {
            Ok(_) => {
                debug!("Successfully decompressed brotli data");
                decompressed
            },
            Err(e) => {
                debug!("Brotli decompression failed ({}), using raw bytes", e);
                bytes.to_vec()
            }
        };

        // Try parsing as CBOR
        debug!("Attempting to parse as CBOR");
        match ZoneFile::from_cbor(&processed_bytes) {
            Ok(zonefile) => {
                debug!("Successfully parsed CBOR data");
                Ok(zonefile)
            },
            Err(e) => {
                debug!("CBOR parsing failed ({}), attempting JSON parsing", e);
                // If CBOR parsing fails, try parsing as JSON string
                match std::str::from_utf8(&processed_bytes) {
                    Ok(str_data) => {
                        debug!("Attempting to parse as JSON string");
                        let result = ZoneFile::from_str(str_data);
                        if result.is_ok() {
                            debug!("Successfully parsed JSON data");
                        } else {
                            error!("Failed to parse JSON data");
                        }
                        result
                    },
                    Err(e) => {
                        error!("Invalid UTF-8 in data: {}", 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>> {
        debug!("Parsing zonefile from {} bytes of CBOR data", cbor_bytes.len());
        let result = ciborium::de::from_reader(cbor_bytes);
        if result.is_err() {
            error!("Failed to parse CBOR data");
        }
        result
    }

    /// Convert the zonefile to CBOR bytes
    pub fn to_cbor(&self) -> Result<Vec<u8>, ciborium::ser::Error<std::io::Error>> {
        debug!("Converting zonefile to CBOR");
        let mut bytes = Vec::new();
        let result = ciborium::ser::into_writer(self, &mut bytes);
        if let Err(ref e) = result {
            error!("Failed to convert to CBOR: {}", e);
        } else {
            debug!("Successfully converted to {} bytes of CBOR", bytes.len());
        }
        result.map(|_| bytes)
    }

    /// Convert the zonefile to compressed CBOR bytes using brotli
    pub fn to_compressed_cbor(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        debug!("Converting zonefile to compressed CBOR");
        let cbor_bytes = self.to_cbor()?;
        let mut compressed = Vec::new();
        {
            let mut reader = &cbor_bytes[..];
            let mut writer = &mut compressed;
            let params = BrotliEncoderParams {
                quality: 11, // Maximum compression
                lgwin: 22,  // Maximum window size
                ..Default::default()
            };
            debug!("Compressing {} bytes of CBOR data", cbor_bytes.len());
            match BrotliCompress(&mut reader, &mut writer, &params) {
                Ok(_) => {
                    debug!("Successfully compressed CBOR data: {} -> {} bytes", cbor_bytes.len(), compressed.len());
                },
                Err(e) => {
                    error!("Failed to compress CBOR data: {}", e);
                    return Err(Box::new(e));
                }
            }
        }
        Ok(compressed)
    }

    fn clarity_buffer_to_uint8_array(hex_string: &str) -> Vec<u8> {
        debug!("Converting clarity buffer hex string to bytes");
        // Remove '0x' prefix if present
        let hex = hex_string.strip_prefix("0x").unwrap_or(hex_string);
        
        // Convert hex string to bytes
        let bytes: Vec<u8> = (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();
        
        debug!("Converted {} hex chars to {} bytes", hex.len(), bytes.len());
        bytes
    }
}

// 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::*;
    use crate::wallet::WalletType;

    const SAMPLE_V0_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_V0_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";
    const SAMPLE_ZONEFILE_HEX_STRING_DEFAULT_ID: &str = "0x070a02000000148b0780a2617661316764656661756c7462696403";
    
    fn setup() {
        let _ = env_logger::builder()
            .is_test(true)
            .try_init();
    }

    #[test]
    fn test_parse_zonefile_valid_v0() {
        setup();
        let result = ZoneFile::from_str(SAMPLE_V0_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]
    #[ignore] // TODO: Fix this test - current hex string may be malformed CBOR data
    fn test_parse_zonefile_valid_v1() {
        setup();
        // Add debug output to see what we're working with
        debug!("Testing V1 zonefile parsing with hex string: {}", SAMPLE_ZONEFILE_HEX_STRING_DEFAULT_ID);
        
        let result = ZoneFile::from_clarity_buffer_hex_string(SAMPLE_ZONEFILE_HEX_STRING_DEFAULT_ID);
        
        // If there's an error, log it
        if let Err(ref e) = result {
            error!("Error parsing zonefile: {}", e);
        }
        
        assert!(result.is_ok());
        
        let zonefile = result.unwrap();
        debug!("Parsed zonefile: {:?}", zonefile);
        
        match zonefile {
            ZoneFile::V1 { default, .. } => {
                assert_eq!(default, Some("id".to_string()));
            },
            _ => panic!("Expected V1 zonefile"),
        }
    }

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

    #[test]
    fn test_zonefile_roundtrip() {
        setup();
        let zonefile = ZoneFile::from_str(SAMPLE_V0_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() {
        setup();
        let zonefile = ZoneFile::from_str(SAMPLE_V0_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());
        debug!("CBOR size: {}, Compressed size: {}", cbor_bytes.len(), compressed_bytes.len());
    }

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

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

    #[test]
    fn test_cbor_empty_fields() {
        setup();
        let zonefile = ZoneFile::from_str(SAMPLE_V0_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() {
        setup();
        // 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() {
        setup();
        // Create a valid zonefile JSON and convert to hex
        let hex = format!("0x{}", hex::encode(SAMPLE_V0_ZONEFILE));
        debug!("Testing with hex string: {}", 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() {
        setup();
        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() {
        setup();
        // 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();
        debug!("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();
        debug!("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();
        debug!("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, id: _, resources: _, wallets: _, dns: _ } => assert_eq!(default, Some("test.btc".to_string())),
            _ => panic!("Expected V1 zonefile"),
        }

        // Test creating and serializing V1 zonefile
        let v1 = ZoneFile::new_v1("test.btc");
        let serialized = v1.to_string().unwrap();
        debug!("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();
        debug!("Serialized V0 from new: {}", serialized);
        assert!(serialized.contains(r#""v":"0""#), "Serialized V0 output should contain version tag");
    }

    #[test]
    fn test_version_tag_simple() {
        setup();
        // 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();
        debug!("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");
        let serialized = serde_json::to_string(&v1).unwrap();
        debug!("Direct V1 serialization: {}", serialized);
        assert!(serialized.contains(r#""v":"1""#), "Direct V1 serialization should contain version tag");
    }

    #[test]
    fn test_zonefile_v1_with_assets() {
        setup();
        let mut resources = HashMap::new();
        
        // Add a text resource
        resources.insert("greeting.txt".to_string(), Resource {
            val: Some(ResourceValue::Text("Hello, world!".to_string())),
            mime: Some("text/plain".to_string()),
        });

        // Add a binary resource
        resources.insert("data.bin".to_string(), Resource {
            val: Some(ResourceValue::Binary(vec![0x01, 0x02, 0x03])),
            mime: Some("application/octet-stream".to_string()),
        });

        let zonefile = ZoneFile::V1 {
            default: Some("example.btc".to_string()),
            id: None,
            resources: Some(resources),
            wallets: None,
            dns: None,
        };

        // Test full zonefile serialization roundtrip
        let cbor_bytes = zonefile.to_cbor().unwrap();
        let parsed_zonefile = ZoneFile::from_cbor(&cbor_bytes).unwrap();

        match parsed_zonefile {
            ZoneFile::V1 { resources: Some(parsed_resources), .. } => {
                assert_eq!(parsed_resources.len(), 2);
                assert!(parsed_resources.contains_key("greeting.txt"));
                assert!(parsed_resources.contains_key("data.bin"));
            },
            _ => panic!("Expected V1 zonefile with resources"),
        }
    }

    #[test]
    fn test_v1_zonefile_with_wallets() {
        setup();
        // Create a wallet map with multiple wallet types
        let mut wallets = HashMap::new();
        wallets.insert(WalletType::bitcoin(), "bc1qxxx...".to_string());
        wallets.insert(WalletType::stacks(), "SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B".to_string());
        wallets.insert(WalletType::solana(), "DxPv2QMA5cWR5Xj7BHt8J9LZkxGGx8DDsicafbLnGm9R".to_string());
        wallets.insert(WalletType::ethereum(), "0x123...".to_string());
        wallets.insert(WalletType::lightning(), "larry@getalby.com".to_string());

        // Create sample binary data for images
        let avatar_data = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; // PNG header
        let banner_data = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46]; // JPEG header

        // Create a resources map
        let mut resources = HashMap::new();
        resources.insert("avatar".to_string(), Resource {
            val: Some(ResourceValue::Binary(avatar_data.clone())),
            mime: Some("image/png".to_string()),
        });
        resources.insert("banner".to_string(), Resource {
            val: Some(ResourceValue::Binary(banner_data.clone())),
            mime: Some("image/jpeg".to_string()),
        });

        // Create a complete V1 zonefile
        let zonefile = ZoneFile::V1 {
            default: Some("larry.btc".to_string()),
            id: None,
            resources: Some(resources),
            wallets: Some(wallets),
            dns: None,
        };

        // Serialize to JSON
        let json = serde_json::to_string_pretty(&zonefile).unwrap();
        debug!("Complete V1 zonefile JSON:\n{}", json);

        // Verify specific parts of the serialized output
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        
        // Check version
        assert_eq!(parsed["v"], "1");
        
        // Check default name
        assert_eq!(parsed["default"], "larry.btc");
        
        // Check wallet IDs are numbers, not strings (except lightning)
        assert_eq!(parsed["wallets"]["0"], "bc1qxxx...");  // Bitcoin
        assert_eq!(parsed["wallets"]["5757"], "SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B");  // Stacks
        assert_eq!(parsed["wallets"]["501"], "DxPv2QMA5cWR5Xj7BHt8J9LZkxGGx8DDsicafbLnGm9R");  // Solana
        assert_eq!(parsed["wallets"]["60"], "0x123...");  // Ethereum
        assert_eq!(parsed["wallets"]["lightning"], "larry@getalby.com");  // Lightning

        // Check resources
        assert_eq!(parsed["resources"]["avatar"]["mime"], "image/png");
        assert_eq!(parsed["resources"]["banner"]["mime"], "image/jpeg");

        // Test deserialization
        let deserialized: ZoneFile = serde_json::from_str(&json).unwrap();
        match deserialized {
            ZoneFile::V1 { default, id, resources, wallets, dns } => {
                assert_eq!(default, Some("larry.btc".to_string()));
                assert_eq!(id, None);
                assert_eq!(dns, None);
                
                // Check wallets deserialized correctly
                let wallets = wallets.unwrap();
                assert_eq!(wallets.get(&WalletType::bitcoin()).unwrap(), "bc1qxxx...");
                assert_eq!(wallets.get(&WalletType::stacks()).unwrap(), "SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B");
                assert_eq!(wallets.get(&WalletType::solana()).unwrap(), "DxPv2QMA5cWR5Xj7BHt8J9LZkxGGx8DDsicafbLnGm9R");
                assert_eq!(wallets.get(&WalletType::ethereum()).unwrap(), "0x123...");
                assert_eq!(wallets.get(&WalletType::lightning()).unwrap(), "larry@getalby.com");

                // Check resources deserialized correctly
                let resources = resources.unwrap();
                match &resources.get("avatar").unwrap().val {
                    Some(ResourceValue::Binary(data)) => assert_eq!(data, &avatar_data),
                    _ => panic!("Expected Binary resource value for avatar"),
                }
                assert_eq!(resources.get("avatar").unwrap().mime, Some("image/png".to_string()));

                match &resources.get("banner").unwrap().val {
                    Some(ResourceValue::Binary(data)) => assert_eq!(data, &banner_data),
                    _ => panic!("Expected Binary resource value for banner"),
                }
                assert_eq!(resources.get("banner").unwrap().mime, Some("image/jpeg".to_string()));
            },
            _ => panic!("Expected V1 zonefile"),
        }
    }

    #[test]
    fn test_zonefile_v1_with_dns() {
        setup();
        // Test with Some(zone)
        let zonefile = ZoneFile::V1 {
            default: Some("example.btc".to_string()),
            id: None,
            resources: None,
            wallets: None,
            dns: Some(Dns {
                zone: Some("example.com".to_string()),
            }),
        };

        // Test serialization
        let json = serde_json::to_string_pretty(&zonefile).unwrap();
        debug!("V1 zonefile with DNS JSON:\n{}", json);

        // Verify JSON structure
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["v"], "1");
        assert_eq!(parsed["default"], "example.btc");
        assert_eq!(parsed["dns"], "example.com");

        // Test with None zone
        let zonefile = ZoneFile::V1 {
            default: Some("example.btc".to_string()),
            id: None,
            resources: None,
            wallets: None,
            dns: Some(Dns { zone: None }),
        };

        let json = serde_json::to_string_pretty(&zonefile).unwrap();
        debug!("V1 zonefile with empty DNS JSON:\n{}", json);

        // Verify DNS field is omitted when zone is None
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(!parsed.as_object().unwrap().contains_key("dns"));

        // Test with None dns
        let zonefile = ZoneFile::V1 {
            default: Some("example.btc".to_string()),
            id: None,
            resources: None,
            wallets: None,
            dns: None,
        };

        let json = serde_json::to_string_pretty(&zonefile).unwrap();
        debug!("V1 zonefile without DNS JSON:\n{}", json);

        // Verify DNS field is omitted when dns is None
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(!parsed.as_object().unwrap().contains_key("dns"));

        // Test CBOR roundtrip with DNS
        let zonefile = ZoneFile::V1 {
            default: Some("example.btc".to_string()),
            id: None,
            resources: None,
            wallets: None,
            dns: Some(Dns {
                zone: Some("example.com".to_string()),
            }),
        };

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

        match parsed_zonefile {
            ZoneFile::V1 { dns: Some(dns), .. } => {
                assert_eq!(dns.zone, Some("example.com".to_string()));
            },
            _ => panic!("Expected V1 zonefile with DNS"),
        }
    }
}