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
/*
  Copyright (c) 2018-present evan GmbH.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

//! This library is intended to be used as a core library for developing own self-sovereign identity based applications.
//!
//! So why the name? "Vade" is an acronym for "VC and DID engine". It focuses on working with VCs and DIDs but does not hold much logic concerning their structure. Confused? Guessed as much, so what this library actually does is:
//!
//! - offering traits that define how actual implementations (aka "plugins") for working with VCs and DIDs should behave
//! - storing those plugins in a [`Vade`] instance
//! - querying against all registered plugins for certain actions (e.g. for getting VCs/DIDs)
//!
//! It has been designed with the idea of offering a consistent interface to work with while supporting to move the actual work into plugins, which also helps to reduce the dependencies.
//!
//! This library is currently under development. Behavior, as well as provided traits, will most probably change over time.
//!
//! ## Basic Flow
//!
//! When a [`Vade`] instance and its plugins have been set up (see next section), it will delegate calls to its plugins.
//!
//! For example when fetching a VC document with a [`Vade`] instance with two plugins (a [`RustStorageCache`] and a [`RustVcResolverEvan`]) the flow looks like this:
//!
//! ![vade_plugin_flow](https://user-images.githubusercontent.com/1394421/81380160-b0322c00-910a-11ea-8670-50455650497b.png)
//!
//! ## Usage
//!
//! ### Basic Usage
//!
//! First add `vade` as a dependency to your `Cargo.toml`. Then you can create new instances in your code (taken from our tests):
//!
//! ```rust
//! extern crate vade;
//!
//! use vade::Vade;
//!
//! #[test]
//! fn library_can_be_created() {
//!     let _vade = Vade::new();
//! }
//! ```
//!
//! Okay, that did not do much yet. The core library also offers a simple in-memory cache, called [`RustStorageCache`], which can be used when working with VC and DID documents, that are available offline and should just be stored and/or retrieved locally. So to use [`RustStorageCache`] as a [`VcResolver`], we just need to add it as a [`VcResolver`] plugin:
//!
//! ```rust
//! extern crate vade;
//!
//! use vade::Vade;
//! use vade::traits::VcResolver;
//! use vade::plugin::rust_storage_cache::RustStorageCache;
//!
//!
//! #[tokio::test]
//! async fn example() {
//!     let mut vade = Vade::new();
//!     let storage = RustStorageCache::new();
//!     vade.register_vc_resolver(Box::from(storage));
//!
//!     match vade.set_vc_document("vc:example123", "{}").await {
//!         Ok(()) => (),
//!         Err(e) => panic!(format!("{}", e)),
//!     }
//!     let fetched = vade.get_vc_document("vc:example123").await.unwrap();
//!     assert!(fetched == "{}");
//! }
//! ```
//!
//! Keep in mind, that the [`RustStorageCache`] resolver can be considered a reference implementation about how resolvers may behave and that it does not validate integrity and validity of given documents. For features like these, you can implement your own resolvers by following the respective traits.
//!
//! ### Examples
//!
//! In the examples here initialization is omitted to keep the readability up. If you want to see the full flow code, you can have a look at the beginning of the [`vade library file`].
//!
//! #### VCs
//!
//! ##### Adding a VC
//!
//! This, of course requires you to have an existing VC, that you can actually set, but this depends on the actual plugins used in your instance. As we use the [`RustStorageCache`] plugin in our examples here, this requirement is not a problem, as it just acts as a key-value store with out any checks around it.
//!
//! ```rust
//! # extern crate vade;
//! # 
//! # use vade::Vade;
//! # use vade::traits::VcResolver;
//! # use vade::plugin::rust_storage_cache::RustStorageCache;
//! # 
//! # 
//! # #[tokio::test]
//! # async fn example() {
//! #     let mut vade = Vade::new();
//! #     let storage = RustStorageCache::new();
//! #     vade.register_vc_resolver(Box::from(storage));
//! # 
//! match vade.set_vc_document("vc:example123", "{}").await {
//!     Ok(()) => (),
//!     Err(e) => panic!(format!("{}", e)),
//! }
//! #     let fetched = vade.get_vc_document("vc:example123").await.unwrap();
//! #     assert!(fetched == "{}");
//! # }
//! ```
//!
//! ##### Getting a VC
//!
//! ```rust
//! # extern crate vade;
//! # 
//! # use vade::Vade;
//! # use vade::traits::VcResolver;
//! # use vade::plugin::rust_storage_cache::RustStorageCache;
//! # 
//! # 
//! # #[tokio::test]
//! # async fn example() {
//! #     let mut vade = Vade::new();
//! #     let storage = RustStorageCache::new();
//! #     vade.register_vc_resolver(Box::from(storage));
//! # 
//! #      match vade.set_vc_document("vc:example123", "{}").await {
//! #          Ok(()) => (),
//! #          Err(e) => panic!(format!("{}", e)),
//! #      }
//! let fetched = vade.get_vc_document("vc:example123").await.unwrap();
//! #     assert!(fetched == "{}");
//! # }
//! ```
//!
//! ##### Validating VCs
//!
//! Note that the outcome of this function heavily depends on the used plugin. [`RustStorageCache`] for example will only accept VCs as valid, if their name is "test".
//!
//! ```rust
//! # extern crate vade;
//! # 
//! # use vade::Vade;
//! # use vade::traits::VcResolver;
//! # use vade::plugin::rust_storage_cache::RustStorageCache;
//! # 
//! # 
//! # #[tokio::test]
//! # async fn example() {
//! #     let mut vade = Vade::new();
//! #     let storage = RustStorageCache::new();
//! #     vade.register_vc_resolver(Box::from(storage));
//! # 
//! #     match vade.set_vc_document("test", "{}").await {
//! #        Ok(()) => (),
//! #        Err(e) => panic!(format!("{}", e)),
//! #     }
//! #     let fetched = vade.get_vc_document("test").await.unwrap();
//! let vc_result = vade.check_vc("test", &fetched).await;
//! match vc_result {
//!     Ok(_) => (),
//!     Err(_) => panic!("VC not valid"),
//! }
//! #     assert!(fetched == "{}");
//! # }
//! ```
//!
//!
//! #### DIDs
//!
//! ##### Adding a DID
//!
//! If your registered plugin allows you to set DIDs you can set it with:
//!
//! ```rust
//! # extern crate vade;
//! # 
//! # use vade::Vade;
//! # use vade::traits::DidResolver;
//! # use vade::plugin::rust_storage_cache::RustStorageCache;
//! # 
//! # 
//! # #[tokio::test]
//! # async fn example() {
//! #     let mut vade = Vade::new();
//! #     let storage = RustStorageCache::new();
//! #     vade.register_did_resolver(Box::from(storage));
//! # 
//! match vade.set_did_document("did:example123", "{}").await {
//!     Ok(()) => (),
//!     Err(e) => panic!(format!("{}", e)),
//! }
//! #     let fetched = vade.get_did_document("did:example123").await.unwrap();
//! #     assert!(fetched == "{}");
//! # }
//! ```
//!
//! ##### Getting a DID
//!
//! ```rust
//! # extern crate vade;
//! # 
//! # use vade::Vade;
//! # use vade::traits::DidResolver;
//! # use vade::plugin::rust_storage_cache::RustStorageCache;
//! # 
//! # 
//! # #[tokio::test]
//! # async fn example() {
//! #     let mut vade = Vade::new();
//! #     let storage = RustStorageCache::new();
//! #     vade.register_did_resolver(Box::from(storage));
//! # 
//! #     match vade.set_did_document("did:example123", "{}").await {
//! #         Ok(()) => (),
//! #         Err(e) => panic!(format!("{}", e)),
//! #     }
//! let fetched = vade.get_did_document("did:example123").await.unwrap();
//! #     assert!(fetched == "{}");
//! # }
//! ```
//!
//! ##### Validating DIDs
//!
//! Again, note that the outcome of this function heavily depends on the used plugin. [`RustStorageCache`] for example will only accept DIDs as valid, if their name is "test".
//!
//! ```rust
//! # extern crate vade;
//! # 
//! # use vade::Vade;
//! # use vade::traits::VcResolver;
//! # use vade::plugin::rust_storage_cache::RustStorageCache;
//! # 
//! # 
//! # #[tokio::test]
//! # async fn example() {
//! #     let mut vade = Vade::new();
//! #     let storage = RustStorageCache::new();
//! #     vade.register_did_resolver(Box::from(storage));
//! # 
//! #     match vade.set_did_document("test", "{}").await {
//! #        Ok(()) => (),
//! #        Err(e) => panic!(format!("{}", e)),
//! #     }
//! #     let fetched = vade.get_did_document("test").await.unwrap();
//! let did_result = vade.check_did("test", &fetched).await;
//! match did_result {
//!     Ok(_) => (),
//!     Err(_) => panic!("VC not valid"),
//! }
//! #     assert!(fetched == "{}");
//! # }
//! ```
//!
//!
//! ## Plugins
//!
//! Plugins are the modules that perform the actual work in the [`Vade`] module. This project already has one plugin included,  [`RustStorageCache`], which can be used as a reference for creating own plugins.
//!
//! ### Create new Plugins
//!
//! Developing plugins for `vade` can be done by implementing one or more traits from [`vade::library::traits`], e.g.
//!
//! - [`VcResolver`]
//! - [`DidResolver`]
//! - [`Logger`] (currently unclear if this plugin will be continued, but can be used for implementation tests)
//!
//! An example for a simple plugin is the provided [`RustStorageCache`]. It implements [`DidResolver`] as well as [`VcResolver`] functionalities. For your implementation you can, of course, decide to implement only a single trait in a plugin.
//!
//! ### Basic Behavior
//!
//! This plugin implements the following traits:
//!
//! - [`VcResolver`] - therefore, it can handle VC documents
//! - [`DidResolver`] - therefore, it can handle DID documents
//!
//! This allows us to register it as these resolvers with
//!
//! - [`register_vc_resolver`]
//! - [`register_did_resolver`]
//!
//! respectively.
//!
//! As soon as they are registered as a plugin for a certain type of operation, they are called for related operations (e.g. [`get_vc_document`]) by the [`Vade`] instance they are registered in.
//!
//! ### Library Functions that utilize Plugins
//!
//! This section shows a short overview over the plugin related functions. For more details, have a look at the [`Vade`] documentation.
//!
//! #### Plugin registration
//!
//! These functions can be used to register new resolver plugins:
//!
//! - [`register_did_resolver`]
//! - [`register_vc_resolver`]
//!
//! #### Setters
//!
//! These functions will call all registered plugins respectively and with given arguments (e.g. setting a DID will only call DID resolver functions, etc.):
//!
//! - [`set_did_document`]
//! - [`set_vc_document`]
//!
//! If multiple plugins are registered, awaits completion of all actions. First plugin that fails lets this request fail.
//!
//! #### Getters
//!
//! These functions will call all registered plugins respectively and with given arguments (e.g. getting a DID will only call DID resolver functions, etc.):
//!
//! - [`get_did_document`]
//! - [`get_vc_document`]
//!
//! If multiple plugins are registered, first **successful** response will be used. Request will fail if all plugins failed.
//!
//! #### Validation
//!
//! These functions will call all registered plugins respectively and with given arguments (e.g. getting a DID will only call DID resolver functions, etc.):
//!
//! - [`check_did_document`]
//! - [`check_vc_document`]
//!
//! A document is considered valid if at least one resolver confirms its validity. Resolvers may throw to indicate:
//!
//! - that they are not responsible for this document
//! - that they consider this document invalid
//!
//! The current validation flow offers only a limited way of feedback for invalidity and may undergo further changes in future.
//!
//! ### More Plugins
//!
//! A plugin working with VCs and DIDs on [evan.network] called [`vade-evan`] has been implemented. Its usage is equivalent to the description above, more details can be found on its project page.
//!
//! You can also start writing your own plugin, by following the behavior outlined with the traits in this library.
//!
//! ## Wasm Support
//!
//! Vade supports Wasm! ^^
//! 
//! For an example how to use [`Vade`] in Wasm and a how to guide, have a look at our [vade-wasm-example] project.
//!
//! [evan.network]: https://evan.network
//! [vade-wasm-example]: https://github.com/evannetwork/vade-wasm-example
//! [`check_did_document`]: traits/trait.DidResolver.html#tymethod.check_did_document
//! [`check_vc_document`]: traits/trait.VcResolver.html#tymethod.check_vc_document
//! [`DidResolver`]: traits/trait.DidResolver.html
//! [`get_did_document`]: traits/trait.DidResolver.html#tymethod.get_did_document
//! [`get_vc_document`]: traits/trait.VcResolver.html#tymethod.get_vc_document
//! [`Logger`]: traits/trait.Logger.html
//! [`register_did_resolver`]: struct.Vade.html#method.register_did_resolver
//! [`register_vc_resolver`]: struct.Vade.html#method.register_did_resolver
//! [`RustStorageCache`]: plugin/rust_storage_cache/struct.RustStorageCache.html
//! [`RustVcResolverEvan`]: https://docs.rs/vade-evan/*/vade_evan/plugin/rust_vcresolver_evan/struct.RustVcResolverEvan.html
//! [`set_did_document`]: traits/trait.DidResolver.html#tymethod.set_did_document
//! [`set_vc_document`]: traits/trait.VcResolver.html#tymethod.set_vc_document
//! [`vade-evan`]: https://docs.rs/vade-evan
//! [`vade::library::traits`]: traits/index.html
//! [`vade library file`]: https://github.com/evannetwork/vade/blob/develop/src/lib.rs
//! [`Vade`]: struct.Vade.html
//! [`VcResolver`]: traits/trait.VcResolver.html

pub mod plugin;
pub mod traits;

#[macro_use]
extern crate simple_error;

use futures::future::{ select_ok, try_join_all };
use simple_error::SimpleError;
use traits::{ DidResolver, Logger, VcResolver };

/// Vade library, that holds plugins and delegates calls to them.
pub struct Vade {
    /// Vector of supported DID resolvers.
    pub did_resolvers: Vec<Box<dyn DidResolver>>,
    /// Vector of supported loggers. Logging will iterate through it and try to
    /// use every logger.
    pub loggers: Vec<Box<dyn Logger>>,
    /// Vector of supported VC resolvers.
    pub vc_resolvers: Vec<Box<dyn VcResolver>>,
}

impl Vade {
    /// Creates new Vade instance, vectors are initialized as empty.
    pub fn new() -> Vade {
        Vade {
            did_resolvers: Vec::new(),
            loggers: Vec::new(),
            vc_resolvers: Vec::new(),
        }
    }

    /// Checks given DID document against registered resolvers.
    /// A DID document is considered as valid if at least one did resolver
    /// confirms its validity.
    /// Resolvers may throw to indicate
    /// - that they are not responsible for this DID
    /// - that they consider this DID as invalid
    ///
    /// # Arguments
    ///
    /// * `did_name` - did_name to check document for
    /// * `value` - value to check
    pub async fn check_did(&mut self, did_name: &str, value: &str) -> Result<(), Box<dyn std::error::Error>> {
        let futures = self.did_resolvers.iter()
            .map(|resolver| resolver.check_did(did_name, value));
        match select_ok(futures).await {
            Ok(_) => Ok(()),
            Err(_e) => Err(Box::new(SimpleError::new(format!("did document not valid")))),
        }
    }

    /// Checks given VC document against registered resolvers.
    /// A VC document is considered as valid if at least one vc resolver
    /// confirms its validity.
    /// Resolvers may throw to indicate
    /// - that they are not responsible for this VC
    /// - that they consider this VC as invalid
    ///
    /// # Arguments
    ///
    /// * `vc_id` - vc_id to check document for
    /// * `value` - value to check
    pub async fn check_vc(&mut self, vc_id: &str, value: &str) -> Result<(), Box<dyn std::error::Error>> {
        let futures = self.vc_resolvers.iter()
            .map(|resolver| resolver.check_vc(vc_id, value));
        match select_ok(futures).await {
            Ok(_) => Ok(()),
            Err(e) => Err(Box::new(SimpleError::new(format!("vc document not valid; {}", e)))),
        }
    }

    /// Gets document for given did name.
    /// If multiple plugins are registered, first **successful** response
    /// will be used. Request will fail if all plugins failed.
    ///
    /// # Arguments
    ///
    /// * `did_name` - did_name to fetch
    pub async fn get_did_document(&self, did_name: &str) -> Result<String, Box<dyn std::error::Error>> {
        let futures = self.did_resolvers.iter()
            .map(|resolver| resolver.get_did_document(did_name));
        match select_ok(futures).await {
            Ok((r, _)) => Ok(r),
            Err(_e) => Err(Box::new(SimpleError::new(format!("could not get did document")))),
        }
    }

    /// Gets document for given vc name.
    /// If multiple plugins are registered, first **successful** response
    /// will be used. Request will fail if all plugins failed.
    ///
    /// # Arguments
    ///
    /// * `vc_name` - vc_name to fetch
    pub async fn get_vc_document(&self, vc_name: &str) -> Result<String, Box<dyn std::error::Error>> {
        let futures = self.vc_resolvers.iter()
            .map(|resolver| resolver.get_vc_document(vc_name));
        match select_ok(futures).await {
            Ok((r, _)) => Ok(r),
            Err(_e) => Err(Box::new(SimpleError::new(format!("could not get vc document")))),
        }
    }

    /// Log given message. Logging will iterate through it and try to use
    /// every logger.
    ///
    /// **Note**: This functionality is currently semi-obsoleted. It has been
    /// used for testing purposes and it is currently unclear wheter it will
    /// stay as it is or undergo further changes to allow to to fulfill its
    /// original role.
    ///
    /// # Arguments
    ///
    /// * `message` - message to log
    pub fn log(&self, message: &str, level: Option<&str>) {
        for logger in self.loggers.iter() {
            logger.log(message, level);
        }
    }

    /// Registers new [`DidResolver`] instance. Note, that `did_resolver` is given
    /// as `Box` to support dynamic avadegnment.
    ///
    /// # Arguments
    ///
    /// * `did_resolver` - an instance of a `struct` that implements
    ///                    [`DidResolver`] trait
    pub fn register_did_resolver(&mut self, did_resolver: Box<dyn DidResolver>) {
        self.did_resolvers.push(did_resolver);
    }

    /// Registers new [`Logger`] instance. Note, that `logger` is given as `Box`
    /// to support dynamic avadegnment.
    ///
    /// # Arguments
    ///
    /// * `logger` - an instance of a `struct` that implements [`Logger`] trait
    pub fn register_logger(&mut self, logger: Box<dyn Logger>) {
        self.loggers.push(logger);
    }

    /// Registers new `VcdResolver` instance. Note, that `vc_resolver` is given
    /// as `Box` to support dynamic avadegnment.
    ///
    /// # Arguments
    ///
    /// * `vc_resolver` - an instance of a `struct` that implements [`VcResolver`]
    ///                   trait
    pub fn register_vc_resolver(&mut self, vc_resolver: Box<dyn VcResolver>) {
        self.vc_resolvers.push(vc_resolver);
    }

    /// Sets document for given did name.
    /// If multiple plugins are registered, awaits completion of all actions.
    /// First plugin, that fails lets this request fail.
    ///
    /// # Arguments
    ///
    /// * `did_name` - did_name to set value for
    /// * `value` - value to set
    pub async fn set_did_document(&mut self, did_name: &str, value: &str) -> Result<(), Box<dyn std::error::Error>> {
        let futures = self.did_resolvers.iter_mut()
            .map(|resolver| resolver.set_did_document(did_name, value));
        match try_join_all(futures).await {
            Ok(_) => Ok(()),
            Err(_e) => Err(Box::new(SimpleError::new(format!("could not set did document")))),
        }
    }

    /// Sets document for given vc name.
    /// If multiple plugins are registered, awaits completion of all actions.
    /// First plugin, that fails lets this request fail.
    ///
    /// # Arguments
    ///
    /// * `vc_name` - vc_name to set value for
    /// * `value` - value to set
    pub async fn set_vc_document(&mut self, vc_name: &str, value: &str) -> Result<(), Box<dyn std::error::Error>> {
        let futures = self.vc_resolvers.iter_mut()
            .map(|resolver| resolver.set_vc_document(vc_name, value));
        match try_join_all(futures).await {
            Ok(_) => Ok(()),
            Err(_e) => Err(Box::new(SimpleError::new(format!("could not set vc document")))),
        }
    }
}