Skip to content

Commit 81ac427

Browse files
authored
Merge pull request #1964 from opentensor/commit-reveal-mandatory
enable the commit reveal for all subnets
2 parents a48e04d + c5ddb8e commit 81ac427

File tree

17 files changed

+321
-91
lines changed

17 files changed

+321
-91
lines changed

evm-tests/test/neuron.precompile.reveal-weights.test.ts

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ import { generateRandomEthersWallet } from "../src/utils"
1111
import { convertH160ToPublicKey } from "../src/address-utils"
1212
import { blake2AsU8a } from "@polkadot/util-crypto"
1313
import {
14-
forceSetBalanceToEthAddress, forceSetBalanceToSs58Address, addNewSubnetwork, setCommitRevealWeightsEnabled, setWeightsSetRateLimit, burnedRegister,
14+
forceSetBalanceToEthAddress, forceSetBalanceToSs58Address, addNewSubnetwork, setWeightsSetRateLimit, burnedRegister,
1515
setTempo, setCommitRevealWeightsInterval,
16-
startCall
16+
startCall,
1717
} from "../src/subtensor"
1818

1919
// hardcode some values for reveal hash
@@ -52,6 +52,7 @@ describe("Test neuron precompile reveal weights", () => {
5252
const coldkey = getRandomSubstrateKeypair();
5353

5454
let api: TypedApi<typeof devnet>
55+
let commitEpoch: number;
5556

5657
// sudo account alice as signer
5758
let alice: PolkadotSigner;
@@ -65,13 +66,11 @@ describe("Test neuron precompile reveal weights", () => {
6566
await forceSetBalanceToSs58Address(api, convertPublicKeyToSs58(coldkey.publicKey))
6667
await forceSetBalanceToEthAddress(api, wallet.address)
6768
let netuid = await addNewSubnetwork(api, hotkey, coldkey)
69+
// await disableCommitRevealWeights(api, netuid)
6870
await startCall(api, netuid, coldkey)
6971

7072
console.log("test the case on subnet ", netuid)
7173

72-
// enable commit reveal feature
73-
await setCommitRevealWeightsEnabled(api, netuid, true)
74-
// set it as 0, we can set the weight anytime
7574
await setWeightsSetRateLimit(api, netuid, BigInt(0))
7675

7776
const ss58Address = convertH160ToSS58(wallet.address)
@@ -90,8 +89,15 @@ describe("Test neuron precompile reveal weights", () => {
9089
const subnetId = totalNetworks - 1
9190
const commitHash = getCommitHash(subnetId, wallet.address)
9291
const contract = new ethers.Contract(INEURON_ADDRESS, INeuronABI, wallet);
93-
const tx = await contract.commitWeights(subnetId, commitHash)
94-
await tx.wait()
92+
try {
93+
const tx = await contract.commitWeights(subnetId, commitHash)
94+
await tx.wait()
95+
} catch (e) {
96+
console.log("commitWeights failed", e)
97+
}
98+
99+
const commitBlock = await api.query.System.Number.getValue()
100+
commitEpoch = Math.trunc(commitBlock / (100 + 1))
95101

96102
const ss58Address = convertH160ToSS58(wallet.address)
97103

@@ -108,9 +114,19 @@ describe("Test neuron precompile reveal weights", () => {
108114
const netuid = totalNetworks - 1
109115
const contract = new ethers.Contract(INEURON_ADDRESS, INeuronABI, wallet);
110116
// set tempo or epoch large, then enough time to reveal weight
111-
await setTempo(api, netuid, 60000)
112-
// set interval epoch as 0, we can reveal at the same epoch
113-
await setCommitRevealWeightsInterval(api, netuid, BigInt(0))
117+
await setTempo(api, netuid, 100)
118+
// set interval epoch as 1, it is the minimum value now
119+
await setCommitRevealWeightsInterval(api, netuid, BigInt(1))
120+
121+
while (true) {
122+
const currentBlock = await api.query.System.Number.getValue()
123+
const currentEpoch = Math.trunc(currentBlock / (100 + 1))
124+
// wait for one second for fast blocks
125+
if (currentEpoch > commitEpoch) {
126+
break
127+
}
128+
await new Promise(resolve => setTimeout(resolve, 1000))
129+
}
114130

115131
const tx = await contract.revealWeights(
116132
netuid,
@@ -120,6 +136,7 @@ describe("Test neuron precompile reveal weights", () => {
120136
version_key
121137
);
122138
await tx.wait()
139+
123140
const ss58Address = convertH160ToSS58(wallet.address)
124141

125142
// check the weight commit is removed after reveal successfully

pallets/admin-utils/src/lib.rs

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,6 @@ pub mod pallet {
107107
BondsMovingAverageMaxReached,
108108
/// Only root can set negative sigmoid steepness values
109109
NegativeSigmoidSteepness,
110-
/// Reveal Peroid is not within the valid range.
111-
RevealPeriodOutOfBounds,
112110
}
113111
/// Enum for specifying the type of precompile operation.
114112
#[derive(
@@ -1311,14 +1309,10 @@ pub mod pallet {
13111309
Error::<T>::SubnetDoesNotExist
13121310
);
13131311

1314-
const MAX_COMMIT_REVEAL_PEROIDS: u64 = 100;
1315-
ensure!(
1316-
interval <= MAX_COMMIT_REVEAL_PEROIDS,
1317-
Error::<T>::RevealPeriodOutOfBounds
1318-
);
1319-
1320-
pallet_subtensor::Pallet::<T>::set_reveal_period(netuid, interval);
13211312
log::debug!("SetWeightCommitInterval( netuid: {netuid:?}, interval: {interval:?} ) ");
1313+
1314+
pallet_subtensor::Pallet::<T>::set_reveal_period(netuid, interval)?;
1315+
13221316
Ok(())
13231317
}
13241318

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1120,7 +1120,7 @@ fn test_sudo_set_commit_reveal_weights_enabled() {
11201120
let netuid = NetUid::from(1);
11211121
add_network(netuid, 10);
11221122

1123-
let to_be_set: bool = true;
1123+
let to_be_set: bool = false;
11241124
let init_value: bool = SubtensorModule::get_commit_reveal_weights_enabled(netuid);
11251125

11261126
assert_ok!(AdminUtils::sudo_set_commit_reveal_weights_enabled(
@@ -1459,7 +1459,7 @@ fn sudo_set_commit_reveal_weights_interval() {
14591459
netuid,
14601460
too_high
14611461
),
1462-
Error::<Test>::RevealPeriodOutOfBounds
1462+
pallet_subtensor::Error::<Test>::RevealPeriodTooLarge
14631463
);
14641464

14651465
let to_be_set = 55;

pallets/subtensor/src/benchmarks.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ mod pallet_benchmarks {
6060
Subtensor::<T>::set_network_registration_allowed(netuid, true);
6161
Subtensor::<T>::set_max_registrations_per_block(netuid, 4096);
6262
Subtensor::<T>::set_target_registrations_per_interval(netuid, 4096);
63+
Subtensor::<T>::set_commit_reveal_weights_enabled(netuid, false);
6364

6465
let mut seed: u32 = 1;
6566
let mut dests = Vec::new();

pallets/subtensor/src/lib.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,11 @@ pub mod pallet {
106106
/// Minimum balance required to perform a coldkey swap
107107
pub const MIN_BALANCE_TO_PERFORM_COLDKEY_SWAP: TaoCurrency = TaoCurrency::new(100_000_000); // 0.1 TAO in RAO
108108

109+
/// Minimum commit reveal periods
110+
pub const MIN_COMMIT_REVEAL_PEROIDS: u64 = 1;
111+
/// Maximum commit reveal periods
112+
pub const MAX_COMMIT_REVEAL_PEROIDS: u64 = 100;
113+
109114
#[pallet::pallet]
110115
#[pallet::without_storage_info]
111116
#[pallet::storage_version(STORAGE_VERSION)]
@@ -761,7 +766,7 @@ pub mod pallet {
761766
#[pallet::type_value]
762767
/// Default value for weight commit/reveal enabled.
763768
pub fn DefaultCommitRevealWeightsEnabled<T: Config>() -> bool {
764-
false
769+
true
765770
}
766771
#[pallet::type_value]
767772
/// Default value for weight commit/reveal version.

pallets/subtensor/src/macros/errors.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,10 @@ mod errors {
244244
SymbolAlreadyInUse,
245245
/// Incorrect commit-reveal version.
246246
IncorrectCommitRevealVersion,
247+
/// Reveal period is too large.
248+
RevealPeriodTooLarge,
249+
/// Reveal period is too small.
250+
RevealPeriodTooSmall,
247251
/// Generic error for out-of-range parameter value
248252
InvalidValue,
249253
}

pallets/subtensor/src/macros/hooks.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ mod hooks {
130130
.saturating_add(migrations::migrate_subnet_symbols::migrate_subnet_symbols::<T>())
131131
// Migrate CRV3 add commit_block
132132
.saturating_add(migrations::migrate_crv3_commits_add_block::migrate_crv3_commits_add_block::<T>())
133+
// Migrate Commit-Reveal Settings
134+
.saturating_add(migrations::migrate_commit_reveal_settings::migrate_commit_reveal_settings::<T>())
133135
//Migrate CRV3 to TimelockedCommits
134136
.saturating_add(migrations::migrate_crv3_v2_to_timelocked::migrate_crv3_v2_to_timelocked::<T>())
135137
// Migrate to fix root counters
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
use alloc::string::String;
2+
3+
use crate::MIN_COMMIT_REVEAL_PEROIDS;
4+
use frame_support::IterableStorageMap;
5+
use frame_support::{traits::Get, weights::Weight};
6+
use subtensor_runtime_common::NetUid;
7+
8+
use super::*;
9+
10+
pub fn migrate_commit_reveal_settings<T: Config>() -> Weight {
11+
let migration_name = b"migrate_commit_reveal_settings".to_vec();
12+
13+
// Initialize the weight with one read operation.
14+
let mut weight = T::DbWeight::get().reads(1);
15+
16+
// Check if the migration has already run
17+
if HasMigrationRun::<T>::get(&migration_name) {
18+
log::info!(
19+
"Migration '{:?}' has already run. Skipping.",
20+
String::from_utf8_lossy(&migration_name)
21+
);
22+
return weight;
23+
}
24+
log::info!(
25+
"Running migration '{}'",
26+
String::from_utf8_lossy(&migration_name)
27+
);
28+
29+
let netuids: Vec<NetUid> = <NetworksAdded<T> as IterableStorageMap<NetUid, bool>>::iter()
30+
.map(|(netuid, _)| netuid)
31+
.collect();
32+
weight = weight.saturating_add(
33+
T::DbWeight::get()
34+
.reads(netuids.len() as u64)
35+
.saturating_mul(2),
36+
);
37+
38+
for netuid in netuids.iter() {
39+
if netuid.is_root() {
40+
continue;
41+
}
42+
if !CommitRevealWeightsEnabled::<T>::get(*netuid) {
43+
CommitRevealWeightsEnabled::<T>::insert(*netuid, true);
44+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
45+
}
46+
47+
if RevealPeriodEpochs::<T>::get(*netuid) == 0 {
48+
RevealPeriodEpochs::<T>::insert(*netuid, MIN_COMMIT_REVEAL_PEROIDS);
49+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
50+
}
51+
}
52+
53+
// Mark the migration as completed
54+
HasMigrationRun::<T>::insert(&migration_name, true);
55+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
56+
57+
log::info!(
58+
"Migration '{:?}' completed.",
59+
String::from_utf8_lossy(&migration_name)
60+
);
61+
62+
// Return the migration weight.
63+
weight
64+
}

pallets/subtensor/src/migrations/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use sp_io::hashing::twox_128;
66
use sp_io::storage::clear_prefix;
77
pub mod migrate_chain_identity;
88
pub mod migrate_coldkey_swap_scheduled;
9+
pub mod migrate_commit_reveal_settings;
910
pub mod migrate_commit_reveal_v2;
1011
pub mod migrate_create_root_network;
1112
pub mod migrate_crv3_commits_add_block;

pallets/subtensor/src/subnets/weights.rs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use super::*;
22
use crate::epoch::math::*;
3+
use crate::{Error, MAX_COMMIT_REVEAL_PEROIDS, MIN_COMMIT_REVEAL_PEROIDS};
34
use codec::Compact;
5+
use frame_support::dispatch::DispatchResult;
46
use safe_math::*;
57
use sp_core::{ConstU32, H256};
68
use sp_runtime::{
@@ -9,7 +11,6 @@ use sp_runtime::{
911
};
1012
use sp_std::{collections::vec_deque::VecDeque, vec};
1113
use subtensor_runtime_common::NetUid;
12-
1314
impl<T: Config> Pallet<T> {
1415
/// ---- The implementation for committing weight hashes.
1516
///
@@ -1062,9 +1063,21 @@ impl<T: Config> Pallet<T> {
10621063
(first_reveal_block, last_reveal_block)
10631064
}
10641065

1065-
pub fn set_reveal_period(netuid: NetUid, reveal_period: u64) {
1066+
pub fn set_reveal_period(netuid: NetUid, reveal_period: u64) -> DispatchResult {
1067+
ensure!(
1068+
reveal_period <= MAX_COMMIT_REVEAL_PEROIDS,
1069+
Error::<T>::RevealPeriodTooLarge
1070+
);
1071+
1072+
ensure!(
1073+
reveal_period >= MIN_COMMIT_REVEAL_PEROIDS,
1074+
Error::<T>::RevealPeriodTooSmall
1075+
);
1076+
10661077
RevealPeriodEpochs::<T>::insert(netuid, reveal_period);
1078+
10671079
Self::deposit_event(Event::CommitRevealPeriodsSet(netuid, reveal_period));
1080+
Ok(())
10681081
}
10691082
pub fn get_reveal_period(netuid: NetUid) -> u64 {
10701083
RevealPeriodEpochs::<T>::get(netuid)

0 commit comments

Comments
 (0)