willow25 0.7.4

A ready-to-use implementation of the Willow specifications.
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
use core::fmt;

#[cfg(feature = "dev")]
use arbitrary::Arbitrary;

#[cfg(feature = "dev")]
use ed25519_dalek::{SecretKey, SigningKey};
use signature::{Keypair, Signer};
use ufotofu::codec_prelude::*;

#[cfg(feature = "dev")]
use crate::authorisation::raw::RawCapability;
use crate::{
    authorisation::raw::{
        AccessMode, Delegation, Genesis, InvalidCapability, PossiblyValidWriteCapability,
        owned_genesis_data_to_sign,
    },
    groupings::private_context::{PrivateAreaContext, PrivateInterest},
    is_bitflagged,
    prelude::*,
};

/// A [valid](https://willowprotocol.org/specs/meadowcap/index.html#cap_valid) write capability.
///
/// ```
/// use rand::rngs::OsRng;
/// use willow25::{prelude::*, authorisation::*};
///
/// # #[cfg(feature = "dev")] {
/// let mut csprng = OsRng;
/// let (subspace_id, secret) = randomly_generate_subspace(&mut csprng);
/// let namespace_id = NamespaceId::from_bytes(&[17; 32]);
///
/// let mut cap = WriteCapability::new_communal(
///     namespace_id,
///     subspace_id.clone(),
/// );
///
/// assert_eq!(cap.receiver(), &subspace_id);
///
/// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
///
/// cap.delegate(&secret, Area::new_subspace_area(subspace_id), new_receiver.clone());
///
/// assert_eq!(cap.receiver(), &new_receiver);
/// # }
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct WriteCapability {
    pub(crate) inner: PossiblyValidWriteCapability,
}

impl fmt::Debug for WriteCapability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WriteCapability")
            .field("genesis", &self.inner.inner.genesis)
            .field("delegations", &self.inner.inner.delegations)
            .finish()
    }
}

impl WriteCapability {
    /// Returns the [receiver](https://willowprotocol.org/specs/meadowcap/index.html#cap_receiver) of this capability.
    ///
    /// ```
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let namespace_id = NamespaceId::from_bytes(&[16; 32]);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let cap = WriteCapability::new_communal(namespace_id, subspace_id.clone());
    ///
    /// assert_eq!(cap.receiver(), &subspace_id);
    /// # }
    /// ```
    pub fn receiver(&self) -> &SubspaceId {
        self.inner.receiver()
    }

    /// Returns the [namespace id to which this grants access](https://willowprotocol.org/specs/meadowcap/index.html#cap_granted_namespace).
    ///
    /// ```
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let namespace_id = NamespaceId::from_bytes(&[16; 32]);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let cap = WriteCapability::new_communal(namespace_id.clone(), subspace_id);
    ///
    /// assert_eq!(cap.granted_namespace(), &namespace_id);
    /// # }
    /// ```
    pub fn granted_namespace(&self) -> &NamespaceId {
        self.inner.granted_namespace()
    }

    /// Returns a reference to the [area to which this grants access](https://willowprotocol.org/specs/meadowcap/index.html#cap_granted_area), or `None` if there is no delegation step which restricts the initial area.
    ///
    /// This method is slightly inconvenient to work with (you need special logic if there are no delegation steps), but it is efficient because it never explicitly creates a new area value. For the more convenient version, see [`granted_area`](WriteCapability::granted_area).
    ///
    /// ```
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (subspace_id, secret) = randomly_generate_subspace(&mut csprng);
    /// let namespace_id = NamespaceId::from_bytes(&[17; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(
    ///     namespace_id,
    ///     subspace_id.clone(),
    /// );
    ///
    /// assert_eq!(cap.granted_area_ref(), None);
    ///
    /// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
    ///
    /// cap.delegate(&secret, Area::new_subspace_area(subspace_id.clone()), new_receiver.clone());
    ///
    /// assert_eq!(cap.granted_area_ref(), Some(&Area::new_subspace_area(subspace_id)));
    /// # }
    /// ```
    pub fn granted_area_ref(&self) -> Option<&Area> {
        self.inner.granted_area_ref()
    }

    /// Returns the [`Genesis`] of this capability.
    ///
    /// ```
    /// use willow25::{prelude::*, authorisation::*, authorisation::raw::AccessMode};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let namespace_id = NamespaceId::from_bytes(&[16; 32]);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(namespace_id.clone(), subspace_id.clone());
    ///
    /// let genesis = cap.genesis();
    ///
    /// assert_eq!(genesis.access_mode(), AccessMode::Write);
    /// assert_eq!(genesis.namespace_key(), &namespace_id);
    /// assert_eq!(genesis.user_key(), &subspace_id);
    /// # }
    /// ```
    pub fn genesis(&self) -> &Genesis {
        self.inner.genesis()
    }

    /// Returns `true` if and only if this is an owned capability.
    ///
    /// ```
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (namespace_id, secret) = randomly_generate_namespace(&mut csprng);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let mut owncap = WriteCapability::new_owned(
    ///     &secret,
    ///     subspace_id.clone(),
    /// );
    ///
    /// assert!(owncap.is_owned());
    ///
    /// let comcap = WriteCapability::new_communal(namespace_id.clone(), subspace_id);
    ///
    /// assert!(!comcap.is_owned());
    /// # }
    /// ```
    pub fn is_owned(&self) -> bool {
        self.inner.is_owned()
    }

    /// Returns the [`Delegations`](Delegation) of this capability as a slice.
    ///
    /// ```
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (subspace_id, secret) = randomly_generate_subspace(&mut csprng);
    /// let namespace_id = NamespaceId::from_bytes(&[17; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(
    ///     namespace_id,
    ///     subspace_id.clone(),
    /// );
    ///
    /// assert!(cap.delegations().is_empty());
    ///
    /// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
    /// cap.delegate(&secret, Area::new_subspace_area(subspace_id.clone()), new_receiver.clone());
    ///
    /// assert_eq!(cap.delegations().len(), 1);
    /// # }
    /// ```
    pub fn delegations(&self) -> &[Delegation] {
        self.inner.delegations()
    }

    /// Creates a new [communal](https://willowprotocol.org/specs/meadowcap/index.html#communal_capabilities) write capability with no delegations.
    ///
    /// ```
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let namespace_id = NamespaceId::from_bytes(&[16; 32]);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let cap = WriteCapability::new_communal(namespace_id.clone(), subspace_id.clone());
    ///
    /// assert!(!cap.is_owned());
    /// assert_eq!(cap.receiver(), &subspace_id);
    /// assert_eq!(cap.granted_namespace(), &namespace_id);
    /// assert_eq!(cap.granted_area(), Area::new_subspace_area(subspace_id));
    /// assert!(cap.delegations().is_empty());
    /// # }
    /// ```
    pub fn new_communal(namespace_key: NamespaceId, user_key: SubspaceId) -> Self {
        Self {
            inner: PossiblyValidWriteCapability::new_communal(namespace_key, user_key),
        }
    }

    /// Creates a new [owned](https://willowprotocol.org/specs/meadowcap/index.html#owned_capabilities) write capability with no delegations.
    ///
    /// ```
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (namespace_id, secret) = randomly_generate_namespace(&mut csprng);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let mut cap = WriteCapability::new_owned(
    ///     &secret,
    ///     subspace_id.clone(),
    /// );
    ///
    /// assert!(cap.is_owned());
    /// assert_eq!(cap.receiver(), &subspace_id);
    /// assert_eq!(cap.granted_namespace(), &namespace_id);
    /// assert_eq!(cap.granted_area(), Area::full());
    /// assert!(cap.delegations().is_empty());
    /// # }
    /// ```
    pub fn new_owned<NamespaceKeypair>(keypair: &NamespaceKeypair, user_key: SubspaceId) -> Self
    where
        NamespaceKeypair: Signer<NamespaceSignature> + Keypair<VerifyingKey = NamespaceId>,
    {
        let data_to_sign = owned_genesis_data_to_sign(AccessMode::Write, &user_key);

        let initial_authorisation = keypair.sign(&data_to_sign[..]);

        Self {
            inner: PossiblyValidWriteCapability::new_owned(
                keypair.verifying_key(),
                user_key,
                initial_authorisation,
            ),
        }
    }

    /// Returns whether the given area is contained in the [granted area](WriteCapability::granted_area_ref) of this capability.
    ///
    /// ```
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let namespace_id = NamespaceId::from_bytes(&[16; 32]);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let cap = WriteCapability::new_communal(namespace_id.clone(), subspace_id.clone());
    ///
    /// assert!(cap.includes_area(&Area::new_subspace_area(subspace_id)));
    /// assert!(!cap.includes_area(&Area::full()));
    /// # }
    /// ```
    pub fn includes_area(&self, area: &Area) -> bool {
        self.inner.includes_area(area)
    }

    /// Returns by value the [area to which this grants access](https://willowprotocol.org/specs/meadowcap/index.html#cap_granted_area).
    ///
    /// Prefer using [`includes`](WriteCapability::includes), [`includes_area`](WriteCapability::includes_area) or [`granted_area_ref`](WriteCapability::granted_area_ref) whenever applicable, as these are more efficient.
    ///
    /// ```
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (namespace_id, namespace_secret) = randomly_generate_namespace(&mut csprng);
    /// let (subspace_id, subspace_secret) = randomly_generate_subspace(&mut csprng);
    ///
    /// let mut cap = WriteCapability::new_owned(
    ///     &namespace_secret,
    ///     subspace_id.clone(),
    /// );
    ///
    /// assert_eq!(cap.granted_area(), Area::full());
    ///
    /// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
    /// cap.delegate(&subspace_secret, Area::new_subspace_area(subspace_id.clone()), new_receiver.clone());
    ///
    /// assert_eq!(cap.granted_area(), Area::new_subspace_area(subspace_id));
    /// # }
    /// ```
    pub fn granted_area(&self) -> Area {
        self.inner.granted_area()
    }

    /// Returns whether the given [namespaced](Namespaced) [coordinate](Coordinatelike) is covered by this capability.
    ///
    /// ```
    /// use willow25::prelude::*;
    /// use willow25::authorisation::raw::*;
    ///
    /// # #[cfg(feature = "dev")] {
    /// let namespace_id = NamespaceId::from_bytes(&[16; 32]);
    /// let subspace_id = SubspaceId::from_bytes(&[17; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(namespace_id.clone(), subspace_id.clone());
    ///
    /// let included_entry = Entry::builder()
    ///     .namespace_id(namespace_id.clone())
    ///     .subspace_id(subspace_id.clone())
    ///     .path(path!(""))
    ///     .timestamp(12345)
    ///     .payload(b"hi")
    ///     .build();
    ///
    /// let outer_entry = Entry::prefilled_builder(&included_entry)
    ///     .subspace_id(SubspaceId::from_bytes(&[18; 32]))
    ///     .build();
    ///
    /// assert!(cap.includes(&included_entry));
    /// assert!(!cap.includes(&outer_entry));
    /// # }
    /// ```
    pub fn includes<T>(&self, t: &T) -> bool
    where
        T: Namespaced + Coordinatelike + ?Sized,
    {
        self.inner.includes(t)
    }

    /// Delegates this capability, returning an error if the resulting granted area would not be included in the previous granted area, or if the public key of the keypair was not the receiver of the capability pre-delegation.
    ///
    /// ```
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (subspace_id, secret) = randomly_generate_subspace(&mut csprng);
    /// let (_subspace_id2, secret2) = randomly_generate_subspace(&mut csprng);
    /// let namespace_id = NamespaceId::from_bytes(&[17; 32]);
    /// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(
    ///     namespace_id,
    ///     subspace_id.clone(),
    /// );
    ///
    /// // Trying to delegate with an invalid secret fails.
    /// assert!(
    ///     cap.try_delegate(
    ///         &secret2,
    ///         Area::new_subspace_area(subspace_id.clone()),
    ///         new_receiver.clone(),
    ///     ).is_err()
    /// );
    ///
    /// // Trying to delegate to a greater area fails.
    /// assert!(
    ///     cap.try_delegate(
    ///         &secret,
    ///         Area::full(),
    ///         new_receiver.clone(),
    ///     ).is_err()
    /// );
    ///
    /// // Delegating with the correct secret and to a contained area succeeds.
    /// assert!(
    ///     cap.try_delegate(
    ///         &secret,
    ///         Area::new_subspace_area(subspace_id.clone()),
    ///         new_receiver.clone(),
    ///     ).is_ok()
    /// );
    /// # }
    /// ```
    pub fn try_delegate<UserKeypair>(
        &mut self,
        keypair: &UserKeypair,
        new_area: Area,
        new_receiver: SubspaceId,
    ) -> Result<(), InvalidCapability>
    where
        UserKeypair: Signer<SubspaceSignature> + Keypair<VerifyingKey = SubspaceId>,
    {
        if !self.granted_area().includes_grouping(&new_area) {
            return Err(InvalidCapability);
        }

        let handover =
            self.inner
                .inner
                .create_handover(&new_area, &new_receiver, self.delegations().last());

        let prev_receiver = self.receiver();

        if prev_receiver != &keypair.verifying_key() {
            return Err(InvalidCapability);
        }

        let signature = keypair.sign(&handover);

        let delegation = Delegation {
            area: new_area,
            user: new_receiver,
            signature,
        };

        // We already performed all required checks, so we append directly to the vec of delegations.
        self.inner.inner.delegations.push(delegation);

        Ok(())
    }

    /// Delegates this capability, panicking if the resulting granted area would not be included in the previous granted area, or if the public key of the keypair was not the receiver of the capability pre-delegation.
    ///
    /// ```
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (subspace_id, secret) = randomly_generate_subspace(&mut csprng);
    /// let namespace_id = NamespaceId::from_bytes(&[17; 32]);
    /// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(
    ///     namespace_id,
    ///     subspace_id.clone(),
    /// );
    ///
    /// // This works =)
    /// cap.delegate(
    ///     &secret,
    ///     Area::new_subspace_area(subspace_id.clone()),
    ///     new_receiver.clone(),
    /// );
    /// # }
    /// ```
    ///
    /// ```should_panic
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(not(feature = "dev"))] {panic!()}
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (subspace_id, secret) = randomly_generate_subspace(&mut csprng);
    /// let (_subspace_id2, secret2) = randomly_generate_subspace(&mut csprng);
    /// let namespace_id = NamespaceId::from_bytes(&[17; 32]);
    /// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(
    ///     namespace_id,
    ///     subspace_id.clone(),
    /// );
    ///
    /// // Delegating with an invalid secret panics.
    /// cap.delegate(
    ///     &secret2,
    ///     Area::new_subspace_area(subspace_id.clone()),
    ///     new_receiver.clone(),
    /// );
    /// # }
    /// ```
    ///
    /// ```should_panic
    /// use rand::rngs::OsRng;
    /// use willow25::{prelude::*, authorisation::*};
    ///
    /// # #[cfg(not(feature = "dev"))] {panic!()}
    /// # #[cfg(feature = "dev")] {
    /// let mut csprng = OsRng;
    /// let (subspace_id, secret) = randomly_generate_subspace(&mut csprng);
    /// let namespace_id = NamespaceId::from_bytes(&[17; 32]);
    /// let new_receiver = SubspaceId::from_bytes(&[18; 32]);
    ///
    /// let mut cap = WriteCapability::new_communal(
    ///     namespace_id,
    ///     subspace_id.clone(),
    /// );
    ///
    /// // Delegating to a greater area panics.
    /// cap.delegate(
    ///     &secret,
    ///     Area::full(),
    ///     new_receiver.clone(),
    /// );
    /// # }
    /// ```
    pub fn delegate<UserKeypair>(
        &mut self,
        keypair: &UserKeypair,
        new_area: Area,
        new_receiver: SubspaceId,
    ) where
        UserKeypair: Signer<SubspaceSignature> + Keypair<VerifyingKey = SubspaceId>,
    {
        self.try_delegate(keypair, new_area, new_receiver).unwrap()
    }
}

impl WriteCapability {
    /// Returns the length of the longest common prefix of this capability's delegation chain and the given delegation chain.
    pub fn longest_common_delegation_prefix_len(&self, delegations: &[Delegation]) -> usize {
        let mut count = 0;

        while count < core::cmp::min(self.delegations().len(), delegations.len()) {
            if self.delegations()[count] == delegations[count] {
                count += 1;
            } else {
                break;
            }
        }

        count
    }
}

/// Implements encoding according to the [encode_mc_capability](https://willowprotocol.org/specs/encodings/index.html#encode_mc_capability) encoding function.
impl Encodable for WriteCapability {
    async fn encode<C>(&self, consumer: &mut C) -> Result<(), C::Error>
    where
        C: BulkConsumer<Item = u8> + ?Sized,
    {
        self.inner.encode(consumer).await
    }
}

impl EncodableKnownLength for WriteCapability {
    fn len_of_encoding(&self) -> usize {
        self.inner.len_of_encoding()
    }
}

/// Implements decoding according to the [EncodeMcCapability](https://willowprotocol.org/specs/encodings/index.html#EncodeMcCapability) encoding relation, and further errors if the decoded capability is a write capability.
impl Decodable for WriteCapability {
    type ErrorReason = Blame;

    async fn decode<P>(
        producer: &mut P,
    ) -> Result<Self, DecodeError<P::Final, P::Error, Self::ErrorReason>>
    where
        P: BulkProducer<Item = u8> + ?Sized,
        Self: Sized,
    {
        let decoded: PossiblyValidWriteCapability = producer.produce_decoded().await?;

        if decoded.is_valid() {
            Ok(Self { inner: decoded })
        } else {
            Err(DecodeError::Other(Blame::TheirFault))
        }
    }
}

/// Implements decoding according to the [encode_mc_capability](https://willowprotocol.org/specs/encodings/index.html#encode_mc_capability) encoding function, and further errors if the decoded capability is a write capability.
impl DecodableCanonic for WriteCapability {
    type ErrorCanonic = Blame;

    async fn decode_canonic<P>(
        producer: &mut P,
    ) -> Result<Self, DecodeError<P::Final, P::Error, Self::ErrorCanonic>>
    where
        P: BulkProducer<Item = u8> + ?Sized,
        Self: Sized,
    {
        let decoded: PossiblyValidWriteCapability = producer.produce_decoded_canonic().await?;

        if decoded.is_valid() {
            Ok(Self { inner: decoded })
        } else {
            Err(DecodeError::Other(Blame::TheirFault))
        }
    }
}

#[cfg(feature = "dev")]
impl<'a> Arbitrary<'a> for WriteCapability {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let (genesis, first_receiver) = Genesis::arbitrary_with_receiver(u)?;

        if genesis.access_mode() == AccessMode::Read {
            return Err(arbitrary::Error::IncorrectFormat);
        }

        let delegation_count: u16 = Arbitrary::arbitrary(u)?;
        let delegation_count = (delegation_count % 260) as usize;

        let mut cap = WriteCapability {
            inner: PossiblyValidWriteCapability {
                inner: RawCapability {
                    genesis,
                    delegations: vec![],
                },
            },
        };

        debug_assert!(cap.inner.is_valid());

        let mut signing_key = first_receiver;

        for _ in 0..delegation_count {
            let sk: SecretKey = Arbitrary::arbitrary(u)?;
            let new_signing_key = SigningKey::from_bytes(&sk);

            let area = arbitrary_area_in_area(&cap.granted_area(), u)?;

            cap.try_delegate(
                &SubspaceSecret::from(signing_key.clone()),
                area,
                SubspaceId::from_bytes(new_signing_key.verifying_key().as_bytes()),
            )
            .map_err(|_| arbitrary::Error::IncorrectFormat)?;

            signing_key = new_signing_key;
        }

        Ok(cap)
    }
}

/// A pair of a prior [`WriteCapability`] and [`Entry`], used to encoded and decode [`WriteCapability`] values privately.
#[derive(Clone, PartialEq, Debug)]
pub struct PriorCapEntryPair {
    /// The previous [`WriteCapability`] which was decoded.
    prior_cap: WriteCapability,
    /// An entry included by the [`WriteCapability`] being privately encoded against.
    entry: Entry,
}

impl PriorCapEntryPair {
    /// Returns a new [`PriorCapEntryPair`] with the given `prior_cap` and `entry`.
    pub fn new(prior_cap: WriteCapability, entry: Entry) -> Self {
        Self { prior_cap, entry }
    }

    /// Returns a [`WriteCapability`] which was previously encoded against..
    pub fn prior_cap(&self) -> &WriteCapability {
        &self.prior_cap
    }

    /// Returns the entry included by the [`WriteCapability`] being privately encoded against.
    pub fn entry(&self) -> &Entry {
        &self.entry
    }
}

#[cfg(feature = "dev")]
impl<'a> Arbitrary<'a> for PriorCapEntryPair {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let prior_cap: WriteCapability = Arbitrary::arbitrary(u)?;

        let entry: Entry = Arbitrary::arbitrary(u)?;

        Ok(Self { prior_cap, entry })
    }
}

/// Implements relative encoding according to the [EncodeCommunalCapabilityRelative](https://willowprotocol.org/specs/encodings/index.html#encsec_EncodeCommunalCapabilityRelative)  and [EncodeOwnedCapabilityRelative](https://willowprotocol.org/specs/encodings/index.html#encsec_EncodeOwnedCapabilityRelative) encoding functions.
impl RelativeEncodable<PriorCapEntryPair> for WriteCapability {
    async fn relative_encode<C>(
        &self,
        rel: &PriorCapEntryPair,
        consumer: &mut C,
    ) -> Result<(), C::Error>
    where
        C: BulkConsumer<Item = u8> + ?Sized,
    {
        let prior_cap = &rel.prior_cap;
        let entry = &rel.entry;

        let (shared, nice_hack) = match (self.genesis(), prior_cap.genesis()) {
            (Genesis::Communal(_), Genesis::Communal(_)) => {
                let shared = self.longest_common_delegation_prefix_len(prior_cap.delegations());
                (shared, shared + 1)
            }
            (Genesis::Owned(genesis), Genesis::Owned(prior_genesis)) => {
                if genesis.user_key != prior_genesis.user_key
                    || genesis.initial_authorisation != prior_genesis.initial_authorisation
                {
                    (0, 0)
                } else {
                    let shared = self.longest_common_delegation_prefix_len(prior_cap.delegations());
                    (shared, shared + 1)
                }
            }
            _ => (0, 0),
        };

        let mut header = 0;

        if self.is_owned() {
            header |= 0b1000_0000;
        }

        compact_u64::write_tag(&mut header, 3, 1, nice_hack as u64);
        compact_u64::write_tag(&mut header, 4, 4, self.delegations().len() as u64);

        consumer.consume(Left(header)).await?;

        compact_u64::cu64_encode(nice_hack as u64, 3, consumer).await?;
        compact_u64::cu64_encode(self.delegations().len() as u64, 4, consumer).await?;

        if let Genesis::Owned(owned_genesis) = self.genesis()
            && nice_hack == 0
        {
            owned_genesis.user_key.encode(consumer).await?;
            owned_genesis.initial_authorisation.encode(consumer).await?;
        }

        let mut prev_area = Area::new_subspace_area(entry.subspace_id().clone());

        for (i, del) in self.delegations().iter().enumerate() {
            if i < shared {
                continue;
            }

            let private_interest = PrivateInterest::new(
                entry.namespace_id().clone(),
                Some(entry.subspace_id().clone()),
                entry.path().clone(),
            );

            let ctx = if i == 0 {
                PrivateAreaContext::new(
                    private_interest,
                    Area::new_subspace_area(entry.subspace_id().clone()),
                )
                .unwrap()
            } else {
                PrivateAreaContext::new(private_interest, prev_area).unwrap()
            };

            prev_area = del.area.clone();

            del.area.relative_encode(&ctx, consumer).await?;
            del.user.encode(consumer).await?;
            del.signature.encode(consumer).await?;
        }

        Ok(())
    }

    /// Returns false if the relative entry's namespace is not `self`'s [granted area](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_granted_namespace), or if the relative entry is not included by `self`'s [granted area](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_granted_area).
    fn can_be_encoded_relative_to(&self, rel: &PriorCapEntryPair) -> bool {
        self.granted_namespace() == rel.entry.namespace_id()
            && self.granted_area().includes(&rel.entry)
    }
}

/// Implements relative decoding according to the [EncodeCommunalCapabilityRelative](https://willowprotocol.org/specs/encodings/index.html#encsec_EncodeCommunalCapabilityRelative)  and [EncodeOwnedCapabilityRelative](https://willowprotocol.org/specs/encodings/index.html#encsec_EncodeOwnedCapabilityRelative) encoding functions.
impl RelativeDecodable<PriorCapEntryPair> for WriteCapability {
    type ErrorReason = Blame;

    async fn relative_decode<P>(
        rel: &PriorCapEntryPair,
        producer: &mut P,
    ) -> Result<Self, DecodeError<P::Final, P::Error, Self::ErrorReason>>
    where
        P: BulkProducer<Item = u8> + ?Sized,
        Self: Sized,
    {
        let header = producer.produce_item().await?;

        let nice_hack = compact_u64::cu64_decode(header, 3, 1, producer)
            .await
            .map_err(|err| err.map_other(|_| Blame::TheirFault))?;

        let del_len = compact_u64::cu64_decode(header, 4, 4, producer)
            .await
            .map_err(|err| err.map_other(|_| Blame::TheirFault))?;

        let prior_cap = &rel.prior_cap;
        let entry = &rel.entry;

        let mut decoded_cap = if is_bitflagged(header, 0) {
            let user_key = if nice_hack == 0 {
                SubspaceId::decode(producer)
                    .await
                    .map_err(|err| err.map_other(|_| Blame::TheirFault))?
            } else {
                match prior_cap.genesis() {
                    Genesis::Communal(_) => {
                        return Err(DecodeError::Other(Blame::OurFault));
                    }
                    Genesis::Owned(owned_genesis) => owned_genesis.user_key.clone(),
                }
            };

            let initial_authorisation = if nice_hack == 0 {
                NamespaceSignature::decode(producer)
                    .await
                    .map_err(|err| err.map_other(|_| Blame::TheirFault))
                    .map(Some)?
            } else {
                None
            };

            let init_auth_to_use = match prior_cap.genesis() {
                Genesis::Communal(_) => {
                    if let Some(init_auth) = initial_authorisation {
                        Ok(init_auth)
                    } else {
                        Err(DecodeError::Other(Blame::OurFault))
                    }
                }
                Genesis::Owned(owned_genesis) => {
                    if let Some(init_auth) = initial_authorisation {
                        Ok(init_auth)
                    } else {
                        Ok(owned_genesis.initial_authorisation.clone())
                    }
                }
            }?;

            PossiblyValidWriteCapability::new_owned(
                entry.namespace_id().clone(),
                user_key,
                init_auth_to_use,
            )
        } else {
            PossiblyValidWriteCapability::new_communal(
                entry.namespace_id().clone(),
                entry.subspace_id().clone(),
            )
        };

        if del_len > 0 {
            let how_many_shared = nice_hack.saturating_sub(1);

            for (i, del) in prior_cap.delegations().iter().enumerate() {
                if (i as u64) < how_many_shared {
                    decoded_cap
                        .try_append_delegation(del.clone())
                        .map_err(|_| DecodeError::Other(Blame::TheirFault))?;
                }
            }

            let how_many_to_decode = del_len
                .checked_sub(how_many_shared)
                .ok_or(DecodeError::Other(Blame::TheirFault))?;

            let mut prev_area = Area::new_subspace_area(entry.subspace_id().clone());

            for _i in 0..how_many_to_decode {
                let private_interest = PrivateInterest::new(
                    entry.namespace_id().clone(),
                    Some(entry.subspace_id().clone()),
                    entry.path().clone(),
                );

                let ctx_to_use = PrivateAreaContext::new(private_interest, prev_area).unwrap();

                let area = Area::relative_decode(&ctx_to_use, producer)
                    .await
                    .map_err(|err| err.map_other(|_| Blame::TheirFault))?;

                prev_area = area.clone();

                let user = SubspaceId::decode(producer)
                    .await
                    .map_err(|err| err.map_other(|_| Blame::TheirFault))?;

                let signature = SubspaceSignature::decode(producer)
                    .await
                    .map_err(|err| err.map_other(|_| Blame::TheirFault))?;

                let delegation = Delegation {
                    area,
                    user,
                    signature,
                };

                decoded_cap
                    .try_append_delegation(delegation)
                    .map_err(|_| DecodeError::Other(Blame::TheirFault))?;
            }
        };

        if !decoded_cap.includes(entry) {
            return Err(DecodeError::Other(Blame::OurFault));
        }

        decoded_cap
            .into_write_capability()
            .map_err(|_| DecodeError::Other(Blame::TheirFault))
    }
}