pkarr 5.0.4

Public-Key Addressable Resource Records (Pkarr); publish and resolve DNS records over Mainline DHT
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
//! Utility structs for Ed25519 keys.

use ed25519_dalek::{
    SecretKey, Signature, SignatureError, Signer, SigningKey, Verifier, VerifyingKey,
};
use std::{
    fmt::{self, Debug, Display, Formatter},
    hash::Hash,
    str::FromStr,
};

use serde::{Deserialize, Serialize};

#[derive(Clone, PartialEq, Eq)]
/// Ed25519 keypair to sign dns [Packet](crate::SignedPacket)s.
pub struct Keypair(pub(crate) SigningKey);

impl Keypair {
    /// Generates a new random `Keypair` using the operating system's CSPRNG.
    pub fn random() -> Keypair {
        let mut bytes = [0u8; 32];

        getrandom::fill(&mut bytes).expect("getrandom failed");

        let signing_key: SigningKey = SigningKey::from_bytes(&bytes);

        Keypair(signing_key)
    }

    /// Creates a `Keypair` from a given `SecretKey`.
    pub fn from_secret_key(secret_key: &SecretKey) -> Keypair {
        Keypair(SigningKey::from_bytes(secret_key))
    }

    /// Signs a message with the private key of this `Keypair`.
    pub fn sign(&self, message: &[u8]) -> Signature {
        self.0.sign(message)
    }

    /// Verifies a message against a given signature using this `Keypair`.
    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), SignatureError> {
        self.0.verify(message, signature)
    }

    /// Returns the secret part of this `Keypair`.
    pub fn secret_key(&self) -> SecretKey {
        self.0.to_bytes()
    }

    /// Returns the [PublicKey] of this `Keypair`.
    pub fn public_key(&self) -> PublicKey {
        PublicKey(self.0.verifying_key())
    }

    /// Converts the public key of this `Keypair` to a z-base32 encoded string.
    pub fn to_z32(&self) -> String {
        self.public_key().to_string()
    }

    /// Converts the public key of this `Keypair` to a URI string.
    pub fn to_uri_string(&self) -> String {
        self.public_key().to_uri_string()
    }
}

// Filesystem-related operations, which are not available for WASM
#[cfg(not(wasm_browser))]
impl Keypair {
    /// Reads the `SecretKey` from a hex file and derives the `Keypair` from it.
    pub fn from_secret_key_file(
        secret_file_path: &std::path::Path,
    ) -> Result<Keypair, std::io::Error> {
        let hex_string = std::fs::read_to_string(secret_file_path)?;
        let hex_string = hex_string.trim();

        let invalid_data_err = |e: &str| std::io::Error::new(std::io::ErrorKind::InvalidData, e);

        if hex_string.len() % 2 != 0 {
            return Err(invalid_data_err("Invalid hex string length"));
        }

        let mut secret_key_bytes_vec = vec![];
        for i in (0..hex_string.len()).step_by(2) {
            let byte_str = &hex_string[i..i + 2];
            let byte = u8::from_str_radix(byte_str, 16)
                .map_err(|_| invalid_data_err("Invalid hex string"))?;
            secret_key_bytes_vec.push(byte);
        }

        let secret_key_bytes: [u8; 32] = secret_key_bytes_vec
            .try_into()
            .map_err(|_| invalid_data_err("Invalid secret key length"))?;

        Ok(Keypair::from_secret_key(&secret_key_bytes))
    }

    /// Writes the secret of the keypair to a file, as a hex encoded string.
    /// If the file already exists, it will be overwritten.
    /// In unix like operating systems, the file permission `600` is set.
    pub fn write_secret_key_file(
        &self,
        secret_file_path: &std::path::Path,
    ) -> Result<(), std::io::Error> {
        let secret = self.secret_key();
        let hex_string: String = secret.iter().map(|b| format!("{b:02x}")).collect();
        std::fs::write(secret_file_path, hex_string)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            std::fs::set_permissions(secret_file_path, std::fs::Permissions::from_mode(0o600))?;
        }
        Ok(())
    }
}

/// Ed25519 public key to verify a signature over dns [Packet](crate::SignedPacket)s.
///
/// It can formatted to and parsed from a z-base32 string.
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct PublicKey(pub(crate) VerifyingKey);

impl PublicKey {
    /// Format the public key as z-base32 string.
    pub fn to_z32(&self) -> String {
        self.to_string()
    }

    /// Format the public key as `pk:` URI string.
    pub fn to_uri_string(&self) -> String {
        format!("pk:{self}")
    }

    /// Verify a signature over a message.
    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), SignatureError> {
        self.0.verify(message, signature)
    }

    /// Return a reference to the underlying [VerifyingKey]
    pub fn verifying_key(&self) -> &VerifyingKey {
        &self.0
    }

    /// Return a the underlying [u8; 32] bytes.
    pub fn to_bytes(&self) -> [u8; 32] {
        self.0.to_bytes()
    }

    /// Return a reference to the underlying [u8; 32] bytes.
    pub fn as_bytes(&self) -> &[u8; 32] {
        self.0.as_bytes()
    }
}

impl AsRef<Keypair> for Keypair {
    fn as_ref(&self) -> &Keypair {
        self
    }
}

impl AsRef<PublicKey> for PublicKey {
    fn as_ref(&self) -> &PublicKey {
        self
    }
}

impl TryFrom<&[u8]> for PublicKey {
    type Error = PublicKeyError;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        let bytes_32: &[u8; 32] = bytes
            .try_into()
            .map_err(|_| PublicKeyError::InvalidPublicKeyLength(bytes.len()))?;

        Ok(Self(
            VerifyingKey::from_bytes(bytes_32)
                .map_err(|_| PublicKeyError::InvalidEd25519PublicKey)?,
        ))
    }
}

impl TryFrom<&[u8; 32]> for PublicKey {
    type Error = PublicKeyError;

    fn try_from(public: &[u8; 32]) -> Result<Self, Self::Error> {
        Ok(Self(
            VerifyingKey::from_bytes(public)
                .map_err(|_| PublicKeyError::InvalidEd25519PublicKey)?,
        ))
    }
}

impl From<VerifyingKey> for PublicKey {
    fn from(verifying_key: VerifyingKey) -> Self {
        Self(verifying_key)
    }
}

impl FromStr for PublicKey {
    type Err = PublicKeyError;

    /// Convert the TLD in a `&str` to a [PublicKey].
    ///
    /// # Examples
    ///
    /// - `o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy`
    /// - `pk:o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy`
    /// - `http://o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy`
    /// - `https://o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy`
    /// - `https://o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy/foo/bar`
    /// - `https://foo.o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy.`
    /// - `https://foo.o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy.#hash`
    /// - `https://foo@bar.o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy.?q=v`
    /// - `https://foo@bar.o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy.:8888?q=v`
    /// - `https://yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no.o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy`
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut s = s;

        if s.len() > 52 {
            // Remove scheme
            s = s.split_once(':').map(|tuple| tuple.1).unwrap_or(s);

            if s.len() > 52 {
                // Remove `//
                s = s.strip_prefix("//").unwrap_or(s);

                if s.len() > 52 {
                    // Remove username
                    s = s.split_once('@').map(|tuple| tuple.1).unwrap_or(s);

                    if s.len() > 52 {
                        // Remove port
                        s = s.split_once(':').map(|tuple| tuple.0).unwrap_or(s);

                        if s.len() > 52 {
                            // Remove trailing path
                            s = s.split_once('/').map(|tuple| tuple.0).unwrap_or(s);

                            if s.len() > 52 {
                                // Remove query
                                s = s.split_once('?').map(|tuple| tuple.0).unwrap_or(s);

                                if s.len() > 52 {
                                    // Remove hash
                                    s = s.split_once('#').map(|tuple| tuple.0).unwrap_or(s);

                                    if s.len() > 52 {
                                        if s.ends_with('.') {
                                            // Remove trailing dot
                                            s = s.trim_matches('.');
                                        }

                                        s = s.rsplit_once('.').map(|tuple| tuple.1).unwrap_or(s);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        let bytes = if let Some(v) = base32::decode(base32::Alphabet::Z, s) {
            Ok(v)
        } else {
            Err(PublicKeyError::InvalidPublicKeyEncoding)
        }?;

        bytes.as_slice().try_into()
    }
}

impl TryFrom<&str> for PublicKey {
    type Error = PublicKeyError;

    fn try_from(s: &str) -> Result<PublicKey, PublicKeyError> {
        PublicKey::from_str(s)
    }
}

impl TryFrom<String> for PublicKey {
    type Error = PublicKeyError;

    fn try_from(s: String) -> Result<PublicKey, PublicKeyError> {
        s.as_str().try_into()
    }
}

impl TryFrom<&String> for PublicKey {
    type Error = PublicKeyError;

    fn try_from(s: &String) -> Result<PublicKey, PublicKeyError> {
        s.as_str().try_into()
    }
}

impl Display for PublicKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            base32::encode(base32::Alphabet::Z, self.0.as_bytes())
        )
    }
}

impl Display for Keypair {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.public_key())
    }
}

impl Debug for Keypair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Keypair({})", self.public_key())
    }
}

impl Debug for PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PublicKey({self})")
    }
}

impl Serialize for PublicKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let bytes = self.to_bytes();
        bytes.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for PublicKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let bytes: [u8; 32] = Deserialize::deserialize(deserializer)?;

        (&bytes).try_into().map_err(serde::de::Error::custom)
    }
}

#[derive(thiserror::Error, Debug, PartialEq, Eq)]
/// Errors while trying to create a [PublicKey]
pub enum PublicKeyError {
    #[error("Invalid PublicKey length, expected 32 bytes but got: {0}")]
    /// Invalid PublicKey length.
    InvalidPublicKeyLength(usize),

    #[error("Invalid Ed25519 publickey; Cannot decompress Edwards point")]
    /// Cannot decompress Edwards point
    InvalidEd25519PublicKey,

    #[error("Invalid PublicKey encoding")]
    /// Invalid PublicKey encoding
    InvalidPublicKeyEncoding,
}

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

    #[test]
    fn test_from_string_ref() {
        let string = "yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no".to_string();
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];
        let public_key: PublicKey = (&string).try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn pkarr_key_generate() {
        let key1 = Keypair::random();
        let key2 = Keypair::from_secret_key(&key1.secret_key());

        assert_eq!(key1.public_key(), key2.public_key())
    }

    #[test]
    fn zbase32() {
        let key1 = Keypair::random();
        let _z32 = key1.public_key().to_string();

        let key2 = Keypair::from_secret_key(&key1.secret_key());

        assert_eq!(key1.public_key(), key2.public_key())
    }

    #[test]
    fn sign_verify() {
        let keypair = Keypair::random();

        let message = b"Hello, world!";
        let signature = keypair.sign(message);

        assert!(keypair.verify(message, &signature).is_ok());

        let public_key = keypair.public_key();
        assert!(public_key.verify(message, &signature).is_ok());
    }

    #[test]
    fn from_string() {
        let str = "yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn to_uri() {
        let bytes = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];
        let expected = "pk:yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no";

        let public_key: PublicKey = (&bytes).try_into().unwrap();

        assert_eq!(public_key.to_uri_string(), expected);
    }

    #[test]
    fn from_uri() {
        let str = "pk:yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_with_path() {
        let str = "https://yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no///foo/bar";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_with_query() {
        let str = "https://yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no?foo=bar";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_with_hash() {
        let str = "https://yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no#foo";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_with_subdomain() {
        let str = "https://foo.bar.yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no#foo";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_with_trailing_dot() {
        let str = "https://foo.yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no.";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_with_username() {
        let str = "https://foo@yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no#foo";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_with_port() {
        let str = "https://yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no:8888";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn from_uri_complex() {
        let str = "https://foo@bar.yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no.:8888?q=v&a=b#foo";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[test]
    fn serde() {
        let str = "yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();

        let bytes = postcard::to_allocvec(&public_key).unwrap();

        assert_eq!(bytes, expected)
    }

    #[test]
    fn from_uri_multiple_pkarr() {
        // Should only catch the TLD.

        let str = "https://o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy.yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no";
        let expected = [
            1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254, 14,
            207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
        ];

        let public_key: PublicKey = str.try_into().unwrap();
        assert_eq!(public_key.verifying_key().as_bytes(), &expected);
    }

    #[cfg(all(not(target_family = "wasm"), feature = "tls"))]
    #[test]
    fn pkcs8() {
        let str = "yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no";
        let public_key: PublicKey = str.try_into().unwrap();

        let der = public_key.to_public_key_der();

        assert_eq!(
            der.as_bytes(),
            [
                // Algorithm and other stuff.
                48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0, //
                // Key
                1, 180, 103, 163, 183, 145, 58, 178, 122, 4, 168, 237, 242, 243, 251, 7, 76, 254,
                14, 207, 75, 171, 225, 8, 214, 123, 227, 133, 59, 15, 38, 197,
            ]
        )
    }

    #[cfg(all(not(target_family = "wasm"), feature = "tls"))]
    #[test]
    fn certificate() {
        use rustls::SignatureAlgorithm;

        let keypair = Keypair::from_secret_key(&[0; 32]);

        let certified_key = keypair.to_rpk_certified_key();

        assert_eq!(certified_key.key.algorithm(), SignatureAlgorithm::ED25519);

        assert_eq!(
            certified_key.end_entity_cert().unwrap().as_ref(),
            [
                48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0, 59, 106, 39, 188, 206, 182, 164, 45,
                98, 163, 168, 208, 42, 111, 13, 115, 101, 50, 21, 119, 29, 226, 67, 166, 58, 192,
                72, 161, 139, 89, 218, 41,
            ]
        )
    }

    #[test]
    fn invalid_key() {
        let key = "c1bkg8tfsyy8wcedtmw4fwhdmm7bbzhgg3z58tf43m5ow8w9mbus";

        assert_eq!(
            PublicKey::try_from(key),
            Err(PublicKeyError::InvalidEd25519PublicKey)
        );
    }

    #[cfg(not(wasm_browser))]
    mod fs_ops {
        use std::fs::write;

        use tempfile::NamedTempFile;

        use crate::Keypair;

        #[test]
        fn test_write_and_read_keypair() {
            let temp_file_path = NamedTempFile::new().unwrap().path().to_path_buf();

            let generated_keypair = Keypair::random();

            let write_keypair_result = generated_keypair.write_secret_key_file(&temp_file_path);
            assert!(write_keypair_result.is_ok());
            assert!(temp_file_path.exists());

            let read_keypair_result = Keypair::from_secret_key_file(&temp_file_path);
            assert!(read_keypair_result.is_ok());

            let read_keypair = read_keypair_result.unwrap();
            assert_eq!(generated_keypair.secret_key(), read_keypair.secret_key());
        }

        #[test]
        fn test_read_keypair_invalid_hex() {
            let temp_file_path = NamedTempFile::new().unwrap().path().to_path_buf();

            write(&temp_file_path, "invalidhex").unwrap();

            // Try to read file with invalid hex data
            let read_keypair_result = Keypair::from_secret_key_file(&temp_file_path);
            assert!(read_keypair_result.is_err());
        }

        #[test]
        fn test_read_keypair_invalid_length() {
            let temp_file_path = NamedTempFile::new().unwrap().path().to_path_buf();

            write(&temp_file_path, "abcd").unwrap();

            // Try to read file with valid hex, but invalid length
            let read_keypair_result = Keypair::from_secret_key_file(&temp_file_path);
            assert!(read_keypair_result.is_err());
        }
    }
}