Skip to content

Commit 67a31c9

Browse files
authored
Merge branch 'devnet-ready' into clean-up-subnet-identities-storage
2 parents a38b4e9 + d802832 commit 67a31c9

File tree

7 files changed

+190
-49
lines changed

7 files changed

+190
-49
lines changed

node/src/mev_shield/author.rs

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,6 @@ where
337337
traits::{ConstU32, TransactionExtension},
338338
};
339339

340-
// Helper: map a Block hash to H256
341340
fn to_h256<H: AsRef<[u8]>>(h: H) -> H256 {
342341
let bytes = h.as_ref();
343342
let mut out = [0u8; 32];
@@ -356,7 +355,7 @@ where
356355
dst.copy_from_slice(src);
357356
H256(out)
358357
} else {
359-
// Extremely unlikely; fall back to zeroed H256 if indices are somehow invalid.
358+
// Extremely defensive fallback.
360359
H256([0u8; 32])
361360
}
362361
}
@@ -365,9 +364,10 @@ where
365364
let public_key: BoundedVec<u8, MaxPk> = BoundedVec::try_from(next_public_key)
366365
.map_err(|_| anyhow::anyhow!("public key too long (>2048 bytes)"))?;
367366

368-
// 1) The runtime call carrying public key bytes.
367+
// 1) Runtime call carrying the public key bytes.
369368
let call = RuntimeCall::MevShield(pallet_shield::Call::announce_next_key { public_key });
370369

370+
// 2) Build the transaction extensions exactly like the runtime.
371371
type Extra = runtime::TransactionExtensions;
372372
let extra: Extra =
373373
(
@@ -390,42 +390,44 @@ where
390390
frame_metadata_hash_extension::CheckMetadataHash::<runtime::Runtime>::new(false),
391391
);
392392

393+
// 3) Manually construct the `Implicit` tuple that the runtime will also derive.
393394
type Implicit = <Extra as TransactionExtension<RuntimeCall>>::Implicit;
394395

395396
let info = client.info();
396397
let genesis_h256: H256 = to_h256(info.genesis_hash);
397398

398399
let implicit: Implicit = (
399400
(), // CheckNonZeroSender
400-
runtime::VERSION.spec_version, // CheckSpecVersion
401-
runtime::VERSION.transaction_version, // CheckTxVersion
402-
genesis_h256, // CheckGenesis
403-
genesis_h256, // CheckEra (Immortal)
404-
(), // CheckNonce (additional part)
405-
(), // CheckWeight
406-
(), // ChargeTransactionPaymentWrapper (additional part)
407-
(), // SubtensorTransactionExtension (additional part)
408-
(), // DrandPriority
409-
None, // CheckMetadataHash (disabled)
401+
runtime::VERSION.spec_version, // CheckSpecVersion::Implicit = u32
402+
runtime::VERSION.transaction_version, // CheckTxVersion::Implicit = u32
403+
genesis_h256, // CheckGenesis::Implicit = Hash
404+
genesis_h256, // CheckEra::Implicit (Immortal => genesis hash)
405+
(), // CheckNonce::Implicit = ()
406+
(), // CheckWeight::Implicit = ()
407+
(), // ChargeTransactionPaymentWrapper::Implicit = ()
408+
(), // SubtensorTransactionExtension::Implicit = ()
409+
(), // DrandPriority::Implicit = ()
410+
None, // CheckMetadataHash::Implicit = Option<[u8; 32]>
410411
);
411412

412-
// Build the exact signable payload.
413+
// 4) Build the exact signable payload from call + extra + implicit.
413414
let payload: SignedPayload = SignedPayload::from_raw(call.clone(), extra.clone(), implicit);
414415

415-
let raw_payload = payload.encode();
416-
417-
// Sign with the local Aura key.
418-
let sig_opt = keystore
419-
.sr25519_sign(AURA_KEY_TYPE, &aura_pub, &raw_payload)
416+
// 5) Sign with the local Aura key using the same SCALE bytes the runtime expects.
417+
let sig_opt = payload
418+
.using_encoded(|bytes| keystore.sr25519_sign(AURA_KEY_TYPE, &aura_pub, bytes))
420419
.map_err(|e| anyhow::anyhow!("keystore sr25519_sign error: {e:?}"))?;
420+
421421
let sig = sig_opt
422422
.ok_or_else(|| anyhow::anyhow!("keystore sr25519_sign returned None for Aura key"))?;
423423

424424
let signature: MultiSignature = sig.into();
425425

426+
// 6) Sender address = AccountId32 derived from the Aura sr25519 public key.
426427
let who: AccountId32 = aura_pub.into();
427428
let address = sp_runtime::MultiAddress::Id(who);
428429

430+
// 7) Assemble the signed extrinsic and submit it to the pool.
429431
let uxt: UncheckedExtrinsic = UncheckedExtrinsic::new_signed(call, address, signature, extra);
430432

431433
let xt_bytes = uxt.encode();

pallets/subtensor/src/macros/hooks.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,8 @@ mod hooks {
159159
.saturating_add(migrations::migrate_reset_unactive_sn::migrate_reset_unactive_sn::<T>())
160160
// Remove old identity map entries(Identities, SubnetIdentities, SubnetIdentitiesV2)
161161
.saturating_add(migrations::migrate_remove_old_identity_maps::migrate_remove_old_identity_maps::<T>());
162+
// Remove unknown neuron axon, certificate prom
163+
.saturating_add(migrations::migrate_remove_unknown_neuron_axon_cert_prom::migrate_remove_unknown_neuron_axon_cert_prom::<T>());
162164
weight
163165
}
164166

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
use super::*;
2+
use crate::HasMigrationRun;
3+
use frame_support::{traits::Get, weights::Weight};
4+
use scale_info::prelude::string::String;
5+
use sp_std::collections::btree_set::BTreeSet;
6+
7+
pub fn migrate_remove_unknown_neuron_axon_cert_prom<T: Config>() -> Weight {
8+
let migration_name = b"migrate_remove_neuron_axon_cert_prom".to_vec();
9+
let mut weight: Weight = T::DbWeight::get().reads(1);
10+
11+
// Skip if already executed
12+
if HasMigrationRun::<T>::get(&migration_name) {
13+
log::info!(
14+
target: "runtime",
15+
"Migration '{}' already run - skipping.",
16+
String::from_utf8_lossy(&migration_name)
17+
);
18+
return weight;
19+
}
20+
log::info!(
21+
"Running migration '{}'",
22+
String::from_utf8_lossy(&migration_name)
23+
);
24+
25+
for network in NetworksAdded::<T>::iter_keys() {
26+
weight.saturating_accrue(T::DbWeight::get().reads(1));
27+
28+
let hotkeys = BTreeSet::from_iter(Uids::<T>::iter_key_prefix(network));
29+
weight.saturating_accrue(T::DbWeight::get().reads(hotkeys.len() as u64));
30+
31+
// Axons
32+
let axons = Axons::<T>::iter_key_prefix(network).collect::<Vec<_>>();
33+
weight.saturating_accrue(T::DbWeight::get().reads(axons.len() as u64));
34+
let mut cleaned_axons: u32 = 0;
35+
for axon_hotkey in axons {
36+
if !hotkeys.contains(&axon_hotkey) {
37+
Axons::<T>::remove(network, &axon_hotkey);
38+
cleaned_axons = cleaned_axons.saturating_add(1);
39+
}
40+
}
41+
weight.saturating_accrue(T::DbWeight::get().writes(cleaned_axons as u64));
42+
43+
// Neuron Certificates
44+
let certificates = NeuronCertificates::<T>::iter_key_prefix(network).collect::<Vec<_>>();
45+
weight.saturating_accrue(T::DbWeight::get().reads(certificates.len() as u64));
46+
let mut cleaned_certificates: u32 = 0;
47+
for certificate_hotkey in certificates {
48+
if !hotkeys.contains(&certificate_hotkey) {
49+
NeuronCertificates::<T>::remove(network, &certificate_hotkey);
50+
cleaned_certificates = cleaned_certificates.saturating_add(1);
51+
}
52+
}
53+
weight.saturating_accrue(T::DbWeight::get().writes(cleaned_certificates as u64));
54+
55+
// Prometheus
56+
let prometheus = Prometheus::<T>::iter_key_prefix(network).collect::<Vec<_>>();
57+
weight.saturating_accrue(T::DbWeight::get().reads(prometheus.len() as u64));
58+
let mut cleaned_prometheus: u32 = 0;
59+
for prometheus_hotkey in prometheus {
60+
if !hotkeys.contains(&prometheus_hotkey) {
61+
Prometheus::<T>::remove(network, &prometheus_hotkey);
62+
cleaned_prometheus = cleaned_prometheus.saturating_add(1);
63+
}
64+
}
65+
weight.saturating_accrue(T::DbWeight::get().writes(cleaned_prometheus as u64));
66+
67+
log::info!(
68+
"Cleaned {cleaned_axons} axons, {cleaned_certificates} neuron certificates, {cleaned_prometheus} prometheus for network {network}"
69+
);
70+
}
71+
72+
HasMigrationRun::<T>::insert(&migration_name, true);
73+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
74+
75+
log::info!(
76+
"Migration '{:?}' completed successfully.",
77+
String::from_utf8_lossy(&migration_name)
78+
);
79+
80+
log::info!("{weight:#?} weight");
81+
82+
weight
83+
}

pallets/subtensor/src/migrations/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ pub mod migrate_remove_old_identity_maps;
3636
pub mod migrate_remove_stake_map;
3737
pub mod migrate_remove_tao_dividends;
3838
pub mod migrate_remove_total_hotkey_coldkey_stakes_this_interval;
39+
pub mod migrate_remove_unknown_neuron_axon_cert_prom;
3940
pub mod migrate_remove_unused_maps_and_values;
4041
pub mod migrate_remove_zero_total_hotkey_alpha;
4142
pub mod migrate_reset_bonds_moving_average;

pallets/subtensor/src/subnets/uids.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,14 +88,13 @@ impl<T: Config> Pallet<T> {
8888
BlockAtRegistration::<T>::insert(netuid, uid_to_replace, block_number); // Fill block at registration.
8989
IsNetworkMember::<T>::insert(new_hotkey.clone(), netuid, true); // Fill network is member.
9090

91-
// 4. Clear neuron certificates
92-
NeuronCertificates::<T>::remove(netuid, old_hotkey.clone());
91+
// 4. Clear neuron axons, certificates and prometheus info
92+
Axons::<T>::remove(netuid, &old_hotkey);
93+
NeuronCertificates::<T>::remove(netuid, &old_hotkey);
94+
Prometheus::<T>::remove(netuid, &old_hotkey);
9395

9496
// 5. Reset new neuron's values.
9597
Self::clear_neuron(netuid, uid_to_replace);
96-
97-
// 5a. reset axon info for the new uid.
98-
Axons::<T>::remove(netuid, old_hotkey);
9998
}
10099

101100
/// Appends the uid to the network.

pallets/subtensor/src/tests/migration.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2751,4 +2751,67 @@ fn test_migrate_remove_old_identity_maps() {
27512751
migration,
27522752
100,
27532753
);
2754+
fn test_migrate_remove_unknown_neuron_axon_cert_prom() {
2755+
use crate::migrations::migrate_remove_unknown_neuron_axon_cert_prom::*;
2756+
const MIGRATION_NAME: &[u8] = b"migrate_remove_neuron_axon_cert_prom";
2757+
2758+
new_test_ext(1).execute_with(|| {
2759+
setup_for(NetUid::from(2), 64, 1231);
2760+
setup_for(NetUid::from(42), 256, 15151);
2761+
setup_for(NetUid::from(99), 1024, 32323);
2762+
assert!(!HasMigrationRun::<Test>::get(MIGRATION_NAME));
2763+
2764+
let w = migrate_remove_unknown_neuron_axon_cert_prom::<Test>();
2765+
assert!(!w.is_zero(), "Weight must be non-zero");
2766+
2767+
assert!(HasMigrationRun::<Test>::get(MIGRATION_NAME));
2768+
assert_for(NetUid::from(2), 64, 1231);
2769+
assert_for(NetUid::from(42), 256, 15151);
2770+
assert_for(NetUid::from(99), 1024, 32323);
2771+
});
2772+
2773+
fn setup_for(netuid: NetUid, uids: u32, items: u32) {
2774+
NetworksAdded::<Test>::insert(netuid, true);
2775+
2776+
for i in 1u32..=uids {
2777+
let hk = U256::from(netuid.inner() as u32 * 1000 + i);
2778+
Uids::<Test>::insert(netuid, hk, i as u16);
2779+
}
2780+
2781+
for i in 1u32..=items {
2782+
let hk = U256::from(netuid.inner() as u32 * 1000 + i);
2783+
Axons::<Test>::insert(netuid, hk, AxonInfo::default());
2784+
NeuronCertificates::<Test>::insert(netuid, hk, NeuronCertificate::default());
2785+
Prometheus::<Test>::insert(netuid, hk, PrometheusInfo::default());
2786+
}
2787+
}
2788+
2789+
fn assert_for(netuid: NetUid, uids: u32, items: u32) {
2790+
assert_eq!(
2791+
Axons::<Test>::iter_key_prefix(netuid).count(),
2792+
uids as usize
2793+
);
2794+
assert_eq!(
2795+
NeuronCertificates::<Test>::iter_key_prefix(netuid).count(),
2796+
uids as usize
2797+
);
2798+
assert_eq!(
2799+
Prometheus::<Test>::iter_key_prefix(netuid).count(),
2800+
uids as usize
2801+
);
2802+
2803+
for i in 1u32..=uids {
2804+
let hk = U256::from(netuid.inner() as u32 * 1000 + i);
2805+
assert!(Axons::<Test>::contains_key(netuid, hk));
2806+
assert!(NeuronCertificates::<Test>::contains_key(netuid, hk));
2807+
assert!(Prometheus::<Test>::contains_key(netuid, hk));
2808+
}
2809+
2810+
for i in uids + 1u32..=items {
2811+
let hk = U256::from(netuid.inner() as u32 * 1000 + i);
2812+
assert!(!Axons::<Test>::contains_key(netuid, hk));
2813+
assert!(!NeuronCertificates::<Test>::contains_key(netuid, hk));
2814+
assert!(!Prometheus::<Test>::contains_key(netuid, hk));
2815+
}
2816+
}
27542817
}

pallets/subtensor/src/tests/uids.rs

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ fn test_replace_neuron() {
3232

3333
let new_hotkey_account_id = U256::from(2);
3434
let _new_colkey_account_id = U256::from(12345);
35-
let certificate = NeuronCertificate::try_from(vec![1, 2, 3]).unwrap();
3635
let evm_address = H160::from_slice(&[1_u8; 20]);
3736
//add network
3837
add_network(netuid, tempo, 0);
@@ -71,28 +70,15 @@ fn test_replace_neuron() {
7170
});
7271
Bonds::<Test>::insert(NetUidStorageIndex::from(netuid), neuron_uid, vec![(0, 1)]);
7372

74-
// serve axon mock address
75-
let ip: u128 = 1676056785;
76-
let port: u16 = 9999;
77-
let ip_type: u8 = 4;
78-
assert!(
79-
SubtensorModule::serve_axon(
80-
<<Test as Config>::RuntimeOrigin>::signed(hotkey_account_id),
81-
netuid,
82-
0,
83-
ip,
84-
port,
85-
ip_type,
86-
0,
87-
0,
88-
0
89-
)
90-
.is_ok()
73+
Axons::<Test>::insert(netuid, hotkey_account_id, AxonInfoOf::default());
74+
NeuronCertificates::<Test>::insert(
75+
netuid,
76+
hotkey_account_id,
77+
NeuronCertificateOf::default(),
9178
);
92-
93-
// Set a neuron certificate for it
94-
NeuronCertificates::<Test>::insert(netuid, hotkey_account_id, certificate);
79+
Prometheus::<Test>::insert(netuid, hotkey_account_id, PrometheusInfoOf::default());
9580
AssociatedEvmAddress::<Test>::insert(netuid, neuron_uid, (evm_address, 1));
81+
9682
// Replace the neuron.
9783
SubtensorModule::replace_neuron(netuid, neuron_uid, &new_hotkey_account_id, block_number);
9884

@@ -139,10 +125,15 @@ fn test_replace_neuron() {
139125
);
140126

141127
// Check axon info is reset.
142-
let axon_info = SubtensorModule::get_axon_info(netuid, &curr_hotkey.unwrap());
143-
assert_eq!(axon_info.ip, 0);
144-
assert_eq!(axon_info.port, 0);
145-
assert_eq!(axon_info.ip_type, 0);
128+
assert!(!Axons::<Test>::contains_key(netuid, curr_hotkey.unwrap()));
129+
assert!(!NeuronCertificates::<Test>::contains_key(
130+
netuid,
131+
curr_hotkey.unwrap()
132+
));
133+
assert!(!Prometheus::<Test>::contains_key(
134+
netuid,
135+
curr_hotkey.unwrap()
136+
));
146137

147138
// Check bonds are cleared.
148139
assert_eq!(

0 commit comments

Comments
 (0)