bc-xid 0.2.0

Unique, stable, extensible, and verifiable identifiers
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
use std::collections::HashSet;

use anyhow::{ bail, Error, Result };
use bc_components::{
    tags::TAG_XID,
    AgreementPublicKey,
    PrivateKeyBase,
    PublicKeyBase,
    Signer,
    SigningPublicKey,
    URI,
    XID,
};
use dcbor::CBOREncodable;
use bc_ur::prelude::*;
use known_values::{ DELEGATE, DELEGATE_RAW, DEREFERENCE_VIA, DEREFERENCE_VIA_RAW, KEY, KEY_RAW, PROVENANCE, PROVENANCE_RAW };
use provenance_mark::ProvenanceMark;
use bc_envelope::prelude::*;

use crate::PrivateKeyOptions;

use super::{ Delegate, Key };

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct XIDDocument {
    xid: XID,
    resolution_methods: HashSet<URI>,
    keys: HashSet<Key>,
    delegates: HashSet<Delegate>,
    provenance: Option<ProvenanceMark>,
}

impl XIDDocument {
    pub fn new(inception_public_key: PublicKeyBase) -> Self {
        let mut doc = Self::new_empty(&inception_public_key);
        doc.add_key(Key::new_allow_all(inception_public_key)).unwrap();
        doc
    }

    pub fn new_empty(inception_public_key: &PublicKeyBase) -> Self {
        let xid = XID::new(inception_public_key.signing_public_key());
        Self {
            xid,
            resolution_methods: HashSet::new(),
            keys: HashSet::new(),
            delegates: HashSet::new(),
            provenance: None,
        }
    }

    pub fn new_with_private_key(inception_private_key: PrivateKeyBase) -> Self {
        let inception_public_key = inception_private_key.schnorr_public_key_base();
        let xid = XID::new(inception_public_key.signing_public_key());
        let inception_key = Key::new_with_private_key(inception_private_key);
        let mut keys = HashSet::new();
        keys.insert(inception_key.clone());
        Self {
            xid,
            resolution_methods: HashSet::new(),
            keys,
            delegates: HashSet::new(),
            provenance: None,
        }
    }

    pub fn new_with_provenance(
        inception_public_key: PublicKeyBase,
        provenance: ProvenanceMark
    ) -> Self {
        let mut doc = Self::new(inception_public_key);
        doc.provenance = Some(provenance);
        doc
    }

    pub fn from_xid(xid: impl Into<XID>) -> Self {
        Self {
            xid: xid.into(),
            resolution_methods: HashSet::new(),
            keys: HashSet::new(),
            delegates: HashSet::new(),
            provenance: None,
        }
    }

    pub fn xid(&self) -> &XID {
        &self.xid
    }

    pub fn resolution_methods(&self) -> &HashSet<URI> {
        &self.resolution_methods
    }

    pub fn resolution_methods_mut(&mut self) -> &mut HashSet<URI> {
        &mut self.resolution_methods
    }

    pub fn add_resolution_method(&mut self, method: URI) {
        self.resolution_methods.insert(method);
    }

    pub fn remove_resolution_method(&mut self, method: &URI) -> Option<URI> {
        self.resolution_methods.take(method)
    }

    pub fn keys(&self) -> &HashSet<Key> {
        &self.keys
    }

    pub fn keys_mut(&mut self) -> &mut HashSet<Key> {
        &mut self.keys
    }

    pub fn add_key(&mut self, key: Key) -> Result<()> {
        if self.keys.contains(&key) {
            bail!("Key already exists");
        }
        self.keys.insert(key);
        Ok(())
    }

    pub fn find_key_by_public_key_base(&self, key: &PublicKeyBase) -> Option<&Key> {
        self.keys.iter().find(|k| k.public_key_base() == key)
    }

    pub fn remove_key(&mut self, key: &Key) -> Option<Key> {
        let public_key_base = key.public_key_base();
        if let Some(key) = self.find_key_by_public_key_base(public_key_base).cloned() {
            self.keys.take(&key)
        } else {
            None
        }
    }

    pub fn is_inception_signing_key(&self, signing_public_key: &SigningPublicKey) -> bool {
        self.xid.validate(signing_public_key)
    }

    pub fn inception_signing_key(&self) -> Option<&SigningPublicKey> {
        if
            let Some(key) = self.keys
                .iter()
                .find(|k| {
                    self.is_inception_signing_key(k.public_key_base().signing_public_key())
                })
        {
            return Some(key.public_key_base().signing_public_key());
        } else {
            None
        }
    }

    pub fn inception_key(&self) -> Option<&Key> {
        self.keys
            .iter()
            .find(|k| { self.is_inception_signing_key(k.public_key_base().signing_public_key()) })
    }

    pub fn remove_inception_key(&mut self) -> Option<Key> {
        if let Some(key) = self.inception_key().cloned() { self.keys.take(&key) } else { None }
    }

    pub fn verification_key(&self) -> Option<&SigningPublicKey> {
        // Prefer the inception key for verification.
        if let Some(key) = self.inception_key() {
            return Some(key.public_key_base().signing_public_key());
        } else if let Some(key) = self.keys.iter().next() {
            return Some(key.public_key_base().signing_public_key());
        } else {
            None
        }
    }

    pub fn encryption_key(&self) -> Option<&AgreementPublicKey> {
        // Prefer the inception key for encryption.
        if let Some(key) = self.inception_key() {
            return Some(key.public_key_base().agreement_public_key());
        } else if let Some(key) = self.keys.iter().next() {
            return Some(key.public_key_base().agreement_public_key());
        } else {
            None
        }
    }

    pub fn is_empty(&self) -> bool {
        self.resolution_methods.is_empty() &&
            self.keys.is_empty() &&
            self.delegates.is_empty() &&
            self.provenance.is_none()
    }

    pub fn delegates(&self) -> &HashSet<Delegate> {
        &self.delegates
    }

    pub fn delegates_mut(&mut self) -> &mut HashSet<Delegate> {
        &mut self.delegates
    }

    pub fn add_delegate(&mut self, delegate: Delegate) {
        self.delegates.insert(delegate);
    }

    pub fn find_delegate(&self, xid: &XID) -> Option<&Delegate> {
        self.delegates.iter().find(|d| d.controller().read().xid() == xid)
    }

    pub fn remove_delegate(&mut self, xid: &XID) -> Option<Delegate> {
        if let Some(delegate) = self.find_delegate(xid).cloned() {
            self.delegates.take(&delegate)
        } else {
            None
        }
    }

    pub fn provenance(&self) -> Option<&ProvenanceMark> {
        self.provenance.as_ref()
    }

    pub fn set_provenance(&mut self, provenance: Option<ProvenanceMark>) {
        self.provenance = provenance;
    }

    pub fn to_unsigned_envelope(&self) -> Envelope {
        self.to_unsigned_envelope_opt(PrivateKeyOptions::default())
    }

    pub fn to_unsigned_envelope_opt(&self, private_key_options: PrivateKeyOptions) -> Envelope {
        let mut envelope = Envelope::new(self.xid.clone());

        // Add an assertion for each resolution method.
        envelope = self.resolution_methods
            .iter()
            .cloned()
            .fold(envelope, |envelope, method| envelope.add_assertion(DEREFERENCE_VIA, method));

        // Add an assertion for each key in the set.
        envelope = self.keys
            .iter()
            .cloned()
            .fold(envelope, |envelope, key|
                envelope.add_assertion(KEY, key.into_envelope_opt(private_key_options))
            );

        // Add an assertion for each delegate.
        envelope = self.delegates
            .iter()
            .cloned()
            .fold(envelope, |envelope, delegate| envelope.add_assertion(DELEGATE, delegate));

        // Add the provenance mark if any.
        if let Some(provenance) = &self.provenance {
            envelope = envelope.add_assertion(PROVENANCE, provenance.clone());
        }

        envelope
    }

    pub fn from_unsigned_envelope(envelope: &Envelope) -> Result<Self> {
        //
        // This technique is more robust than the commented-out technique below,
        // because it will fail if there are unexpected attributes in the envelope.
        //
        
        let xid: XID = envelope.subject().try_leaf()?.try_into()?;
        let mut xid_document = XIDDocument::from(xid);
        for assertion in envelope.assertions() {
            let predicate = assertion.try_predicate()?.try_known_value()?.value();
            let object = assertion.try_object()?;
            match predicate {
                DEREFERENCE_VIA_RAW => {
                    let method: URI = object
                        .try_leaf()?
                        .try_into()
                        .map_err(|_| Error::msg("Invalid resolution method"))?;
                    xid_document.add_resolution_method(method);
                }
                KEY_RAW => {
                    let key = Key::try_from(object)?;
                    xid_document.add_key(key)?;
                }
                DELEGATE_RAW => {
                    let delegate = Delegate::try_from(object)?;
                    xid_document.add_delegate(delegate);
                }
                PROVENANCE_RAW => {
                    let provenance = ProvenanceMark::try_from(object)?;
                    if xid_document.provenance().is_some() {
                        bail!("Multiple provenance marks");
                    }
                    xid_document.set_provenance(Some(provenance));
                }
                _ => bail!("Unexpected predicate: {}", predicate),
            }
        }

        Ok(xid_document)

        //
        // Do not use this technique to extract attributes from an envelope, unless
        // you want to ignore unexpected attributes.
        //

        // let resolution_methods = envelope
        //     .extract_objects_for_predicate::<URI>(DEREFERENCE_VIA)?
        //     .into_iter()
        //     .collect::<HashSet<_>>();

        // let keys = envelope
        //     .objects_for_predicate(KEY)
        //     .into_iter()
        //     .map(|key| key.try_into())
        //     .collect::<Result<HashSet<_>>>()?;

        // let delegates = envelope
        //     .object_for_predicate(DELEGATE)
        //     .into_iter()
        //     .map(|delegate| delegate.try_into())
        //     .collect::<Result<HashSet<_>>>()?;

        // let provenance = match envelope.optional_object_for_predicate(PROVENANCE)? {
        //     Some(p) => Some(ProvenanceMark::try_from(p)?),
        //     None => None,
        // };

        // Ok(Self {
        //     xid,
        //     resolution_methods,
        //     keys,
        //     delegates,
        //     provenance,
        // })
    }

    pub fn to_signed_envelope(&self, signing_key: &impl Signer) -> Envelope {
        self.to_signed_envelope_opt(signing_key, PrivateKeyOptions::default())
    }

    pub fn to_signed_envelope_opt(
        &self,
        signing_key: &impl Signer,
        private_key_options: PrivateKeyOptions
    ) -> Envelope {
        self.to_unsigned_envelope_opt(private_key_options).sign(signing_key)
    }

    pub fn try_from_signed_envelope(signed_envelope: &Envelope) -> Result<Self> {
        // Unwrap the envelope and construct a provisional XIDDocument.
        let xid_document = XIDDocument::try_from(&signed_envelope.unwrap_envelope()?)?;
        // Extract the inception key from the provisional XIDDocument, throwing an error if it is missing.
        let inception_key = xid_document
            .inception_signing_key()
            .ok_or_else(|| Error::msg("Missing inception key"))?;
        // Verify the signature on the envelope using the inception key.
        signed_envelope.verify(inception_key)?;
        // Extract the XID from the provisional XIDDocument.
        let xid = xid_document.xid();
        // Verify that the inception key is the one that generated the XID.
        if xid.validate(inception_key) {
            // If the inception key is valid return the XIDDocument, now verified.
            Ok(xid_document)
        } else {
            bail!("Invalid XID")
        }
    }
}

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

impl From<XIDDocument> for XID {
    fn from(doc: XIDDocument) -> Self {
        doc.xid
    }
}

impl From<XID> for XIDDocument {
    fn from(xid: XID) -> Self {
        XIDDocument::from_xid(xid)
    }
}

impl From<&XID> for XIDDocument {
    fn from(xid: &XID) -> Self {
        XIDDocument::from_xid(xid.clone())
    }
}

impl From<PublicKeyBase> for XIDDocument {
    fn from(inception_key: PublicKeyBase) -> Self {
        XIDDocument::new(inception_key)
    }
}

impl From<PrivateKeyBase> for XIDDocument {
    fn from(inception_key: PrivateKeyBase) -> Self {
        XIDDocument::new_with_private_key(inception_key)
    }
}

impl From<&PrivateKeyBase> for XIDDocument {
    fn from(inception_key: &PrivateKeyBase) -> Self {
        XIDDocument::new_with_private_key(inception_key.clone())
    }
}

impl EnvelopeEncodable for XIDDocument {
    fn into_envelope(self) -> Envelope {
        self.to_unsigned_envelope()
    }
}

impl TryFrom<&Envelope> for XIDDocument {
    type Error = Error;

    fn try_from(envelope: &Envelope) -> Result<Self> {
        Self::from_unsigned_envelope(envelope)
    }
}

impl TryFrom<Envelope> for XIDDocument {
    type Error = Error;

    fn try_from(envelope: Envelope) -> Result<Self> {
        XIDDocument::try_from(&envelope)
    }
}

impl CBORTagged for XIDDocument {
    fn cbor_tags() -> Vec<Tag> {
        tags_for_values(&[TAG_XID])
    }
}

impl From<XIDDocument> for CBOR {
    fn from(value: XIDDocument) -> Self {
        value.tagged_cbor()
    }
}

impl CBORTaggedEncodable for XIDDocument {
    fn untagged_cbor(&self) -> CBOR {
        if self.is_empty() {
            return self.xid.untagged_cbor();
        }
        self.to_envelope().to_cbor()
    }
}

impl TryFrom<CBOR> for XIDDocument {
    type Error = Error;

    fn try_from(cbor: CBOR) -> Result<Self> {
        Self::from_tagged_cbor(cbor)
    }
}

impl CBORTaggedDecodable for XIDDocument {
    fn from_untagged_cbor(cbor: CBOR) -> Result<Self> {
        if let Some(byte_string) = cbor.clone().into_byte_string() {
            let xid = XID::from_data_ref(byte_string)?;
            return Ok(Self::from_xid(xid));
        }

        Envelope::try_from(cbor)?.try_into()
    }
}

#[cfg(test)]
mod tests {
    use bc_envelope::prelude::*;
    use bc_rand::make_fake_random_number_generator;
    use indoc::indoc;
    use bc_components::{ tags, PrivateKeyBase, URI, XID };
    use provenance_mark::{ ProvenanceMarkGenerator, ProvenanceMarkResolution, ProvenanceSeed };

    use crate::{ Key, PrivateKeyOptions, XIDDocument };

    #[test]
    fn xid_document() {
        // Create a XID document.
        let mut rng = make_fake_random_number_generator();
        let private_key_base = PrivateKeyBase::new_using(&mut rng);
        let public_key_base = private_key_base.schnorr_public_key_base();
        let xid_document = XIDDocument::new(public_key_base);

        // Extract the XID from the XID document.
        let xid = xid_document.xid();

        // Convert the XID document to an Envelope.
        let envelope = xid_document.clone().into_envelope();
        let expected_format = (
            indoc! {
                r#"
        XID(71274df1) [
            'key': PublicKeyBase [
                'allow': 'All'
            ]
        ]
        "#
            }
        ).trim();
        assert_eq!(envelope.format(), expected_format);

        // Convert the Envelope back to a XIDDocument.
        let xid_document2 = XIDDocument::try_from(envelope).unwrap();
        assert_eq!(xid_document, xid_document2);

        // Convert the XID document to a UR
        let xid_document_ur = xid_document.ur_string();
        assert_eq!(
            xid_document_ur,
            "ur:xid/tpsplftpsotanshdhdcxjsdigtwneocmnybadpdlzobysbstmekteypspeotcfldynlpsfolsbintyjkrhfnoyaylftpsotansgylftanshfhdcxhslkfzemaylrwttynsdlghrydpmdfzvdglndloimaahykorefddtsguogmvlahqztansgrhdcxetlewzvlwyfdtobeytidosbamkswaomwwfyabakssakggegychesmerkcatekpcxoycsfncsfggmplgshd"
        );
        let xid_document2 = XIDDocument::from_ur_string(&xid_document_ur).unwrap();
        assert_eq!(xid_document, xid_document2);

        // Print the document's XID in debug format, which shows the full
        // identifier.
        let xid_debug = format!("{:?}", xid);
        assert_eq!(
            xid_debug,
            "XID(71274df133169a0e2d2ffb11cbc7917732acafa31989f685cca6cb69d473b93c)"
        );

        // Print the document's XID in display format, which shows the short
        // identifier (first 4 bytes).
        let xid_display = format!("{}", xid);
        assert_eq!(xid_display, "XID(71274df1)");

        // Print the CBOR diagnostic notation for the XID.
        let xid_cbor_diagnostic = xid.to_cbor().diagnostic();
        assert_eq!(
            xid_cbor_diagnostic,
            (
                indoc! {
                    r#"
        40024(
            h'71274df133169a0e2d2ffb11cbc7917732acafa31989f685cca6cb69d473b93c'
        )
        "#
                }
            ).trim()
        );

        // Print the hex encoding of the XID.
        with_tags!(|tags: &dyn dcbor::TagsStoreTrait| {
            assert_eq!(tags.name_for_value(tags::TAG_XID), "xid");
        });

        let xid_cbor_hex = xid.to_cbor().hex_annotated();
        assert_eq!(
            xid_cbor_hex,
            (
                indoc! {
                    r#"
        d9 9c58                                 # tag(40024) xid
            5820                                # bytes(32)
                71274df133169a0e2d2ffb11cbc7917732acafa31989f685cca6cb69d473b93c
        "#
                }
            ).trim()
        );

        // Print the XID's Bytewords and Bytemoji identifiers.
        let bytewords_identifier = xid.bytewords_identifier(true);
        assert_eq!(bytewords_identifier, "🅧 JUGS DELI GIFT WHEN");
        let bytemoji_identifier = xid.bytemoji_identifier(true);
        assert_eq!(bytemoji_identifier, "🅧 🌊 😹 🌽 🐞");

        // Print the XID's LifeHash fingerprint.
        assert_eq!(
            format!("{}", xid.lifehash_fingerprint()),
            "Digest(fc7b562825afa07ee9d49fe99991f767ad4bdad495724c08a918e13ee0eabd5e)"
        );

        // Print the XID's UR.
        let xid_ur = xid.ur_string();
        assert_eq!(
            xid_ur,
            "ur:xid/hdcxjsdigtwneocmnybadpdlzobysbstmekteypspeotcfldynlpsfolsbintyjkrhfnvsbyrdfw"
        );
        let xid2 = XID::from_ur_string(&xid_ur).unwrap();
        assert_eq!(xid, &xid2);
    }

    #[test]
    fn minimal_xid_document() {
        // Create a XID.
        let mut rng = make_fake_random_number_generator();
        let private_key_base = PrivateKeyBase::new_using(&mut rng);
        let xid = XID::from(&private_key_base);

        // Create a XIDDocument directly from the XID.
        let xid_document = XIDDocument::from(&xid);

        // Convert the XIDDocument to an Envelope.
        let envelope = xid_document.clone().into_envelope();

        // The envelope is just the XID as its subject, with no assertions.
        let expected_format = (
            indoc! {
                r#"
        XID(71274df1)
        "#
            }
        ).trim();
        assert_eq!(envelope.format(), expected_format);

        // Convert the Envelope back to a XIDDocument.
        let xid_document2 = XIDDocument::try_from(envelope).unwrap();
        assert_eq!(xid_document, xid_document2);

        // The CBOR encoding of the XID and the XIDDocument should be the same.
        let xid_cbor = xid.to_cbor();
        let xid_document_cbor = xid_document.to_cbor();
        assert_eq!(xid_cbor, xid_document_cbor);

        // Either a XID or a XIDDocument can be created from the CBOR encoding.
        let xid2 = XID::try_from(xid_cbor).unwrap();
        assert_eq!(xid, xid2);
        let xid_document2 = XIDDocument::try_from(xid_document_cbor).unwrap();
        assert_eq!(xid_document, xid_document2);

        // The UR of the XID and the XIDDocument should be the same.
        let xid_ur = xid.ur_string();
        let expected_ur =
            "ur:xid/hdcxjsdigtwneocmnybadpdlzobysbstmekteypspeotcfldynlpsfolsbintyjkrhfnvsbyrdfw";
        assert_eq!(xid_ur, expected_ur);
        let xid_document_ur = xid_document.ur_string();
        assert_eq!(xid_document_ur, expected_ur);
    }

    #[test]
    fn document_with_resolution_methods() {
        // Create a XID document.
        let mut rng = make_fake_random_number_generator();
        let private_key_base = PrivateKeyBase::new_using(&mut rng);
        let public_key_base = private_key_base.schnorr_public_key_base();
        let mut xid_document = XIDDocument::new_empty(&public_key_base);

        // Add resolution methods.
        xid_document.add_resolution_method(URI::from("https://resolver.example.com"));
        xid_document.add_resolution_method(URI::from("btcr:01234567"));

        // Convert the XID document to an Envelope.
        let envelope = xid_document.clone().into_envelope();
        println!("{}", envelope.format());
        let expected_format = (
            indoc! {
                r#"
        XID(71274df1) [
            'dereferenceVia': URI(btcr:01234567)
            'dereferenceVia': URI(https://resolver.example.com)
        ]
        "#
            }
        ).trim();
        assert_eq!(envelope.format(), expected_format);

        // Convert the Envelope back to a XIDDocument.
        let xid_document2 = XIDDocument::try_from(envelope).unwrap();
        assert_eq!(xid_document, xid_document2);

        // let cbor = xid_document.to_cbor();
        // println!("{}", cbor.diagnostic());
        // let ur = xid_document.ur();
        // println!("{}", ur);
    }

    #[test]
    fn signed_xid_document() {
        // Generate the inception key.
        let mut rng = make_fake_random_number_generator();
        let private_inception_key = PrivateKeyBase::new_using(&mut rng);
        let public_inception_key = private_inception_key.schnorr_public_key_base();

        // Create a XIDDocument for the inception key.
        let xid_document = XIDDocument::new(public_inception_key);

        let envelope = xid_document.clone().into_envelope();
        let expected_format = (
            indoc! {
                r#"
        XID(71274df1) [
            'key': PublicKeyBase [
                'allow': 'All'
            ]
        ]
        "#
            }
        ).trim();
        assert_eq!(envelope.format(), expected_format);

        let signed_envelope = xid_document.to_signed_envelope(&private_inception_key);
        // println!("{}", signed_envelope.format());
        let expected_format = (
            indoc! {
                r#"
        {
            XID(71274df1) [
                'key': PublicKeyBase [
                    'allow': 'All'
                ]
            ]
        } [
            'signed': Signature
        ]
        "#
            }
        ).trim();
        assert_eq!(signed_envelope.format(), expected_format);

        let self_certified_xid_document = XIDDocument::try_from_signed_envelope(
            &signed_envelope
        ).unwrap();
        assert_eq!(xid_document, self_certified_xid_document);
    }

    #[test]
    fn with_provenance() {
        provenance_mark::register_tags();

        let mut rng = make_fake_random_number_generator();
        let private_inception_key = PrivateKeyBase::new_using(&mut rng);
        let inception_key = private_inception_key.schnorr_public_key_base();

        let genesis_seed = ProvenanceSeed::new_using(&mut rng);

        let mut generator = ProvenanceMarkGenerator::new_with_seed(
            ProvenanceMarkResolution::Quartile,
            genesis_seed
        );
        let date = dcbor::Date::from_string("2025-01-01").unwrap();
        let provenance = generator.next(date, None::<String>);
        let xid_document = XIDDocument::new_with_provenance(inception_key, provenance);
        let signed_envelope = xid_document.to_signed_envelope(&private_inception_key);
        let expected_format = (
            indoc! {
                r#"
            {
                XID(71274df1) [
                    'key': PublicKeyBase [
                        'allow': 'All'
                    ]
                    'provenance': ProvenanceMark(4bf5c551)
                ]
            } [
                'signed': Signature
            ]
        "#
            }
        ).trim();
        assert_eq!(signed_envelope.format(), expected_format);

        let self_certified_xid_document = XIDDocument::try_from_signed_envelope(
            &signed_envelope
        ).unwrap();
        assert_eq!(xid_document, self_certified_xid_document);
    }

    #[test]
    fn with_private_key() {
        let mut rng = make_fake_random_number_generator();
        let private_inception_key = PrivateKeyBase::new_using(&mut rng);
        let public_inception_key = private_inception_key.schnorr_public_key_base();

        //
        // A `XIDDocument` can be created from a private key, in which case it
        // will include the private key.
        //

        let xid_document_including_private_key = XIDDocument::new_with_private_key(
            private_inception_key.clone()
        );

        //
        // By default, the `Envelope` representation of a `XIDDocument` will
        // omit the private key.
        //

        let signed_envelope_omitting_private_key =
            xid_document_including_private_key.to_signed_envelope(&private_inception_key);
        let expected_format = (
            indoc! {
                r#"
            {
                XID(71274df1) [
                    'key': PublicKeyBase [
                        'allow': 'All'
                    ]
                ]
            } [
                'signed': Signature
            ]
        "#
            }
        ).trim();
        assert_eq!(signed_envelope_omitting_private_key.format(), expected_format);
        let xid_document2 = XIDDocument::try_from_signed_envelope(
            &signed_envelope_omitting_private_key
        ).unwrap();

        //
        // A `XIDDocument` can be created from a public key, in which case its
        // `Envelope` representation is identical to the default representation.
        //

        let xid_document_excluding_private_key = XIDDocument::new(public_inception_key);
        assert_eq!(xid_document_excluding_private_key, xid_document2);

        //
        // The private key can be included in the `Envelope` by explicitly
        // specifying that it should be included.
        //
        // The 'privateKey' assertion is salted to decorrelate the the private key.
        //

        let signed_envelope_including_private_key =
            xid_document_including_private_key.to_signed_envelope_opt(
                &private_inception_key,
                PrivateKeyOptions::Include
            );
        let expected_format = (
            indoc! {
                r#"
            {
                XID(71274df1) [
                    'key': PublicKeyBase [
                        {
                            'privateKey': PrivateKeyBase
                        } [
                            'salt': Salt
                        ]
                        'allow': 'All'
                    ]
                ]
            } [
                'signed': Signature
            ]
        "#
            }
        ).trim();
        assert_eq!(signed_envelope_including_private_key.format(), expected_format);

        //
        // If the private key is included, the `XIDDocument` is reconstructed
        // with it and is exactly the same as the original.
        //

        let xid_document2 = XIDDocument::try_from_signed_envelope(
            &signed_envelope_including_private_key
        ).unwrap();
        assert_eq!(xid_document_including_private_key, xid_document2);

        //
        // The private key assertion can be elided.
        //

        let signed_document_eliding_private_key =
            xid_document_including_private_key.to_signed_envelope_opt(
                &private_inception_key,
                PrivateKeyOptions::Elide
            );
        let expected_format = (
            indoc! {
                r#"
            {
                XID(71274df1) [
                    'key': PublicKeyBase [
                        'allow': 'All'
                        ELIDED
                    ]
                ]
            } [
                'signed': Signature
            ]
        "#
            }
        ).trim();
        assert_eq!(signed_document_eliding_private_key.format(), expected_format);

        //
        // A `XIDDocument` reconstructed from an envelope with the private key
        // elided is the same as the `XIDDocument` created from only the public key.
        //

        let xid_document2 = XIDDocument::try_from_signed_envelope(
            &signed_document_eliding_private_key
        ).unwrap();
        assert_eq!(xid_document_excluding_private_key, xid_document2);
    }

    #[test]
    fn change_key() {
        // Create a XID document.
        let mut rng = make_fake_random_number_generator();
        let private_key_base = PrivateKeyBase::new_using(&mut rng);
        let xid_document = XIDDocument::from(&private_key_base);

        // Remove the inception key.
        let mut xid_document_2 = xid_document.clone();
        let inception_key = xid_document_2.remove_inception_key().unwrap();
        assert_eq!(xid_document.inception_key(), Some(&inception_key));
        assert!(xid_document_2.inception_key().is_none());
        assert!(xid_document_2.is_empty());

        let xid_document2_envelope = xid_document_2.to_envelope();
        let expected_format = (
            indoc! {
                r#"
            XID(71274df1)
        "#
            }
        ).trim();
        assert_eq!(xid_document2_envelope.format(), expected_format);

        // Create a new key.
        let private_key_base_2 = PrivateKeyBase::new_using(&mut rng);
        let public_key_base_2 = private_key_base_2.schnorr_public_key_base();

        // Add the new key to the empty XID document.
        let key_2 = Key::new_allow_all(public_key_base_2);
        xid_document_2.add_key(key_2.clone()).unwrap();
        let xid_document2_envelope = xid_document_2.to_envelope();
        let expected_format = (
            indoc! {
                r#"
            XID(71274df1) [
                'key': PublicKeyBase [
                    'allow': 'All'
                ]
            ]
        "#
            }
        ).trim();
        assert_eq!(xid_document2_envelope.format(), expected_format);

        // Same XID, but different key.
        assert_ne!(xid_document, xid_document_2);

        // The new XID document does not have an inception key.
        assert!(xid_document_2.inception_key().is_none());

        // But it does have an encrypter and a verifier.
        assert!(xid_document_2.encryption_key().is_some());
        assert!(xid_document_2.verification_key().is_some());
    }
}