Skip to content

Commit

Permalink
complete tests
Browse files Browse the repository at this point in the history
  • Loading branch information
1xstj committed Jan 24, 2024
1 parent df02694 commit 0dfb264
Show file tree
Hide file tree
Showing 6 changed files with 231 additions and 53 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

193 changes: 175 additions & 18 deletions pallets/jobs/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::*;
use frame_support::{assert_noop, assert_ok};
use mock::*;

use pallet_roles::profile::{Profile, Record, SharedRestakeProfile};
use pallet_roles::profile::{IndependentRestakeProfile, Profile, Record, SharedRestakeProfile};
use tangle_primitives::{
jobs::{
DKGTSSPhaseOneJobType, DKGTSSPhaseTwoJobType, DKGTSSSignatureResult, DigitalSignatureType,
Expand All @@ -28,6 +28,7 @@ use tangle_primitives::{
},
roles::{RoleType, ThresholdSignatureRoleType, ZeroKnowledgeRoleType},
};

const ALICE: u8 = 1;
const BOB: u8 = 2;
const CHARLIE: u8 = 3;
Expand All @@ -41,7 +42,10 @@ const HUNDRED: u8 = 100;
pub fn shared_profile() -> Profile<Runtime> {
let profile = SharedRestakeProfile {
records: BoundedVec::try_from(vec![
Record { role: RoleType::Tss(ThresholdSignatureRoleType::TssGG20), amount: None },
Record {
role: RoleType::Tss(ThresholdSignatureRoleType::ZengoGG20Secp256k1),
amount: None,
},
Record { role: RoleType::ZkSaaS(ZeroKnowledgeRoleType::ZkSaaSGroth16), amount: None },
])
.unwrap(),
Expand Down Expand Up @@ -511,19 +515,172 @@ fn jobs_submission_e2e_works_for_zksaas() {
});
}

// #[test]
// fn withdraw_validator_rewards_works() {
// new_test_ext(vec![ALICE, BOB, CHARLIE, DAVE, EVE]).execute_with(|| {
// System::set_block_number(1);
//
// ValidatorRewards::<Runtime>::insert(1, 100);
// ValidatorRewards::<Runtime>::insert(2, 100);
// ValidatorRewards::<Runtime>::insert(3, 100);
//
// // can withdraw the reward by validator
// for validator in [1, 2, 3] {
// assert_ok!(Jobs::withdraw_rewards(RuntimeOrigin::signed(validator)));
// assert_eq!(ValidatorRewards::<Runtime>::get(validator), None);
// }
// });
// }
#[test]
fn jobs_validator_checks_work() {
new_test_ext(vec![ALICE, BOB, CHARLIE, DAVE, EVE]).execute_with(|| {
Balances::make_free_balance_be(&mock_pub_key(TEN), 100);

let participants = vec![ALICE, BOB, CHARLIE, DAVE, EVE];

// all validators sign up in roles pallet
let profile = shared_profile();
for validator in participants.clone() {
assert_ok!(Roles::create_profile(
RuntimeOrigin::signed(mock_pub_key(validator)),
profile.clone()
));
}

// submit job with existing validators
let threshold_signature_role_type = ThresholdSignatureRoleType::ZengoGG20Secp256k1;
let submission = JobSubmission {
expiry: 10,
ttl: 200,
job_type: JobType::DKGTSSPhaseOne(DKGTSSPhaseOneJobType {
participants: participants.clone().iter().map(|x| mock_pub_key(*x)).collect(),
threshold: 3,
permitted_caller: Some(mock_pub_key(TEN)),
role_type: threshold_signature_role_type,
}),
};
assert_ok!(Jobs::submit_job(RuntimeOrigin::signed(mock_pub_key(TEN)), submission));

// ======= active validator cannot reduce stake ===============
let reduced_profile = SharedRestakeProfile {
records: BoundedVec::try_from(vec![
Record {
role: RoleType::Tss(ThresholdSignatureRoleType::ZengoGG20Secp256k1),
amount: None,
},
Record {
role: RoleType::ZkSaaS(ZeroKnowledgeRoleType::ZkSaaSGroth16),
amount: None,
},
])
.unwrap(),
amount: 500, // reduce stake by 50%
};

for validator in participants.clone() {
assert_noop!(
Roles::update_profile(
RuntimeOrigin::signed(mock_pub_key(validator)),
Profile::Shared(reduced_profile.clone())
),
pallet_roles::Error::<Runtime>::InsufficientRestakingBond
);
}

// ========= active validator cannot delete profile with active job =============
for validator in participants.clone() {
assert_noop!(
Roles::delete_profile(RuntimeOrigin::signed(mock_pub_key(validator)),),
pallet_roles::Error::<Runtime>::ProfileDeleteRequestFailed
);
}

// ========= active validator cannot remove role with active job =============
let reduced_profile = SharedRestakeProfile {
records: BoundedVec::try_from(vec![Record {
role: RoleType::ZkSaaS(ZeroKnowledgeRoleType::ZkSaaSGroth16),
amount: None,
}])
.unwrap(),
amount: 500, // reduce stake by 50%
};
for validator in participants.clone() {
assert_noop!(
Roles::update_profile(
RuntimeOrigin::signed(mock_pub_key(validator)),
Profile::Shared(reduced_profile.clone())
),
pallet_roles::Error::<Runtime>::RoleCannotBeRemoved
);
}

// ========= active validator can remove role without active job =========
let reduced_profile = SharedRestakeProfile {
records: BoundedVec::try_from(vec![Record {
role: RoleType::Tss(ThresholdSignatureRoleType::ZengoGG20Secp256k1),
amount: None,
}])
.unwrap(),
amount: 1000,
};

for validator in participants.clone() {
assert_ok!(Roles::update_profile(
RuntimeOrigin::signed(mock_pub_key(validator)),
Profile::Shared(reduced_profile.clone())
));
}

// ========= active validator can add a new role with current active role =========
let updated_profile = SharedRestakeProfile {
records: BoundedVec::try_from(vec![
Record {
role: RoleType::Tss(ThresholdSignatureRoleType::ZengoGG20Secp256k1),
amount: None,
},
Record {
role: RoleType::ZkSaaS(ZeroKnowledgeRoleType::ZkSaaSGroth16),
amount: None,
},
])
.unwrap(),
amount: 1000,
};

for validator in participants.clone() {
assert_ok!(Roles::update_profile(
RuntimeOrigin::signed(mock_pub_key(validator)),
Profile::Shared(updated_profile.clone())
));
}

// ========= active validator can increase stake with current active role =========
let updated_profile = SharedRestakeProfile {
records: BoundedVec::try_from(vec![
Record {
role: RoleType::Tss(ThresholdSignatureRoleType::ZengoGG20Secp256k1),
amount: None,
},
Record {
role: RoleType::ZkSaaS(ZeroKnowledgeRoleType::ZkSaaSGroth16),
amount: None,
},
])
.unwrap(),
amount: 1500,
};

for validator in participants.clone() {
assert_ok!(Roles::update_profile(
RuntimeOrigin::signed(mock_pub_key(validator)),
Profile::Shared(updated_profile.clone())
));
}

// ========= active validator can reduce stake on non active role =========
let updated_profile = IndependentRestakeProfile {
records: BoundedVec::try_from(vec![
Record {
role: RoleType::Tss(ThresholdSignatureRoleType::ZengoGG20Secp256k1),
amount: Some(1500),
},
Record {
role: RoleType::ZkSaaS(ZeroKnowledgeRoleType::ZkSaaSGroth16),
amount: Some(500), // reduced by 3x
},
])
.unwrap(),
};

for validator in participants.clone() {
assert_ok!(Roles::update_profile(
RuntimeOrigin::signed(mock_pub_key(validator)),
Profile::Independent(updated_profile.clone())
));
}
});
}
2 changes: 2 additions & 0 deletions pallets/roles/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ serde_json = { workspace = true }
sp-core = { workspace = true }
sp-runtime = { workspace = true }
hex = { workspace = true }
pallet-jobs = { workspace = true }

[features]
default = ["std"]
Expand All @@ -60,6 +61,7 @@ std = [
"tangle-primitives/std",
"tangle-crypto-primitives/std",
"frame-election-provider-support/std",
"pallet-jobs/std"
]

try-runtime = ["frame-support/try-runtime"]
Expand Down
15 changes: 3 additions & 12 deletions pallets/roles/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,23 +450,14 @@ pub mod pallet {
pallet_staking::Validators::<T>::contains_key(&stash_account),
Error::<T>::NotValidator
);
let mut ledger = Ledger::<T>::get(&stash_account).ok_or(Error::<T>::NoProfileFound)?;
let ledger = Ledger::<T>::get(&stash_account).ok_or(Error::<T>::NoProfileFound)?;

// Submit request to exit from all the services.
let active_jobs = T::JobsHandler::get_active_jobs(stash_account.clone());
let mut pending_jobs = Vec::new();
for job in active_jobs {
let role_type = job.0;
// Submit request to exit from the known set.
let res =
T::JobsHandler::exit_from_known_set(stash_account.clone(), role_type, job.1);

if res.is_err() {
pending_jobs.push((role_type, job.1));
} else {
// Remove role from the profile.
ledger.profile.remove_role_from_profile(role_type);
}
pending_jobs.push((role_type, job.1));
}

if !pending_jobs.is_empty() {
Expand All @@ -481,7 +472,7 @@ pub mod pallet {
// the moment.
Self::deposit_event(Event::<T>::PendingJobs { pending_jobs });
return Err(Error::<T>::ProfileDeleteRequestFailed.into())
};
}

Self::deposit_event(Event::<T>::ProfileDeleted { account: stash_account.clone() });

Expand Down
72 changes: 50 additions & 22 deletions pallets/roles/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ use frame_election_provider_support::{
use frame_support::{
construct_runtime, parameter_types,
traits::{ConstU128, ConstU32, ConstU64, Contains, Hooks},
PalletId,
};
use frame_system::EnsureSigned;
use pallet_session::historical as pallet_session_historical;
use sp_core::{
sr25519::{self, Signature},
Expand All @@ -43,7 +45,7 @@ use sp_staking::{
use tangle_crypto_primitives::crypto::AuthorityId as RoleKeyId;
use tangle_primitives::{
jobs::{
traits::{JobsHandler, MPCHandler},
traits::{JobToFee, JobsHandler, MPCHandler},
*,
},
roles::ValidatorRewardDistribution,
Expand Down Expand Up @@ -96,26 +98,6 @@ impl pallet_balances::Config for Runtime {
type MaxFreezes = ();
}

pub struct MockMPCHandler;

impl MPCHandler<AccountId, BlockNumber, Balance> for MockMPCHandler {
fn verify(_data: JobWithResult<AccountId>) -> DispatchResult {
Ok(())
}

fn verify_validator_report(
_validator: AccountId,
_offence: ValidatorOffenceType,
_signatures: Vec<Vec<u8>>,
) -> DispatchResult {
Ok(())
}

fn validate_authority_key(_validator: AccountId, _authority_key: Vec<u8>) -> DispatchResult {
Ok(())
}
}

type IdentificationTuple = (AccountId, AccountId);
type Offence = crate::offences::ValidatorOffence<IdentificationTuple>;

Expand Down Expand Up @@ -278,14 +260,59 @@ impl JobsHandler<AccountId> for MockJobsHandler {
}
}

pub struct MockJobToFeeHandler;

impl JobToFee<AccountId, BlockNumber> for MockJobToFeeHandler {
type Balance = Balance;

fn job_to_fee(_job: &JobSubmission<AccountId, BlockNumber>) -> Balance {
Default::default()
}
}

pub struct MockMPCHandler;

impl MPCHandler<AccountId, BlockNumber, Balance> for MockMPCHandler {
fn verify(_data: JobWithResult<AccountId>) -> DispatchResult {
Ok(())
}

fn verify_validator_report(
_validator: AccountId,
_offence: ValidatorOffenceType,
_signatures: Vec<Vec<u8>>,
) -> DispatchResult {
Ok(())
}

fn validate_authority_key(_validator: AccountId, _authority_key: Vec<u8>) -> DispatchResult {
Ok(())
}
}

parameter_types! {
pub const JobsPalletId: PalletId = PalletId(*b"py/jobss");
}

impl pallet_jobs::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ForceOrigin = EnsureSigned<AccountId>;
type Currency = Balances;
type JobToFee = MockJobToFeeHandler;
type RolesHandler = Roles;
type MPCHandler = MockMPCHandler;
type PalletId = JobsPalletId;
type WeightInfo = ();
}

parameter_types! {
pub InflationRewardPerSession: Balance = 10_000;
pub Reward : ValidatorRewardDistribution = ValidatorRewardDistribution::try_new(Percent::from_rational(1_u32,2_u32), Percent::from_rational(1_u32,2_u32)).unwrap();
}

impl Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type JobsHandler = MockJobsHandler;
type JobsHandler = Jobs;
type MaxRolesPerAccount = ConstU32<2>;
type MPCHandler = MockMPCHandler;
type InflationRewardPerSession = InflationRewardPerSession;
Expand All @@ -308,6 +335,7 @@ construct_runtime!(
Session: pallet_session,
Staking: pallet_staking,
Historical: pallet_session_historical,
Jobs: pallet_jobs
}
);

Expand Down
1 change: 0 additions & 1 deletion pallets/roles/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,6 @@ fn test_create_profile_should_fail_if_min_required_restake_condition_is_not_met_
#[test]
fn test_update_profile_from_independent_to_shared() {
new_test_ext(vec![1, 2, 3, 4]).execute_with(|| {
println!("{:?}", pallet::MinRestakingBond::<Runtime>::get());
// Lets create independent profile.
let profile = independent_profile();
assert_ok!(Roles::create_profile(RuntimeOrigin::signed(mock_pub_key(1)), profile.clone()));
Expand Down

0 comments on commit 0dfb264

Please sign in to comment.