Skip to content

Commit 2d613cf

Browse files
authored
Merge pull request #1880 from opentensor/commit-reveal-v3-improvments
fix/CRV3 Improvements
2 parents 1367c34 + 22cfb35 commit 2d613cf

File tree

20 files changed

+1504
-495
lines changed

20 files changed

+1504
-495
lines changed

pallets/admin-utils/src/benchmarking.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,5 +335,16 @@ mod benchmarks {
335335
_(RawOrigin::Root, 1u16.into()/*netuid*/, true/*enabled*/)/*set_commit_reveal_weights_enabled*/;
336336
}
337337

338+
#[benchmark]
339+
fn sudo_set_commit_reveal_version() {
340+
pallet_subtensor::Pallet::<T>::init_new_network(
341+
1u16.into(), /*netuid*/
342+
1u16, /*sudo_tempo*/
343+
);
344+
345+
#[extrinsic_call]
346+
_(RawOrigin::Root, 5u16/*version*/)/*sudo_set_commit_reveal_version()*/;
347+
}
348+
338349
//impl_benchmark_test_suite!(AdminUtils, crate::mock::new_test_ext(), crate::mock::Test);
339350
}

pallets/admin-utils/src/lib.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,7 @@ pub mod pallet {
405405
/// It is only callable by the root account or subnet owner.
406406
/// The extrinsic will call the Subtensor pallet to set the adjustment beta.
407407
#[pallet::call_index(12)]
408-
#[pallet::weight(Weight::from_parts(19_240_000, 0)
408+
#[pallet::weight(Weight::from_parts(14_850_000, 0)
409409
.saturating_add(<T as frame_system::Config>::DbWeight::get().reads(1_u64))
410410
.saturating_add(<T as frame_system::Config>::DbWeight::get().writes(1_u64)))]
411411
pub fn sudo_set_max_weight_limit(
@@ -480,7 +480,7 @@ pub mod pallet {
480480
/// It is only callable by the root account.
481481
/// The extrinsic will call the Subtensor pallet to set the maximum allowed UIDs for a subnet.
482482
#[pallet::call_index(15)]
483-
#[pallet::weight(Weight::from_parts(23_820_000, 0)
483+
#[pallet::weight(Weight::from_parts(18_770_000, 0)
484484
.saturating_add(<T as frame_system::Config>::DbWeight::get().reads(2_u64))
485485
.saturating_add(<T as frame_system::Config>::DbWeight::get().writes(1_u64)))]
486486
pub fn sudo_set_max_allowed_uids(
@@ -578,7 +578,7 @@ pub mod pallet {
578578
/// The extrinsic will call the Subtensor pallet to set the network registration allowed.
579579
#[pallet::call_index(19)]
580580
#[pallet::weight((
581-
Weight::from_parts(8_696_000, 0)
581+
Weight::from_parts(6_722_000, 0)
582582
.saturating_add(<T as frame_system::Config>::DbWeight::get().reads(0))
583583
.saturating_add(<T as frame_system::Config>::DbWeight::get().writes(1)),
584584
DispatchClass::Operational,
@@ -1102,7 +1102,7 @@ pub mod pallet {
11021102
/// It is only callable by the root account or subnet owner.
11031103
/// The extrinsic will call the Subtensor pallet to set the value.
11041104
#[pallet::call_index(49)]
1105-
#[pallet::weight(Weight::from_parts(19_480_000, 0)
1105+
#[pallet::weight(Weight::from_parts(14_780_000, 0)
11061106
.saturating_add(<T as frame_system::Config>::DbWeight::get().reads(1_u64))
11071107
.saturating_add(<T as frame_system::Config>::DbWeight::get().writes(1_u64)))]
11081108
pub fn sudo_set_commit_reveal_weights_enabled(
@@ -1655,6 +1655,18 @@ pub mod pallet {
16551655
);
16561656
Ok(())
16571657
}
1658+
1659+
/// Sets the commit-reveal weights version for all subnets
1660+
#[pallet::call_index(71)]
1661+
#[pallet::weight((0, DispatchClass::Operational, Pays::No))]
1662+
pub fn sudo_set_commit_reveal_version(
1663+
origin: OriginFor<T>,
1664+
version: u16,
1665+
) -> DispatchResult {
1666+
ensure_root(origin)?;
1667+
pallet_subtensor::Pallet::<T>::set_commit_reveal_weights_version(version);
1668+
Ok(())
1669+
}
16581670
}
16591671
}
16601672

pallets/admin-utils/src/tests/mod.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1930,3 +1930,24 @@ fn test_sudo_set_yuma3_enabled() {
19301930
assert_eq!(SubtensorModule::get_yuma3_enabled(netuid), !to_be_set);
19311931
});
19321932
}
1933+
1934+
#[test]
1935+
fn test_sudo_set_commit_reveal_version() {
1936+
new_test_ext().execute_with(|| {
1937+
add_network(NetUid::from(1), 10);
1938+
1939+
let to_be_set: u16 = 5;
1940+
let init_value: u16 = SubtensorModule::get_commit_reveal_weights_version();
1941+
1942+
assert_ok!(AdminUtils::sudo_set_commit_reveal_version(
1943+
<<Test as Config>::RuntimeOrigin>::root(),
1944+
to_be_set
1945+
));
1946+
1947+
assert!(init_value != to_be_set);
1948+
assert_eq!(
1949+
SubtensorModule::get_commit_reveal_weights_version(),
1950+
to_be_set
1951+
);
1952+
});
1953+
}

pallets/drand/src/lib.rs

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ use sp_runtime::{
5858
};
5959

6060
pub mod bls12_381;
61+
pub mod migrations;
6162
pub mod types;
6263
pub mod utils;
6364
pub mod verifier;
@@ -91,6 +92,8 @@ pub const QUICKNET_CHAIN_HASH: &str =
9192
const CHAIN_HASH: &str = QUICKNET_CHAIN_HASH;
9293

9394
pub const MAX_PULSES_TO_FETCH: u64 = 50;
95+
pub const MAX_KEPT_PULSES: u64 = 216_000; // 1 week
96+
pub const MAX_REMOVED_PULSES: u64 = 100;
9497

9598
/// Defines application identifier for crypto keys of this module.
9699
///
@@ -212,12 +215,24 @@ pub mod pallet {
212215
}
213216
}
214217

218+
/// Define a maximum length for the migration key
219+
type MigrationKeyMaxLen = ConstU32<128>;
220+
221+
/// Storage for migration run status
222+
#[pallet::storage]
223+
pub type HasMigrationRun<T: Config> =
224+
StorageMap<_, Identity, BoundedVec<u8, MigrationKeyMaxLen>, bool, ValueQuery>;
225+
215226
/// map round number to pulse
216227
#[pallet::storage]
217228
pub type Pulses<T: Config> = StorageMap<_, Blake2_128Concat, RoundNumber, Pulse, OptionQuery>;
218229

219230
#[pallet::storage]
220-
pub(super) type LastStoredRound<T: Config> = StorageValue<_, RoundNumber, ValueQuery>;
231+
pub type LastStoredRound<T: Config> = StorageValue<_, RoundNumber, ValueQuery>;
232+
233+
/// oldest stored round
234+
#[pallet::storage]
235+
pub type OldestStoredRound<T: Config> = StorageValue<_, RoundNumber, ValueQuery>;
221236

222237
/// Defines the block when next unsigned transaction will be accepted.
223238
///
@@ -261,6 +276,14 @@ pub mod pallet {
261276
log::debug!("Drand: Failed to fetch pulse from drand. {e:?}");
262277
}
263278
}
279+
fn on_runtime_upgrade() -> frame_support::weights::Weight {
280+
/* let weight = */
281+
frame_support::weights::Weight::from_parts(0, 0) /*;*/
282+
283+
//weight = weight.saturating_add(migrations::migrate_prune_old_pulses::<T>());
284+
285+
//weight
286+
}
264287
}
265288

266289
#[pallet::validate_unsigned]
@@ -308,8 +331,8 @@ pub mod pallet {
308331
/// Verify and write a pulse from the beacon into the runtime
309332
#[pallet::call_index(0)]
310333
#[pallet::weight(Weight::from_parts(5_708_000_000, 0)
311-
.saturating_add(T::DbWeight::get().reads(2_u64))
312-
.saturating_add(T::DbWeight::get().writes(3_u64)))]
334+
.saturating_add(T::DbWeight::get().reads(3_u64))
335+
.saturating_add(T::DbWeight::get().writes(4_u64)))]
313336
pub fn write_pulse(
314337
origin: OriginFor<T>,
315338
pulses_payload: PulsesPayload<T::Public, BlockNumberFor<T>>,
@@ -321,6 +344,10 @@ pub mod pallet {
321344
let mut last_stored_round = LastStoredRound::<T>::get();
322345
let mut new_rounds = Vec::new();
323346

347+
let oldest_stored_round = OldestStoredRound::<T>::get();
348+
let is_first_storage = last_stored_round == 0 && oldest_stored_round == 0;
349+
let mut first_new_round: Option<RoundNumber> = None;
350+
324351
for pulse in &pulses_payload.pulses {
325352
let is_verified = T::Verifier::verify(config.clone(), pulse.clone())
326353
.map_err(|_| Error::<T>::PulseVerificationError)?;
@@ -339,12 +366,25 @@ pub mod pallet {
339366

340367
// Collect the new round
341368
new_rounds.push(pulse.round);
369+
370+
// Set the first new round if this is the initial storage
371+
if is_first_storage && first_new_round.is_none() {
372+
first_new_round = Some(pulse.round);
373+
}
342374
}
343375
}
344376

345377
// Update LastStoredRound storage
346378
LastStoredRound::<T>::put(last_stored_round);
347379

380+
// Set OldestStoredRound if this was the first storage
381+
if let Some(first_round) = first_new_round {
382+
OldestStoredRound::<T>::put(first_round);
383+
}
384+
385+
// Prune old pulses
386+
Self::prune_old_pulses(last_stored_round);
387+
348388
// Update the next unsigned block number
349389
let current_block = frame_system::Pallet::<T>::block_number();
350390
<NextUnsignedAt<T>>::put(current_block);
@@ -628,6 +668,24 @@ impl<T: Config> Pallet<T> {
628668
.propagate(true)
629669
.build()
630670
}
671+
672+
fn prune_old_pulses(last_stored_round: RoundNumber) {
673+
let mut oldest = OldestStoredRound::<T>::get();
674+
if oldest == 0 {
675+
return;
676+
}
677+
678+
let mut removed: u64 = 0;
679+
while last_stored_round.saturating_sub(oldest) + 1 > MAX_KEPT_PULSES
680+
&& removed < MAX_REMOVED_PULSES
681+
{
682+
Pulses::<T>::remove(oldest);
683+
oldest = oldest.saturating_add(1);
684+
removed = removed.saturating_add(1);
685+
}
686+
687+
OldestStoredRound::<T>::put(oldest);
688+
}
631689
}
632690

633691
/// construct a message (e.g. signed by drand)
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
use crate::*;
2+
use frame_support::{traits::Get, weights::Weight};
3+
use log;
4+
5+
pub fn migrate_prune_old_pulses<T: Config>() -> Weight {
6+
let migration_name = BoundedVec::truncate_from(b"migrate_prune_old_pulses".to_vec());
7+
8+
// Initialize the weight with one read operation.
9+
let mut weight = T::DbWeight::get().reads(1);
10+
11+
// Check if the migration has already run
12+
if HasMigrationRun::<T>::get(&migration_name) {
13+
log::info!(
14+
"Migration '{:?}' has already run. Skipping.",
15+
String::from_utf8_lossy(&migration_name)
16+
);
17+
return weight;
18+
}
19+
log::info!(
20+
"Running migration '{}'",
21+
String::from_utf8_lossy(&migration_name)
22+
);
23+
24+
// Collect all round numbers
25+
let mut rounds: Vec<RoundNumber> = Pulses::<T>::iter_keys().collect();
26+
weight = weight.saturating_add(T::DbWeight::get().reads(rounds.len() as u64));
27+
28+
if rounds.is_empty() {
29+
OldestStoredRound::<T>::put(0u64);
30+
LastStoredRound::<T>::put(0u64);
31+
weight = weight.saturating_add(T::DbWeight::get().writes(2));
32+
} else {
33+
rounds.sort();
34+
let num_pulses = rounds.len() as u64;
35+
36+
let mut new_oldest = rounds[0];
37+
if num_pulses > MAX_KEPT_PULSES {
38+
let num_to_delete = num_pulses - MAX_KEPT_PULSES;
39+
new_oldest = rounds[num_to_delete as usize];
40+
41+
for &round in &rounds[0..num_to_delete as usize] {
42+
Pulses::<T>::remove(round);
43+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
44+
}
45+
}
46+
47+
OldestStoredRound::<T>::put(new_oldest);
48+
LastStoredRound::<T>::put(*rounds.last().unwrap());
49+
weight = weight.saturating_add(T::DbWeight::get().writes(2));
50+
}
51+
52+
// Mark the migration as completed
53+
HasMigrationRun::<T>::insert(&migration_name, true);
54+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
55+
56+
log::info!(
57+
"Migration '{:?}' completed.",
58+
String::from_utf8_lossy(&migration_name)
59+
);
60+
61+
// Return the migration weight.
62+
weight
63+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
pub mod migrate_prune_old_pulses;
2+
pub use migrate_prune_old_pulses::*;

0 commit comments

Comments
 (0)