Skip to content

Commit

Permalink
Merge pull request #396 from opentensor/commit-reveal-weights
Browse files Browse the repository at this point in the history
Commit-Reveal Weights
  • Loading branch information
distributedstatemachine authored May 14, 2024
2 parents c823cd8 + 22a9a66 commit dd93e0c
Show file tree
Hide file tree
Showing 5 changed files with 788 additions and 109 deletions.
87 changes: 87 additions & 0 deletions pallets/subtensor/src/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use frame_benchmarking::{account, benchmarks, whitelisted_caller};
use frame_support::assert_ok;
use frame_system::RawOrigin;
pub use pallet::*;
use sp_core::H256;
use sp_runtime::traits::{BlakeTwo256, Hash};
use sp_std::vec;

benchmarks! {
Expand Down Expand Up @@ -333,4 +335,89 @@ benchmarks! {
assert_ok!(Subtensor::<T>::add_stake(RawOrigin::Signed(coldkey).into(), old_hotkey.clone(), 1_000_000_000));
}
}: _(RawOrigin::Signed(coldkey), old_hotkey, new_hotkey)

commit_weights {
let tempo: u16 = 1;
let netuid: u16 = 1;
let version_key: u64 = 0;
let uids: Vec<u16> = vec![0];
let weight_values: Vec<u16> = vec![10];
let hotkey: T::AccountId = account("hot", 0, 1);
let coldkey: T::AccountId = account("cold", 0, 2);
let start_nonce = 300000;

let commit_hash: H256 = BlakeTwo256::hash_of(&(
hotkey.clone(),
netuid,
uids.clone(),
weight_values.clone(),
version_key,
));

Subtensor::<T>::init_new_network(netuid, tempo);

let block_number: u64 = Subtensor::<T>::get_current_block_as_u64();
let (nonce, work): (u64, Vec<u8>) = Subtensor::<T>::create_work_for_block_number(
netuid,
block_number,
start_nonce,
&hotkey,
);
let result = Subtensor::<T>::register(
<T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(hotkey.clone())),
netuid,
block_number,
nonce,
work,
hotkey.clone(),
coldkey,
);
Subtensor::<T>::set_validator_permit_for_uid(netuid, 0, true);

}: commit_weights(RawOrigin::Signed(hotkey.clone()), netuid, commit_hash)

reveal_weights {
let tempo: u16 = 0;
let netuid: u16 = 1;
let version_key: u64 = 0;
let uids: Vec<u16> = vec![0];
let weight_values: Vec<u16> = vec![10];
let hotkey: T::AccountId = account("hot", 0, 1);
let coldkey: T::AccountId = account("cold", 1, 2);

Subtensor::<T>::init_new_network(netuid, tempo);
Subtensor::<T>::set_network_registration_allowed(netuid, true);
Subtensor::<T>::set_network_pow_registration_allowed(netuid, true);

let block_number: u64 = Subtensor::<T>::get_current_block_as_u64();
let (nonce, work): (u64, Vec<u8>) = Subtensor::<T>::create_work_for_block_number(
netuid,
block_number,
3,
&hotkey,
);

let _ = Subtensor::<T>::register(
<T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(hotkey.clone())),
netuid,
block_number,
nonce,
work.clone(),
hotkey.clone(),
coldkey.clone(),
);

Subtensor::<T>::set_validator_permit_for_uid(netuid, 0, true);
Subtensor::<T>::set_weight_commit_interval(0);

let commit_hash: H256 = BlakeTwo256::hash_of(&(
hotkey.clone(),
netuid,
uids.clone(),
weight_values.clone(),
version_key,
));
let _ = Subtensor::<T>::commit_weights(<T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(hotkey.clone())), netuid, commit_hash);

}: reveal_weights(RawOrigin::Signed(hotkey.clone()), netuid, uids, weight_values, version_key)
}
8 changes: 8 additions & 0 deletions pallets/subtensor/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,13 @@ mod errors {
NomStakeBelowMinimumThreshold,
/// delegate take is being set out of bounds
InvalidTake,
/// Not allowed to commit weights
CommitNotAllowed,
/// No commit found for provided hotkey+netuid when attempting to reveal weights
NoCommitFound,
/// Not the correct block/range to reveal weights
InvalidRevealTempo,
/// Committed hash does not equal the hashed reveal data
InvalidReveal,
}
}
130 changes: 127 additions & 3 deletions pallets/subtensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ pub mod pallet {
traits::{tokens::fungible, UnfilteredDispatchable},
};
use frame_system::pallet_prelude::*;
use sp_core::H256;
use sp_runtime::traits::TrailingZeroInput;
use sp_std::vec;
use sp_std::vec::Vec;
Expand Down Expand Up @@ -786,6 +787,27 @@ pub mod pallet {
pub type AdjustmentAlpha<T: Config> =
StorageMap<_, Identity, u16, u64, ValueQuery, DefaultAdjustmentAlpha<T>>;

// --- MAP (netuid, who) --> (hash, weight) | Returns the hash and weight committed by an account for a given netuid.
#[pallet::storage]
pub type WeightCommits<T: Config> = StorageDoubleMap<
_,
Twox64Concat,
u16,
Twox64Concat,
T::AccountId,
(H256, u64),
OptionQuery,
>;

#[pallet::type_value]
pub fn DefaultWeightCommitRevealInterval<T: Config>() -> u64 {
1000
}

#[pallet::storage]
pub type WeightCommitRevealInterval<T> =
StorageValue<_, u64, ValueQuery, DefaultWeightCommitRevealInterval<T>>;

// =======================================
// ==== Subnetwork Consensus Storage ====
// =======================================
Expand Down Expand Up @@ -1184,8 +1206,8 @@ pub mod pallet {
// - Attempting to set weights with max value exceeding limit.
#[pallet::call_index(0)]
#[pallet::weight((Weight::from_parts(10_151_000_000, 0)
.saturating_add(T::DbWeight::get().reads(4104))
.saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))]
.saturating_add(T::DbWeight::get().reads(4104))
.saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))]
pub fn set_weights(
origin: OriginFor<T>,
netuid: u16,
Expand All @@ -1196,6 +1218,76 @@ pub mod pallet {
Self::do_set_weights(origin, netuid, dests, weights, version_key)
}

/// ---- Used to commit a hash of your weight values to later be revealed.
///
/// # Args:
/// * `origin`: (`<T as frame_system::Config>::RuntimeOrigin`):
/// - The signature of the committing hotkey.
///
/// * `netuid` (`u16`):
/// - The u16 network identifier.
///
/// * `commit_hash` (`H256`):
/// - The hash representing the committed weights.
///
/// # Raises:
/// * `CommitNotAllowed`:
/// - Attempting to commit when it is not allowed.
///
#[pallet::call_index(96)]
#[pallet::weight((Weight::from_parts(46_000_000, 0)
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::No))]
pub fn commit_weights(
origin: T::RuntimeOrigin,
netuid: u16,
commit_hash: H256,
) -> DispatchResult {
Self::do_commit_weights(origin, netuid, commit_hash)
}

/// ---- Used to reveal the weights for a previously committed hash.
///
/// # Args:
/// * `origin`: (`<T as frame_system::Config>::RuntimeOrigin`):
/// - The signature of the revealing hotkey.
///
/// * `netuid` (`u16`):
/// - The u16 network identifier.
///
/// * `uids` (`Vec<u16>`):
/// - The uids for the weights being revealed.
///
/// * `values` (`Vec<u16>`):
/// - The values of the weights being revealed.
///
/// * `version_key` (`u64`):
/// - The network version key.
///
/// # Raises:
/// * `NoCommitFound`:
/// - Attempting to reveal weights without an existing commit.
///
/// * `InvalidRevealTempo`:
/// - Attempting to reveal weights outside the valid tempo.
///
/// * `InvalidReveal`:
/// - The revealed hash does not match the committed hash.
///
#[pallet::call_index(97)]
#[pallet::weight((Weight::from_parts(103_000_000, 0)
.saturating_add(T::DbWeight::get().reads(11))
.saturating_add(T::DbWeight::get().writes(3)), DispatchClass::Normal, Pays::No))]
pub fn reveal_weights(
origin: T::RuntimeOrigin,
netuid: u16,
uids: Vec<u16>,
values: Vec<u16>,
version_key: u64,
) -> DispatchResult {
Self::do_reveal_weights(origin, netuid, uids, values, version_key)
}

// # Args:
// * `origin`: (<T as frame_system::Config>Origin):
// - The caller, a hotkey who wishes to set their weights.
Expand Down Expand Up @@ -1756,7 +1848,7 @@ pub mod pallet {

#[pallet::call_index(60)]
#[pallet::weight((Weight::from_parts(91_000_000, 0)
.saturating_add(T::DbWeight::get().reads(27))
.saturating_add(T::DbWeight::get().reads(27))
.saturating_add(T::DbWeight::get().writes(22)), DispatchClass::Normal, Pays::No))]
pub fn faucet(
origin: OriginFor<T>,
Expand Down Expand Up @@ -1908,6 +2000,30 @@ where
_len: usize,
) -> TransactionValidity {
match call.is_sub_type() {
Some(Call::commit_weights { netuid, .. }) => {
if Self::check_weights_min_stake(who) {
let priority: u64 = Self::get_priority_set_weights(who, *netuid);
Ok(ValidTransaction {
priority,
longevity: 1,
..Default::default()
})
} else {
Err(InvalidTransaction::Call.into())
}
}
Some(Call::reveal_weights { netuid, .. }) => {
if Self::check_weights_min_stake(who) {
let priority: u64 = Self::get_priority_set_weights(who, *netuid);
Ok(ValidTransaction {
priority,
longevity: 1,
..Default::default()
})
} else {
Err(InvalidTransaction::Call.into())
}
}
Some(Call::set_weights { netuid, .. }) => {
if Self::check_weights_min_stake(who) {
let priority: u64 = Self::get_priority_set_weights(who, *netuid);
Expand Down Expand Up @@ -1986,6 +2102,14 @@ where
let transaction_fee = 0;
Ok((CallType::SetWeights, transaction_fee, who.clone()))
}
Some(Call::commit_weights { .. }) => {
let transaction_fee = 0;
Ok((CallType::SetWeights, transaction_fee, who.clone()))
}
Some(Call::reveal_weights { .. }) => {
let transaction_fee = 0;
Ok((CallType::SetWeights, transaction_fee, who.clone()))
}
Some(Call::register { .. }) => {
let transaction_fee = 0;
Ok((CallType::Register, transaction_fee, who.clone()))
Expand Down
Loading

0 comments on commit dd93e0c

Please sign in to comment.