Skip to content

Commit

Permalink
Improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
olegnn committed Oct 27, 2023
1 parent 9d31e58 commit df00a81
Show file tree
Hide file tree
Showing 7 changed files with 141 additions and 108 deletions.
12 changes: 6 additions & 6 deletions node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ pub fn development_config() -> ChainSpec {
b"Charlie\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
]
.iter()
.map(|d| Did(**d))
.map(|d| Did(**d).into())
.collect::<BTreeSet<_>>()
.try_into()
.unwrap(),
Expand Down Expand Up @@ -257,7 +257,7 @@ pub fn local_testnet_config() -> ChainSpec {
b"Charlie\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
]
.iter()
.map(|d| Did(**d))
.map(|d| Did(**d).into())
.collect::<BTreeSet<_>>()
.try_into()
.unwrap(),
Expand Down Expand Up @@ -352,7 +352,7 @@ pub fn pos_testnet_config() -> ChainSpec {
b"ec\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
]
.iter()
.map(|d| Did(**d))
.map(|d| Did(**d).into())
.collect::<BTreeSet<_>>()
.try_into()
.unwrap(),
Expand Down Expand Up @@ -516,7 +516,7 @@ pub fn pos_devnet_config() -> ChainSpec {
b"ec\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
]
.iter()
.map(|d| Did(**d))
.map(|d| Did(**d).into())
.collect::<BTreeSet<_>>()
.try_into()
.unwrap(),
Expand Down Expand Up @@ -720,7 +720,7 @@ pub fn pos_mainnet_config() -> ChainSpec {
b"ec\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
]
.iter()
.map(|d| Did(**d))
.map(|d| Did(**d).into())
.collect::<BTreeSet<_>>()
.try_into()
.unwrap(),
Expand Down Expand Up @@ -931,7 +931,7 @@ impl GenesisBuilder {
fn validate(&self) -> Result<(), String> {
// Every DID in master must be pre-declared
for did in self.master.members.iter() {
if !self.dids.iter().any(|(k, _v)| k == did) {
if !self.dids.iter().any(|(k, _v)| k == &**did) {
return Err(format!(
"Master contains DID {:x?}.. that is not pre-declared",
did,
Expand Down
22 changes: 12 additions & 10 deletions pallets/core/src/common/authorization.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{common::Signature, did, util::Action};
use codec::Encode;
use core::ops::Deref;

use super::ToStateChange;

Expand All @@ -21,7 +22,8 @@ type AuthorizationResult<T, S> =
/// Signature that can authorize a signed action.
pub trait AuthorizeSignedAction<A: Action>: Signature
where
Self::Signer: AuthorizeTarget<A::Target, Self::Key>,
Self::Signer: AuthorizeTarget<A::Target, Self::Key> + Deref,
<Self::Signer as Deref>::Target: AuthorizeTarget<A::Target, Self::Key>,
{
/// This signature allows `Self::Signer` to perform the supplied action.
fn authorizes_signed_action<T: did::Config>(&self, action: &A) -> AuthorizationResult<T, Self>
Expand All @@ -31,24 +33,24 @@ where
let signer_pubkey = self.key::<T>().ok_or(did::Error::<T>::NoKeyForDid)?;
let encoded_state_change = action.to_state_change().encode();

(*self.signer()).ensure_authorizes_target(&signer_pubkey, action)?;
self.signer()
.ensure_authorizes_target(&signer_pubkey, action)?;

self.verify_raw_bytes(&encoded_state_change, &signer_pubkey)
.map_err(Into::into)
.map(|yes| {
yes.then(|| Authorization {
signer: self.signer(),
key: signer_pubkey,
})
})
let ok = self.verify_raw_bytes(&encoded_state_change, &signer_pubkey)?;

Ok(ok.then(|| Authorization {
signer: self.signer(),
key: signer_pubkey,
}))
}
}

impl<A: Action, S> AuthorizeSignedAction<A> for S
where
S: Signature,
S::Signer: AuthorizeTarget<A::Target, S::Key>,
S::Signer: AuthorizeTarget<A::Target, S::Key> + Deref,
<S::Signer as Deref>::Target: AuthorizeTarget<A::Target, S::Key>,
{
}

Expand Down
1 change: 1 addition & 0 deletions pallets/core/src/common/signed_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ where
A: ActionWithNonce<T> + ToStateChange<T>,
Sig: AuthorizeSignedAction<A>,
Sig::Signer: AuthorizeTarget<A::Target, Sig::Key> + Deref,
<Sig::Signer as Deref>::Target: AuthorizeTarget<A::Target, Sig::Key>,
{
/// Verifies signer's signature and nonce, then executes given action providing a reference to the
/// value associated with the target.
Expand Down
57 changes: 34 additions & 23 deletions pallets/core/src/modules/did/base/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,40 +30,51 @@ pub enum DidOrDidMethodKey {
DidMethodKey(DidMethodKey),
}

impl From<Did> for DidOrDidMethodKey {
fn from(did: Did) -> Self {
Self::Did(did)
impl<Target> AuthorizeTarget<Target, DidKey> for DidOrDidMethodKey
where
Did: AuthorizeTarget<Target, DidKey>,
{
fn ensure_authorizes_target<T, A>(&self, key: &DidKey, action: &A) -> Result<(), Error<T>>
where
T: crate::did::Config,
A: Action<Target = Target>,
{
match self {
DidOrDidMethodKey::Did(did) => did.ensure_authorizes_target(key, action),
_ => Err(Error::<T>::ExpectedDid),
}
}
}

impl From<DidMethodKey> for DidOrDidMethodKey {
fn from(did: DidMethodKey) -> Self {
Self::DidMethodKey(did)
impl<Target> AuthorizeTarget<Target, DidMethodKey> for DidOrDidMethodKey
where
DidMethodKey: AuthorizeTarget<Target, DidMethodKey>,
{
fn ensure_authorizes_target<T, A>(&self, key: &DidMethodKey, action: &A) -> Result<(), Error<T>>
where
T: crate::did::Config,
A: Action<Target = Target>,
{
match self {
DidOrDidMethodKey::DidMethodKey(did_method_key) => {
did_method_key.ensure_authorizes_target(key, action)
}
_ => Err(Error::<T>::ExpectedDid),
}
}
}

impl TryFrom<DidKeyOrDidMethodKey> for DidKey {
type Error = DidMethodKey;

fn try_from(did_key_or_did_method_key: DidKeyOrDidMethodKey) -> Result<Self, Self::Error> {
match did_key_or_did_method_key {
DidKeyOrDidMethodKey::DidKey(did_key) => Ok(did_key),
DidKeyOrDidMethodKey::DidMethodKey(did_method_key) => Err(did_method_key),
}
impl From<Did> for DidOrDidMethodKey {
fn from(did: Did) -> Self {
Self::Did(did)
}
}

impl TryFrom<DidKeyOrDidMethodKey> for DidMethodKey {
type Error = DidKey;

fn try_from(did_key_or_did_method_key: DidKeyOrDidMethodKey) -> Result<Self, Self::Error> {
match did_key_or_did_method_key {
DidKeyOrDidMethodKey::DidKey(did_key) => Err(did_key),
DidKeyOrDidMethodKey::DidMethodKey(did_method_key) => Ok(did_method_key),
}
impl From<DidMethodKey> for DidOrDidMethodKey {
fn from(did: DidMethodKey) -> Self {
Self::DidMethodKey(did)
}
}

impl TryFrom<DidOrDidMethodKey> for Did {
type Error = DidMethodKey;

Expand Down
61 changes: 32 additions & 29 deletions pallets/core/src/modules/did/base/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,53 +7,56 @@ use crate::common::{
};
use frame_support::traits::Get;

/// Either `DidKey` or `DidMethodKey`.
pub enum DidKeyOrDidMethodKey {
DidKey(DidKey),
DidMethodKey(DidMethodKey),
}

impl TryFrom<DidKeyOrDidMethodKey> for DidKey {
type Error = DidMethodKey;

fn try_from(did_key_or_did_method_key: DidKeyOrDidMethodKey) -> Result<Self, Self::Error> {
match did_key_or_did_method_key {
DidKeyOrDidMethodKey::DidKey(did_key) => Ok(did_key),
DidKeyOrDidMethodKey::DidMethodKey(did_method_key) => Err(did_method_key),
}
}
}

impl TryFrom<DidKeyOrDidMethodKey> for DidMethodKey {
type Error = DidKey;

fn try_from(did_key_or_did_method_key: DidKeyOrDidMethodKey) -> Result<Self, Self::Error> {
match did_key_or_did_method_key {
DidKeyOrDidMethodKey::DidKey(did_key) => Err(did_key),
DidKeyOrDidMethodKey::DidMethodKey(did_method_key) => Ok(did_method_key),
}
}
}

impl<Target, Authorizer> AuthorizeTarget<Target, DidKeyOrDidMethodKey> for Authorizer
where
Authorizer: AuthorizeTarget<Target, DidKey>
+ AuthorizeTarget<Target, DidMethodKey>
+ Into<DidOrDidMethodKey>
+ Clone,
Authorizer: AuthorizeTarget<Target, DidKey> + AuthorizeTarget<Target, DidMethodKey>,
{
fn ensure_authorizes_target<T, A>(
&self,
key: &DidKeyOrDidMethodKey,
action: &A,
) -> Result<(), Error<T>>
) -> Result<(), super::Error<T>>
where
T: Config,
T: super::Config,
A: Action<Target = Target>,
{
match key {
DidKeyOrDidMethodKey::DidKey(did_key) => {
let self_did: Did = self
.clone()
.into()
.try_into()
.map_err(|_| Error::<T>::ExpectedDid)?;

self_did.ensure_authorizes_target(did_key, action)?;
self.ensure_authorizes_target(did_key, action)
}
DidKeyOrDidMethodKey::DidKey(did_key) => self.ensure_authorizes_target(did_key, action),
DidKeyOrDidMethodKey::DidMethodKey(did_method_key) => {
let self_did_method_key: DidMethodKey = self
.clone()
.into()
.try_into()
.map_err(|_| Error::<T>::ExpectedDidMethodKey)?;

self_did_method_key.ensure_authorizes_target(did_method_key, action)?;
self.ensure_authorizes_target(did_method_key, action)
}
}
}
}

/// Either `DidKey` or `DidMethodKey`.
pub enum DidKeyOrDidMethodKey {
DidKey(DidKey),
DidMethodKey(DidMethodKey),
}

/// `DID`'s signature along with the used `DID`s key reference.
#[derive(Encode, Decode, Debug, Clone, PartialEq, Eq, MaxEncodedLen)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
Expand Down
35 changes: 25 additions & 10 deletions pallets/core/src/modules/master/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,11 @@
#[cfg(feature = "serde")]
use crate::util::btree_set;
use crate::{
common::{signatures::ForSigType, Authorization, AuthorizeSignedAction, Limits, Types},
did::{self, Did, DidSignature},
common::{
signatures::ForSigType, Authorization, AuthorizeSignedAction, AuthorizeTarget, Limits,
Types,
},
did::{self, Did, DidKey, DidSignature},
util::WithNonce,
};
use alloc::{boxed::Box, collections::BTreeMap, vec::Vec};
Expand Down Expand Up @@ -101,10 +104,22 @@ mod tests;
#[scale_info(omit_prefix)]
pub struct Membership<T: Limits> {
#[cfg_attr(feature = "serde", serde(with = "btree_set"))]
pub members: BoundedBTreeSet<Did, T::MaxMasterMembers>,
pub members: BoundedBTreeSet<Master, T::MaxMasterMembers>,
pub vote_requirement: u64,
}

/// Master `DID`.
#[derive(Encode, Decode, Clone, Debug, Copy, PartialEq, Eq, Ord, PartialOrd, MaxEncodedLen)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[derive(scale_info_derive::TypeInfo)]
#[scale_info(omit_prefix)]
pub struct Master(pub Did);

crate::impl_wrapper!(Master(Did));

impl AuthorizeTarget<(), DidKey> for Master {}

impl<T: Limits> Default for Membership<T> {
fn default() -> Self {
Membership {
Expand Down Expand Up @@ -151,7 +166,7 @@ const MIN_WEIGHT: Weight = Weight::from_ref_time(10_000);

/// Minimum weight for master's extrinsics. Considers cost of signature verification and update to round no
fn get_min_weight_for_execute<T: Types>(
auth: &[WithNonce<T, DidSignature<Did>>],
auth: &[WithNonce<T, DidSignature<Master>>],
db_weights: RuntimeDbWeight,
) -> Weight {
MIN_WEIGHT
Expand Down Expand Up @@ -186,11 +201,11 @@ pub mod pallet {
pub enum Event<T: Config> {
/// A proposal succeeded and was executed. The dids listed are the members whose votes were
/// used as proof of authorization. The executed call is provided.
Executed(Vec<Did>, Box<<T as Config>::Call>),
Executed(Vec<Master>, Box<<T as Config>::Call>),
/// The membership of Master has changed.
UnderNewOwnership,
/// A proposal failed to execute
ExecutionFailed(Vec<Did>, Box<<T as Config>::Call>, DispatchError),
ExecutionFailed(Vec<Master>, Box<<T as Config>::Call>, DispatchError),
}

#[pallet::config]
Expand Down Expand Up @@ -236,7 +251,7 @@ pub mod pallet {
pub fn execute(
origin: OriginFor<T>,
proposal: Box<<T as Config>::Call>,
auth: Vec<WithNonce<T, DidSignature<Did>>>,
auth: Vec<WithNonce<T, DidSignature<Master>>>,
) -> DispatchResultWithPostInfo {
ensure_signed(origin)?;

Expand All @@ -258,7 +273,7 @@ pub mod pallet {
pub fn execute_unchecked_weight(
origin: OriginFor<T>,
proposal: Box<<T as Config>::Call>,
auth: Vec<WithNonce<T, DidSignature<Did>>>,
auth: Vec<WithNonce<T, DidSignature<Master>>>,
_weight: Weight,
) -> DispatchResultWithPostInfo {
ensure_signed(origin)?;
Expand Down Expand Up @@ -326,7 +341,7 @@ pub mod pallet {
/// in this case
fn execute_(
proposal: Box<<T as Config>::Call>,
auth: Vec<WithNonce<T, DidSignature<Did>>>,
auth: Vec<WithNonce<T, DidSignature<Master>>>,
given_weight: Option<Weight>,
) -> DispatchResultWithPostInfo {
// check
Expand Down Expand Up @@ -380,7 +395,7 @@ pub mod pallet {

// The nonce of each DID must be updated
for (signer, did_details) in new_did_details {
did::Pallet::<T>::insert_did_details(signer, did_details);
did::Pallet::<T>::insert_did_details(*signer, did_details);
}

// Weight from dispatch's declaration. If dispatch does not return a weight in `PostDispatchInfo`,
Expand Down
Loading

0 comments on commit df00a81

Please sign in to comment.