Skip to content

Commit

Permalink
feat/removing vali blacklist (#227)
Browse files Browse the repository at this point in the history
* feat: removing validator blacklist

* fix: removing validator blacklist and tranfering proposal rewards from treasury
  • Loading branch information
functor-flow authored Sep 18, 2024
1 parent a1fa029 commit 11959f4
Show file tree
Hide file tree
Showing 6 changed files with 13 additions and 170 deletions.
15 changes: 7 additions & 8 deletions pallets/governance/src/proposal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,7 @@ fn distribute_proposal_rewards<T: crate::Config>(
) {
use frame_support::sp_runtime::traits::IntegerSquareRoot;

let dao_treasury_address = DaoTreasuryAddress::<T>::get();
let account_sqrt_stakes: Vec<_> = account_stakes
.into_iter()
.map(|(acc_id, stake)| (acc_id, stake.integer_sqrt()))
Expand All @@ -630,14 +631,12 @@ fn distribute_proposal_rewards<T: crate::Config>(
let percentage = I92F36::from_num(stake).checked_div(total_stake).unwrap_or_default();

let reward: u64 = total_allocation.checked_mul(percentage).unwrap_or_default().to_num();
let reward = match pallet_subspace::Pallet::<T>::u64_to_balance(reward) {
Some(balance) => balance,
None => {
log::error!("could not transform {reward} into T::Balance");
continue;
}
};

pallet_subspace::Pallet::<T>::add_balance_to_account(&acc_id, reward);
// Transfer the proposal reward to the accounts from treasury
let _ = PalletSubspace::<T>::transfer_balance_to_account(
&dao_treasury_address,
&acc_id,
reward,
);
}
}
19 changes: 6 additions & 13 deletions pallets/subnet_emission/src/subnet_consensus/yuma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use frame_support::{ensure, weights::Weight, DebugNoBound};
use pallet_subspace::{
math::*, Active, Bonds, BondsMovingAverage, Config, Consensus, Dividends, Emission, Founder,
Incentive, Kappa, Keys, LastUpdate, MaxAllowedValidators, MaxWeightAge,
Pallet as PalletSubspace, PruningScores, Rank, Trust, Uids, ValidatorBlacklist,
ValidatorPermits, ValidatorTrust, Vec, Weights, N,
Pallet as PalletSubspace, PruningScores, Rank, Trust, Uids, ValidatorPermits, ValidatorTrust,
Vec, Weights, N,
};
use sp_std::vec;
use substrate_fixed::types::{I32F32, I64F64, I96F32};
Expand Down Expand Up @@ -115,8 +115,7 @@ impl<T: Config> YumaEpoch<T> {
let max_validators = self.max_allowed_validators;
let mut new_permits = vec![false; stake.as_ref().len()];

let mut sorted_indexed_stake: Vec<(u16, T::AccountId, u64)> = (0u16..(stake.as_ref().len()
as u16))
let mut sorted_indexed_stake: Vec<(u16, u64)> = (0u16..(stake.as_ref().len() as u16))
.map(|idx| {
self.weight_counter.read(1);
let key = match PalletSubspace::<T>::get_key_for_uid(self.netuid, idx) {
Expand All @@ -126,28 +125,22 @@ impl<T: Config> YumaEpoch<T> {

self.weight_counter.read(1);
let stake = PalletSubspace::<T>::get_delegated_stake(&key);
Ok((idx, key, stake))
Ok((idx, stake))
})
.collect::<Result<Vec<_>, EmissionError>>()?;
sorted_indexed_stake.sort_by_key(|(_, _, stake)| *stake);
sorted_indexed_stake.sort_by_key(|(_, stake)| *stake);
sorted_indexed_stake.reverse();

let blacklist = ValidatorBlacklist::<T>::get(self.netuid);
self.weight_counter.read(1);
let current_block = PalletSubspace::<T>::get_current_block_number();
self.weight_counter.read(1);
let min_stake = pallet_subspace::MinValidatorStake::<T>::get(self.netuid);
self.weight_counter.read(1);
let mut validator_count = 0;
for (idx, key, stake) in sorted_indexed_stake {
for (idx, stake) in sorted_indexed_stake {
if max_validators.is_some_and(|max| max <= validator_count) {
break;
}

if blacklist.contains(&key) {
continue;
}

if stake < min_stake {
continue;
}
Expand Down
18 changes: 0 additions & 18 deletions pallets/subspace/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,22 +251,4 @@ benchmarks! {
);
}: register_subnet(RawOrigin::Signed(key.clone()), "testnet".as_bytes().to_vec(), Some(b"testmetadata".to_vec()))

add_blacklist {
let owner: T::AccountId = account("Alice", 0, 1);
let stake = 100000000000000u64;
let blacklisted: T::AccountId = account("Module", 0, 2);
register_mock::<T>(owner.clone(), owner.clone(), b"owner".to_vec()).unwrap();
register_mock::<T>(owner.clone(), owner.clone(), b"blacklisted".to_vec()).unwrap();
let netuid = SubspaceMod::<T>::get_netuid_for_name(b"testnet").unwrap();
}: add_blacklist(RawOrigin::Signed(owner), netuid, blacklisted)

remove_blacklist {
let owner: T::AccountId = account("Alice", 0, 1);
let stake = 100000000000000u64;
let blacklisted: T::AccountId = account("Module", 0, 2);
register_mock::<T>(owner.clone(), owner.clone(), b"owner".to_vec()).unwrap();
register_mock::<T>(owner.clone(), owner.clone(), b"blacklisted".to_vec()).unwrap();
let netuid = SubspaceMod::<T>::get_netuid_for_name(b"testnet").unwrap();
SubspaceMod::<T>::add_blacklist(RawOrigin::Signed(owner.clone()).into(), netuid, blacklisted.clone()).unwrap();
}: remove_blacklist(RawOrigin::Signed(owner), netuid, blacklisted)
}
29 changes: 0 additions & 29 deletions pallets/subspace/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,10 +421,6 @@ pub mod pallet {
FloorFounderShare::<T>::get() as u16
}

#[pallet::storage]
pub type ValidatorBlacklist<T: Config> =
StorageMap<_, Identity, u16, BTreeSet<T::AccountId>, ValueQuery>;

// ---------------------------------
// Module Variables
// ---------------------------------
Expand Down Expand Up @@ -716,10 +712,6 @@ pub mod pallet {
InvalidMinValidatorStake,
/// The maximum allowed validators value is invalid, minimum is 10.
InvalidMaxAllowedValidators,
/// Module is already on the subnet blacklist
AlreadyBlacklisted,
/// Module is not on the subnet blacklist
NotBlacklisted,
}

// ---------------------------------
Expand Down Expand Up @@ -1047,29 +1039,8 @@ pub mod pallet {
) -> DispatchResult {
Self::do_register_subnet(origin, name, metadata)
}

#[pallet::call_index(13)]
#[pallet::weight((T::WeightInfo::delegate_rootnet_control(), DispatchClass::Normal, Pays::No))]
pub fn add_blacklist(
origin: OriginFor<T>,
netuid: u16,
module: T::AccountId,
) -> DispatchResult {
Self::do_add_blacklist(origin, netuid, module)
}

#[pallet::call_index(14)]
#[pallet::weight((T::WeightInfo::delegate_rootnet_control(), DispatchClass::Normal, Pays::No))]
pub fn remove_blacklist(
origin: OriginFor<T>,
netuid: u16,
module: T::AccountId,
) -> DispatchResult {
Self::do_remove_blacklist(origin, netuid, module)
}
}
}

impl<T: Config> Pallet<T> {
/// Returns the total amount staked by the given key to other keys.
#[inline]
Expand Down
38 changes: 0 additions & 38 deletions pallets/subspace/src/subnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,42 +564,4 @@ impl<T: Config> Pallet<T> {
Some(SubnetConsensus::Root)
)
}

pub fn do_add_blacklist(
origin: T::RuntimeOrigin,
netuid: u16,
module: T::AccountId,
) -> DispatchResult {
let key = ensure_signed(origin)?;

let params = Self::subnet_params(netuid);
ensure!(params.founder == key, Error::<T>::NotFounder);

let mut blacklist = ValidatorBlacklist::<T>::get(netuid);
ensure!(!blacklist.contains(&module), Error::<T>::AlreadyBlacklisted);

blacklist.insert(module);
ValidatorBlacklist::<T>::set(netuid, blacklist);

Ok(())
}

pub fn do_remove_blacklist(
origin: T::RuntimeOrigin,
netuid: u16,
module: T::AccountId,
) -> DispatchResult {
let key = ensure_signed(origin)?;

let params = Self::subnet_params(netuid);
ensure!(params.founder == key, Error::<T>::NotFounder);

let mut blacklist = ValidatorBlacklist::<T>::get(netuid);
ensure!(blacklist.contains(&module), Error::<T>::NotBlacklisted);

blacklist.remove(&module);
ValidatorBlacklist::<T>::set(netuid, blacklist);

Ok(())
}
}
64 changes: 0 additions & 64 deletions tests/src/subnet_emission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,67 +1260,3 @@ fn yuma_change_permits() {
);
});
}

#[test]
fn yuma_change_permits_blacklisted() {
new_test_ext().execute_with(|| {
zero_min_burn();

let netuid = 6;
let first_uid = register_module(netuid, 0, 1, false).unwrap();
let second_uid = register_module(netuid, 1, to_nano(51000), false).unwrap();
let third_uid = register_module(netuid, 2, to_nano(52000), false).unwrap();

dbg!(ValidatorBlacklist::<Test>::get(netuid));
pallet_subspace::Pallet::<Test>::add_blacklist(
get_origin(first_uid.into()),
netuid,
third_uid.into(),
)
.unwrap();

dbg!(ValidatorBlacklist::<Test>::get(netuid));

MaxAllowedValidators::<Test>::set(netuid, Some(2));

set_weights(netuid, 2, vec![first_uid, second_uid], vec![50, 60]);

assert_ok!(YumaEpoch::<Test>::new(netuid, ONE).run());

assert_eq!(
ValidatorPermits::<Test>::get(netuid)[first_uid as usize],
false
);
assert_eq!(
ValidatorPermits::<Test>::get(netuid)[second_uid as usize],
false
);
assert_eq!(
ValidatorPermits::<Test>::get(netuid)[third_uid as usize],
false
);

let fourth_uid = register_module(netuid, 3, to_nano(54000), false).unwrap();
set_weights(netuid, 1, vec![third_uid, fourth_uid], vec![50, 60]);
set_weights(netuid, 3, vec![first_uid, second_uid], vec![50, 60]);

assert_ok!(YumaEpoch::<Test>::new(netuid, ONE).run());

assert_eq!(
ValidatorPermits::<Test>::get(netuid)[first_uid as usize],
false
);
assert_eq!(
ValidatorPermits::<Test>::get(netuid)[second_uid as usize],
true
);
assert_eq!(
ValidatorPermits::<Test>::get(netuid)[third_uid as usize],
false
);
assert_eq!(
ValidatorPermits::<Test>::get(netuid)[fourth_uid as usize],
true
);
});
}

0 comments on commit 11959f4

Please sign in to comment.