Skip to content

Commit

Permalink
Tests completed
Browse files Browse the repository at this point in the history
  • Loading branch information
ntn-x2 committed Jan 10, 2025
1 parent f81762e commit f28c46f
Show file tree
Hide file tree
Showing 8 changed files with 453 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,14 @@

// If you feel like getting in touch with us, you can do so at [email protected]

#[cfg(test)]
mod tests;

use sp_std::marker::PhantomData;
use sp_weights::Weight;

use crate::{Config, DidIdentifierOf};

pub trait DidLifecycleHooks<T>
where
T: Config,
{
type DeletionHook: DidDeletionHook<T>;
}

impl<T> DidLifecycleHooks<T> for ()
where
T: Config,
{
type DeletionHook = ();
}

pub trait DidDeletionHook<T>
where
T: Config,
Expand Down
80 changes: 80 additions & 0 deletions pallets/did/src/traits/lifecycle_hooks/deletion/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// KILT Blockchain – https://botlabs.org
// Copyright (C) 2019-2024 BOTLabs GmbH

// The KILT Blockchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The KILT Blockchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// If you feel like getting in touch with us, you can do so at [email protected]

use sp_runtime::AccountId32;
use sp_weights::Weight;

use crate::{
traits::lifecycle_hooks::{deletion::EvaluateAll, mock::TestRuntime, DidDeletionHook},
DidIdentifierOf,
};

struct False;

impl DidDeletionHook<TestRuntime> for False {
const MAX_WEIGHT: Weight = Weight::from_all(10);

fn can_delete(_did: &DidIdentifierOf<TestRuntime>) -> Result<(), Weight> {
Err(Weight::from_all(5))
}
}

struct True;

impl DidDeletionHook<TestRuntime> for True {
const MAX_WEIGHT: Weight = Weight::from_all(20);

fn can_delete(did: &DidIdentifierOf<TestRuntime>) -> Result<(), Weight> {
Ok(())
}
}

#[test]
fn first_false() {
type TestSubject = EvaluateAll<False, True>;

// Max weight is the sum.
assert_eq!(TestSubject::MAX_WEIGHT, Weight::from_all(30));
// Failure consumes `False`'s weight.
assert_eq!(
TestSubject::can_delete(&AccountId32::new([0u8; 32])),
Err(Weight::from_all(5))
);
}

#[test]
fn second_false() {
type TestSubject = EvaluateAll<True, False>;

// Max weight is the sum.
assert_eq!(TestSubject::MAX_WEIGHT, Weight::from_all(30));
// Failure consumes the sum of `True`'s max weight and `False`'s weight.
assert_eq!(
TestSubject::can_delete(&AccountId32::new([0u8; 32])),
Err(Weight::from_all(25))
);
}

#[test]
fn both_true() {
type TestSubject = EvaluateAll<True, True>;

// Max weight is the sum.
assert_eq!(TestSubject::MAX_WEIGHT, Weight::from_all(40));
assert_eq!(TestSubject::can_delete(&AccountId32::new([0u8; 32])), Ok(()));
}
199 changes: 199 additions & 0 deletions pallets/did/src/traits/lifecycle_hooks/mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
// KILT Blockchain – https://botlabs.org
// Copyright (C) 2019-2024 BOTLabs GmbH

// The KILT Blockchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The KILT Blockchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// If you feel like getting in touch with us, you can do so at [email protected]

use frame_support::{
construct_runtime,
dispatch::DispatchResult,
parameter_types,
traits::{
fungible::{Balanced, Dust, Inspect, InspectHold, Mutate, MutateHold, Unbalanced, UnbalancedHold},
tokens::{DepositConsequence, Fortitude, Preservation, Provenance, WithdrawConsequence},
},
};
use frame_system::{mocking::MockBlock, EnsureSigned};
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_core::{ConstU32, ConstU64, H256};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
AccountId32, DispatchError,
};

use crate::{
Config, DeriveDidCallAuthorizationVerificationKeyRelationship, DeriveDidCallKeyRelationshipResult,
DidVerificationKeyRelationship,
};

construct_runtime!(
pub enum TestRuntime
{
System: frame_system,
Did: crate,
}
);

impl frame_system::Config for TestRuntime {
type AccountData = ();
type AccountId = AccountId32;
type BaseCallFilter = ();
type Block = MockBlock<TestRuntime>;
type BlockHashCount = ConstU64<1>;
type BlockLength = ();
type BlockWeights = ();
type DbWeight = ();
type Hash = H256;
type Hashing = BlakeTwo256;
type Lookup = IdentityLookup<Self::AccountId>;
type MaxConsumers = ConstU32<1>;
type Nonce = u64;
type OnKilledAccount = ();
type OnNewAccount = ();
type OnSetCode = ();
type PalletInfo = PalletInfo;
type RuntimeEvent = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type RuntimeTask = ();
type SS58Prefix = ();
type SystemWeightInfo = ();
type Version = ();
}

pub struct MockCurrency;

impl MutateHold<AccountId32> for MockCurrency {}

impl UnbalancedHold<AccountId32> for MockCurrency {
fn set_balance_on_hold(_reason: &Self::Reason, _who: &AccountId32, _amount: Self::Balance) -> DispatchResult {
Ok(())
}
}

impl InspectHold<AccountId32> for MockCurrency {
type Reason = RuntimeHoldReason;

fn total_balance_on_hold(_who: &AccountId32) -> Self::Balance {
Self::Balance::default()
}

fn balance_on_hold(_reason: &Self::Reason, _who: &AccountId32) -> Self::Balance {
Self::Balance::default()
}
}

impl Mutate<AccountId32> for MockCurrency {}

impl Inspect<AccountId32> for MockCurrency {
type Balance = u64;

fn active_issuance() -> Self::Balance {
Self::Balance::default()
}

fn balance(_who: &AccountId32) -> Self::Balance {
Self::Balance::default()
}

fn can_deposit(_who: &AccountId32, _amount: Self::Balance, _provenance: Provenance) -> DepositConsequence {
DepositConsequence::Success
}

fn can_withdraw(_who: &AccountId32, _amount: Self::Balance) -> WithdrawConsequence<Self::Balance> {
WithdrawConsequence::Success
}

fn minimum_balance() -> Self::Balance {
Self::Balance::default()
}

fn reducible_balance(_who: &AccountId32, _preservation: Preservation, _force: Fortitude) -> Self::Balance {
Self::Balance::default()
}

fn total_balance(_who: &AccountId32) -> Self::Balance {
Self::Balance::default()
}

fn total_issuance() -> Self::Balance {
Self::Balance::default()
}
}

impl Unbalanced<AccountId32> for MockCurrency {
fn handle_dust(_dust: Dust<AccountId32, Self>) {}

fn write_balance(_who: &AccountId32, _amount: Self::Balance) -> Result<Option<Self::Balance>, DispatchError> {
Ok(Some(Self::Balance::default()))
}

fn set_total_issuance(_amount: Self::Balance) {}
}

impl Balanced<AccountId32> for MockCurrency {
type OnDropDebt = ();
type OnDropCredit = ();
}

parameter_types! {
#[derive(TypeInfo, Debug, PartialEq, Eq, Clone, Encode, Decode)]
pub const MaxNewKeyAgreementKeys: u32 = 1;
#[derive(TypeInfo, Debug, PartialEq, Eq, Clone, Encode, Decode)]
pub const MaxTotalKeyAgreementKeys: u32 = 1;
}

impl DeriveDidCallAuthorizationVerificationKeyRelationship for RuntimeCall {
fn derive_verification_key_relationship(&self) -> DeriveDidCallKeyRelationshipResult {
Ok(DidVerificationKeyRelationship::Authentication)
}

#[cfg(feature = "runtime-benchmarks")]
fn get_call_for_did_call_benchmark() -> Self {
Self::System(frame_system::Call::remark {
remark: b"test".to_vec(),
})
}
}

impl Config for TestRuntime {
type BalanceMigrationManager = ();
type BaseDeposit = ConstU64<1>;
type Currency = MockCurrency;
type DidIdentifier = AccountId32;
type DidLifecycleHooks = ();
type EnsureOrigin = EnsureSigned<AccountId32>;
type Fee = ConstU64<1>;
type FeeCollector = ();
type KeyDeposit = ConstU64<1>;
type MaxBlocksTxValidity = ConstU64<1>;
type MaxNewKeyAgreementKeys = MaxNewKeyAgreementKeys;
type MaxNumberOfServicesPerDid = ConstU32<1>;
type MaxNumberOfTypesPerService = ConstU32<1>;
type MaxNumberOfUrlsPerService = ConstU32<1>;
type MaxPublicKeysPerDid = ConstU32<1>;
type MaxServiceIdLength = ConstU32<1>;
type MaxServiceTypeLength = ConstU32<1>;
type MaxServiceUrlLength = ConstU32<1>;
type MaxTotalKeyAgreementKeys = MaxTotalKeyAgreementKeys;
type OriginSuccess = AccountId32;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = ();
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeOrigin = RuntimeOrigin;
type ServiceEndpointDeposit = ConstU64<1>;
type WeightInfo = ();
}
41 changes: 41 additions & 0 deletions pallets/did/src/traits/lifecycle_hooks/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// KILT Blockchain – https://botlabs.org
// Copyright (C) 2019-2024 BOTLabs GmbH

// The KILT Blockchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The KILT Blockchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// If you feel like getting in touch with us, you can do so at [email protected]

pub mod deletion;
pub use deletion::DidDeletionHook;

// We need this mock since the trait requires the implementation of the did's
// `Config` trait.
#[cfg(test)]
mod mock;

use crate::Config;

pub trait DidLifecycleHooks<T>
where
T: Config,
{
type DeletionHook: DidDeletionHook<T>;
}

impl<T> DidLifecycleHooks<T> for ()
where
T: Config,
{
type DeletionHook = ();
}
20 changes: 20 additions & 0 deletions pallets/did/src/traits/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// KILT Blockchain – https://botlabs.org
// Copyright (C) 2019-2024 BOTLabs GmbH

// The KILT Blockchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The KILT Blockchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// If you feel like getting in touch with us, you can do so at [email protected]

mod lifecycle_hooks;
pub use lifecycle_hooks::{deletion, DidDeletionHook, DidLifecycleHooks};
2 changes: 1 addition & 1 deletion runtimes/common/src/did/deletion_hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ where
const MAX_WEIGHT: Weight = Weight::from_parts(READ_WEIGHT_TIME, READ_WEIGHT_SIZE);

fn can_delete(did: &did::DidIdentifierOf<T>) -> Result<(), Weight> {
if pallet_web3_names::Names::<T, Web3NameDeployment>::contains_key(did) {
if !pallet_web3_names::Names::<T, Web3NameDeployment>::contains_key(did) {
Ok(())
} else {
Err(<Self as did::traits::DidDeletionHook<T>>::MAX_WEIGHT)
Expand Down
Loading

0 comments on commit f28c46f

Please sign in to comment.