-
Notifications
You must be signed in to change notification settings - Fork 338
Expand file tree
/
Copy pathweights.rs
More file actions
1397 lines (1242 loc) · 55.2 KB
/
Copy pathweights.rs
File metadata and controls
1397 lines (1242 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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::{
BoundedVec,
traits::{BlakeTwo256, Hash},
};
use sp_std::{collections::btree_set::BTreeSet, collections::vec_deque::VecDeque, vec};
use subtensor_runtime_common::{MechId, NetUid, NetUidStorageIndex};
impl<T: Config> Pallet<T> {
/// The implementation for committing weight hashes.
///
/// # Arguments
/// * `origin`: The signature of the committing hotkey.
///
/// * `netuid`: The u16 network identifier.
///
/// * `commit_hash`: The hash representing the committed weights.
///
/// # Errors
/// * `CommitRevealDisabled`: Raised if commit-reveal is disabled for the specified network.
///
/// * `HotKeyNotRegisteredInSubNet`: Raised if the hotkey is not registered on the specified network.
///
/// * `CommittingWeightsTooFast`: Raised if the hotkey's commit rate exceeds the permitted limit.
///
/// * `TooManyUnrevealedCommits`: Raised if the hotkey has reached the maximum number of unrevealed commits.
///
/// # Events
/// * `WeightsCommitted`: Emitted upon successfully storing the weight hash.
pub fn do_commit_weights(
origin: OriginFor<T>,
netuid: NetUid,
commit_hash: H256,
) -> DispatchResult {
Self::internal_commit_weights(origin, netuid, MechId::MAIN, commit_hash)
}
pub fn do_commit_mechanism_weights(
origin: OriginFor<T>,
netuid: NetUid,
mecid: MechId,
commit_hash: H256,
) -> DispatchResult {
Self::internal_commit_weights(origin, netuid, mecid, commit_hash)
}
fn internal_commit_weights(
origin: OriginFor<T>,
netuid: NetUid,
mecid: MechId,
commit_hash: H256,
) -> DispatchResult {
// Ensure netuid and mecid exist
Self::ensure_mechanism_exists(netuid, mecid)?;
// Calculate subnet storage index
let netuid_index = Self::get_mechanism_storage_index(netuid, mecid);
// 1. Verify the caller's signature (hotkey).
let who = ensure_signed(origin)?;
log::debug!("do_commit_weights(hotkey: {who:?}, netuid: {netuid:?})");
// 2. Ensure commit-reveal is enabled.
ensure!(
Self::get_commit_reveal_weights_enabled(netuid),
Error::<T>::CommitRevealDisabled
);
// 3. Ensure the hotkey is registered on the network.
ensure!(
Self::is_hotkey_registered_on_network(netuid, &who),
Error::<T>::HotKeyNotRegisteredInSubNet
);
// 4. Check that the commit rate does not exceed the allowed frequency.
let commit_block = Self::get_current_block_as_u64();
let neuron_uid = Self::get_uid_for_net_and_hotkey(netuid, &who)?;
ensure!(
// Rate limiting should happen per sub-subnet, so use netuid_index here
Self::check_rate_limit(netuid_index, neuron_uid, commit_block),
Error::<T>::CommittingWeightsTooFast
);
// 5. Resolve the epoch this commit belongs to under the stateful counter.
let commit_epoch = Self::current_epoch_with_lookahead(netuid);
// 6. Retrieve or initialize the VecDeque of commits for the hotkey.
WeightCommits::<T>::try_mutate(netuid_index, &who, |maybe_commits| -> DispatchResult {
// Tuple shape `(hash, commit_epoch, commit_block, _)`. `commit_epoch`
// drives reveal-window timing; `commit_block` is kept for the epoch's
// commit-reveal weight column-mask. The 4th field is a legacy
// reveal-block bound, now unused and left at 0.
let mut commits: VecDeque<(H256, u64, u64, u64)> =
maybe_commits.take().unwrap_or_default();
// 7. Remove any expired commits from the front of the queue.
while let Some((_, commit_epoch_existing, _, _)) = commits.front() {
if Self::is_commit_expired(netuid, *commit_epoch_existing) {
commits.pop_front();
} else {
break;
}
}
// 8. Verify that the number of unrevealed commits is within the allowed limit.
ensure!(commits.len() < 10, Error::<T>::TooManyUnrevealedCommits);
// 9. Append the new commit, tagged with its epoch and block.
commits.push_back((commit_hash, commit_epoch, commit_block, 0));
// 10. Store the updated commits queue back to storage.
*maybe_commits = Some(commits);
// 11. Emit the WeightsCommitted event
Self::deposit_event(Event::WeightsCommitted(
who.clone(),
netuid_index,
commit_hash,
));
// 12. Update the last commit block for the hotkey's UID.
Self::set_last_update_for_uid(netuid_index, neuron_uid, commit_block);
// 13. Return success.
Ok(())
})
}
/// The implementation for the extrinsic batch_commit_weights.
///
/// This call runs a batch of commit weights calls, continuing on errors.
///
/// # Arguments
/// * `origin`: The signature of the calling hotkey.
///
/// * `netuids`: The u16 network identifiers.
///
/// * `commit_hashes`: The commit hashes to be committed, one hash for each netuid in the batch.
///
/// # Events
/// * `WeightsCommitted`: On successfully storing the weight hashes.
/// * `BatchCompletedWithErrors`: Emitted when at least on of the weight commits has an error.
/// * `BatchWeightItemFailed`: Emitted for each error within the batch.
/// * `BatchWeightsCompleted`: Emitted when the batch of weights is completed.
/// * `InputLengthsUnequal`: Emitted when the lengths of the input vectors are not equal.
///
pub fn do_batch_commit_weights(
origin: OriginFor<T>,
netuids: Vec<Compact<NetUid>>,
commit_hashes: Vec<H256>,
) -> dispatch::DispatchResult {
// --- 1. Check the caller's signature. This is the hotkey of a registered account.
let hotkey = ensure_signed(origin.clone())?;
log::debug!(
"do_batch_commit_weights( origin:{hotkey:?}, netuids:{netuids:?}, hashes:{commit_hashes:?} )"
);
ensure!(
netuids.len() == commit_hashes.len(),
Error::<T>::InputLengthsUnequal
);
let results: Vec<(NetUid, dispatch::DispatchResult)> = netuids
.iter()
.zip(commit_hashes.iter())
.map(|(&netuid, &commit_hash)| {
let origin_cloned = origin.clone();
let netuid: NetUid = netuid.into();
(
netuid,
Self::do_commit_weights(origin_cloned, netuid, commit_hash),
)
})
.collect();
let mut completed_with_errors: bool = false;
for (netuid, result) in results {
if let Some(err) = result.err() {
if !completed_with_errors {
Self::deposit_event(Event::BatchCompletedWithErrors());
completed_with_errors = true;
}
Self::deposit_event(Event::BatchWeightItemFailed(netuid, err));
}
}
// --- 19. Emit the tracking event.
log::debug!("BatchWeightsCompleted( netuids:{netuids:?}, hotkey:{hotkey:?} )");
Self::deposit_event(Event::BatchWeightsCompleted(netuids, hotkey));
// --- 20. Return ok.
Ok(())
}
/// Commits a timelocked, encrypted weight payload (Commit-Reveal v3).
///
/// # Arguments
/// * `origin` (`<T as frame_system::Config>::RuntimeOrigin`):
/// The signed origin of the committing hotkey.
/// * `netuid` (`NetUid` = `u16`):
/// Unique identifier for the subnet on which the commit is made.
/// * `commit` (`BoundedVec<u8, ConstU32<MAX_CRV3_COMMIT_SIZE_BYTES>>`):
/// The encrypted weight payload, produced as follows:
/// 1. Build a [`WeightsPayload`] structure.
/// 2. SCALE-encode it (`parity_scale_codec::Encode`).
/// 3. Encrypt it following the steps
/// [here](https://github.com/ideal-lab5/tle/blob/f8e6019f0fb02c380ebfa6b30efb61786dede07b/timelock/src/tlock.rs#L283-L336) to
/// produce a [`TLECiphertext<TinyBLS381>`].
/// 4. Compress & serialise.
/// * `reveal_round` (`u64`):
/// DRAND round whose output becomes known during epoch `n + 1`; the payload
/// must be revealed in that epoch.
/// * `commit_reveal_version` (`u16`):
/// Version tag that **must** match [`get_commit_reveal_weights_version`] for
/// the call to succeed. Used to gate runtime upgrades.
///
/// # Behaviour
/// 1. Verifies the caller’s signature and registration on `netuid`.
/// 2. Ensures commit-reveal is enabled **and** the supplied
/// `commit_reveal_version` is current.
/// 3. Enforces per-neuron rate-limiting via [`Pallet::check_rate_limit`].
/// 4. Rejects the call when the hotkey already has ≥ 10 unrevealed commits in
/// the current epoch.
/// 5. Appends `(hotkey, commit_block, commit, reveal_round)` to
/// `TimelockedWeightCommits[netuid][epoch]`.
/// 6. Emits `TimelockedWeightsCommitted` with the Blake2 hash of `commit`.
/// 7. Updates `LastUpdateForUid` so subsequent rate-limit checks include this
/// commit.
///
/// # Errors
/// * `CommitRevealDisabled` – Commit-reveal is disabled on `netuid`.
/// * `IncorrectCommitRevealVersion` – Provided version ≠ runtime version.
/// * `HotKeyNotRegisteredInSubNet` – Caller’s hotkey is not registered.
/// * `CommittingWeightsTooFast` – Caller exceeds commit-rate limit.
/// * `TooManyUnrevealedCommits` – Caller already has 10 unrevealed commits.
///
/// # Events
/// * `TimelockedWeightsCommitted(hotkey, netuid, commit_hash, reveal_round)` – Fired after the commit is successfully stored.
pub fn do_commit_timelocked_weights(
origin: OriginFor<T>,
netuid: NetUid,
commit: BoundedVec<u8, ConstU32<MAX_CRV3_COMMIT_SIZE_BYTES>>,
reveal_round: u64,
commit_reveal_version: u16,
) -> DispatchResult {
Self::internal_commit_timelocked_weights(
origin,
netuid,
MechId::MAIN,
commit,
reveal_round,
commit_reveal_version,
)
}
pub fn do_commit_timelocked_mechanism_weights(
origin: OriginFor<T>,
netuid: NetUid,
mecid: MechId,
commit: BoundedVec<u8, ConstU32<MAX_CRV3_COMMIT_SIZE_BYTES>>,
reveal_round: u64,
commit_reveal_version: u16,
) -> DispatchResult {
Self::internal_commit_timelocked_weights(
origin,
netuid,
mecid,
commit,
reveal_round,
commit_reveal_version,
)
}
pub fn internal_commit_timelocked_weights(
origin: OriginFor<T>,
netuid: NetUid,
mecid: MechId,
commit: BoundedVec<u8, ConstU32<MAX_CRV3_COMMIT_SIZE_BYTES>>,
reveal_round: u64,
commit_reveal_version: u16,
) -> DispatchResult {
// Ensure netuid and mecid exist
Self::ensure_mechanism_exists(netuid, mecid)?;
// Calculate netuid storage index
let netuid_index = Self::get_mechanism_storage_index(netuid, mecid);
// 1. Verify the caller's signature (hotkey).
let who = ensure_signed(origin)?;
log::debug!("do_commit_v3_weights(hotkey: {who:?}, netuid: {netuid:?})");
// 2. Ensure commit-reveal is enabled.
ensure!(
Self::get_commit_reveal_weights_enabled(netuid),
Error::<T>::CommitRevealDisabled
);
// 3. Ensure correct client version
ensure!(
commit_reveal_version == Self::get_commit_reveal_weights_version(),
Error::<T>::IncorrectCommitRevealVersion
);
// 4. Ensure the hotkey is registered on the network.
ensure!(
Self::is_hotkey_registered_on_network(netuid, &who),
Error::<T>::HotKeyNotRegisteredInSubNet
);
// 5. Check that the commit rate does not exceed the allowed frequency.
let commit_block = Self::get_current_block_as_u64();
let neuron_uid = Self::get_uid_for_net_and_hotkey(netuid, &who)?;
ensure!(
Self::check_rate_limit(netuid_index, neuron_uid, commit_block),
Error::<T>::CommittingWeightsTooFast
);
// 6. Retrieve or initialize the VecDeque of commits for the hotkey.
let cur_block = Self::get_current_block_as_u64();
// Key the commit by the epoch it belongs to under the stateful counter.
let cur_epoch = Self::current_epoch_with_lookahead(netuid);
TimelockedWeightCommits::<T>::try_mutate(
netuid_index,
cur_epoch,
|commits| -> DispatchResult {
// 7. Verify that the number of unrevealed commits is within the allowed limit.
let unrevealed_commits_for_who = commits
.iter()
.filter(|(account, _, _, _)| account == &who)
.count();
ensure!(
unrevealed_commits_for_who < 10,
Error::<T>::TooManyUnrevealedCommits
);
// 8. Append the new commit with calculated reveal blocks.
// Hash the commit before it is moved, for the event
let commit_hash = BlakeTwo256::hash(&commit);
commits.push_back((who.clone(), cur_block, commit, reveal_round));
// 9. Emit the WeightsCommitted event
Self::deposit_event(Event::TimelockedWeightsCommitted(
who.clone(),
netuid_index,
commit_hash,
reveal_round,
));
// 10. Update the last commit block for the hotkey's UID.
Self::set_last_update_for_uid(netuid_index, neuron_uid, commit_block);
// 11. Return success.
Ok(())
},
)
}
/// The implementation for revealing committed weights.
///
/// # Arguments
/// * `origin`: The signature of the revealing hotkey.
///
/// * `netuid`: The u16 network identifier.
///
/// * `uids`: The uids for the weights being revealed.
///
/// * `values`: The values of the weights being revealed.
///
/// * `salt`: The salt used to generate the commit hash.
///
/// * `version_key`: The network version key.
///
/// # Errors
/// * `CommitRevealDisabled`: Attempting to reveal weights when the commit-reveal mechanism is disabled.
///
/// * `NoWeightsCommitFound`: Attempting to reveal weights without an existing commit.
///
/// * `ExpiredWeightCommit`: Attempting to reveal a weight commit that has expired.
///
/// * `RevealTooEarly`: Attempting to reveal weights outside the valid reveal period.
///
/// * `InvalidRevealCommitHashNotMatch`: The revealed hash does not match any committed hash.
pub fn do_reveal_weights(
origin: OriginFor<T>,
netuid: NetUid,
uids: Vec<u16>,
values: Vec<u16>,
salt: Vec<u16>,
version_key: u64,
) -> DispatchResult {
Self::internal_reveal_weights(
origin,
netuid,
MechId::MAIN,
uids,
values,
salt,
version_key,
)
}
pub fn do_reveal_mechanism_weights(
origin: OriginFor<T>,
netuid: NetUid,
mecid: MechId,
uids: Vec<u16>,
values: Vec<u16>,
salt: Vec<u16>,
version_key: u64,
) -> DispatchResult {
Self::internal_reveal_weights(origin, netuid, mecid, uids, values, salt, version_key)
}
fn internal_reveal_weights(
origin: OriginFor<T>,
netuid: NetUid,
mecid: MechId,
uids: Vec<u16>,
values: Vec<u16>,
salt: Vec<u16>,
version_key: u64,
) -> DispatchResult {
ensure!(Self::if_subnet_exist(netuid), Error::<T>::SubnetNotExists);
// Calculate netuid storage index
let netuid_index = Self::get_mechanism_storage_index(netuid, mecid);
// --- 1. Check the caller's signature (hotkey).
let who = ensure_signed(origin.clone())?;
log::debug!("do_reveal_weights( hotkey:{who:?} netuid:{netuid:?})");
// --- 2. Ensure commit-reveal is enabled for the network.
ensure!(
Self::get_commit_reveal_weights_enabled(netuid),
Error::<T>::CommitRevealDisabled
);
// --- 3. Mutate the WeightCommits to retrieve existing commits for the user.
WeightCommits::<T>::try_mutate_exists(
netuid_index,
&who,
|maybe_commits| -> DispatchResult {
let commits = maybe_commits
.as_mut()
.ok_or(Error::<T>::NoWeightsCommitFound)?;
// --- 4. Remove any expired commits from the front of the queue, collecting their hashes.
let mut expired_hashes = Vec::new();
while let Some((hash, commit_block, _, _)) = commits.front() {
if Self::is_commit_expired(netuid, *commit_block) {
// Collect the expired commit hash
expired_hashes.push(*hash);
commits.pop_front();
} else {
break;
}
}
// --- 5. Hash the provided data.
let provided_hash: H256 =
Self::get_commit_hash(&who, netuid_index, &uids, &values, &salt, version_key);
// --- 6. After removing expired commits, check if any commits are left.
if commits.is_empty() {
// Check if provided_hash matches any expired commits
if expired_hashes.contains(&provided_hash) {
return Err(Error::<T>::ExpiredWeightCommit.into());
} else {
return Err(Error::<T>::NoWeightsCommitFound.into());
}
}
// --- 7. Search for the provided_hash in the non-expired commits.
if let Some(position) = commits
.iter()
.position(|(hash, _, _, _)| *hash == provided_hash)
{
// --- 8. Get the commit block for the commit being revealed.
let (_, commit_block, _, _) = commits
.get(position)
.ok_or(Error::<T>::NoWeightsCommitFound)?;
// --- 9. Ensure the commit is ready to be revealed in the current block range.
ensure!(
Self::is_reveal_block_range(netuid, *commit_block),
Error::<T>::RevealTooEarly
);
// --- 10. Remove all commits up to and including the one being revealed.
for _ in 0..=position {
commits.pop_front();
}
// --- 11. If the queue is now empty, remove the storage entry for the user.
if commits.is_empty() {
*maybe_commits = None;
}
// --- 12. Proceed to set the revealed weights.
Self::do_set_mechanism_weights(
origin,
netuid,
mecid,
uids.clone(),
values.clone(),
version_key,
)?;
// --- 13. Emit the WeightsRevealed event.
Self::deposit_event(Event::WeightsRevealed(
who.clone(),
netuid_index,
provided_hash,
));
// --- 14. Return ok.
Ok(())
} else {
// --- 15. The provided_hash does not match any non-expired commits.
if expired_hashes.contains(&provided_hash) {
Err(Error::<T>::ExpiredWeightCommit.into())
} else {
Err(Error::<T>::InvalidRevealCommitHashNotMatch.into())
}
}
},
)
}
/// The implementation for batch revealing committed weights.
///
/// # Arguments
/// * `origin`: The signature of the revealing hotkey.
///
/// * `netuid`: The u16 network identifier.
///
/// * `uids_list`: A list of uids for each set of weights being revealed.
///
/// * `values_list`: A list of values for each set of weights being revealed.
///
/// * `salts_list`: A list of salts used to generate the commit hashes.
///
/// * `version_keys`: A list of network version keys.
///
/// # Errors
/// * `CommitRevealDisabled`: Attempting to reveal weights when the commit-reveal mechanism is disabled.
///
/// * `NoWeightsCommitFound`: Attempting to reveal weights without an existing commit.
///
/// * `ExpiredWeightCommit`: Attempting to reveal a weight commit that has expired.
///
/// * `RevealTooEarly`: Attempting to reveal weights outside the valid reveal period.
///
/// * `InvalidRevealCommitHashNotMatch`: The revealed hash does not match any committed hash.
///
/// * `InputLengthsUnequal`: The input vectors are of mismatched lengths.
pub fn do_batch_reveal_weights(
origin: OriginFor<T>,
netuid: NetUid,
uids_list: Vec<Vec<u16>>,
values_list: Vec<Vec<u16>>,
salts_list: Vec<Vec<u16>>,
version_keys: Vec<u64>,
) -> DispatchResult {
ensure!(Self::if_subnet_exist(netuid), Error::<T>::SubnetNotExists);
// Calculate netuid storage index
let netuid_index = Self::get_mechanism_storage_index(netuid, MechId::MAIN);
// --- 1. Check that the input lists are of the same length.
let num_reveals = uids_list.len();
ensure!(
num_reveals == values_list.len()
&& num_reveals == salts_list.len()
&& num_reveals == version_keys.len(),
Error::<T>::InputLengthsUnequal
);
// --- 2. Check the caller's signature (hotkey).
let who = ensure_signed(origin.clone())?;
log::debug!("do_batch_reveal_weights( hotkey:{who:?} netuid:{netuid:?})");
// --- 3. Ensure commit-reveal is enabled for the network.
ensure!(
Self::get_commit_reveal_weights_enabled(netuid),
Error::<T>::CommitRevealDisabled
);
// --- 4. Mutate the WeightCommits to retrieve existing commits for the user.
WeightCommits::<T>::try_mutate_exists(
netuid_index,
&who,
|maybe_commits| -> DispatchResult {
let commits = maybe_commits
.as_mut()
.ok_or(Error::<T>::NoWeightsCommitFound)?;
// --- 5. Remove any expired commits from the front of the queue, collecting their hashes.
let mut expired_hashes = Vec::new();
while let Some((hash, commit_block, _, _)) = commits.front() {
if Self::is_commit_expired(netuid, *commit_block) {
// Collect the expired commit hash
expired_hashes.push(*hash);
commits.pop_front();
} else {
break;
}
}
// --- 6. Prepare to collect all provided hashes and their corresponding reveals.
let mut provided_hashes = Vec::new();
let mut reveals = Vec::new();
let mut revealed_hashes: Vec<H256> = Vec::with_capacity(num_reveals);
for ((uids, values), (salt, version_key)) in uids_list
.into_iter()
.zip(values_list)
.zip(salts_list.into_iter().zip(version_keys))
{
// --- 6a. Hash the provided data.
let provided_hash: H256 = BlakeTwo256::hash_of(&(
who.clone(),
netuid,
uids.clone(),
values.clone(),
salt.clone(),
version_key,
));
provided_hashes.push(provided_hash);
reveals.push((uids, values, version_key, provided_hash));
}
// --- 7. Validate all reveals first to ensure atomicity.
for (_uids, _values, _version_key, provided_hash) in &reveals {
// --- 7a. Check if the provided_hash is in the non-expired commits.
if !commits
.iter()
.any(|(hash, _, _, _)| *hash == *provided_hash)
{
// --- 7b. If not found, check if it matches any expired commits.
if expired_hashes.contains(provided_hash) {
return Err(Error::<T>::ExpiredWeightCommit.into());
} else {
return Err(Error::<T>::InvalidRevealCommitHashNotMatch.into());
}
}
// --- 7c. Find the commit corresponding to the provided_hash.
let commit = commits
.iter()
.find(|(hash, _, _, _)| *hash == *provided_hash)
.ok_or(Error::<T>::NoWeightsCommitFound)?;
// --- 7d. Check if the commit is within the reveal window.
ensure!(
Self::is_reveal_block_range(netuid, commit.1),
Error::<T>::RevealTooEarly
);
}
// --- 8. All reveals are valid. Proceed to remove and process each reveal.
for (uids, values, version_key, provided_hash) in reveals {
// --- 8a. Find the position of the provided_hash.
if let Some(position) = commits
.iter()
.position(|(hash, _, _, _)| *hash == provided_hash)
{
// --- 8b. Remove the commit from the queue.
commits.remove(position);
// --- 8c. Proceed to set the revealed weights.
Self::do_set_weights(origin.clone(), netuid, uids, values, version_key)?;
// --- 8d. Collect the revealed hash.
revealed_hashes.push(provided_hash);
} else if expired_hashes.contains(&provided_hash) {
return Err(Error::<T>::ExpiredWeightCommit.into());
} else {
return Err(Error::<T>::InvalidRevealCommitHashNotMatch.into());
}
}
// --- 9. If the queue is now empty, remove the storage entry for the user.
if commits.is_empty() {
*maybe_commits = None;
}
// --- 10. Emit the WeightsBatchRevealed event with all revealed hashes.
Self::deposit_event(Event::WeightsBatchRevealed(
who.clone(),
netuid,
revealed_hashes,
));
// --- 11. Return ok.
Ok(())
},
)
}
fn internal_set_weights(
origin: OriginFor<T>,
netuid: NetUid,
mecid: MechId,
uids: Vec<u16>,
values: Vec<u16>,
version_key: u64,
) -> dispatch::DispatchResult {
// Calculate subnet storage index
let netuid_index = Self::get_mechanism_storage_index(netuid, mecid);
// --- 1. Check the caller's signature. This is the hotkey of a registered account.
let hotkey = ensure_signed(origin)?;
log::debug!(
"do_set_weights( origin:{hotkey:?} netuid:{netuid:?}, uids:{uids:?}, values:{values:?})"
);
// --- Check that the netuid is not the root network.
ensure!(!netuid.is_root(), Error::<T>::CanNotSetRootNetworkWeights);
// --- 2. Check that the length of uid list and value list are equal for this network.
ensure!(
Self::uids_match_values(&uids, &values),
Error::<T>::WeightVecNotEqualSize
);
// --- 3. Check to see if this is a valid network and sub-subnet.
Self::ensure_mechanism_exists(netuid, mecid)?;
// --- 4. Check to see if the number of uids is within the max allowed uids for this network.
ensure!(
Self::check_len_uids_within_allowed(netuid, &uids),
Error::<T>::UidsLengthExceedUidsInSubNet
);
// --- 5. Check to see if the hotkey is registered to the passed network.
ensure!(
Self::is_hotkey_registered_on_network(netuid, &hotkey),
Error::<T>::HotKeyNotRegisteredInSubNet
);
// --- 6. Check to see if the hotkey has enough stake to set weights.
ensure!(
Self::check_weights_min_stake(&hotkey, netuid),
Error::<T>::NotEnoughStakeToSetWeights
);
// --- 7. Ensure version_key is up-to-date.
ensure!(
Self::check_version_key(netuid, version_key),
Error::<T>::IncorrectWeightVersionKey
);
// --- 9. Ensure the uid is not setting weights faster than the weights_set_rate_limit.
let neuron_uid = Self::get_uid_for_net_and_hotkey(netuid, &hotkey)?;
let current_block: u64 = Self::get_current_block_as_u64();
if !Self::get_commit_reveal_weights_enabled(netuid) {
ensure!(
// Rate limit should apply per sub-subnet, so use netuid_index here
Self::check_rate_limit(netuid_index, neuron_uid, current_block),
Error::<T>::SettingWeightsTooFast
);
}
// --- 10. Check that the neuron uid is an allowed validator permitted to set non-self weights.
ensure!(
Self::check_validator_permit(netuid, neuron_uid, &uids, &values),
Error::<T>::NeuronNoValidatorPermit
);
// --- 11. Ensure the passed uids contain no duplicates.
ensure!(!Self::has_duplicate_uids(&uids), Error::<T>::DuplicateUids);
// --- 12. Ensure that the passed uids are valid for the network.
ensure!(
!Self::contains_invalid_uids(netuid, &uids),
Error::<T>::UidVecContainInvalidOne
);
// --- 13. Ensure that the weights have the required length.
ensure!(
Self::check_length(netuid, neuron_uid, &uids, &values),
Error::<T>::WeightVecLengthIsLow
);
// --- 14. Max-upscale the weights.
let max_upscaled_weights: Vec<u16> = vec_u16_max_upscale_to_u16(&values);
// --- 15. Ensure the weights are max weight limited
ensure!(
Self::max_weight_limited(netuid, neuron_uid, &uids, &max_upscaled_weights),
Error::<T>::MaxWeightExceeded
);
// --- 16. Zip weights for sinking to storage map.
let mut zipped_weights: Vec<(u16, u16)> = vec![];
for (uid, val) in uids.iter().zip(max_upscaled_weights.iter()) {
zipped_weights.push((*uid, *val))
}
// --- 17. Set weights under netuid_index (sub-subnet), uid double map entry.
Weights::<T>::insert(netuid_index, neuron_uid, zipped_weights);
// --- 18. Set the activity for the weights on this network.
if !Self::get_commit_reveal_weights_enabled(netuid) {
Self::set_last_update_for_uid(netuid_index, neuron_uid, current_block);
}
// --- 19. Emit the tracking event.
log::debug!("WeightsSet( netuid:{netuid_index:?}, neuron_uid:{neuron_uid:?} )");
Self::deposit_event(Event::WeightsSet(netuid_index, neuron_uid));
// --- 20. Return ok.
Ok(())
}
/// The implementation for the extrinsic set_weights.
///
/// # Arguments
/// * `origin`: The signature of the calling hotkey.
///
/// * `netuid`: The u16 network identifier.
///
/// * `uids`: The uids of the weights to be set on the chain.
///
/// * `values`: The values of the weights to set on the chain.
///
/// * `version_key`: The network version key.
///
/// # Events
/// * `WeightsSet`: On successfully setting the weights on chain.
///
/// # Errors
/// * `MechanismDoesNotExist`: Attempting to set weights on a non-existent network.
///
/// * `NotRegistered`: Attempting to set weights from a non registered account.
///
/// * `IncorrectWeightVersionKey`: Attempting to set weights without having an up-to-date version_key.
///
/// * `SettingWeightsTooFast`: Attempting to set weights faster than the weights_set_rate_limit.
///
/// * `NeuronNoValidatorPermit`: Attempting to set non-self weights without a validator permit.
///
/// * `WeightVecNotEqualSize`: Attempting to set weights with uids not of same length.
///
/// * `DuplicateUids`: Attempting to set weights with duplicate uids.
///
/// * `UidsLengthExceedUidsInSubNet`: Attempting to set weights above the max allowed uids.
///
/// * `UidVecContainInvalidOne`: Attempting to set weights with invalid uids.
///
/// * `WeightVecLengthIsLow`: Attempting to set weights with fewer weights than min.
///
/// * `MaxWeightExceeded`: Attempting to set weights with max value exceeding limit.
///
pub fn do_set_weights(
origin: OriginFor<T>,
netuid: NetUid,
uids: Vec<u16>,
values: Vec<u16>,
version_key: u64,
) -> dispatch::DispatchResult {
Self::internal_set_weights(origin, netuid, MechId::MAIN, uids, values, version_key)
}
/// Sets a root validator's basket distribution vector `w` on the root subnet (netuid 0).
///
/// Unlike normal subnet weights, the `dests` here are interpreted as *subnet netuids* and the
/// values as the proportion of the validator's root dividends to deploy into each subnet's
/// alpha basket. Stored under `Weights[NetUidStorageIndex::ROOT][uid]` and consumed by
/// `distribute_root_alpha_to_basket` during emission.
pub fn do_set_root_weights(
origin: OriginFor<T>,
dests: Vec<u16>,
values: Vec<u16>,
) -> dispatch::DispatchResult {
// --- 1. Signed by the root validator hotkey.
let hotkey = ensure_signed(origin)?;
log::debug!("do_set_root_weights( hotkey:{hotkey:?}, dests:{dests:?}, values:{values:?} )");
// --- 1.5. Weight setting must be enabled network-wide. Root Reborn launches with
// this gate closed so every fund runs the null (accumulate in place) strategy
// first; see `RootWeightSettingEnabled`.
ensure!(
RootWeightSettingEnabled::<T>::get(),
Error::<T>::RootWeightSettingDisabled
);
// --- 2. Lengths match.
ensure!(
Self::uids_match_values(&dests, &values),
Error::<T>::WeightVecNotEqualSize
);
// --- 3. Cap vector length before any further O(n) work. Every destination is a netuid,
// so the vector cannot exceed the number of existing networks. Without this, a huge
// unique-uid payload could burn CPU (and many storage reads) before validity fails.
// Bound by the NetworksAdded set (not TotalNetworks) so the cap matches what the
// validity loop below will accept.
let available = Self::get_all_subnet_netuids().len();
ensure!(
dests.len() <= available,
Error::<T>::UidsLengthExceedUidsInSubNet
);
// --- 4. Caller must be a registered root validator.
ensure!(
Self::is_hotkey_registered_on_network(NetUid::ROOT, &hotkey),
Error::<T>::HotKeyNotRegisteredInSubNet
);
// --- 5. Must hold enough stake to set weights.
ensure!(
Self::check_weights_min_stake(&hotkey, NetUid::ROOT),
Error::<T>::NotEnoughStakeToSetWeights
);
// --- 6. Rate limit on the root weights index.
let neuron_uid = Self::get_uid_for_net_and_hotkey(NetUid::ROOT, &hotkey)?;
let current_block: u64 = Self::get_current_block_as_u64();
ensure!(
Self::check_rate_limit(NetUidStorageIndex::ROOT, neuron_uid, current_block),
Error::<T>::SettingWeightsTooFast
);
// --- 7. No duplicate destination subnets.
ensure!(!Self::has_duplicate_uids(&dests), Error::<T>::DuplicateUids);
// --- 8. Every destination must be root (uid 0) or an existing subnet. Root is a valid
// basket destination: that weight slice is held as root stake (TAO) instead of being
// deployed into a subnet, letting a validator opt out of subnet exposure. This must mirror
// the consumer filter in `distribute_root_alpha_to_basket`.
for dest in dests.iter() {
let dest_netuid = NetUid::from(*dest);
ensure!(
dest_netuid.is_root() || Self::if_subnet_exist(dest_netuid),
Error::<T>::UidVecContainInvalidOne
);
}
// --- 8.5 At least MIN_ROOT_BASKET_WEIGHTS positive entries (softened when fewer
// destinations exist than the floor — e.g. young chains / unit tests).
let nonzero = values.iter().filter(|w| **w > 0).count();
let required = (crate::MIN_ROOT_BASKET_WEIGHTS as usize).min(available);
ensure!(nonzero >= required, Error::<T>::WeightVecLengthIsLow);
// --- 8.6 Concentration cap: no destination may take a larger share of the vector
// than `RootWeightsCap` (u16-normalized, share = value / sum). A cap of 1/16 needs
// at least 16 destinations to be satisfiable, so — mirroring the diversity floor
// above — the check is skipped while the chain has fewer destinations than the cap
// demands (young chains, tests). Checked on the raw values so the cap is
// independent of the max-upscale that follows.
let cap = RootWeightsCap::<T>::get(NetUid::ROOT) as u64;
let min_dests_for_cap = (u16::MAX as u64).div_ceil(cap.max(1));
if available as u64 >= min_dests_for_cap {
let sum: u64 = values.iter().map(|w| *w as u64).sum();
ensure!(
values
.iter()
.all(|w| (*w as u64).saturating_mul(u16::MAX as u64)
<= cap.saturating_mul(sum)),
Error::<T>::RootWeightCapExceeded
);
}
// --- 9. Max-upscale the weights.
let max_upscaled_weights: Vec<u16> = vec_u16_max_upscale_to_u16(&values);
// --- 10. Zip and store under the root weights index (reusing the root weights plumbing).
let zipped_weights: Vec<(u16, u16)> = dests
.iter()
.copied()
.zip(max_upscaled_weights.iter().copied())
.collect();
Weights::<T>::insert(NetUidStorageIndex::ROOT, neuron_uid, zipped_weights);
// --- 11. Record activity for the rate limit.
Self::set_last_update_for_uid(NetUidStorageIndex::ROOT, neuron_uid, current_block);
// --- 12. Emit event.
log::debug!("RootWeightsSet( uid:{neuron_uid:?} )");
Self::deposit_event(Event::RootWeightsSet(neuron_uid));
Ok(())
}
/// The implementation for the extrinsic set_weights.
///
/// # Arguments
/// * `origin`: The signature of the calling hotkey.
///