Skip to content
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
37 changes: 27 additions & 10 deletions evm-tests/test/neuron.precompile.reveal-weights.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import { generateRandomEthersWallet } from "../src/utils"
import { convertH160ToPublicKey } from "../src/address-utils"
import { blake2AsU8a } from "@polkadot/util-crypto"
import {
forceSetBalanceToEthAddress, forceSetBalanceToSs58Address, addNewSubnetwork, setCommitRevealWeightsEnabled, setWeightsSetRateLimit, burnedRegister,
forceSetBalanceToEthAddress, forceSetBalanceToSs58Address, addNewSubnetwork, setWeightsSetRateLimit, burnedRegister,
setTempo, setCommitRevealWeightsInterval,
startCall
startCall,
} from "../src/subtensor"

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

let api: TypedApi<typeof devnet>
let commitEpoch: number;

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

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

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

const ss58Address = convertH160ToSS58(wallet.address)
Expand All @@ -90,8 +89,15 @@ describe("Test neuron precompile reveal weights", () => {
const subnetId = totalNetworks - 1
const commitHash = getCommitHash(subnetId, wallet.address)
const contract = new ethers.Contract(INEURON_ADDRESS, INeuronABI, wallet);
const tx = await contract.commitWeights(subnetId, commitHash)
await tx.wait()
try {
const tx = await contract.commitWeights(subnetId, commitHash)
await tx.wait()
} catch (e) {
console.log("commitWeights failed", e)
}

const commitBlock = await api.query.System.Number.getValue()
commitEpoch = Math.trunc(commitBlock / (100 + 1))

const ss58Address = convertH160ToSS58(wallet.address)

Expand All @@ -108,9 +114,19 @@ describe("Test neuron precompile reveal weights", () => {
const netuid = totalNetworks - 1
const contract = new ethers.Contract(INEURON_ADDRESS, INeuronABI, wallet);
// set tempo or epoch large, then enough time to reveal weight
await setTempo(api, netuid, 60000)
// set interval epoch as 0, we can reveal at the same epoch
await setCommitRevealWeightsInterval(api, netuid, BigInt(0))
await setTempo(api, netuid, 100)
// set interval epoch as 1, it is the minimum value now
await setCommitRevealWeightsInterval(api, netuid, BigInt(1))

while (true) {
const currentBlock = await api.query.System.Number.getValue()
const currentEpoch = Math.trunc(currentBlock / (100 + 1))
// wait for one second for fast blocks
if (currentEpoch > commitEpoch) {
break
}
await new Promise(resolve => setTimeout(resolve, 1000))
}

const tx = await contract.revealWeights(
netuid,
Expand All @@ -120,6 +136,7 @@ describe("Test neuron precompile reveal weights", () => {
version_key
);
await tx.wait()

const ss58Address = convertH160ToSS58(wallet.address)

// check the weight commit is removed after reveal successfully
Expand Down
12 changes: 3 additions & 9 deletions pallets/admin-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,6 @@ pub mod pallet {
BondsMovingAverageMaxReached,
/// Only root can set negative sigmoid steepness values
NegativeSigmoidSteepness,
/// Reveal Peroid is not within the valid range.
RevealPeriodOutOfBounds,
}
/// Enum for specifying the type of precompile operation.
#[derive(
Expand Down Expand Up @@ -1311,14 +1309,10 @@ pub mod pallet {
Error::<T>::SubnetDoesNotExist
);

const MAX_COMMIT_REVEAL_PEROIDS: u64 = 100;
ensure!(
interval <= MAX_COMMIT_REVEAL_PEROIDS,
Error::<T>::RevealPeriodOutOfBounds
);

pallet_subtensor::Pallet::<T>::set_reveal_period(netuid, interval);
log::debug!("SetWeightCommitInterval( netuid: {netuid:?}, interval: {interval:?} ) ");

pallet_subtensor::Pallet::<T>::set_reveal_period(netuid, interval)?;

Ok(())
}

Expand Down
4 changes: 2 additions & 2 deletions pallets/admin-utils/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1120,7 +1120,7 @@ fn test_sudo_set_commit_reveal_weights_enabled() {
let netuid = NetUid::from(1);
add_network(netuid, 10);

let to_be_set: bool = true;
let to_be_set: bool = false;
let init_value: bool = SubtensorModule::get_commit_reveal_weights_enabled(netuid);

assert_ok!(AdminUtils::sudo_set_commit_reveal_weights_enabled(
Expand Down Expand Up @@ -1459,7 +1459,7 @@ fn sudo_set_commit_reveal_weights_interval() {
netuid,
too_high
),
Error::<Test>::RevealPeriodOutOfBounds
pallet_subtensor::Error::<Test>::RevealPeriodTooLarge
);

let to_be_set = 55;
Expand Down
1 change: 1 addition & 0 deletions pallets/subtensor/src/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ mod pallet_benchmarks {
Subtensor::<T>::set_network_registration_allowed(netuid, true);
Subtensor::<T>::set_max_registrations_per_block(netuid, 4096);
Subtensor::<T>::set_target_registrations_per_interval(netuid, 4096);
Subtensor::<T>::set_commit_reveal_weights_enabled(netuid, false);

let mut seed: u32 = 1;
let mut dests = Vec::new();
Expand Down
7 changes: 6 additions & 1 deletion pallets/subtensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ pub mod pallet {
/// Minimum balance required to perform a coldkey swap
pub const MIN_BALANCE_TO_PERFORM_COLDKEY_SWAP: TaoCurrency = TaoCurrency::new(100_000_000); // 0.1 TAO in RAO

/// Minimum commit reveal periods
pub const MIN_COMMIT_REVEAL_PEROIDS: u64 = 1;
/// Maximum commit reveal periods
pub const MAX_COMMIT_REVEAL_PEROIDS: u64 = 100;

#[pallet::pallet]
#[pallet::without_storage_info]
#[pallet::storage_version(STORAGE_VERSION)]
Expand Down Expand Up @@ -761,7 +766,7 @@ pub mod pallet {
#[pallet::type_value]
/// Default value for weight commit/reveal enabled.
pub fn DefaultCommitRevealWeightsEnabled<T: Config>() -> bool {
false
true
}
#[pallet::type_value]
/// Default value for weight commit/reveal version.
Expand Down
4 changes: 4 additions & 0 deletions pallets/subtensor/src/macros/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,10 @@ mod errors {
SymbolAlreadyInUse,
/// Incorrect commit-reveal version.
IncorrectCommitRevealVersion,
/// Reveal period is too large.
RevealPeriodTooLarge,
/// Reveal period is too small.
RevealPeriodTooSmall,
/// Generic error for out-of-range parameter value
InvalidValue,
}
Expand Down
2 changes: 2 additions & 0 deletions pallets/subtensor/src/macros/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ mod hooks {
.saturating_add(migrations::migrate_subnet_symbols::migrate_subnet_symbols::<T>())
// Migrate CRV3 add commit_block
.saturating_add(migrations::migrate_crv3_commits_add_block::migrate_crv3_commits_add_block::<T>())
// Migrate Commit-Reveal Settings
.saturating_add(migrations::migrate_commit_reveal_settings::migrate_commit_reveal_settings::<T>())
//Migrate CRV3 to TimelockedCommits
.saturating_add(migrations::migrate_crv3_v2_to_timelocked::migrate_crv3_v2_to_timelocked::<T>())
// Migrate to fix root counters
Expand Down
64 changes: 64 additions & 0 deletions pallets/subtensor/src/migrations/migrate_commit_reveal_settings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use alloc::string::String;

use crate::MIN_COMMIT_REVEAL_PEROIDS;
use frame_support::IterableStorageMap;
use frame_support::{traits::Get, weights::Weight};
use subtensor_runtime_common::NetUid;

use super::*;

pub fn migrate_commit_reveal_settings<T: Config>() -> Weight {
let migration_name = b"migrate_commit_reveal_settings".to_vec();

// Initialize the weight with one read operation.
let mut weight = T::DbWeight::get().reads(1);

// Check if the migration has already run
if HasMigrationRun::<T>::get(&migration_name) {
log::info!(
"Migration '{:?}' has already run. Skipping.",
String::from_utf8_lossy(&migration_name)
);
return weight;
}
log::info!(
"Running migration '{}'",
String::from_utf8_lossy(&migration_name)
);

let netuids: Vec<NetUid> = <NetworksAdded<T> as IterableStorageMap<NetUid, bool>>::iter()
.map(|(netuid, _)| netuid)
.collect();
weight = weight.saturating_add(
T::DbWeight::get()
.reads(netuids.len() as u64)
.saturating_mul(2),
);

for netuid in netuids.iter() {
if netuid.is_root() {
continue;
}
if !CommitRevealWeightsEnabled::<T>::get(*netuid) {
CommitRevealWeightsEnabled::<T>::insert(*netuid, true);
weight = weight.saturating_add(T::DbWeight::get().writes(1));
}

if RevealPeriodEpochs::<T>::get(*netuid) == 0 {
RevealPeriodEpochs::<T>::insert(*netuid, MIN_COMMIT_REVEAL_PEROIDS);
weight = weight.saturating_add(T::DbWeight::get().writes(1));
}
}

// Mark the migration as completed
HasMigrationRun::<T>::insert(&migration_name, true);
weight = weight.saturating_add(T::DbWeight::get().writes(1));

log::info!(
"Migration '{:?}' completed.",
String::from_utf8_lossy(&migration_name)
);

// Return the migration weight.
weight
}
1 change: 1 addition & 0 deletions pallets/subtensor/src/migrations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use sp_io::hashing::twox_128;
use sp_io::storage::clear_prefix;
pub mod migrate_chain_identity;
pub mod migrate_coldkey_swap_scheduled;
pub mod migrate_commit_reveal_settings;
pub mod migrate_commit_reveal_v2;
pub mod migrate_create_root_network;
pub mod migrate_crv3_commits_add_block;
Expand Down
17 changes: 15 additions & 2 deletions pallets/subtensor/src/subnets/weights.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use super::*;
use crate::epoch::math::*;
use crate::{Error, MAX_COMMIT_REVEAL_PEROIDS, MIN_COMMIT_REVEAL_PEROIDS};
use codec::Compact;
use frame_support::dispatch::DispatchResult;
use safe_math::*;
use sp_core::{ConstU32, H256};
use sp_runtime::{
Expand All @@ -9,7 +11,6 @@ use sp_runtime::{
};
use sp_std::{collections::vec_deque::VecDeque, vec};
use subtensor_runtime_common::NetUid;

impl<T: Config> Pallet<T> {
/// ---- The implementation for committing weight hashes.
///
Expand Down Expand Up @@ -1062,9 +1063,21 @@ impl<T: Config> Pallet<T> {
(first_reveal_block, last_reveal_block)
}

pub fn set_reveal_period(netuid: NetUid, reveal_period: u64) {
pub fn set_reveal_period(netuid: NetUid, reveal_period: u64) -> DispatchResult {
ensure!(
reveal_period <= MAX_COMMIT_REVEAL_PEROIDS,
Error::<T>::RevealPeriodTooLarge
);

ensure!(
reveal_period >= MIN_COMMIT_REVEAL_PEROIDS,
Error::<T>::RevealPeriodTooSmall
);

RevealPeriodEpochs::<T>::insert(netuid, reveal_period);

Self::deposit_event(Event::CommitRevealPeriodsSet(netuid, reveal_period));
Ok(())
}
pub fn get_reveal_period(netuid: NetUid) -> u64 {
RevealPeriodEpochs::<T>::get(netuid)
Expand Down
8 changes: 5 additions & 3 deletions pallets/subtensor/src/tests/children.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2637,7 +2637,8 @@ fn test_childkey_set_weights_single_parent() {
new_test_ext(1).execute_with(|| {
let subnet_owner_coldkey = U256::from(1001);
let subnet_owner_hotkey = U256::from(1002);
let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey);
let netuid =
add_dynamic_network_disable_commit_reveal(&subnet_owner_hotkey, &subnet_owner_coldkey);
Tempo::<Test>::insert(netuid, 1);

// Define hotkeys
Expand Down Expand Up @@ -2746,7 +2747,8 @@ fn test_set_weights_no_parent() {
new_test_ext(1).execute_with(|| {
let subnet_owner_coldkey = U256::from(1001);
let subnet_owner_hotkey = U256::from(1002);
let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey);
let netuid =
add_dynamic_network_disable_commit_reveal(&subnet_owner_hotkey, &subnet_owner_coldkey);

let hotkey: U256 = U256::from(2);
let spare_hk: U256 = U256::from(3);
Expand Down Expand Up @@ -3568,7 +3570,7 @@ fn test_dividend_distribution_with_children() {
fn test_dynamic_parent_child_relationships() {
new_test_ext(1).execute_with(|| {
let netuid = NetUid::from(1);
add_network(netuid, 1, 0);
add_network_disable_commit_reveal(netuid, 1, 0);

// Define hotkeys and coldkeys
let parent = U256::from(1);
Expand Down
4 changes: 3 additions & 1 deletion pallets/subtensor/src/tests/coinbase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2444,7 +2444,7 @@ fn test_drain_pending_emission_no_miners_all_drained() {
#[test]
fn test_drain_pending_emission_zero_emission() {
new_test_ext(1).execute_with(|| {
let netuid = add_dynamic_network(&U256::from(1), &U256::from(2));
let netuid = add_dynamic_network_disable_commit_reveal(&U256::from(1), &U256::from(2));
let hotkey = U256::from(3);
let coldkey = U256::from(4);
let miner_hk = U256::from(5);
Expand Down Expand Up @@ -2522,6 +2522,7 @@ fn test_run_coinbase_not_started() {
let sn_owner_ck = U256::from(8);

add_network_without_emission_block(netuid, tempo, 0);
SubtensorModule::set_commit_reveal_weights_enabled(netuid, false);
assert_eq!(FirstEmissionBlockNumber::<Test>::get(netuid), None);

SubnetOwner::<Test>::insert(netuid, sn_owner_ck);
Expand Down Expand Up @@ -2610,6 +2611,7 @@ fn test_run_coinbase_not_started_start_after() {
let sn_owner_ck = U256::from(8);

add_network_without_emission_block(netuid, tempo, 0);
SubtensorModule::set_commit_reveal_weights_enabled(netuid, false);
assert_eq!(FirstEmissionBlockNumber::<Test>::get(netuid), None);

SubnetOwner::<Test>::insert(netuid, sn_owner_ck);
Expand Down
Loading
Loading