Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow swap of hotkeys on registered coldkeys #192

Merged
merged 8 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions pallets/subtensor/src/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -547,4 +547,32 @@ benchmarks! {
Subtensor::<T>::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap());
assert_ok!(Subtensor::<T>::register_network(RawOrigin::Signed(coldkey.clone()).into()));
}: dissolve_network(RawOrigin::Signed(coldkey), 1)

swap_hotkey {
let seed: u32 = 1;
let coldkey: T::AccountId = account("Alice", 0, seed);
let old_hotkey: T::AccountId = account("Bob", 0, seed);
let new_hotkey: T::AccountId = account("Charlie", 0, seed);

let netuid = 1u16;
Subtensor::<T>::init_new_network(netuid, 100);
Subtensor::<T>::set_min_burn(netuid, 1);
Subtensor::<T>::set_max_burn(netuid, 1);
Subtensor::<T>::set_target_registrations_per_interval(netuid, 256);
Subtensor::<T>::set_max_registrations_per_block(netuid, 256);

Subtensor::<T>::add_balance_to_coldkey_account(&coldkey.clone(), Subtensor::<T>::u64_to_balance(10_000_000_000).unwrap());
assert_ok!(Subtensor::<T>::burned_register(RawOrigin::Signed(coldkey.clone()).into(), netuid, old_hotkey.clone()));
assert_ok!(Subtensor::<T>::become_delegate(RawOrigin::Signed(coldkey.clone()).into(), old_hotkey.clone()));

let max_uids = Subtensor::<T>::get_max_allowed_uids(netuid) as u32;
for i in 0..max_uids - 1 {
let coldkey: T::AccountId = account("Axon", 0, i);
let hotkey: T::AccountId = account("Hotkey", 0, i);

Subtensor::<T>::add_balance_to_coldkey_account(&coldkey.clone(), Subtensor::<T>::u64_to_balance(10_000_000_000).unwrap());
assert_ok!(Subtensor::<T>::burned_register(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey));
assert_ok!(Subtensor::<T>::add_stake(RawOrigin::Signed(coldkey).into(), old_hotkey.clone(), 1_000_000_000));
}
}: _(RawOrigin::Signed(coldkey), old_hotkey, new_hotkey)
}
8 changes: 8 additions & 0 deletions pallets/subtensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,7 @@ pub mod pallet {
NetworkMinLockCostSet(u64), // Event created when the network minimum locking cost is set.
SubnetLimitSet(u16), // Event created when the maximum number of subnets is set
NetworkLockCostReductionIntervalSet(u64), // Event created when the lock cost reduction is set
HotkeySwapped{coldkey: T::AccountId, old_hotkey: T::AccountId, new_hotkey: T::AccountId} // Event created when a hotkey is swapped
}

// Errors inform users that something went wrong.
Expand Down Expand Up @@ -914,6 +915,7 @@ pub mod pallet {
OperationNotPermittedonRootSubnet,
StakeTooLowForRoot, // --- Thrown when a hotkey attempts to join the root subnet with too little stake
AllNetworksInImmunity, // --- Thrown when all subnets are in the immunity period
NotEnoughBalance,
}

// ==================
Expand Down Expand Up @@ -1520,6 +1522,12 @@ pub mod pallet {
Self::do_burned_registration(origin, netuid, hotkey)
}

#[pallet::call_index(69)]
#[pallet::weight((0, DispatchClass::Operational, Pays::No))]
pub fn swap_hotkey(origin: OriginFor<T>, hotkey: T::AccountId, new_hotkey: T::AccountId) -> DispatchResultWithPostInfo {
Self::do_swap_hotkey(origin, &hotkey, &new_hotkey)
}

#[pallet::call_index(8)]
#[pallet::weight((Weight::from_ref_time(81_000_000)
.saturating_add(T::DbWeight::get().reads(21))
Expand Down
133 changes: 131 additions & 2 deletions pallets/subtensor/src/registration.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use super::*;
use crate::system::ensure_root;
use frame_support::pallet_prelude::DispatchResult;
use frame_support::pallet_prelude::{DispatchResult, DispatchResultWithPostInfo};
use frame_system::ensure_signed;
use sp_core::{H256, U256};
use sp_core::{H256, U256, Get};
use sp_io::hashing::{keccak_256, sha2_256};
use sp_runtime::MultiAddress;
use sp_std::convert::TryInto;
use sp_std::vec::Vec;
use frame_support::storage::IterableStorageDoubleMap;

const LOG_TARGET: &'static str = "runtime::subtensor::registration";

Expand Down Expand Up @@ -762,4 +763,132 @@ impl<T: Config> Pallet<T> {
let vec_work: Vec<u8> = Self::hash_to_vec(work);
return (nonce, vec_work);
}

pub fn do_swap_hotkey(origin: T::RuntimeOrigin, old_hotkey: &T::AccountId, new_hotkey: &T::AccountId) -> DispatchResultWithPostInfo {
let coldkey = ensure_signed(origin)?;

let mut weight = T::DbWeight::get().reads_writes(2, 0);
ensure!(Self::coldkey_owns_hotkey(&coldkey, old_hotkey), Error::<T>::NonAssociatedColdKey);

let block: u64 = Self::get_current_block_as_u64();
ensure!(
!Self::exceeds_tx_rate_limit(Self::get_last_tx_block(&coldkey), block),
Error::<T>::TxRateLimitExceeded
);

weight.saturating_accrue(T::DbWeight::get().reads(2));

ensure!(old_hotkey != new_hotkey, Error::<T>::AlreadyRegistered);
ensure!(!Self::is_hotkey_registered_on_any_network(new_hotkey), Error::<T>::AlreadyRegistered);

weight.saturating_accrue(T::DbWeight::get().reads((TotalNetworks::<T>::get() + 1u16) as u64));

let swap_cost = 1_000_000_000u64;
let swap_cost_as_balance = Self::u64_to_balance(swap_cost).unwrap();
ensure!(
Self::can_remove_balance_from_coldkey_account(&coldkey, swap_cost_as_balance),
Error::<T>::NotEnoughBalance
);
ensure!(
Self::remove_balance_from_coldkey_account(&coldkey, swap_cost_as_balance)
== true,
Error::<T>::BalanceWithdrawalError
);
Self::burn_tokens(swap_cost);

Owner::<T>::remove(old_hotkey);
Owner::<T>::insert(new_hotkey, coldkey.clone());
weight.saturating_accrue(T::DbWeight::get().writes(2));

if let Ok(total_hotkey_stake) = TotalHotkeyStake::<T>::try_get(old_hotkey) {
TotalHotkeyStake::<T>::remove(old_hotkey);
TotalHotkeyStake::<T>::insert(new_hotkey, total_hotkey_stake);

weight.saturating_accrue(T::DbWeight::get().writes(2));
}

if let Ok(delegate_take) = Delegates::<T>::try_get(old_hotkey) {
Delegates::<T>::remove(old_hotkey);
Delegates::<T>::insert(new_hotkey, delegate_take);

weight.saturating_accrue(T::DbWeight::get().writes(2));
}

if let Ok(last_tx) = LastTxBlock::<T>::try_get(old_hotkey) {
LastTxBlock::<T>::remove(old_hotkey);
LastTxBlock::<T>::insert(new_hotkey, last_tx);

weight.saturating_accrue(T::DbWeight::get().writes(2));
}

let mut coldkey_stake: Vec<(T::AccountId, u64)> = vec![];
for (coldkey, stake_amount) in Stake::<T>::iter_prefix(old_hotkey) {
coldkey_stake.push((coldkey.clone(), stake_amount));
}

let _ = Stake::<T>::clear_prefix(old_hotkey, coldkey_stake.len() as u32, None);
weight.saturating_accrue(T::DbWeight::get().writes(coldkey_stake.len() as u64));

for (coldkey, stake_amount) in coldkey_stake {
Stake::<T>::insert(new_hotkey, coldkey, stake_amount);
weight.saturating_accrue(T::DbWeight::get().writes(1));
}

let mut netuid_is_member: Vec<u16> = vec![];
for netuid in <IsNetworkMember<T> as IterableStorageDoubleMap<T::AccountId, u16, bool>>::iter_key_prefix(old_hotkey) {
netuid_is_member.push(netuid);
}

let _ = IsNetworkMember::<T>::clear_prefix(old_hotkey, netuid_is_member.len() as u32, None);
weight.saturating_accrue(T::DbWeight::get().writes(netuid_is_member.len() as u64));

for netuid in netuid_is_member.iter() {
IsNetworkMember::<T>::insert(new_hotkey, netuid, true);
weight.saturating_accrue(T::DbWeight::get().writes(1));
}

for netuid in netuid_is_member.iter() {
if let Ok(axon_info) = Axons::<T>::try_get(netuid, old_hotkey) {
Axons::<T>::remove(netuid, old_hotkey);
Axons::<T>::insert(netuid, new_hotkey, axon_info);

weight.saturating_accrue(T::DbWeight::get().writes(2));
}
}

for netuid in netuid_is_member.iter() {
if let Ok(uid) = Uids::<T>::try_get(netuid, old_hotkey) {
Uids::<T>::remove(netuid, old_hotkey);
Uids::<T>::insert(netuid, new_hotkey, uid);

weight.saturating_accrue(T::DbWeight::get().writes(2));

Keys::<T>::insert(netuid, uid, new_hotkey);

weight.saturating_accrue(T::DbWeight::get().writes(1));

LoadedEmission::<T>::mutate(netuid, |emission_exists| {
match emission_exists {
Some(emissions) => {
if let Some(emission) = emissions.get_mut(uid as usize) {
let (_, se, ve) = emission;
*emission = (new_hotkey.clone(), *se, *ve);

}
}
None => {}
}
});

weight.saturating_accrue(T::DbWeight::get().writes(1));
}
}

Self::set_last_tx_block(&coldkey, block);
weight.saturating_accrue(T::DbWeight::get().writes(1));

Self::deposit_event(Event::HotkeySwapped{coldkey, old_hotkey: old_hotkey.clone(), new_hotkey: new_hotkey.clone()});

Ok(Some(weight).into())
}
}
118 changes: 117 additions & 1 deletion pallets/subtensor/tests/registration.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use frame_support::traits::Currency;

use crate::mock::*;
use frame_support::assert_ok;
use frame_support::{assert_ok, assert_err};
use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays};
use frame_support::sp_runtime::DispatchError;
use frame_system::Config;
Expand Down Expand Up @@ -1571,3 +1571,119 @@ fn test_registration_disabled() {
assert_eq!(result, Err(Error::<Test>::RegistrationDisabled.into()));
});
}

#[test]
fn test_hotkey_swap_ok() {
new_test_ext().execute_with(|| {
let netuid: u16 = 1;
let tempo: u16 = 13;
let hotkey_account_id = U256::from(1);
let burn_cost = 1000;
let coldkey_account_id = U256::from(667);

SubtensorModule::set_burn(netuid, burn_cost);
add_network(netuid, tempo, 0);

// Give it some $$$ in his coldkey balance
SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10_000_000_000);

// Subscribe and check extrinsic output
assert_ok!(SubtensorModule::burned_register(
<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id),
netuid,
hotkey_account_id
));

let new_hotkey = U256::from(1337);
assert_ok!(SubtensorModule::swap_hotkey(<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id), hotkey_account_id, new_hotkey));
assert_ne!(SubtensorModule::get_owning_coldkey_for_hotkey(&hotkey_account_id), coldkey_account_id);
assert_eq!(SubtensorModule::get_owning_coldkey_for_hotkey(&new_hotkey), coldkey_account_id);
});
}

#[test]
fn test_hotkey_swap_not_owner() {
new_test_ext().execute_with(|| {
let netuid: u16 = 1;
let tempo: u16 = 13;
let hotkey_account_id = U256::from(1);
let burn_cost = 1000;
let coldkey_account_id = U256::from(2);
let not_owner_coldkey = U256::from(3);

SubtensorModule::set_burn(netuid, burn_cost);
add_network(netuid, tempo, 0);

// Give it some $$$ in his coldkey balance
SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000);

// Subscribe and check extrinsic output
assert_ok!(SubtensorModule::burned_register(
<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id),
netuid,
hotkey_account_id
));

let new_hotkey = U256::from(4);
assert_err!(SubtensorModule::swap_hotkey(<<Test as Config>::RuntimeOrigin>::signed(not_owner_coldkey), hotkey_account_id, new_hotkey), Error::<Test>::NonAssociatedColdKey);
});
}

#[test]
fn test_hotkey_swap_same_key() {
new_test_ext().execute_with(|| {
let netuid: u16 = 1;
let tempo: u16 = 13;
let hotkey_account_id = U256::from(1);
let burn_cost = 1000;
let coldkey_account_id = U256::from(2);

SubtensorModule::set_burn(netuid, burn_cost);
add_network(netuid, tempo, 0);

// Give it some $$$ in his coldkey balance
SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000);

// Subscribe and check extrinsic output
assert_ok!(SubtensorModule::burned_register(
<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id),
netuid,
hotkey_account_id
));

assert_err!(SubtensorModule::swap_hotkey(<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id), hotkey_account_id, hotkey_account_id), Error::<Test>::AlreadyRegistered);
});
}

#[test]
fn test_hotkey_swap_registered_key() {
new_test_ext().execute_with(|| {
let netuid: u16 = 1;
let tempo: u16 = 13;
let hotkey_account_id = U256::from(1);
let burn_cost = 1000;
let coldkey_account_id = U256::from(2);

SubtensorModule::set_burn(netuid, burn_cost);
add_network(netuid, tempo, 0);

// Give it some $$$ in his coldkey balance
SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 100_000_000_000);

// Subscribe and check extrinsic output
assert_ok!(SubtensorModule::burned_register(
<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id),
netuid,
hotkey_account_id
));

let new_hotkey = U256::from(3);
assert_ok!(SubtensorModule::burned_register(
<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id),
netuid,
new_hotkey
));

assert_err!(SubtensorModule::swap_hotkey(<<Test as Config>::RuntimeOrigin>::signed(coldkey_account_id), hotkey_account_id, new_hotkey), Error::<Test>::AlreadyRegistered);
});
}
Loading