willow25 0.7.0

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
//! Lower-level details of Meadowcap.
//!
//! In particular, this module allows working with capabilities that are not guaranteed to be [valid](https://willowprotocol.org/specs/meadowcap/index.html#cap_valid).

use alloc::{boxed::Box, vec, vec::Vec};

use core::hash::Hash;

use derive_more::{Display, Error};
use signature::Verifier;

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

use compact_u64::*;
use ufotofu::codec_prelude::*;

mod possibly_valid_write_capability;
pub use possibly_valid_write_capability::*;

mod possibly_valid_read_capability;
pub use possibly_valid_read_capability::*;

use crate::prelude::*;

/// The [access mode](https://willowprotocol.org/specs/meadowcap/index.html#cap_mode) of a capability.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "dev", derive(Arbitrary))]
pub enum AccessMode {
    /// The access mode of capabilities that grant *read* access.
    Read,
    /// The access mode of capabilities that grant *write* access.
    Write,
}

/// The information in a [communal capability](https://willowprotocol.org/specs/meadowcap/index.html#CommunalCapability) except for its [delegations](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_delegations).
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "dev", derive(Arbitrary))]
pub struct CommunalGenesis {
    /// The [access_mode](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_access_mode) of the capability.
    pub access_mode: AccessMode,
    /// The [namespace_key](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_namespace) of the capability.
    pub namespace_key: NamespaceId,
    /// The [user_key](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_user) of the capability.
    pub user_key: SubspaceId,
}

/// The information in an [owned capability](https://willowprotocol.org/specs/meadowcap/index.html#OwnedCapability) except for its [delegations](https://willowprotocol.org/specs/meadowcap/index.html#owned_cap_delegations).
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "dev", derive(Arbitrary))]
pub struct OwnedGenesis {
    /// The [access_mode](https://willowprotocol.org/specs/meadowcap/index.html#owned_cap_access_mode) of the capability.
    pub access_mode: AccessMode,
    /// The [namespace_key](https://willowprotocol.org/specs/meadowcap/index.html#owned_cap_namespace) of the capability.
    pub namespace_key: NamespaceId,
    /// The [user_key](https://willowprotocol.org/specs/meadowcap/index.html#owned_cap_user) of the capability.
    pub user_key: SubspaceId,
    /// The [initial_authorisation](https://willowprotocol.org/specs/meadowcap/index.html#owned_cap_initial_authorisation) of the capability.
    pub initial_authorisation: NamespaceSignature,
}

/// The information in a capability except for its delegations.
///
/// Selling England by the pound.
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "dev", derive(Arbitrary))]
pub enum Genesis {
    /// All non-[delegation](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_delegations) information of a [communal capability](https://willowprotocol.org/specs/meadowcap/index.html#CommunalCapability).
    Communal(CommunalGenesis),
    /// All non-[delegation](https://willowprotocol.org/specs/meadowcap/index.html#owned_cap_delegations) information of a [communal capability](https://willowprotocol.org/specs/meadowcap/index.html#OwnedCapability).
    Owned(OwnedGenesis),
}

impl Genesis {
    /// Returns the access mode of the genesis.
    pub fn access_mode(&self) -> AccessMode {
        match self {
            Genesis::Communal(g) => g.access_mode,
            Genesis::Owned(g) => g.access_mode,
        }
    }

    /// Returns the namespace key of the genesis.
    pub fn namespace_key(&self) -> &NamespaceId {
        match self {
            Genesis::Communal(g) => &g.namespace_key,
            Genesis::Owned(g) => &g.namespace_key,
        }
    }

    /// Returns the user key of the genesis.
    pub fn user_key(&self) -> &SubspaceId {
        match self {
            Genesis::Communal(g) => &g.user_key,
            Genesis::Owned(g) => &g.user_key,
        }
    }

    /// Returns `true` if and only if this is the genesis of an owned capability.
    pub fn is_owned(&self) -> bool {
        matches!(self, Genesis::Owned(_))
    }

    /// Returns whether the given area is contained in the [granted area](PossiblyValidWriteCapability::granted_area_ref) of this genesis.
    pub fn includes_area(&self, area: &Area) -> bool {
        match &self {
            Genesis::Communal(comcap) => Some(&comcap.user_key) == area.subspace(),
            Genesis::Owned(_) => true,
        }
    }

    /// Returns whether this genesis is valid.
    pub fn is_valid(&self) -> bool {
        match self {
            Genesis::Communal(_) => true,
            Genesis::Owned(OwnedGenesis {
                access_mode,
                namespace_key,
                user_key,
                initial_authorisation,
            }) => {
                let data_to_sign = owned_genesis_data_to_sign(*access_mode, user_key);

                namespace_key
                    .verify(&data_to_sign[..], initial_authorisation)
                    .is_ok()
            }
        }
    }

    fn granted_area(&self) -> Area {
        match self {
            Genesis::Communal(comcap) => Area::new_subspace_area(comcap.user_key.clone()),
            Genesis::Owned(_) => Area::full(),
        }
    }
}

pub(crate) fn owned_genesis_data_to_sign(
    access_mode: AccessMode,
    user_key: &SubspaceId,
) -> Box<[u8]>
where
    SubspaceId: EncodableKnownLength,
{
    let mut data_to_sign = vec![0; 1 + user_key.len_of_encoding()];
    data_to_sign[0] = if access_mode == AccessMode::Read {
        2
    } else {
        3
    };

    pollster::block_on(async {
        user_key.encode(&mut (&mut data_to_sign[1..]).into_consumer()).await
                        .expect("`user_key.len_of_encoding()` should have been accurate, so the slice should have been sufficiently large");
    });

    data_to_sign.into_boxed_slice()
}

/// The information describing a single delegation of a capability.
///
/// Specification: [communal](https://willowprotocol.org/specs/meadowcap/index.html#communal_cap_delegations) and [owned](https://willowprotocol.org/specs/meadowcap/index.html#owned_cap_delegations) (both are identical data types).
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "dev", derive(Arbitrary))]
pub struct Delegation {
    /// The area for which to bestow access rights.
    pub area: Area,
    /// The user to whom to bestow access rights.
    pub user: SubspaceId,
    /// A signature by the previous recipient of the capability, authorising the delegation.
    pub signature: SubspaceSignature,
}

/// An error indicating that an operation would create an invalid capability.
#[derive(Clone, Display, Error, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[display("operation would create invalid capability")]
#[cfg_attr(feature = "dev", derive(Arbitrary))]
pub struct InvalidCapability;

impl Delegation {
    /// Creates a new delegation, with a given area, user public key, and signature.
    pub fn new(area: Area, user: SubspaceId, signature: SubspaceSignature) -> Self {
        Delegation {
            area,
            user,
            signature,
        }
    }
}

/// Our internal representation of a capability that must not necessarily be valid.
///
/// This type *does* enforce that each delegation is contained in the prior granted area.
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) struct RawCapability {
    pub genesis: Genesis,
    pub delegations: Vec<Delegation>,
}

impl RawCapability {
    pub fn access_mode(&self) -> AccessMode {
        self.genesis.access_mode()
    }

    pub fn receiver(&self) -> &SubspaceId {
        match self.delegations.last() {
            None => self.genesis.user_key(),
            Some(final_delegation) => &final_delegation.user,
        }
    }

    pub fn granted_namespace(&self) -> &NamespaceId {
        self.genesis.namespace_key()
    }

    /// Returns a reference to the [area to which this grants access](https://willowprotocol.org/specs/meadowcap/index.html#cap_granted_area) (assuming this capability is valid), 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. Hence, we use this this method internally whenever possible.
    pub fn granted_area_ref(&self) -> Option<&Area> {
        match self.delegations.last() {
            None => None,
            Some(final_delegation) => Some(&final_delegation.area),
        }
    }

    /// Returns the [`Genesis`] of this capability.
    pub fn genesis(&self) -> &Genesis {
        &self.genesis
    }

    /// Returns `true` if and only if this is an owned capability.
    pub fn is_owned(&self) -> bool {
        self.genesis.is_owned()
    }

    /// Returns a slice of the [`Delegations`](Delegation) of this capability.
    pub fn delegations(&self) -> &[Delegation] {
        &self.delegations
    }

    /// Creates a new [communal](https://willowprotocol.org/specs/meadowcap/index.html#communal_capabilities) capability with no delegations.
    pub fn new_communal(
        access_mode: AccessMode,
        namespace_key: NamespaceId,
        user_key: SubspaceId,
    ) -> Self {
        Self {
            genesis: Genesis::Communal(CommunalGenesis {
                access_mode,
                namespace_key,
                user_key,
            }),
            delegations: vec![],
        }
    }

    /// Creates a new [owned](https://willowprotocol.org/specs/meadowcap/index.html#owned_capabilities) capability with no delegations.
    pub fn new_owned(
        access_mode: AccessMode,
        namespace_key: NamespaceId,
        user_key: SubspaceId,
        initial_authorisation: NamespaceSignature,
    ) -> Self {
        Self {
            genesis: Genesis::Owned(OwnedGenesis {
                access_mode,
                namespace_key,
                user_key,
                initial_authorisation,
            }),
            delegations: vec![],
        }
    }

    /// Returns whether the given area is contained in the [granted area](PossiblyValidWriteCapability::granted_area_ref) of this capability.
    pub fn includes_area(&self, area: &Area) -> bool {
        match self.granted_area_ref() {
            Some(granted_area) => granted_area.includes_grouping(area),
            None => self.genesis.includes_area(area),
        }
    }

    /// Appends a new [`Delegation`] to this capability, returning an error if the resulting granted area would not be included in the previous granted area. **Does not verify any signatures.**
    pub fn try_append_delegation(
        &mut self,
        delegation: Delegation,
    ) -> Result<(), InvalidCapability> {
        if self.includes_area(&delegation.area) {
            self.delegations.push(delegation);
            Ok(())
        } else {
            Err(InvalidCapability)
        }
    }

    /// Appends a new [`Delegation`] to this capability, panicking if the resulting granted area would not be included in the previous granted area. **Does not verify any signatures.**
    pub fn append_delegation(&mut self, delegation: Delegation) {
        self.try_append_delegation(delegation).unwrap()
    }

    pub fn granted_area(&self) -> Area {
        match self.granted_area_ref() {
            Some(area) => area.clone(),
            None => self.genesis.granted_area(),
        }
    }

    /// Returns whether the given [namespaced](Namespaced) [coordinate](Coordinatelike) is covered by this capability.
    pub fn includes<T>(&self, t: &T) -> bool
    where
        T: Namespaced + Coordinatelike + ?Sized,
    {
        if t.namespace_id() == self.granted_namespace() {
            match self.granted_area_ref() {
                Some(area) => area.includes(t),
                None => match &self.genesis {
                    Genesis::Communal(comcap) => &comcap.user_key == t.subspace_id(),
                    Genesis::Owned(_) => true,
                },
            }
        } else {
            false
        }
    }

    pub fn is_valid(&self) -> bool {
        if !self.genesis.is_valid() {
            return false;
        }

        match self.delegations.first() {
            None => true,
            Some(first_delegation) => {
                if !self.genesis.includes_area(&first_delegation.area) {
                    return false;
                }

                match self.validate_first_delegation(first_delegation) {
                    Err(InvalidCapability) => false,
                    Ok((mut prev_area, mut prev_signature, mut prev_receiver)) => {
                        for delegation in self.delegations[1..].iter() {
                            if !prev_area.includes_grouping(&delegation.area) {
                                return false;
                            }

                            match Self::validate_non_first_delegation(
                                delegation,
                                prev_area,
                                prev_signature,
                                prev_receiver,
                            ) {
                                Ok((new_area, new_signature, new_receiver)) => {
                                    prev_area = new_area;
                                    prev_signature = new_signature;
                                    prev_receiver = new_receiver;
                                }
                                Err(InvalidCapability) => {
                                    return false;
                                }
                            }
                        }

                        true
                    }
                }
            }
        }
    }

    /// When calling this on a valid capability and this returns Ok(()), self is guaranteed to stay valid.
    pub fn try_append_delegation_checking_validity(
        &mut self,
        new_delegation: Delegation,
    ) -> Result<(), InvalidCapability> {
        if self.includes_area(&new_delegation.area) {
            match self.delegations.last() {
                None => {
                    self.validate_first_delegation(&new_delegation)?;
                }
                Some(prev_delegation) => {
                    Self::validate_non_first_delegation(
                        &new_delegation,
                        &prev_delegation.area,
                        &prev_delegation.signature,
                        &prev_delegation.user,
                    )?;
                }
            }

            self.delegations.push(new_delegation);
            Ok(())
        } else {
            Err(InvalidCapability)
        }
    }

    pub(crate) fn create_handover(
        &self,
        new_area: &Area,
        new_receiver: &SubspaceId,
        last_delegation: Option<&Delegation>,
    ) -> Box<[u8]> {
        match last_delegation {
            None => match self.genesis() {
                Genesis::Communal(CommunalGenesis {
                    access_mode,
                    namespace_key,
                    user_key,
                }) => {
                    let initial_area = Area::new_subspace_area(user_key.clone());

                    let delegation_area = new_area;

                    let mut handover = vec![
                        0;
                        1 + namespace_key.len_of_encoding()
                            + delegation_area
                                .len_of_relative_encoding(&initial_area)
                            + new_receiver.len_of_encoding()
                    ];

                    handover[0] = if access_mode == &AccessMode::Read {
                        0
                    } else {
                        1
                    };

                    pollster::block_on(async {
                        let mut con = (&mut handover[1..]).into_consumer();

                        con.consume_encoded(namespace_key).await.unwrap();
                        con.consume_relative_encoded(&delegation_area, &initial_area)
                            .await
                            .unwrap();
                        con.consume_encoded(new_receiver).await.unwrap();
                    });

                    handover.into_boxed_slice()
                }
                Genesis::Owned(OwnedGenesis {
                    initial_authorisation,
                    ..
                }) => {
                    let initial_area = Area::full();

                    let mut handover = Vec::with_capacity(
                        new_area.len_of_relative_encoding(&initial_area)
                            + initial_authorisation.len_of_encoding()
                            + new_receiver.len_of_encoding(),
                    );

                    pollster::block_on(async {
                        let mut con = (&mut handover).into_consumer();

                        con.consume_relative_encoded(new_area, &initial_area)
                            .await
                            .unwrap();
                        con.consume_encoded(initial_authorisation).await.unwrap();
                        con.consume_encoded(&new_receiver).await.unwrap();
                    });

                    handover.into_boxed_slice()
                }
            },
            Some(last_delegation) => {
                let mut handover = Vec::with_capacity(
                    new_area.len_of_relative_encoding(&last_delegation.area)
                        + last_delegation.signature.len_of_encoding()
                        + new_receiver.len_of_encoding(),
                );

                pollster::block_on(async {
                    let mut con = (&mut handover).into_consumer();

                    con.consume_relative_encoded(new_area, &last_delegation.area)
                        .await
                        .unwrap();
                    con.consume_encoded(&last_delegation.signature)
                        .await
                        .unwrap();
                    con.consume_encoded(new_receiver).await.unwrap();
                });

                handover.into_boxed_slice()
            }
        }
    }

    fn validate_first_delegation<'dele>(
        &self,
        first_delegation: &'dele Delegation,
    ) -> Result<(&'dele Area, &'dele SubspaceSignature, &'dele SubspaceId), InvalidCapability> {
        Ok(match self.genesis() {
            Genesis::Communal(CommunalGenesis { user_key, .. }) => {
                let handover =
                    self.create_handover(&first_delegation.area, &first_delegation.user, None);

                if user_key
                    .verify(&handover, &first_delegation.signature)
                    .is_ok()
                {
                    (
                        &first_delegation.area,
                        &first_delegation.signature,
                        &first_delegation.user,
                    )
                } else {
                    return Err(InvalidCapability);
                }
            }
            Genesis::Owned(OwnedGenesis { user_key, .. }) => {
                let handover =
                    self.create_handover(&first_delegation.area, &first_delegation.user, None);

                if user_key
                    .verify(&handover, &first_delegation.signature)
                    .is_ok()
                {
                    (
                        &first_delegation.area,
                        &first_delegation.signature,
                        &first_delegation.user,
                    )
                } else {
                    return Err(InvalidCapability);
                }
            }
        })
    }

    fn validate_non_first_delegation<'dele>(
        delegation: &'dele Delegation,
        prev_area: &'dele Area,
        prev_signature: &'dele SubspaceSignature,
        prev_receiver: &'dele SubspaceId,
    ) -> Result<(&'dele Area, &'dele SubspaceSignature, &'dele SubspaceId), InvalidCapability> {
        let current_area = &delegation.area;

        let mut handover = Vec::with_capacity(
            current_area.len_of_relative_encoding(prev_area)
                + prev_signature.len_of_encoding()
                + delegation.user.len_of_encoding(),
        );

        pollster::block_on(async {
            let mut con = (&mut handover).into_consumer();

            con.consume_relative_encoded(&current_area, prev_area)
                .await
                .unwrap();
            con.consume_encoded(prev_signature).await.unwrap();
            con.consume_encoded(&delegation.user).await.unwrap();
        });

        if prev_receiver
            .verify(&handover, &delegation.signature)
            .is_ok()
        {
            Ok((current_area, &delegation.signature, &delegation.user))
        } else {
            Err(InvalidCapability)
        }
    }
}

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

        if self.is_owned() {
            header |= 0b1000_0000;
        }
        if self.access_mode() == AccessMode::Write {
            header |= 0b0100_0000;
        }

        let delegations_length = self.delegations.len() as u64;
        write_tag(&mut header, 6, 2, delegations_length);

        consumer.consume_item(header).await?;

        let mut prev_area = match self.genesis() {
            Genesis::Communal(CommunalGenesis {
                namespace_key,
                user_key,
                ..
            }) => {
                consumer.consume_encoded(namespace_key).await?;
                consumer.consume_encoded(user_key).await?;

                Area::new_subspace_area(user_key.clone())
            }
            Genesis::Owned(OwnedGenesis {
                namespace_key,
                user_key,
                initial_authorisation,
                ..
            }) => {
                consumer.consume_encoded(namespace_key).await?;
                consumer.consume_encoded(user_key).await?;
                consumer.consume_encoded(initial_authorisation).await?;

                Area::full()
            }
        };

        cu64_encode(delegations_length, 6, consumer).await?;

        let mut current_area;

        for delegation in self.delegations.iter() {
            current_area = delegation.area.clone();

            consumer
                .consume_relative_encoded(&current_area, &prev_area)
                .await?;
            consumer.consume_encoded(&delegation.user).await?;
            consumer.consume_encoded(&delegation.signature).await?;

            prev_area = current_area;
        }

        Ok(())
    }
}

impl EncodableKnownLength for RawCapability {
    fn len_of_encoding(&self) -> usize {
        let mut len = 1; // header byte

        let mut prev_area = match self.genesis() {
            Genesis::Communal(CommunalGenesis {
                namespace_key,
                user_key,
                ..
            }) => {
                len += namespace_key.len_of_encoding();
                len += user_key.len_of_encoding();

                Area::new_subspace_area(user_key.clone())
            }
            Genesis::Owned(OwnedGenesis {
                namespace_key,
                user_key,
                initial_authorisation,
                ..
            }) => {
                len += namespace_key.len_of_encoding();
                len += user_key.len_of_encoding();
                len += initial_authorisation.len_of_encoding();

                Area::full()
            }
        };

        len += cu64_len_of_encoding(6, self.delegations.len() as u64);

        let mut current_area;

        for delegation in self.delegations.iter() {
            current_area = delegation.area.clone();

            len += current_area.len_of_relative_encoding(&prev_area);
            len += delegation.user.len_of_encoding();
            len += delegation.signature.len_of_encoding();

            prev_area = current_area;
        }

        len
    }
}

/// Implements decoding according to the [EncodeMcCapability](https://willowprotocol.org/specs/encodings/index.html#EncodeMcCapability) encoding relation. **Does not check the validity** of the decoded capability.
impl Decodable for RawCapability {
    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 header = producer.produce_item().await?;

        let owned = header & 0b1000_0000 > 0;

        let access_mode = if header & 0b0100_0000 > 0 {
            AccessMode::Write
        } else {
            AccessMode::Read
        };

        let namespace_key = producer
            .produce_decoded_canonic()
            .await
            .map_err(|err| err.map_other(Into::into))?;
        let user_key: SubspaceId = producer
            .produce_decoded_canonic()
            .await
            .map_err(|err| err.map_other(Into::into))?;

        let (genesis, initial_area) = if owned {
            (
                Genesis::Owned(OwnedGenesis {
                    access_mode,
                    namespace_key,
                    user_key,
                    initial_authorisation: producer
                        .produce_decoded_canonic()
                        .await
                        .map_err(|err| err.map_other(Into::into))?,
                }),
                Area::full(),
            )
        } else {
            (
                Genesis::Communal(CommunalGenesis {
                    access_mode,
                    namespace_key,
                    user_key: user_key.clone(),
                }),
                Area::new_subspace_area(user_key),
            )
        };

        let delegations_length = cu64_decode(header, 6, 2, producer)
            .await
            .map_err(|err| err.map_other(|_| Blame::TheirFault))?;

        let mut delegations = Vec::new();

        for _ in 0..usize::try_from(delegations_length)
            .map_err(|_| DecodeError::Other(Blame::OurFault))?
        {
            let area = producer
                .produce_relative_decoded(
                    delegations
                        .last()
                        .map(|del_ref: &Delegation| &del_ref.area)
                        .unwrap_or(&initial_area),
                )
                .await?;
            let user = producer
                .produce_decoded_canonic()
                .await
                .map_err(|err| err.map_other(Into::into))?;
            let signature = producer
                .produce_decoded_canonic()
                .await
                .map_err(|err| err.map_other(Into::into))?;

            delegations.push(Delegation {
                area,
                user,
                signature,
            });
        }

        Ok(Self {
            genesis,
            delegations,
        })
    }
}

/// Implements decoding according to the [encode_mc_capability](https://willowprotocol.org/specs/encodings/index.html#encode_mc_capability) encoding function. **Does not check the validity** of the decoded capability.
impl DecodableCanonic for RawCapability {
    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 header = producer.produce_item().await?;

        let owned = header & 0b1000_0000 > 0;

        let access_mode = if header & 0b0100_0000 > 0 {
            AccessMode::Write
        } else {
            AccessMode::Read
        };

        let namespace_key = producer
            .produce_decoded_canonic()
            .await
            .map_err(|err| err.map_other(Into::into))?;
        let user_key: SubspaceId = producer
            .produce_decoded_canonic()
            .await
            .map_err(|err| err.map_other(Into::into))?;

        let (genesis, initial_area) = if owned {
            (
                Genesis::Owned(OwnedGenesis {
                    access_mode,
                    namespace_key,
                    user_key,
                    initial_authorisation: producer
                        .produce_decoded_canonic()
                        .await
                        .map_err(|err| err.map_other(Into::into))?,
                }),
                Area::full(),
            )
        } else {
            (
                Genesis::Communal(CommunalGenesis {
                    access_mode,
                    namespace_key,
                    user_key: user_key.clone(),
                }),
                Area::new_subspace_area(user_key),
            )
        };

        let delegations_length = cu64_decode_canonic(header, 6, 2, producer)
            .await
            .map_err(|err| err.map_other(|_| Blame::TheirFault))?;

        let mut delegations = Vec::new();

        for _ in 0..usize::try_from(delegations_length)
            .map_err(|_| DecodeError::Other(Blame::OurFault))?
        {
            let area = producer
                .produce_relative_decoded_canonic(
                    delegations
                        .last()
                        .map(|del_ref: &Delegation| &del_ref.area)
                        .unwrap_or(&initial_area),
                )
                .await?;
            let user = producer
                .produce_decoded_canonic()
                .await
                .map_err(|err| err.map_other(Into::into))?;
            let signature = producer
                .produce_decoded_canonic()
                .await
                .map_err(|err| err.map_other(Into::into))?;

            delegations.push(Delegation {
                area,
                user,
                signature,
            });
        }

        Ok(Self {
            genesis,
            delegations,
        })
    }
}

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

        let delegation_count = usize::arbitrary(u)? % 8;
        let mut delegations = Vec::with_capacity(delegation_count);

        if delegation_count > 0 {
            let area = match &genesis {
                Genesis::Owned(_) => Area::full(),
                Genesis::Communal(CommunalGenesis { user_key, .. }) => {
                    Area::new_subspace_area(user_key.clone())
                }
            };

            delegations.push(Delegation {
                area,
                user: SubspaceId::arbitrary(u)?,
                signature: SubspaceSignature::arbitrary(u)?,
            });
        }

        for i in 1..delegation_count {
            let prev_area = &delegations.get(i - 1).unwrap().area;
            let area = arbitrary_area_in_area(prev_area, u)?;
            delegations.push(Delegation {
                area,
                user: SubspaceId::arbitrary(u)?,
                signature: SubspaceSignature::arbitrary(u)?,
            });
        }

        Ok(RawCapability {
            genesis,
            delegations,
        })
    }
}