Skip to content

Commit dd28ad4

Browse files
authored
Merge pull request #1721 from opentensor/migrate-rate-limits-v2
Migrate last tx block maps
2 parents e831393 + 915700a commit dd28ad4

File tree

12 files changed

+442
-59
lines changed

12 files changed

+442
-59
lines changed

pallets/subtensor/src/coinbase/root.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -565,10 +565,10 @@ impl<T: Config> Pallet<T> {
565565
NetworkLastLockCost::<T>::get()
566566
}
567567
pub fn get_network_last_lock_block() -> u64 {
568-
NetworkLastRegistered::<T>::get()
568+
Self::get_rate_limited_last_block(&RateLimitKey::NetworkLastRegistered)
569569
}
570570
pub fn set_network_last_lock_block(block: u64) {
571-
NetworkLastRegistered::<T>::set(block);
571+
Self::set_rate_limited_last_block(&RateLimitKey::NetworkLastRegistered, block);
572572
}
573573
pub fn set_lock_reduction_interval(interval: u64) {
574574
NetworkLockReductionInterval::<T>::set(interval);
@@ -588,10 +588,13 @@ impl<T: Config> Pallet<T> {
588588
let halved_interval: I64F64 = interval.saturating_mul(halving);
589589
halved_interval.saturating_to_num::<u64>()
590590
}
591-
pub fn get_rate_limited_last_block(rate_limit_key: &RateLimitKey) -> u64 {
591+
pub fn get_rate_limited_last_block(rate_limit_key: &RateLimitKey<T::AccountId>) -> u64 {
592592
LastRateLimitedBlock::<T>::get(rate_limit_key)
593593
}
594-
pub fn set_rate_limited_last_block(rate_limit_key: &RateLimitKey, block: u64) {
595-
LastRateLimitedBlock::<T>::set(rate_limit_key, block);
594+
pub fn set_rate_limited_last_block(rate_limit_key: &RateLimitKey<T::AccountId>, block: u64) {
595+
LastRateLimitedBlock::<T>::insert(rate_limit_key, block);
596+
}
597+
pub fn remove_rate_limited_last_block(rate_limit_key: &RateLimitKey<T::AccountId>) {
598+
LastRateLimitedBlock::<T>::remove(rate_limit_key);
596599
}
597600
}

pallets/subtensor/src/lib.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ extern crate alloc;
5454

5555
pub const MAX_CRV3_COMMIT_SIZE_BYTES: u32 = 5000;
5656

57+
#[allow(deprecated)]
5758
#[deny(missing_docs)]
5859
#[import_section(errors::errors)]
5960
#[import_section(events::events)]
@@ -525,11 +526,6 @@ pub mod pallet {
525526
T::InitialNetworkImmunityPeriod::get()
526527
}
527528
#[pallet::type_value]
528-
/// Default value for network last registered.
529-
pub fn DefaultNetworkLastRegistered<T: Config>() -> u64 {
530-
0
531-
}
532-
#[pallet::type_value]
533529
/// Default value for network min allowed UIDs.
534530
pub fn DefaultNetworkMinAllowedUids<T: Config>() -> u16 {
535531
T::InitialNetworkMinAllowedUids::get()
@@ -1173,10 +1169,6 @@ pub mod pallet {
11731169
pub type NetworkImmunityPeriod<T> =
11741170
StorageValue<_, u64, ValueQuery, DefaultNetworkImmunityPeriod<T>>;
11751171
#[pallet::storage]
1176-
/// ITEM( network_last_registered_block )
1177-
pub type NetworkLastRegistered<T> =
1178-
StorageValue<_, u64, ValueQuery, DefaultNetworkLastRegistered<T>>;
1179-
#[pallet::storage]
11801172
/// ITEM( min_network_lock_cost )
11811173
pub type NetworkMinLockCost<T> =
11821174
StorageValue<_, TaoCurrency, ValueQuery, DefaultNetworkMinLockCost<T>>;
@@ -1209,7 +1201,7 @@ pub mod pallet {
12091201
#[pallet::storage]
12101202
/// --- MAP ( RateLimitKey ) --> Block number in which the last rate limited operation occured
12111203
pub type LastRateLimitedBlock<T: Config> =
1212-
StorageMap<_, Identity, RateLimitKey, u64, ValueQuery, DefaultZeroU64<T>>;
1204+
StorageMap<_, Identity, RateLimitKey<T::AccountId>, u64, ValueQuery, DefaultZeroU64<T>>;
12131205

12141206
/// ============================
12151207
/// ==== Subnet Locks =====
@@ -1666,14 +1658,17 @@ pub mod pallet {
16661658
u64,
16671659
ValueQuery,
16681660
>;
1661+
#[deprecated]
16691662
#[pallet::storage]
16701663
/// --- MAP ( key ) --> last_block
16711664
pub type LastTxBlock<T: Config> =
16721665
StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock<T>>;
1666+
#[deprecated]
16731667
#[pallet::storage]
16741668
/// --- MAP ( key ) --> last_tx_block_childkey_take
16751669
pub type LastTxBlockChildKeyTake<T: Config> =
16761670
StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock<T>>;
1671+
#[deprecated]
16771672
#[pallet::storage]
16781673
/// --- MAP ( key ) --> last_tx_block_delegate_take
16791674
pub type LastTxBlockDelegateTake<T: Config> =
@@ -2144,9 +2139,17 @@ impl<T: Config + pallet_balances::Config<Balance = u64>>
21442139
/// Enum that defines types of rate limited operations for
21452140
/// storing last block when this operation occured
21462141
#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, TypeInfo)]
2147-
pub enum RateLimitKey {
2142+
pub enum RateLimitKey<AccountId> {
21482143
// The setting sn owner hotkey operation is rate limited per netuid
21492144
SetSNOwnerHotkey(NetUid),
2145+
// Subnet registration rate limit
2146+
NetworkLastRegistered,
2147+
// Last tx block limit per account ID
2148+
LastTxBlock(AccountId),
2149+
// Last tx block child key limit per account ID
2150+
LastTxBlockChildKeyTake(AccountId),
2151+
// Last tx block delegate key limit per account ID
2152+
LastTxBlockDelegateTake(AccountId),
21502153
}
21512154

21522155
pub trait ProxyInterface<AccountId> {

pallets/subtensor/src/macros/dispatches.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2031,7 +2031,7 @@ mod dispatches {
20312031
/// * commit_reveal_version (`u16`):
20322032
/// - The client (bittensor-drand) version
20332033
#[pallet::call_index(113)]
2034-
#[pallet::weight((Weight::from_parts(64_530_000, 0)
2034+
#[pallet::weight((Weight::from_parts(80_690_000, 0)
20352035
.saturating_add(T::DbWeight::get().reads(7_u64))
20362036
.saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))]
20372037
pub fn commit_timelocked_weights(

pallets/subtensor/src/macros/hooks.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,9 @@ mod hooks {
135135
//Migrate CRV3 to TimelockedCommits
136136
.saturating_add(migrations::migrate_crv3_v2_to_timelocked::migrate_crv3_v2_to_timelocked::<T>())
137137
// Migrate to fix root counters
138-
.saturating_add(migrations::migrate_fix_root_tao_and_alpha_in::migrate_fix_root_tao_and_alpha_in::<T>());
138+
.saturating_add(migrations::migrate_fix_root_tao_and_alpha_in::migrate_fix_root_tao_and_alpha_in::<T>())
139+
// Migrate last block rate limiting storage items
140+
.saturating_add(migrations::migrate_rate_limiting_last_blocks::migrate_obsolete_rate_limiting_last_blocks_storage::<T>());
139141
weight
140142
}
141143

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
use crate::Vec;
2+
use crate::{Config, HasMigrationRun, Pallet};
3+
use alloc::string::String;
4+
use codec::Decode;
5+
use frame_support::traits::Get;
6+
use frame_support::weights::Weight;
7+
use sp_io::hashing::twox_128;
8+
use sp_io::storage::{clear, get};
9+
10+
pub fn migrate_obsolete_rate_limiting_last_blocks_storage<T: Config>() -> Weight {
11+
migrate_network_last_registered::<T>()
12+
.saturating_add(migrate_last_tx_block::<T>())
13+
.saturating_add(migrate_last_tx_block_childkey_take::<T>())
14+
.saturating_add(migrate_last_tx_block_delegate_take::<T>())
15+
}
16+
17+
pub fn migrate_network_last_registered<T: Config>() -> Weight {
18+
let migration_name = b"migrate_network_last_registered".to_vec();
19+
let pallet_name = "SubtensorModule";
20+
let storage_name = "NetworkLastRegistered";
21+
22+
migrate_value::<T, _>(migration_name, pallet_name, storage_name, |limit| {
23+
Pallet::<T>::set_network_last_lock_block(limit);
24+
})
25+
}
26+
27+
#[allow(deprecated)]
28+
pub fn migrate_last_tx_block<T: Config>() -> Weight {
29+
let migration_name = b"migrate_last_tx_block".to_vec();
30+
31+
migrate_last_block_map::<T, _, _>(
32+
migration_name,
33+
|| crate::LastTxBlock::<T>::drain().collect::<Vec<_>>(),
34+
|account, block| {
35+
Pallet::<T>::set_last_tx_block(&account, block);
36+
},
37+
)
38+
}
39+
40+
#[allow(deprecated)]
41+
pub fn migrate_last_tx_block_childkey_take<T: Config>() -> Weight {
42+
let migration_name = b"migrate_last_tx_block_childkey_take".to_vec();
43+
44+
migrate_last_block_map::<T, _, _>(
45+
migration_name,
46+
|| crate::LastTxBlockChildKeyTake::<T>::drain().collect::<Vec<_>>(),
47+
|account, block| {
48+
Pallet::<T>::set_last_tx_block_childkey(&account, block);
49+
},
50+
)
51+
}
52+
53+
#[allow(deprecated)]
54+
pub fn migrate_last_tx_block_delegate_take<T: Config>() -> Weight {
55+
let migration_name = b"migrate_last_tx_block_delegate_take".to_vec();
56+
57+
migrate_last_block_map::<T, _, _>(
58+
migration_name,
59+
|| crate::LastTxBlockDelegateTake::<T>::drain().collect::<Vec<_>>(),
60+
|account, block| {
61+
Pallet::<T>::set_last_tx_block_delegate_take(&account, block);
62+
},
63+
)
64+
}
65+
66+
fn migrate_value<T, SetValueFunction>(
67+
migration_name: Vec<u8>,
68+
pallet_name: &str,
69+
storage_name: &str,
70+
set_value: SetValueFunction,
71+
) -> Weight
72+
where
73+
T: Config,
74+
SetValueFunction: Fn(u64 /*limit in blocks*/),
75+
{
76+
// Initialize the weight with one read operation.
77+
let mut weight = T::DbWeight::get().reads(1);
78+
79+
// Check if the migration has already run
80+
if HasMigrationRun::<T>::get(&migration_name) {
81+
log::info!("Migration '{migration_name:?}' has already run. Skipping.",);
82+
return weight;
83+
}
84+
log::info!(
85+
"Running migration '{}'",
86+
String::from_utf8_lossy(&migration_name)
87+
);
88+
89+
let pallet_name_hash = twox_128(pallet_name.as_bytes());
90+
let storage_name_hash = twox_128(storage_name.as_bytes());
91+
let full_key = [pallet_name_hash, storage_name_hash].concat();
92+
93+
if let Some(value_bytes) = get(&full_key) {
94+
if let Ok(rate_limit) = Decode::decode(&mut &value_bytes[..]) {
95+
set_value(rate_limit);
96+
}
97+
98+
clear(&full_key);
99+
}
100+
101+
weight = weight.saturating_add(T::DbWeight::get().writes(2));
102+
weight = weight.saturating_add(T::DbWeight::get().reads(1));
103+
104+
// Mark the migration as completed
105+
HasMigrationRun::<T>::insert(&migration_name, true);
106+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
107+
108+
log::info!(
109+
"Migration '{:?}' completed.",
110+
String::from_utf8_lossy(&migration_name)
111+
);
112+
113+
// Return the migration weight.
114+
weight
115+
}
116+
117+
fn migrate_last_block_map<T, GetValuesFunction, SetValueFunction>(
118+
migration_name: Vec<u8>,
119+
get_values: GetValuesFunction,
120+
set_value: SetValueFunction,
121+
) -> Weight
122+
where
123+
T: Config,
124+
GetValuesFunction: Fn() -> Vec<(T::AccountId, u64)>, // (account, limit in blocks)
125+
SetValueFunction: Fn(T::AccountId, u64),
126+
{
127+
// Initialize the weight with one read operation.
128+
let mut weight = T::DbWeight::get().reads(1);
129+
130+
// Check if the migration has already run
131+
if HasMigrationRun::<T>::get(&migration_name) {
132+
log::info!("Migration '{migration_name:?}' has already run. Skipping.",);
133+
return weight;
134+
}
135+
log::info!(
136+
"Running migration '{}'",
137+
String::from_utf8_lossy(&migration_name)
138+
);
139+
140+
let key_values = get_values();
141+
weight = weight.saturating_add(T::DbWeight::get().reads(key_values.len() as u64));
142+
143+
for (account, block) in key_values.into_iter() {
144+
set_value(account, block);
145+
146+
weight = weight.saturating_add(T::DbWeight::get().writes(2));
147+
weight = weight.saturating_add(T::DbWeight::get().reads(1));
148+
}
149+
150+
// Mark the migration as completed
151+
HasMigrationRun::<T>::insert(&migration_name, true);
152+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
153+
154+
log::info!(
155+
"Migration '{:?}' completed.",
156+
String::from_utf8_lossy(&migration_name)
157+
);
158+
159+
// Return the migration weight.
160+
weight
161+
}

pallets/subtensor/src/migrations/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ pub mod migrate_init_total_issuance;
2222
pub mod migrate_orphaned_storage_items;
2323
pub mod migrate_populate_owned_hotkeys;
2424
pub mod migrate_rao;
25+
pub mod migrate_rate_limiting_last_blocks;
2526
pub mod migrate_remove_commitments_rate_limit;
2627
pub mod migrate_remove_stake_map;
2728
pub mod migrate_remove_total_hotkey_coldkey_stakes_this_interval;

pallets/subtensor/src/subnets/subnet.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ impl<T: Config> Pallet<T> {
174174
log::debug!("SubnetMechanism for netuid {netuid_to_register:?} set to: {mechid:?}");
175175

176176
// --- 12. Set the creation terms.
177-
NetworkLastRegistered::<T>::set(current_block);
177+
Self::set_network_last_lock_block(current_block);
178178
NetworkRegisteredAt::<T>::insert(netuid_to_register, current_block);
179179

180180
// --- 13. Set the symbol.

pallets/subtensor/src/swap/swap_hotkey.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,21 +64,18 @@ impl<T: Config> Pallet<T> {
6464
);
6565

6666
// 8. Swap LastTxBlock
67-
// LastTxBlock( hotkey ) --> u64 -- the last transaction block for the hotkey.
68-
let last_tx_block: u64 = LastTxBlock::<T>::get(old_hotkey);
69-
LastTxBlock::<T>::insert(new_hotkey, last_tx_block);
67+
let last_tx_block: u64 = Self::get_last_tx_block(old_hotkey);
68+
Self::set_last_tx_block(new_hotkey, last_tx_block);
7069
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
7170

7271
// 9. Swap LastTxBlockDelegateTake
73-
// LastTxBlockDelegateTake( hotkey ) --> u64 -- the last transaction block for the hotkey delegate take.
74-
let last_tx_block_delegate_take: u64 = LastTxBlockDelegateTake::<T>::get(old_hotkey);
75-
LastTxBlockDelegateTake::<T>::insert(new_hotkey, last_tx_block_delegate_take);
72+
let last_tx_block_delegate_take: u64 = Self::get_last_tx_block_delegate_take(old_hotkey);
73+
Self::set_last_tx_block_delegate_take(new_hotkey, last_tx_block_delegate_take);
7674
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
7775

7876
// 10. Swap LastTxBlockChildKeyTake
79-
// LastTxBlockChildKeyTake( hotkey ) --> u64 -- the last transaction block for the hotkey child key take.
80-
let last_tx_block_child_key_take: u64 = LastTxBlockChildKeyTake::<T>::get(old_hotkey);
81-
LastTxBlockChildKeyTake::<T>::insert(new_hotkey, last_tx_block_child_key_take);
77+
let last_tx_block_child_key_take: u64 = Self::get_last_tx_block_childkey_take(old_hotkey);
78+
Self::set_last_tx_block_childkey(new_hotkey, last_tx_block_child_key_take);
8279
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
8380

8481
// 11. fork for swap hotkey on a specific subnet case after do the common check
@@ -197,17 +194,17 @@ impl<T: Config> Pallet<T> {
197194

198195
// 6. Swap LastTxBlock
199196
// LastTxBlock( hotkey ) --> u64 -- the last transaction block for the hotkey.
200-
LastTxBlock::<T>::remove(old_hotkey);
197+
Self::remove_last_tx_block(old_hotkey);
201198
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
202199

203200
// 7. Swap LastTxBlockDelegateTake
204201
// LastTxBlockDelegateTake( hotkey ) --> u64 -- the last transaction block for the hotkey delegate take.
205-
LastTxBlockDelegateTake::<T>::remove(old_hotkey);
202+
Self::remove_last_tx_block_delegate_take(old_hotkey);
206203
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
207204

208205
// 8. Swap LastTxBlockChildKeyTake
209206
// LastTxBlockChildKeyTake( hotkey ) --> u64 -- the last transaction block for the hotkey child key take.
210-
LastTxBlockChildKeyTake::<T>::remove(old_hotkey);
207+
Self::remove_last_tx_block_childkey(old_hotkey);
211208
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
212209

213210
// 9. Swap Senate members.

0 commit comments

Comments
 (0)