-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathstate.rs
1307 lines (1176 loc) · 42.3 KB
/
state.rs
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 {
crate::{
constants::TVC_MULTIPLIER,
crds_value::{ContactInfo, LegacyContactInfo, LegacyVersion, Version2},
errors::ValidatorHistoryError,
utils::{cast_epoch, find_insert_position, get_max_epoch, get_min_epoch},
},
anchor_lang::prelude::*,
borsh::{BorshDeserialize, BorshSerialize},
std::{cmp::Ordering, collections::HashMap, mem::size_of, net::IpAddr},
type_layout::TypeLayout,
};
static_assertions::const_assert_eq!(size_of::<Config>(), 104);
#[account]
#[derive(Default)]
pub struct Config {
// This program is used to distribute MEV + track which validators are running jito-solana for a given epoch
pub tip_distribution_program: Pubkey,
// Has the ability to upgrade config fields
pub admin: Pubkey,
// Has the ability to publish data for specific permissioned fields (e.g. stake per validator)
pub oracle_authority: Pubkey,
// Tracks number of initialized ValidatorHistory accounts
pub counter: u32,
pub bump: u8,
}
impl Config {
pub const SEED: &'static [u8] = b"config";
pub const SIZE: usize = 8 + size_of::<Self>();
}
static_assertions::const_assert_eq!(size_of::<ValidatorHistoryEntry>(), 128);
#[derive(BorshSerialize, TypeLayout)]
#[zero_copy]
pub struct ValidatorHistoryEntry {
pub activated_stake_lamports: u64,
pub epoch: u16,
// MEV commission in basis points
pub mev_commission: u16,
// Number of successful votes in current epoch. Not finalized until subsequent epoch
pub epoch_credits: u32,
// Validator commission in points
pub commission: u8,
// 0 if Solana Labs client, 1 if Jito client, >1 if other
pub client_type: u8,
pub version: ClientVersion,
pub ip: [u8; 4],
// Required so that `rank` is aligned such that curr_offset % 4 == 0 (u32 field.alignment) as per https://doc.rust-lang.org/reference/type-layout.html#reprc-structs
// without it - `rank` would have offset 27, and the compiler would add an implicit padding byte after `is_superminority` and before `rank`
pub padding0: u8,
// 0 if not a superminority validator, 1 if superminority validator
pub is_superminority: u8,
// rank of validator by stake amount
pub rank: u32,
// Most recent updated slot for epoch credits and commission
pub vote_account_last_update_slot: u64,
// MEV earned, stored as 1/100th SOL. mev_earned = 100 means 1.00 SOL earned
pub mev_earned: u32,
pub padding1: [u8; 84],
}
// Default values for fields in `ValidatorHistoryEntry` are the type's max value.
// It's important to ensure that the max value is not a valid value for the field, so we can check if the field has been set.
impl Default for ValidatorHistoryEntry {
fn default() -> Self {
Self {
activated_stake_lamports: u64::MAX,
epoch: u16::MAX,
mev_commission: u16::MAX,
epoch_credits: u32::MAX,
commission: u8::MAX,
client_type: u8::MAX,
version: ClientVersion {
major: u8::MAX,
minor: u8::MAX,
patch: u16::MAX,
},
ip: [u8::MAX; 4],
padding0: u8::MAX,
is_superminority: u8::MAX,
rank: u32::MAX,
vote_account_last_update_slot: u64::MAX,
mev_earned: u32::MAX,
padding1: [u8::MAX; 84],
}
}
}
#[derive(BorshSerialize, BorshDeserialize)]
#[zero_copy]
pub struct ClientVersion {
pub major: u8,
pub minor: u8,
pub patch: u16,
}
const MAX_ITEMS: usize = 512;
#[derive(BorshSerialize)]
#[zero_copy]
pub struct CircBuf {
pub idx: u64,
pub is_empty: u8,
pub padding: [u8; 7],
pub arr: [ValidatorHistoryEntry; MAX_ITEMS],
}
impl Default for CircBuf {
fn default() -> Self {
Self {
arr: [ValidatorHistoryEntry::default(); MAX_ITEMS],
idx: 0,
is_empty: 1,
padding: [0; 7],
}
}
}
macro_rules! field_latest {
($self:expr, $field:ident) => {
if let Some(entry) = $self.last() {
if entry.$field != ValidatorHistoryEntry::default().$field {
return Some(entry.$field);
} else {
None
}
} else {
None
}
};
}
macro_rules! field_range {
($self:expr, $start_epoch:expr, $end_epoch:expr, $field:ident, $type:ty) => {{
let epoch_range = $self.epoch_range($start_epoch, $end_epoch);
epoch_range
.iter()
.map(|maybe_entry| {
maybe_entry
.as_ref()
.map(|entry| entry.$field)
.filter(|&field| field != ValidatorHistoryEntry::default().$field)
})
.collect::<Vec<Option<$type>>>()
}};
}
impl CircBuf {
pub fn push(&mut self, item: ValidatorHistoryEntry) {
self.idx = (self.idx + 1) % self.arr.len() as u64;
self.arr[self.idx as usize] = item;
self.is_empty = 0;
}
pub fn is_empty(&self) -> bool {
self.is_empty == 1
}
pub fn last(&self) -> Option<&ValidatorHistoryEntry> {
if self.is_empty() {
None
} else {
Some(&self.arr[self.idx as usize])
}
}
pub fn last_mut(&mut self) -> Option<&mut ValidatorHistoryEntry> {
if self.is_empty() {
None
} else {
Some(&mut self.arr[self.idx as usize])
}
}
pub fn arr_mut(&mut self) -> &mut [ValidatorHistoryEntry] {
&mut self.arr
}
/// Given a new entry and epoch, inserts the entry into the buffer in sorted order
/// Will not insert if the epoch is out of range or already exists in the buffer
fn insert(&mut self, entry: ValidatorHistoryEntry, epoch: u16) -> Result<()> {
if self.is_empty() {
return Err(ValidatorHistoryError::EpochOutOfRange.into());
}
// Find the lowest epoch in the buffer to ensure the new epoch is valid
let min_epoch = {
let next_i = (self.idx as usize + 1) % self.arr.len();
if self.arr[next_i].epoch == ValidatorHistoryEntry::default().epoch {
self.arr[0].epoch
} else {
self.arr[next_i].epoch
}
};
// If epoch is less than min_epoch or greater than max_epoch in the buffer, return error
if epoch < min_epoch || epoch > self.arr[self.idx as usize].epoch {
return Err(ValidatorHistoryError::EpochOutOfRange.into());
}
let insert_pos = find_insert_position(&self.arr, self.idx as usize, epoch)
.ok_or(ValidatorHistoryError::DuplicateEpoch)?;
// If idx < insert_pos, the shifting needs to wrap around
let end_index = if self.idx < insert_pos as u64 {
self.idx as usize + self.arr.len()
} else {
self.idx as usize
};
// Shift all elements to the right to make space for the new entry, starting with current idx
for i in (insert_pos..=end_index).rev() {
let i = i % self.arr.len();
let next_i = (i + 1) % self.arr.len();
self.arr[next_i] = self.arr[i];
}
self.arr[insert_pos] = entry;
self.idx = (self.idx + 1) % self.arr.len() as u64;
Ok(())
}
/// Returns &ValidatorHistoryEntry for each existing entry in range [start_epoch, end_epoch] inclusive, factoring for wraparound
/// Returns None for each epoch that doesn't exist in the CircBuf
pub fn epoch_range(
&self,
start_epoch: u16,
end_epoch: u16,
) -> Vec<Option<&ValidatorHistoryEntry>> {
// creates an iterator that lays out the entries in consecutive order, handling wraparound
let mut entries = self.arr[(self.idx as usize + 1)..] // if self.idx + 1 == self.arr.len() this will just return an empty slice
.iter()
.chain(self.arr[..=(self.idx as usize)].iter())
.filter(|entry| entry.epoch >= start_epoch && entry.epoch <= end_epoch)
.peekable();
(start_epoch..=end_epoch)
.map(|epoch| {
if let Some(&entry) = entries.peek() {
if entry.epoch == epoch {
entries.next();
return Some(entry);
}
}
None
})
.collect()
}
pub fn commission_latest(&self) -> Option<u8> {
field_latest!(self, commission)
}
pub fn commission_range(&self, start_epoch: u16, end_epoch: u16) -> Vec<Option<u8>> {
field_range!(self, start_epoch, end_epoch, commission, u8)
}
pub fn mev_commission_latest(&self) -> Option<u16> {
field_latest!(self, mev_commission)
}
pub fn mev_commission_range(&self, start_epoch: u16, end_epoch: u16) -> Vec<Option<u16>> {
field_range!(self, start_epoch, end_epoch, mev_commission, u16)
}
pub fn epoch_credits_latest(&self) -> Option<u32> {
field_latest!(self, epoch_credits)
}
/// Normalized epoch credits, accounting for Timely Vote Credits making the max number of credits 16x higher
/// for every epoch starting at `tvc_activation_epoch`
pub fn epoch_credits_latest_normalized(
&self,
current_epoch: u64,
tvc_activation_epoch: u64,
) -> Option<u32> {
self.epoch_credits_latest().map(|credits| {
if current_epoch < tvc_activation_epoch {
credits.saturating_mul(TVC_MULTIPLIER)
} else {
credits
}
})
}
pub fn epoch_credits_range(&self, start_epoch: u16, end_epoch: u16) -> Vec<Option<u32>> {
field_range!(self, start_epoch, end_epoch, epoch_credits, u32)
}
/// Normalized epoch credits, accounting for Timely Vote Credits making the max number of credits 8x higher
/// for every epoch starting at `tvc_activation_epoch`
pub fn epoch_credits_range_normalized(
&self,
start_epoch: u16,
end_epoch: u16,
tvc_activation_epoch: u64,
) -> Vec<Option<u32>> {
field_range!(self, start_epoch, end_epoch, epoch_credits, u32)
.into_iter()
.zip(start_epoch..=end_epoch)
.map(|(maybe_credits, epoch)| {
maybe_credits.map(|credits| {
if (epoch as u64) < tvc_activation_epoch {
credits.saturating_mul(TVC_MULTIPLIER)
} else {
credits
}
})
})
.collect()
}
pub fn superminority_latest(&self) -> Option<u8> {
// Protect against unexpected values
if let Some(value) = field_latest!(self, is_superminority) {
if value == 0 || value == 1 {
return Some(value);
}
}
None
}
pub fn superminority_range(&self, start_epoch: u16, end_epoch: u16) -> Vec<Option<u8>> {
field_range!(self, start_epoch, end_epoch, is_superminority, u8)
.into_iter()
.map(|maybe_value| {
maybe_value.and_then(|value| {
if value == 0 || value == 1 {
Some(value)
} else {
None
}
})
})
.collect()
}
pub fn vote_account_last_update_slot_latest(&self) -> Option<u64> {
field_latest!(self, vote_account_last_update_slot)
}
}
pub enum ValidatorHistoryVersion {
V0 = 0,
}
static_assertions::const_assert_eq!(size_of::<ValidatorHistory>(), 65848);
#[derive(BorshSerialize)]
#[account(zero_copy)]
pub struct ValidatorHistory {
// Cannot be enum due to Pod and Zeroable trait limitations
pub struct_version: u32,
pub vote_account: Pubkey,
// Index of validator of all ValidatorHistory accounts
pub index: u32,
pub bump: u8,
pub _padding0: [u8; 7],
// These Crds gossip values are only signed and dated once upon startup and then never updated
// so we track latest time on-chain to make sure old messages aren't uploaded
pub last_ip_timestamp: u64,
pub last_version_timestamp: u64,
pub _padding1: [u8; 232],
pub history: CircBuf,
}
impl ValidatorHistory {
pub const SIZE: usize = 8 + size_of::<Self>();
pub const MAX_ITEMS: usize = MAX_ITEMS;
pub const SEED: &'static [u8] = b"validator-history";
pub fn set_mev_commission(
&mut self,
epoch: u16,
commission: u16,
mev_earned: u32,
) -> Result<()> {
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.mev_earned = mev_earned;
entry.mev_commission = commission;
return Ok(());
}
Ordering::Greater => {
if let Some(entry) = self
.history
.arr_mut()
.iter_mut()
.find(|entry| entry.epoch == epoch)
{
entry.mev_earned = mev_earned;
entry.mev_commission = commission;
}
return Ok(());
}
Ordering::Less => {}
}
}
let entry = ValidatorHistoryEntry {
epoch,
mev_commission: commission,
mev_earned,
..ValidatorHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
pub fn set_stake(
&mut self,
epoch: u16,
stake: u64,
rank: u32,
is_superminority: bool,
) -> Result<()> {
// Only one authority for upload here, so any epoch can be updated in case of missed upload
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.activated_stake_lamports = stake;
entry.rank = rank;
entry.is_superminority = is_superminority as u8;
return Ok(());
}
Ordering::Greater => {
for entry in self.history.arr_mut().iter_mut() {
if entry.epoch == epoch {
entry.activated_stake_lamports = stake;
entry.rank = rank;
entry.is_superminority = is_superminority as u8;
return Ok(());
}
}
return Err(ValidatorHistoryError::EpochOutOfRange.into());
}
Ordering::Less => {}
}
}
let entry = ValidatorHistoryEntry {
epoch,
activated_stake_lamports: stake,
rank,
is_superminority: is_superminority as u8,
..ValidatorHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
/// Given epoch credits from the vote account, determines which entries do not exist in the history and inserts them.
/// Shifts all existing entries that come later in the history and evicts the oldest entries if the buffer is full.
/// Skips entries which are not already in the (min_epoch, max_epoch) range of the buffer.
pub fn insert_missing_entries(
&mut self,
epoch_credits: &[(
u64, /* epoch */
u64, /* epoch cumulative votes */
u64, /* prev epoch cumulative votes */
)],
) -> Result<()> {
// For each epoch in the list, insert a new entry if it doesn't exist
let start_epoch = get_min_epoch(epoch_credits)?;
let end_epoch = get_max_epoch(epoch_credits)?;
let entries = self
.history
.epoch_range(start_epoch, end_epoch)
.iter()
.map(|entry| entry.is_some())
.collect::<Vec<bool>>();
let epoch_credits_map: HashMap<u16, u32> =
HashMap::from_iter(epoch_credits.iter().map(|(epoch, cur, prev)| {
(
cast_epoch(*epoch).unwrap(), // all epochs in list will be valid if current epoch is valid
(cur.checked_sub(*prev)
.ok_or(ValidatorHistoryError::InvalidEpochCredits)
.unwrap() as u32),
)
}));
for (entry_is_some, epoch) in entries.iter().zip(start_epoch as u16..=end_epoch) {
if !*entry_is_some && epoch_credits_map.contains_key(&epoch) {
// Inserts blank entry that will have credits copied to it later
let entry = ValidatorHistoryEntry {
epoch,
..ValidatorHistoryEntry::default()
};
// Skips if epoch is out of range or duplicate
self.history.insert(entry, epoch).unwrap_or_default();
}
}
Ok(())
}
pub fn set_epoch_credits(
&mut self,
epoch_credits: &[(
u64, /* epoch */
u64, /* epoch cumulative votes */
u64, /* prev epoch cumulative votes */
)],
) -> Result<()> {
// Assumes `set_commission` has already been run in `copy_vote_account`,
// guaranteeing an entry exists for the current epoch
if epoch_credits.is_empty() {
return Ok(());
}
let epoch_credits_map: HashMap<u16, u32> =
HashMap::from_iter(epoch_credits.iter().map(|(epoch, cur, prev)| {
(
cast_epoch(*epoch).unwrap(), // all epochs in list will be valid if current epoch is valid
(cur.checked_sub(*prev)
.ok_or(ValidatorHistoryError::InvalidEpochCredits)
.unwrap() as u32),
)
}));
let min_epoch = get_min_epoch(epoch_credits)?;
// Traverses entries in reverse order, breaking once we hit the lowest epoch in epoch_credits
let len = self.history.arr.len();
for i in 0..len {
let position = (self.history.idx as usize + len - i) % len;
let entry = &mut self.history.arr[position];
if let Some(&epoch_credits) = epoch_credits_map.get(&entry.epoch) {
entry.epoch_credits = epoch_credits;
}
if entry.epoch == min_epoch {
break;
}
}
Ok(())
}
pub fn set_commission_and_slot(&mut self, epoch: u16, commission: u8, slot: u64) -> Result<()> {
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.commission = commission;
entry.vote_account_last_update_slot = slot;
return Ok(());
}
Ordering::Greater => {
if let Some(entry) = self
.history
.arr_mut()
.iter_mut()
.find(|entry| entry.epoch == epoch)
{
entry.commission = commission;
entry.vote_account_last_update_slot = slot;
}
return Ok(());
}
Ordering::Less => {}
}
}
let entry = ValidatorHistoryEntry {
epoch,
commission,
vote_account_last_update_slot: slot,
..ValidatorHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
pub fn set_contact_info(
&mut self,
epoch: u16,
contact_info: &ContactInfo,
contact_info_ts: u64,
) -> Result<()> {
let ip = if let IpAddr::V4(address) = contact_info.addrs[0] {
address.octets()
} else {
return Err(ValidatorHistoryError::UnsupportedIpFormat.into());
};
if self.last_ip_timestamp > contact_info_ts || self.last_version_timestamp > contact_info_ts
{
return Err(ValidatorHistoryError::GossipDataTooOld.into());
}
self.last_ip_timestamp = contact_info_ts;
self.last_version_timestamp = contact_info_ts;
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.ip = ip;
entry.client_type = contact_info.version.client as u8;
entry.version.major = contact_info.version.major as u8;
entry.version.minor = contact_info.version.minor as u8;
entry.version.patch = contact_info.version.patch;
return Ok(());
}
Ordering::Greater => {
if let Some(entry) = self
.history
.arr_mut()
.iter_mut()
.find(|entry| entry.epoch == epoch)
{
entry.ip = ip;
entry.client_type = contact_info.version.client as u8;
entry.version.major = contact_info.version.major as u8;
entry.version.minor = contact_info.version.minor as u8;
entry.version.patch = contact_info.version.patch;
}
return Ok(());
}
Ordering::Less => {}
}
}
let entry = ValidatorHistoryEntry {
epoch,
ip,
client_type: contact_info.version.client as u8,
version: ClientVersion {
major: contact_info.version.major as u8,
minor: contact_info.version.minor as u8,
patch: contact_info.version.patch,
},
..ValidatorHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
pub fn set_legacy_contact_info(
&mut self,
epoch: u16,
legacy_contact_info: &LegacyContactInfo,
contact_info_ts: u64,
) -> Result<()> {
let ip = if let IpAddr::V4(address) = legacy_contact_info.gossip.ip() {
address.octets()
} else {
return Err(ValidatorHistoryError::UnsupportedIpFormat.into());
};
if self.last_ip_timestamp > contact_info_ts {
return Err(ValidatorHistoryError::GossipDataTooOld.into());
}
self.last_ip_timestamp = contact_info_ts;
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.ip = ip;
return Ok(());
}
Ordering::Greater => {
if let Some(entry) = self
.history
.arr_mut()
.iter_mut()
.find(|entry| entry.epoch == epoch)
{
entry.ip = ip;
}
return Ok(());
}
Ordering::Less => {}
}
}
let entry = ValidatorHistoryEntry {
epoch,
ip,
..ValidatorHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
pub fn set_version(&mut self, epoch: u16, version: &Version2, version_ts: u64) -> Result<()> {
if self.last_version_timestamp > version_ts {
return Err(ValidatorHistoryError::GossipDataTooOld.into());
}
self.last_version_timestamp = version_ts;
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.version.major = version.version.major as u8;
entry.version.minor = version.version.minor as u8;
entry.version.patch = version.version.patch;
return Ok(());
}
Ordering::Greater => {
if let Some(entry) = self
.history
.arr_mut()
.iter_mut()
.find(|entry| entry.epoch == epoch)
{
entry.version.major = version.version.major as u8;
entry.version.minor = version.version.minor as u8;
entry.version.patch = version.version.patch;
}
return Ok(());
}
Ordering::Less => {}
}
}
let entry = ValidatorHistoryEntry {
epoch,
version: ClientVersion {
major: version.version.major as u8,
minor: version.version.minor as u8,
patch: version.version.patch,
},
..ValidatorHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
pub fn set_legacy_version(
&mut self,
epoch: u16,
legacy_version: &LegacyVersion,
version_ts: u64,
) -> Result<()> {
if self.last_version_timestamp > version_ts {
return Err(ValidatorHistoryError::GossipDataTooOld.into());
}
self.last_version_timestamp = version_ts;
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.version.major = legacy_version.version.major as u8;
entry.version.minor = legacy_version.version.minor as u8;
entry.version.patch = legacy_version.version.patch;
return Ok(());
}
Ordering::Greater => {
if let Some(entry) = self
.history
.arr_mut()
.iter_mut()
.find(|entry| entry.epoch == epoch)
{
entry.version.major = legacy_version.version.major as u8;
entry.version.minor = legacy_version.version.minor as u8;
entry.version.patch = legacy_version.version.patch;
}
return Ok(());
}
Ordering::Less => {}
}
}
let entry = ValidatorHistoryEntry {
epoch,
version: ClientVersion {
major: legacy_version.version.major as u8,
minor: legacy_version.version.minor as u8,
patch: legacy_version.version.patch,
},
..ValidatorHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
}
#[derive(BorshSerialize)]
#[account(zero_copy)]
pub struct ClusterHistory {
pub struct_version: u64,
pub bump: u8,
pub _padding0: [u8; 7],
pub cluster_history_last_update_slot: u64,
pub _padding1: [u8; 232],
pub history: CircBufCluster,
}
#[derive(BorshSerialize)]
#[zero_copy]
pub struct ClusterHistoryEntry {
pub total_blocks: u32,
pub epoch: u16,
pub padding0: [u8; 2],
pub epoch_start_timestamp: u64,
pub padding: [u8; 240],
}
impl Default for ClusterHistoryEntry {
fn default() -> Self {
Self {
total_blocks: u32::MAX,
epoch: u16::MAX,
padding0: [u8::MAX; 2],
epoch_start_timestamp: u64::MAX,
padding: [u8::MAX; 240],
}
}
}
#[derive(BorshSerialize)]
#[zero_copy]
pub struct CircBufCluster {
pub idx: u64,
pub is_empty: u8,
pub padding: [u8; 7],
pub arr: [ClusterHistoryEntry; MAX_ITEMS],
}
impl Default for CircBufCluster {
fn default() -> Self {
Self {
arr: [ClusterHistoryEntry::default(); MAX_ITEMS],
idx: 0,
is_empty: 1,
padding: [0; 7],
}
}
}
impl CircBufCluster {
pub fn push(&mut self, item: ClusterHistoryEntry) {
self.idx = (self.idx + 1) % self.arr.len() as u64;
self.arr[self.idx as usize] = item;
self.is_empty = 0;
}
pub fn is_empty(&self) -> bool {
self.is_empty == 1
}
pub fn last(&self) -> Option<&ClusterHistoryEntry> {
if self.is_empty() {
None
} else {
Some(&self.arr[self.idx as usize])
}
}
pub fn last_mut(&mut self) -> Option<&mut ClusterHistoryEntry> {
if self.is_empty() {
None
} else {
Some(&mut self.arr[self.idx as usize])
}
}
pub fn arr_mut(&mut self) -> &mut [ClusterHistoryEntry] {
&mut self.arr
}
/// Returns &ClusterHistoryEntry for each existing entry in range [start_epoch, end_epoch], factoring for wraparound
/// Returns None for each epoch that doesn't exist in the CircBuf
pub fn epoch_range(
&self,
start_epoch: u16,
end_epoch: u16,
) -> Vec<Option<&ClusterHistoryEntry>> {
// creates an iterator that lays out the entries in consecutive order, handling wraparound
let mut entries = self.arr[(self.idx as usize + 1)..] // if self.idx + 1 == self.arr.len() this will just return an empty slice
.iter()
.chain(self.arr[..=(self.idx as usize)].iter())
.filter(|entry| entry.epoch >= start_epoch && entry.epoch <= end_epoch)
.peekable();
(start_epoch..=end_epoch)
.map(|epoch| {
if let Some(&entry) = entries.peek() {
if entry.epoch == epoch {
entries.next();
return Some(entry);
}
}
None
})
.collect()
}
pub fn total_blocks_latest(&self) -> Option<u32> {
if let Some(entry) = self.last() {
if entry.total_blocks != ClusterHistoryEntry::default().total_blocks {
Some(entry.total_blocks)
} else {
None
}
} else {
None
}
}
pub fn total_blocks_range(&self, start_epoch: u16, end_epoch: u16) -> Vec<Option<u32>> {
let epoch_range = self.epoch_range(start_epoch, end_epoch);
epoch_range
.iter()
.map(|maybe_entry| {
maybe_entry
.as_ref()
.map(|entry| entry.total_blocks)
.filter(|&field| field != ClusterHistoryEntry::default().total_blocks)
})
.collect::<Vec<Option<u32>>>()
}
}
impl ClusterHistory {
pub const SIZE: usize = 8 + size_of::<Self>();
pub const MAX_ITEMS: usize = MAX_ITEMS;
pub const SEED: &'static [u8] = b"cluster-history";
// Sets total blocks for the target epoch
pub fn set_blocks(&mut self, epoch: u16, blocks_in_epoch: u32) -> Result<()> {
if let Some(entry) = self.history.last_mut() {
match entry.epoch.cmp(&epoch) {
Ordering::Equal => {
entry.total_blocks = blocks_in_epoch;
return Ok(());
}
Ordering::Greater => {
if let Some(entry) = self
.history
.arr_mut()
.iter_mut()
.find(|entry| entry.epoch == epoch)
{
entry.total_blocks = blocks_in_epoch;
}
return Ok(());
}
Ordering::Less => {}
}
}
let entry = ClusterHistoryEntry {
epoch,
total_blocks: blocks_in_epoch,
..ClusterHistoryEntry::default()
};
self.history.push(entry);
Ok(())
}
pub fn set_epoch_start_timestamp(
&mut self,
epoch: u16,
epoch_start_timestamp: u64,
) -> Result<()> {
// Always called after `set_blocks` so we can assume the entry for this epoch exists
if let Some(entry) = self.history.last_mut() {
if entry.epoch == epoch {
entry.epoch_start_timestamp = epoch_start_timestamp;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
// Utility test to see struct layout
#[test]
fn test_validator_history_layout() {
println!("{}", ValidatorHistoryEntry::type_layout());
}
#[test]
fn test_epoch_range() {
// Add in 4 CircBuf entries, with epoch 0, 1, 2, 3
let mut circ_buf = CircBuf::default();
for i in 0..4 {
let entry = ValidatorHistoryEntry {
epoch: i,
..ValidatorHistoryEntry::default()
};
circ_buf.push(entry);
}
// Test epoch range [0, 3]
let epoch_range: Vec<Option<&ValidatorHistoryEntry>> = circ_buf.epoch_range(0, 3);
assert_eq!(