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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
use borsh::{BorshDeserialize, BorshSerialize};
use derive_more::{AsRef as DeriveAsRef, From as DeriveFrom};
use serde::{Deserialize, Serialize};
use std::ops;
use near_crypto::PublicKey;
use crate::account::{AccessKey, Account};
use crate::challenge::ChallengesResult;
use crate::errors::EpochError;
use crate::hash::CryptoHash;
use crate::serialize::u128_dec_format;
use crate::trie_key::TrieKey;
use crate::receipt::Receipt;
pub use near_primitives_core::types::*;
pub type StateRoot = CryptoHash;
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(Serialize, Deserialize, BorshSerialize, BorshDeserialize, Clone, Debug, PartialEq, Eq)]
pub enum Finality {
#[serde(rename = "optimistic")]
None,
#[serde(rename = "near-final")]
DoomSlug,
#[serde(rename = "final")]
Final,
}
impl Default for Finality {
fn default() -> Self {
Finality::Final
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AccountWithPublicKey {
pub account_id: AccountId,
pub public_key: PublicKey,
}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct AccountInfo {
pub account_id: AccountId,
pub public_key: PublicKey,
#[serde(with = "u128_dec_format")]
pub amount: Balance,
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(
Debug, Clone, PartialEq, Eq, DeriveAsRef, DeriveFrom, BorshSerialize, BorshDeserialize,
)]
#[as_ref(forward)]
pub struct StoreKey(Vec<u8>);
#[derive(
Debug, Clone, PartialEq, Eq, DeriveAsRef, DeriveFrom, BorshSerialize, BorshDeserialize,
)]
#[as_ref(forward)]
pub struct StoreValue(Vec<u8>);
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(
Debug, Clone, PartialEq, Eq, DeriveAsRef, DeriveFrom, BorshSerialize, BorshDeserialize,
)]
#[as_ref(forward)]
pub struct FunctionArgs(Vec<u8>);
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
pub enum StateChangeKind {
AccountTouched { account_id: AccountId },
AccessKeyTouched { account_id: AccountId },
DataTouched { account_id: AccountId },
ContractCodeTouched { account_id: AccountId },
}
pub type StateChangesKinds = Vec<StateChangeKind>;
#[easy_ext::ext(StateChangesKindsExt)]
impl StateChangesKinds {
pub fn from_changes(
raw_changes: &mut dyn Iterator<Item = Result<RawStateChangesWithTrieKey, std::io::Error>>,
) -> Result<StateChangesKinds, std::io::Error> {
raw_changes
.filter_map(|raw_change| {
let RawStateChangesWithTrieKey { trie_key, .. } = match raw_change {
Ok(p) => p,
Err(e) => return Some(Err(e)),
};
match trie_key {
TrieKey::Account { account_id } => {
Some(Ok(StateChangeKind::AccountTouched { account_id }))
}
TrieKey::ContractCode { account_id } => {
Some(Ok(StateChangeKind::ContractCodeTouched { account_id }))
}
TrieKey::AccessKey { account_id, .. } => {
Some(Ok(StateChangeKind::AccessKeyTouched { account_id }))
}
TrieKey::ContractData { account_id, .. } => {
Some(Ok(StateChangeKind::DataTouched { account_id }))
}
_ => None,
}
})
.collect()
}
}
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
pub enum StateChangeCause {
NotWritableToDisk,
InitialState,
TransactionProcessing { tx_hash: CryptoHash },
ActionReceiptProcessingStarted { receipt_hash: CryptoHash },
ActionReceiptGasReward { receipt_hash: CryptoHash },
ReceiptProcessing { receipt_hash: CryptoHash },
PostponedReceipt { receipt_hash: CryptoHash },
UpdatedDelayedReceipts,
ValidatorAccountsUpdate,
Migration,
Resharding,
}
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
pub struct RawStateChange {
pub cause: StateChangeCause,
pub data: Option<Vec<u8>>,
}
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
pub struct RawStateChangesWithTrieKey {
pub trie_key: TrieKey,
pub changes: Vec<RawStateChange>,
}
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
pub struct ConsolidatedStateChange {
pub trie_key: TrieKey,
pub value: Option<Vec<u8>>,
}
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
pub struct StateChangesForSplitStates {
pub changes: Vec<ConsolidatedStateChange>,
pub processed_delayed_receipts: Vec<Receipt>,
}
impl StateChangesForSplitStates {
pub fn from_raw_state_changes(
changes: &[RawStateChangesWithTrieKey],
processed_delayed_receipts: Vec<Receipt>,
) -> Self {
let changes = changes
.iter()
.map(|RawStateChangesWithTrieKey { trie_key, changes }| {
let value = changes.last().expect("state_changes must not be empty").data.clone();
ConsolidatedStateChange { trie_key: trie_key.clone(), value }
})
.collect();
Self { changes, processed_delayed_receipts }
}
}
pub type RawStateChanges = std::collections::BTreeMap<Vec<u8>, RawStateChangesWithTrieKey>;
#[derive(Debug)]
pub enum StateChangesRequest {
AccountChanges { account_ids: Vec<AccountId> },
SingleAccessKeyChanges { keys: Vec<AccountWithPublicKey> },
AllAccessKeyChanges { account_ids: Vec<AccountId> },
ContractCodeChanges { account_ids: Vec<AccountId> },
DataChanges { account_ids: Vec<AccountId>, key_prefix: StoreKey },
}
#[derive(Debug)]
pub enum StateChangeValue {
AccountUpdate { account_id: AccountId, account: Account },
AccountDeletion { account_id: AccountId },
AccessKeyUpdate { account_id: AccountId, public_key: PublicKey, access_key: AccessKey },
AccessKeyDeletion { account_id: AccountId, public_key: PublicKey },
DataUpdate { account_id: AccountId, key: StoreKey, value: StoreValue },
DataDeletion { account_id: AccountId, key: StoreKey },
ContractCodeUpdate { account_id: AccountId, code: Vec<u8> },
ContractCodeDeletion { account_id: AccountId },
}
impl StateChangeValue {
pub fn affected_account_id(&self) -> &AccountId {
match &self {
StateChangeValue::AccountUpdate { account_id, .. }
| StateChangeValue::AccountDeletion { account_id }
| StateChangeValue::AccessKeyUpdate { account_id, .. }
| StateChangeValue::AccessKeyDeletion { account_id, .. }
| StateChangeValue::DataUpdate { account_id, .. }
| StateChangeValue::DataDeletion { account_id, .. }
| StateChangeValue::ContractCodeUpdate { account_id, .. }
| StateChangeValue::ContractCodeDeletion { account_id } => account_id,
}
}
}
#[derive(Debug)]
pub struct StateChangeWithCause {
pub cause: StateChangeCause,
pub value: StateChangeValue,
}
pub type StateChanges = Vec<StateChangeWithCause>;
#[easy_ext::ext(StateChangesExt)]
impl StateChanges {
pub fn from_changes(
raw_changes: impl Iterator<Item = Result<RawStateChangesWithTrieKey, std::io::Error>>,
) -> Result<StateChanges, std::io::Error> {
let mut state_changes = Self::new();
for raw_change in raw_changes {
let RawStateChangesWithTrieKey { trie_key, changes } = raw_change?;
match trie_key {
TrieKey::Account { account_id } => state_changes.extend(changes.into_iter().map(
|RawStateChange { cause, data }| StateChangeWithCause {
cause,
value: if let Some(change_data) = data {
StateChangeValue::AccountUpdate {
account_id: account_id.clone(),
account: <_>::try_from_slice(&change_data).expect(
"Failed to parse internally stored account information",
),
}
} else {
StateChangeValue::AccountDeletion { account_id: account_id.clone() }
},
},
)),
TrieKey::AccessKey { account_id, public_key } => {
state_changes.extend(changes.into_iter().map(
|RawStateChange { cause, data }| StateChangeWithCause {
cause,
value: if let Some(change_data) = data {
StateChangeValue::AccessKeyUpdate {
account_id: account_id.clone(),
public_key: public_key.clone(),
access_key: <_>::try_from_slice(&change_data)
.expect("Failed to parse internally stored access key"),
}
} else {
StateChangeValue::AccessKeyDeletion {
account_id: account_id.clone(),
public_key: public_key.clone(),
}
},
},
))
}
TrieKey::ContractCode { account_id } => {
state_changes.extend(changes.into_iter().map(
|RawStateChange { cause, data }| StateChangeWithCause {
cause,
value: match data {
Some(change_data) => StateChangeValue::ContractCodeUpdate {
account_id: account_id.clone(),
code: change_data,
},
None => StateChangeValue::ContractCodeDeletion {
account_id: account_id.clone(),
},
},
},
));
}
TrieKey::ContractData { account_id, key } => {
state_changes.extend(changes.into_iter().map(
|RawStateChange { cause, data }| StateChangeWithCause {
cause,
value: if let Some(change_data) = data {
StateChangeValue::DataUpdate {
account_id: account_id.clone(),
key: key.to_vec().into(),
value: change_data.into(),
}
} else {
StateChangeValue::DataDeletion {
account_id: account_id.clone(),
key: key.to_vec().into(),
}
},
},
));
}
TrieKey::ReceivedData { .. } => {}
TrieKey::PostponedReceiptId { .. } => {}
TrieKey::PendingDataCount { .. } => {}
TrieKey::PostponedReceipt { .. } => {}
TrieKey::DelayedReceiptIndices => {}
TrieKey::DelayedReceipt { .. } => {}
}
}
Ok(state_changes)
}
pub fn from_account_changes(
raw_changes: impl Iterator<Item = Result<RawStateChangesWithTrieKey, std::io::Error>>,
) -> Result<StateChanges, std::io::Error> {
let state_changes = Self::from_changes(raw_changes)?;
Ok(state_changes
.into_iter()
.filter(|state_change| {
matches!(
state_change.value,
StateChangeValue::AccountUpdate { .. }
| StateChangeValue::AccountDeletion { .. }
)
})
.collect())
}
pub fn from_access_key_changes(
raw_changes: impl Iterator<Item = Result<RawStateChangesWithTrieKey, std::io::Error>>,
) -> Result<StateChanges, std::io::Error> {
let state_changes = Self::from_changes(raw_changes)?;
Ok(state_changes
.into_iter()
.filter(|state_change| {
matches!(
state_change.value,
StateChangeValue::AccessKeyUpdate { .. }
| StateChangeValue::AccessKeyDeletion { .. }
)
})
.collect())
}
pub fn from_contract_code_changes(
raw_changes: impl Iterator<Item = Result<RawStateChangesWithTrieKey, std::io::Error>>,
) -> Result<StateChanges, std::io::Error> {
let state_changes = Self::from_changes(raw_changes)?;
Ok(state_changes
.into_iter()
.filter(|state_change| {
matches!(
state_change.value,
StateChangeValue::ContractCodeUpdate { .. }
| StateChangeValue::ContractCodeDeletion { .. }
)
})
.collect())
}
pub fn from_data_changes(
raw_changes: impl Iterator<Item = Result<RawStateChangesWithTrieKey, std::io::Error>>,
) -> Result<StateChanges, std::io::Error> {
let state_changes = Self::from_changes(raw_changes)?;
Ok(state_changes
.into_iter()
.filter(|state_change| {
matches!(
state_change.value,
StateChangeValue::DataUpdate { .. } | StateChangeValue::DataDeletion { .. }
)
})
.collect())
}
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(PartialEq, Eq, Clone, Debug, BorshSerialize, BorshDeserialize, Serialize)]
pub struct StateRootNode {
pub data: Vec<u8>,
pub memory_usage: u64,
}
impl StateRootNode {
pub fn empty() -> Self {
StateRootNode { data: vec![], memory_usage: 0 }
}
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(
Debug,
Clone,
Default,
Hash,
Eq,
PartialEq,
PartialOrd,
DeriveAsRef,
BorshSerialize,
BorshDeserialize,
Serialize,
Deserialize,
)]
#[as_ref(forward)]
pub struct EpochId(pub CryptoHash);
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct ApprovalStake {
pub account_id: AccountId,
pub public_key: PublicKey,
pub stake_this_epoch: Balance,
pub stake_next_epoch: Balance,
}
pub mod validator_stake {
use crate::types::ApprovalStake;
use borsh::{BorshDeserialize, BorshSerialize};
use near_crypto::PublicKey;
use near_primitives_core::types::{AccountId, Balance};
use serde::Serialize;
pub use super::ValidatorStakeV1;
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, PartialEq, Eq)]
#[serde(tag = "validator_stake_struct_version")]
pub enum ValidatorStake {
V1(ValidatorStakeV1),
#[cfg(feature = "protocol_feature_chunk_only_producers")]
V2(ValidatorStakeV2),
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[cfg(feature = "protocol_feature_chunk_only_producers")]
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct ValidatorStakeV2 {
pub account_id: AccountId,
pub public_key: PublicKey,
pub stake: Balance,
pub is_chunk_only: bool,
}
pub struct ValidatorStakeIter<'a> {
collection: ValidatorStakeIterSource<'a>,
curr_index: usize,
len: usize,
}
impl<'a> ValidatorStakeIter<'a> {
pub fn empty() -> Self {
Self { collection: ValidatorStakeIterSource::V2(&[]), curr_index: 0, len: 0 }
}
pub fn v1(collection: &'a [ValidatorStakeV1]) -> Self {
Self {
collection: ValidatorStakeIterSource::V1(collection),
curr_index: 0,
len: collection.len(),
}
}
pub fn new(collection: &'a [ValidatorStake]) -> Self {
Self {
collection: ValidatorStakeIterSource::V2(collection),
curr_index: 0,
len: collection.len(),
}
}
pub fn len(&self) -> usize {
self.len
}
}
impl<'a> Iterator for ValidatorStakeIter<'a> {
type Item = ValidatorStake;
fn next(&mut self) -> Option<Self::Item> {
if self.curr_index < self.len {
let item = match self.collection {
ValidatorStakeIterSource::V1(collection) => {
ValidatorStake::V1(collection[self.curr_index].clone())
}
ValidatorStakeIterSource::V2(collection) => collection[self.curr_index].clone(),
};
self.curr_index += 1;
Some(item)
} else {
None
}
}
}
enum ValidatorStakeIterSource<'a> {
V1(&'a [ValidatorStakeV1]),
V2(&'a [ValidatorStake]),
}
impl ValidatorStake {
pub fn new_v1(account_id: AccountId, public_key: PublicKey, stake: Balance) -> Self {
Self::V1(ValidatorStakeV1 { account_id, public_key, stake })
}
#[cfg(not(feature = "protocol_feature_chunk_only_producers"))]
pub fn new(account_id: AccountId, public_key: PublicKey, stake: Balance) -> Self {
Self::new_v1(account_id, public_key, stake)
}
#[cfg(feature = "protocol_feature_chunk_only_producers")]
pub fn new(
account_id: AccountId,
public_key: PublicKey,
stake: Balance,
is_chunk_only: bool,
) -> Self {
Self::V2(ValidatorStakeV2 { account_id, public_key, stake, is_chunk_only })
}
pub fn into_v1(self) -> ValidatorStakeV1 {
match self {
Self::V1(v1) => v1,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => {
ValidatorStakeV1 {
account_id: v2.account_id,
public_key: v2.public_key,
stake: v2.stake,
}
}
}
}
#[inline]
pub fn is_chunk_only(&self) -> bool {
match self {
Self::V1(_) => false,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => v2.is_chunk_only,
}
}
#[inline]
pub fn account_and_stake(self) -> (AccountId, Balance) {
match self {
Self::V1(v1) => (v1.account_id, v1.stake),
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => (v2.account_id, v2.stake),
}
}
#[inline]
pub fn destructure(self) -> (AccountId, PublicKey, Balance) {
match self {
Self::V1(v1) => (v1.account_id, v1.public_key, v1.stake),
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => (v2.account_id, v2.public_key, v2.stake),
}
}
#[inline]
pub fn take_account_id(self) -> AccountId {
match self {
Self::V1(v1) => v1.account_id,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => v2.account_id,
}
}
#[inline]
pub fn account_id(&self) -> &AccountId {
match self {
Self::V1(v1) => &v1.account_id,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => &v2.account_id,
}
}
#[inline]
pub fn take_public_key(self) -> PublicKey {
match self {
Self::V1(v1) => v1.public_key,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => v2.public_key,
}
}
#[inline]
pub fn public_key(&self) -> &PublicKey {
match self {
Self::V1(v1) => &v1.public_key,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => &v2.public_key,
}
}
#[inline]
pub fn stake(&self) -> Balance {
match self {
Self::V1(v1) => v1.stake,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => v2.stake,
}
}
#[inline]
pub fn stake_mut(&mut self) -> &mut Balance {
match self {
Self::V1(v1) => &mut v1.stake,
#[cfg(feature = "protocol_feature_chunk_only_producers")]
Self::V2(v2) => &mut v2.stake,
}
}
pub fn get_approval_stake(&self, is_next_epoch: bool) -> ApprovalStake {
ApprovalStake {
account_id: self.account_id().clone(),
public_key: self.public_key().clone(),
stake_this_epoch: if is_next_epoch { 0 } else { self.stake() },
stake_next_epoch: if is_next_epoch { self.stake() } else { 0 },
}
}
}
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(BorshSerialize, BorshDeserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct ValidatorStakeV1 {
pub account_id: AccountId,
pub public_key: PublicKey,
pub stake: Balance,
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize, Clone, Eq)]
pub struct BlockExtra {
pub challenges_result: ChallengesResult,
}
pub mod chunk_extra {
use crate::types::validator_stake::{ValidatorStake, ValidatorStakeIter};
use crate::types::StateRoot;
use borsh::{BorshDeserialize, BorshSerialize};
use near_primitives_core::hash::CryptoHash;
use near_primitives_core::types::{Balance, Gas};
pub use super::ChunkExtraV1;
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize, Clone, Eq)]
pub enum ChunkExtra {
V1(ChunkExtraV1),
V2(ChunkExtraV2),
}
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize, Clone, Eq)]
pub struct ChunkExtraV2 {
pub state_root: StateRoot,
pub outcome_root: CryptoHash,
pub validator_proposals: Vec<ValidatorStake>,
pub gas_used: Gas,
pub gas_limit: Gas,
pub balance_burnt: Balance,
}
impl ChunkExtra {
pub fn new_with_only_state_root(state_root: &StateRoot) -> Self {
Self::new(state_root, CryptoHash::default(), vec![], 0, 0, 0)
}
pub fn new(
state_root: &StateRoot,
outcome_root: CryptoHash,
validator_proposals: Vec<ValidatorStake>,
gas_used: Gas,
gas_limit: Gas,
balance_burnt: Balance,
) -> Self {
Self::V2(ChunkExtraV2 {
state_root: *state_root,
outcome_root,
validator_proposals,
gas_used,
gas_limit,
balance_burnt,
})
}
#[inline]
pub fn outcome_root(&self) -> &StateRoot {
match self {
Self::V1(v1) => &v1.outcome_root,
Self::V2(v2) => &v2.outcome_root,
}
}
#[inline]
pub fn state_root(&self) -> &StateRoot {
match self {
Self::V1(v1) => &v1.state_root,
Self::V2(v2) => &v2.state_root,
}
}
#[inline]
pub fn state_root_mut(&mut self) -> &mut StateRoot {
match self {
Self::V1(v1) => &mut v1.state_root,
Self::V2(v2) => &mut v2.state_root,
}
}
#[inline]
pub fn validator_proposals(&self) -> ValidatorStakeIter {
match self {
Self::V1(v1) => ValidatorStakeIter::v1(&v1.validator_proposals),
Self::V2(v2) => ValidatorStakeIter::new(&v2.validator_proposals),
}
}
#[inline]
pub fn gas_limit(&self) -> Gas {
match self {
Self::V1(v1) => v1.gas_limit,
Self::V2(v2) => v2.gas_limit,
}
}
#[inline]
pub fn gas_used(&self) -> Gas {
match self {
Self::V1(v1) => v1.gas_used,
Self::V2(v2) => v2.gas_used,
}
}
#[inline]
pub fn balance_burnt(&self) -> Balance {
match self {
Self::V1(v1) => v1.balance_burnt,
Self::V2(v2) => v2.balance_burnt,
}
}
}
}
#[derive(Debug, PartialEq, BorshSerialize, BorshDeserialize, Clone, Eq)]
pub struct ChunkExtraV1 {
pub state_root: StateRoot,
pub outcome_root: CryptoHash,
pub validator_proposals: Vec<ValidatorStakeV1>,
pub gas_used: Gas,
pub gas_limit: Gas,
pub balance_burnt: Balance,
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[serde(untagged)]
pub enum BlockId {
Height(BlockHeight),
Hash(CryptoHash),
}
pub type MaybeBlockId = Option<BlockId>;
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncCheckpoint {
Genesis,
EarliestAvailable,
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlockReference {
BlockId(BlockId),
Finality(Finality),
SyncCheckpoint(SyncCheckpoint),
}
impl BlockReference {
pub fn latest() -> Self {
Self::Finality(Finality::None)
}
}
impl From<BlockId> for BlockReference {
fn from(block_id: BlockId) -> Self {
Self::BlockId(block_id)
}
}
impl From<Finality> for BlockReference {
fn from(finality: Finality) -> Self {
Self::Finality(finality)
}
}
#[derive(Default, BorshSerialize, BorshDeserialize, Clone, Debug, PartialEq)]
pub struct ValidatorStats {
pub produced: NumBlocks,
pub expected: NumBlocks,
}
#[derive(Debug, BorshSerialize, BorshDeserialize)]
pub struct BlockChunkValidatorStats {
pub block_stats: ValidatorStats,
pub chunk_stats: ValidatorStats,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum EpochReference {
EpochId(EpochId),
BlockId(BlockId),
Latest,
}
impl Serialize for EpochReference {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
EpochReference::EpochId(epoch_id) => {
s.serialize_newtype_variant("EpochReference", 0, "epoch_id", epoch_id)
}
EpochReference::BlockId(block_id) => {
s.serialize_newtype_variant("EpochReference", 1, "block_id", block_id)
}
EpochReference::Latest => {
s.serialize_newtype_variant("EpochReference", 2, "latest", &())
}
}
}
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum ValidatorKickoutReason {
Slashed,
NotEnoughBlocks { produced: NumBlocks, expected: NumBlocks },
NotEnoughChunks { produced: NumBlocks, expected: NumBlocks },
Unstaked,
NotEnoughStake {
#[serde(with = "u128_dec_format", rename = "stake_u128")]
stake: Balance,
#[serde(with = "u128_dec_format", rename = "threshold_u128")]
threshold: Balance,
},
DidNotGetASeat,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TransactionOrReceiptId {
Transaction { transaction_hash: CryptoHash, sender_id: AccountId },
Receipt { receipt_id: CryptoHash, receiver_id: AccountId },
}
pub trait CompiledContractCache: Send + Sync {
fn put(&self, key: &[u8], value: &[u8]) -> Result<(), std::io::Error>;
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, std::io::Error>;
}
pub trait EpochInfoProvider {
fn validator_stake(
&self,
epoch_id: &EpochId,
last_block_hash: &CryptoHash,
account_id: &AccountId,
) -> Result<Option<Balance>, EpochError>;
fn validator_total_stake(
&self,
epoch_id: &EpochId,
last_block_hash: &CryptoHash,
) -> Result<Balance, EpochError>;
fn minimum_stake(&self, prev_block_hash: &CryptoHash) -> Result<Balance, EpochError>;
}
#[derive(Debug, Copy, Clone)]
pub enum TrieCacheMode {
CachingShard,
CachingChunk,
}
#[derive(Debug, PartialEq)]
pub struct TrieNodesCount {
pub db_reads: u64,
pub mem_reads: u64,
}
impl ops::Sub for TrieNodesCount {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
db_reads: self.db_reads - other.db_reads,
mem_reads: self.mem_reads - other.mem_reads,
}
}
}