Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "did_doc"
version = "0.3.1"
version = "0.4.0"
authors = ["David Huseby", "Mike Lodder"]
edition = "2018"
description = "Library for loading/saving DID documents."
Expand All @@ -14,16 +14,15 @@ license = "Apache-2.0"
[lib]
name = "did_doc"
path = "src/lib.rs"
crate-type = ["staticlib", "rlib", "cdylib"]
crate-type = ["rlib"]

[dependencies]
failure = "0.1.5"
indexmap = { version = "1.2.0", features = ["serde-1"] }
log = "0.4.6"
serde = "1.0"
serde_derive = "1.0"
nom = "5.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
strum = "0.15.0"
strum_macros = "0.15.0"
void = "1.0.2"
failure = "0.1.5"
nom = "5.0.0"
2 changes: 1 addition & 1 deletion src/doc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::fields::{string_or_list, Context, PublicKey, ServiceEndpoint, Subject};
use indexmap::IndexMap;
use serde_derive::{Deserialize, Serialize};
use serde::{Deserialize, Serialize};
use serde_json::{self, Value};
use std::str::FromStr;
use std::string::{String, ToString};
Expand Down
4 changes: 2 additions & 2 deletions src/fields/context.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde::ser::{Serialize, SerializeSeq, Serializer};
use serde_derive::Deserialize;
use serde::ser::{SerializeSeq, Serializer};
use serde::{Serialize, Deserialize};
use std::default::Default;
use std::str::FromStr;
use void::Void;
Expand Down
6 changes: 3 additions & 3 deletions src/fields/publickey.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::fields::Subject;
use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde_derive::{Deserialize, Serialize};
use serde::de::{self, Deserializer, MapAccess, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::fmt;
use std::str::FromStr;
Expand Down
2 changes: 1 addition & 1 deletion src/fields/service_endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::fields::{string_or_list, Context, Subject};
use indexmap::IndexMap;
use serde_derive::{Deserialize, Serialize};
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Serialize, Deserialize, Debug)]
Expand Down
14 changes: 13 additions & 1 deletion src/fields/subject.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use serde_derive::{Deserialize, Serialize};
use serde::{Deserialize, Serialize};
use std::cmp::Eq;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
Expand Down Expand Up @@ -34,6 +34,18 @@ impl PartialEq<str> for Subject {
}
}

impl PartialEq<Uri> for Subject {
fn eq(&self, rhs: &Uri) -> bool {
self.0 == *rhs
}
}

impl PartialEq<Uri> for &Subject {
fn eq(&self, rhs: &Uri) -> bool {
self.0 == *rhs
}
}

impl PartialEq for Subject {
fn eq(&self, rhs: &Subject) -> bool {
self == rhs
Expand Down
114 changes: 69 additions & 45 deletions src/uri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::{DidError, DidErrorKind};
use std::{
collections::BTreeMap,
default::Default,
fmt,
str::FromStr
};

Expand All @@ -16,14 +15,15 @@ use nom::{
IResult,
};

use serde::de::{self, Deserialize, Deserializer, Visitor};
use serde::ser::{Serialize, Serializer};
use serde::{Serialize, Deserialize};
use serde::{de::{Deserializer, Visitor, Error}, ser::Serializer};

#[derive(Debug)]
pub struct Uri {
empty: bool,
pub id: String,
pub method: String,
pub path: Option<Vec<String>>,
pub params: Option<BTreeMap<String, String>>,
pub query: Option<BTreeMap<String, String>>,
pub fragment: Option<String>,
Expand Down Expand Up @@ -67,6 +67,7 @@ impl Default for Uri {
empty: true,
id: String::default(),
method: String::default(),
path: None,
params: None,
query: None,
fragment: None
Expand All @@ -91,6 +92,7 @@ impl Clone for Uri {
empty: self.empty,
id: self.id.clone(),
method: self.method.clone(),
path: self.path.clone(),
params: self.params.clone(),
query: self.query.clone(),
fragment: self.fragment.clone(),
Expand All @@ -104,9 +106,17 @@ impl std::fmt::Display for Uri {
return write!(f, "");
}

let mut path = String::new();
if let Some(p) = &self.path {
path.push('/');
path.push_str(&p.join("/"));
}

let mut params = String::new();
if let Some(p) = &self.params {
params.push(';');
if params.len() == 0 {
params.push(';');
}
params.push_str(
&p.iter()
.map(|(k, v)| format!("{}={}", k, v))
Expand All @@ -131,18 +141,58 @@ impl std::fmt::Display for Uri {

write!(
f,
"did:{}:{}{}{}{}",
self.method, self.id, params, query, fragment
"did:{}:{}{}{}{}{}",
self.method, self.id, path, params, query, fragment
)
}
}

impl<'de> Deserialize<'de> for Uri {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct UriVisitor;

impl<'de> Visitor<'de> for UriVisitor {
type Value = Uri;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("DID string")
}

fn visit_str<E>(self, value: &str) -> Result<Uri, E>
where
E: Error,
{
match Uri::from_str(value) {
Ok(d) => Ok(d),
Err(e) => Err(Error::custom(e.to_string()))
}
}
}

deserializer.deserialize_any(UriVisitor)
}
}

impl Serialize for Uri {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = self.to_string();
serializer.serialize_str(s.as_str())
}
}

fn parse_did_string(i: &[u8]) -> IResult<&[u8], Uri> {
if i.len() == 0 {
return Ok((i, Uri {
empty: true,
id: String::default(),
method: String::default(),
path: None,
params: None,
query: None,
fragment: None
Expand All @@ -153,6 +203,7 @@ fn parse_did_string(i: &[u8]) -> IResult<&[u8], Uri> {
let (i, method) = map(take_while(is_did_method_char), std::str::from_utf8)(i)?;
let (i, _) = char(':')(i)?;
let (i, id) = map(take_while(is_did_id_char), std::str::from_utf8)(i)?;
let (i, path) = opt(did_path)(i)?;
let (i, params) = opt(did_params)(i)?;
let (i, query) = opt(did_query)(i)?;
let (i, fragment) = opt(did_fragment)(i)?;
Expand All @@ -163,6 +214,7 @@ fn parse_did_string(i: &[u8]) -> IResult<&[u8], Uri> {
empty: false,
id: id.unwrap().to_string(),
method: method.unwrap().to_string(),
path: path.map(|s| { s.into_iter().map(|g| g.to_string()).collect() }),
params: params.map(|m| {
m.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
Expand All @@ -186,6 +238,11 @@ fn is_did_id_char(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-'
}

fn did_path(i: &[u8]) -> IResult<&[u8], Vec<&str>> {
let (i, segments) = preceded(char('/'), separated_list(char('/'), map_res(is_a("abcedfghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-%:@!$&'().*+,"), std::str::from_utf8)))(i)?;
Ok((i, segments.into_iter().collect()))
}

fn did_params(i: &[u8]) -> IResult<&[u8], BTreeMap<&str, &str>> {
let (i, lst) = preceded(char(';'), separated_list(char(';'), param_item))(i)?;

Expand Down Expand Up @@ -223,45 +280,6 @@ fn did_fragment(i: &[u8]) -> IResult<&[u8], &str> {
preceded(char('#'), map_res(is_not(":#[]"), std::str::from_utf8))(i)
}

impl<'de> Deserialize<'de> for Uri {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct UriVisitor;

impl<'de> Visitor<'de> for UriVisitor {
type Value = Uri;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("DID string")
}

fn visit_str<E>(self, value: &str) -> Result<Uri, E>
where
E: de::Error,
{
match Uri::from_str(value) {
Ok(d) => Ok(d),
Err(e) => Err(de::Error::custom(e.to_string()))
}
}
}

deserializer.deserialize_any(UriVisitor)
}
}

impl Serialize for Uri {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = self.to_string();
serializer.serialize_str(s.as_str())
}
}

#[cfg(test)]
mod resolve_method_tests {
use super::*;
Expand Down Expand Up @@ -296,4 +314,10 @@ mod resolve_method_tests {
assert_eq!(d.get("%61"), Some(&"%62"));
}

#[test]
fn test_did_path() {
let path = b"/spec/trust_ping/1.0/ping";
let p = did_path(path).unwrap().1;
assert_eq!(p, vec!["spec", "trust_ping", "1.0", "ping"].iter().map(|s| s.to_string()).collect::<Vec<String>>());
}
}
10 changes: 10 additions & 0 deletions tests/uri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,13 @@ fn did_uri_2() {
}
}

#[test]
fn did_uri_3() {
let s = "did:sov:wjb4bjwb1235kbg1235/spec/tree/d7879f5e/text";
let did = s.parse::<Uri>();
assert!(did.is_ok());
let did = did.unwrap();
assert_eq!(did.id, "wjb4bjwb1235kbg1235");
assert!(did.path.is_some());
assert_eq!(did.path, Some(vec!["spec".to_string(), "tree".to_string(), "d7879f5e".to_string(), "text".to_string()]));
}