Skip to content

Commit

Permalink
Merge branch 'main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewwhitehead authored Aug 10, 2023
2 parents 619291c + 77cb8d0 commit 8f5cc46
Show file tree
Hide file tree
Showing 17 changed files with 2,314 additions and 1,896 deletions.
13 changes: 5 additions & 8 deletions libindy_vdr/src/ffi/ledger.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::str::FromStr;

use crate::common::error::prelude::*;
use crate::ledger::constants::UpdateRole;
#[cfg(any(feature = "rich_schema", test))]
use crate::ledger::identifiers::RichSchemaId;
use crate::ledger::identifiers::{CredentialDefinitionId, RevocationRegistryId, SchemaId};
Expand Down Expand Up @@ -419,14 +422,8 @@ pub extern "C" fn indy_vdr_build_nym_request(
let dest = DidValue::from_str(dest.as_str())?;
let verkey = verkey.into_opt_string();
let alias = alias.into_opt_string();
let role = role.into_opt_string();
let diddoc_content = match diddoc_content.as_opt_str() {
Some(s) => {
let js = serde_json::from_str(s).with_input_err("Error deserializing raw value as JSON")?;
Some(js)
}
None => None,
};
let role = role.as_opt_str().map(UpdateRole::from_str).transpose()?;
let diddoc_content = diddoc_content.as_opt_str().map(serde_json::from_str).transpose().with_input_err("Error deserializing raw value as JSON")?;
let version = if version == -1 { None } else { Some(version) };
let req = builder.build_nym_request(&identifier, &dest, verkey, alias, role, diddoc_content.as_ref(), version)?;
let handle = add_request(req)?;
Expand Down
205 changes: 194 additions & 11 deletions libindy_vdr/src/ledger/constants.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, str::FromStr};

use crate::common::error::{input_err, VdrError};

pub const NODE: &str = "0";
pub const NYM: &str = "1";
pub const GET_TXN: &str = "3";
Expand Down Expand Up @@ -29,6 +34,7 @@ pub const GET_AUTH_RULE: &str = "121";
pub const AUTH_RULES: &str = "122";
pub const FLAG: &str = "130";
pub const GET_FLAG: &str = "131";

// RichSchema objects
pub const RICH_SCHEMA_CTX: &str = "200";
pub const RICH_SCHEMA: &str = "201";
Expand Down Expand Up @@ -96,26 +102,203 @@ pub const READ_REQUESTS: [&str; 14] = [
GET_RICH_SCHEMA_BY_METADATA,
];

pub const TRUSTEE: &str = "0";
pub const STEWARD: &str = "2";
pub const ENDORSER: &str = "101";
pub const NETWORK_MONITOR: &str = "201";
pub const ROLE_REMOVE: &str = "";
pub const ROLE_TRUSTEE: usize = 0;
pub const ROLE_STEWARD: usize = 2;
pub const ROLE_ENDORSER: usize = 101;
pub const ROLE_NETWORK_MONITOR: usize = 201;

pub const RS_SCHEMA_TYPE_VALUE: &str = "sch";
pub const RS_ENCODING_TYPE_VALUE: &str = "enc";
pub const RS_CONTEXT_TYPE_VALUE: &str = "ctx";
pub const RS_MAPPING_TYPE_VALUE: &str = "map";
pub const RS_CRED_DEF_TYPE_VALUE: &str = "cdf";
pub const RS_PRES_DEF_TYPE_VALUE: &str = "pdf";

pub const ROLES: [&str; 4] = [TRUSTEE, STEWARD, ENDORSER, NETWORK_MONITOR];

// Method/version of self-certification
pub const DEFAULT: i32 = 0; // No (enforced) self-certification
pub const DID_SOV: i32 = 1; // Legacy self-certification
pub const DID_INDY: i32 = 2; // Self-certification based on did:indy method spec
/// No (enforced) self-certification
pub const CERT_DEFAULT: i32 = 0;
/// Legacy self-certification
pub const CERT_DID_SOV: i32 = 1;
/// Self-certification based on did:indy method spec
pub const CERT_DID_INDY: i32 = 2;

pub const SELF_CERT_VERSIONS: [i32; 3] = [CERT_DEFAULT, CERT_DID_SOV, CERT_DID_INDY];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(usize)]
pub enum LedgerRole {
Trustee,
Steward,
Endorser,
NetworkMonitor,
Custom(usize),
}

impl LedgerRole {
pub fn to_usize(self) -> usize {
match self {
Self::Trustee => ROLE_TRUSTEE,
Self::Steward => ROLE_STEWARD,
Self::Endorser => ROLE_ENDORSER,
Self::NetworkMonitor => ROLE_NETWORK_MONITOR,
Self::Custom(val) => val,
}
}

pub fn to_code(self) -> String {
self.to_usize().to_string()
}
}

impl fmt::Display for LedgerRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ident = match self {
Self::Trustee => "TRUSTEE",
Self::Steward => "STEWARD",
Self::Endorser => "ENDORSER",
Self::NetworkMonitor => "NETWORK_MONITOR",
Self::Custom(role) => return write!(f, "{}", role),
};
f.write_str(ident)
}
}

impl FromStr for LedgerRole {
type Err = VdrError;

fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"TRUSTEE" => Ok(Self::Trustee),
"STEWARD" => Ok(Self::Steward),
"TRUST_ANCHOR" | "ENDORSER" => Ok(Self::Endorser),
"NETWORK_MONITOR" => Ok(Self::NetworkMonitor),
_ => {
if let Ok(role) = value.parse::<usize>() {
Ok(Self::from(role))
} else {
Err(input_err(format!("Invalid ledger role: {value}")))
}
}
}
}
}

impl From<usize> for LedgerRole {
fn from(value: usize) -> Self {
match value {
ROLE_TRUSTEE => Self::Trustee,
ROLE_STEWARD => Self::Steward,
ROLE_ENDORSER => Self::Endorser,
ROLE_NETWORK_MONITOR => Self::NetworkMonitor,
other => Self::Custom(other),
}
}
}

impl From<LedgerRole> for usize {
fn from(value: LedgerRole) -> Self {
value.to_usize()
}
}

pub const SELF_CERT_VERSIONS: [i32; 3] = [DEFAULT, DID_SOV, DID_INDY];
impl<'d> Deserialize<'d> for LedgerRole {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'d>,
{
struct Vis;

impl<'v> Visitor<'v> for Vis {
type Value = LedgerRole;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("expected a ledger role identifier")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
LedgerRole::from_str(v).map_err(|e| E::custom(e.to_string()))
}
}

deserializer.deserialize_any(Vis)
}
}

impl Serialize for LedgerRole {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(&self.to_usize())
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UpdateRole {
Reset,
Set(LedgerRole),
}

impl FromStr for UpdateRole {
type Err = VdrError;

fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"" => Ok(Self::Reset),
_ => LedgerRole::from_str(value).map(Self::Set),
}
}
}

impl<'d> Deserialize<'d> for UpdateRole {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'d>,
{
struct Vis;

impl<'v> Visitor<'v> for Vis {
type Value = UpdateRole;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("expected a ledger role identifier")
}

fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(UpdateRole::Reset)
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
LedgerRole::from_str(v)
.map_err(|e| E::custom(e.to_string()))
.map(UpdateRole::Set)
}
}

deserializer.deserialize_any(Vis)
}
}

impl Serialize for UpdateRole {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Reset => serializer.serialize_none(),
Self::Set(role) => serializer.collect_str(&role.to_usize()),
}
}
}

pub fn txn_name_to_code(txn: &str) -> Option<&str> {
if REQUESTS.contains(&txn) {
Expand Down
7 changes: 3 additions & 4 deletions libindy_vdr/src/ledger/request_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use super::requests::cred_def::{CredDefOperation, CredentialDefinition, GetCredD
use super::requests::flag::{FlagOperation, GetFlagOperation};
use super::requests::ledgers_freeze::{GetFrozenLedgersOperation, LedgersFreezeOperation};
use super::requests::node::{NodeOperation, NodeOperationData};
use super::requests::nym::{role_to_code, GetNymOperation, NymOperation};
use super::requests::nym::{GetNymOperation, NymOperation};
use super::requests::pool::{
PoolConfigOperation, PoolRestartOperation, PoolUpgradeOperation, Schedule,
};
Expand All @@ -47,7 +47,7 @@ use super::requests::txn::GetTxnOperation;
use super::requests::validator_info::GetValidatorInfoOperation;
use super::requests::{Request, RequestType};

use super::constants::txn_name_to_code;
use super::constants::{txn_name_to_code, UpdateRole};

fn datetime_to_date_timestamp(time: u64) -> u64 {
const SEC_IN_DAY: u64 = 86400;
Expand Down Expand Up @@ -156,11 +156,10 @@ impl RequestBuilder {
dest: &DidValue,
verkey: Option<String>,
alias: Option<String>,
role: Option<String>,
role: Option<UpdateRole>,
diddoc_content: Option<&SJsonValue>,
version: Option<i32>,
) -> VdrResult<PreparedRequest> {
let role = role_to_code(role)?;
let operation = NymOperation::new(
dest.to_short(),
verkey,
Expand Down
3 changes: 2 additions & 1 deletion libindy_vdr/src/ledger/requests/auth_rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::ops::Not;
use super::constants::{AUTH_RULE, AUTH_RULES, GET_AUTH_RULE};
use super::{ProtocolVersion, RequestType};
use crate::common::error::prelude::*;
use crate::ledger::constants::LedgerRole;

#[allow(non_camel_case_types)]
#[derive(Deserialize, Debug, Serialize, PartialEq)]
Expand Down Expand Up @@ -54,7 +55,7 @@ pub enum Constraint {
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct RoleConstraint {
pub sig_count: u32,
pub role: Option<String>,
pub role: Option<LedgerRole>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(default)]
Expand Down
27 changes: 4 additions & 23 deletions libindy_vdr/src/ledger/requests/nym.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use sha2::{Digest, Sha256};
use super::constants::{GET_NYM, NYM};
use super::did::ShortDidValue;
use super::{ProtocolVersion, RequestType};
use crate::common::error::{input_err, VdrResult};
use crate::ledger::constants::{ENDORSER, NETWORK_MONITOR, ROLES, ROLE_REMOVE, STEWARD, TRUSTEE};
use crate::common::error::VdrResult;
use crate::ledger::constants::UpdateRole;

#[derive(Serialize, PartialEq, Debug)]
#[serde(rename_all = "camelCase")]
Expand All @@ -16,7 +16,7 @@ pub struct NymOperation {
#[serde(skip_serializing_if = "Option::is_none")]
pub alias: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub role: Option<::serde_json::Value>,
pub role: Option<UpdateRole>,
#[serde(skip_serializing_if = "Option::is_none")]
pub diddoc_content: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
Expand All @@ -28,7 +28,7 @@ impl NymOperation {
dest: ShortDidValue,
verkey: Option<String>,
alias: Option<String>,
role: Option<::serde_json::Value>,
role: Option<UpdateRole>,
diddoc_content: Option<String>,
version: Option<i32>,
) -> NymOperation {
Expand Down Expand Up @@ -86,22 +86,3 @@ impl RequestType for GetNymOperation {
Ok(Some(hash))
}
}

pub fn role_to_code(role: Option<String>) -> VdrResult<Option<serde_json::Value>> {
if let Some(r) = role {
Ok(Some(if r == ROLE_REMOVE {
serde_json::Value::Null
} else {
json!(match r.as_str() {
"STEWARD" => STEWARD,
"TRUSTEE" => TRUSTEE,
"TRUST_ANCHOR" | "ENDORSER" => ENDORSER,
"NETWORK_MONITOR" => NETWORK_MONITOR,
role if ROLES.contains(&role) => role,
role => return Err(input_err(format!("Invalid role: {}", role))),
})
}))
} else {
Ok(None)
}
}
4 changes: 2 additions & 2 deletions libindy_vdr/tests/auth_rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const VALUE: &str = "0";
fn _role_constraint() -> Constraint {
Constraint::RoleConstraint(RoleConstraint {
sig_count: 1,
role: Some(constants::TRUSTEE.to_string()),
role: Some(constants::LedgerRole::Trustee),
metadata: Some(json!({})),
need_to_be_owner: false,
off_ledger_signature: false,
Expand All @@ -35,7 +35,7 @@ fn _complex_constraint() -> Constraint {
_role_constraint(),
Constraint::RoleConstraint(RoleConstraint {
sig_count: 2,
role: Some("2".to_string()),
role: Some(constants::LedgerRole::Custom(2)),
metadata: None,
need_to_be_owner: true,
off_ledger_signature: false,
Expand Down
2 changes: 1 addition & 1 deletion libindy_vdr/tests/cred_def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ mod send_cred_def {

#[rstest]
fn test_pool_send_cred_def_requests(pool: TestPool) {
let identity = helpers::new_ledger_identity(&pool, Some(String::from("TRUSTEE")));
let identity = helpers::new_ledger_identity(&pool, Some(constants::LedgerRole::Trustee));

let schema = helpers::schema::default_schema(&identity.did);
let (_schema_id, schema_seq_no) = helpers::schema::publish(&identity, &pool, &schema);
Expand Down
Loading

0 comments on commit 8f5cc46

Please sign in to comment.