willow25 0.4.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
use core::fmt;

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

use meadowcap::raw::InvalidCapability;

use signature::{Keypair, Signer};
use ufotofu::codec_prelude::*;

use crate::{
    authorisation::raw::{Delegation, Genesis},
    prelude::*,
};

wrapper! {
    /// 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(PartialEq, Eq, Clone)]
    #[cfg_attr(feature = "dev", derive(Arbitrary))]
    WriteCapability; meadowcap::WriteCapability<MCL, MCC, MPL, NamespaceId, NamespaceSignature, SubspaceId, SubspaceSignature>
}

impl fmt::Debug for WriteCapability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

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.0.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.0.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.0.granted_area_ref().map(Into::into)
    }

    /// 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.0.genesis().into()
    }

    /// 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.0.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] {
        let inner_delegations = self.0.delegations();
        let as_delegation25_ptr = inner_delegations.as_ptr() as *const Delegation;

        // SAFETY: all necessary invariants are already upheld by the original slice, and the layout is identical because `willow25::authorisation::raw::Delegation` is `repr(transparent)`
        unsafe { core::slice::from_raw_parts(as_delegation25_ptr, inner_delegations.len()) }
    }

    /// 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(meadowcap::WriteCapability::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>,
    {
        Self(meadowcap::WriteCapability::new_owned(keypair, user_key))
    }

    /// 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.0.includes_area(area.into())
    }

    /// 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.0.granted_area().into()
    }

    /// 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().unwrap();
    ///
    /// let outer_entry = Entry::prefilled_builder(&included_entry)
    ///     .subspace_id(SubspaceId::from_bytes(&[18; 32]))
    ///     .build().unwrap();
    ///
    /// assert!(cap.includes(&included_entry));
    /// assert!(!cap.includes(&outer_entry));
    /// # }
    /// ```
    pub fn includes<T>(&self, t: &T) -> bool
    where
        T: Namespaced + Coordinatelike + ?Sized,
    {
        self.0.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>,
    {
        self.0.try_delegate(keypair, new_area.into(), new_receiver)
    }

    /// 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.0.delegate(keypair, new_area.into(), new_receiver)
    }
}

/// 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.0.encode(consumer).await
    }
}

impl EncodableKnownLength for WriteCapability {
    fn len_of_encoding(&self) -> usize {
        self.0.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,
    {
        meadowcap::WriteCapability::<
            MCL,
            MCC,
            MPL,
            NamespaceId,
            NamespaceSignature,
            SubspaceId,
            SubspaceSignature,
        >::decode(producer)
        .await
        .map(Into::into)
    }
}

/// 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,
    {
        meadowcap::WriteCapability::<
            MCL,
            MCC,
            MPL,
            NamespaceId,
            NamespaceSignature,
            SubspaceId,
            SubspaceSignature,
        >::decode_canonic(producer)
        .await
        .map(Into::into)
    }
}