-
Notifications
You must be signed in to change notification settings - Fork 659
/
Copy pathviews.rs
2882 lines (2671 loc) · 104 KB
/
views.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
//! This module defines "stable" internal API to view internal data using view_client.
//!
//! These types should only change when we cannot avoid this. Thus, when the counterpart internal
//! type gets changed, the view should preserve the old shape and only re-map the necessary bits
//! from the source structure in the relevant `From<SourceStruct>` impl.
use crate::account::{AccessKey, AccessKeyPermission, Account, FunctionCallPermission};
use crate::block::{Block, BlockHeader, Tip};
use crate::block_header::{
BlockHeaderInnerLite, BlockHeaderInnerRest, BlockHeaderInnerRestV2, BlockHeaderInnerRestV3,
BlockHeaderV1, BlockHeaderV2, BlockHeaderV3,
};
#[cfg(feature = "protocol_feature_block_header_v4")]
use crate::block_header::{BlockHeaderInnerRestV4, BlockHeaderV4};
use crate::challenge::{Challenge, ChallengesResult};
#[cfg(feature = "protocol_feature_block_header_v4")]
use crate::checked_feature;
use crate::contract::ContractCode;
use crate::delegate_action::{DelegateAction, SignedDelegateAction};
use crate::errors::TxExecutionError;
use crate::hash::{hash, CryptoHash};
use crate::merkle::{combine_hash, MerklePath};
use crate::network::PeerId;
use crate::receipt::{ActionReceipt, DataReceipt, DataReceiver, Receipt, ReceiptEnum};
use crate::runtime::config::RuntimeConfig;
use crate::serialize::dec_format;
use crate::sharding::{
ChunkHash, ShardChunk, ShardChunkHeader, ShardChunkHeaderInner, ShardChunkHeaderInnerV2,
ShardChunkHeaderV3,
};
use crate::transaction::{
Action, AddKeyAction, CreateAccountAction, DeleteAccountAction, DeleteKeyAction,
DeployContractAction, ExecutionMetadata, ExecutionOutcome, ExecutionOutcomeWithIdAndProof,
ExecutionStatus, FunctionCallAction, PartialExecutionOutcome, PartialExecutionStatus,
SignedTransaction, StakeAction, TransferAction,
};
use crate::types::{
AccountId, AccountWithPublicKey, Balance, BlockHeight, EpochHeight, EpochId, FunctionArgs, Gas,
Nonce, NumBlocks, ShardId, StateChangeCause, StateChangeKind, StateChangeValue,
StateChangeWithCause, StateChangesRequest, StateRoot, StorageUsage, StoreKey, StoreValue,
ValidatorKickoutReason,
};
use crate::version::{ProtocolVersion, Version};
use borsh::{BorshDeserialize, BorshSerialize};
use chrono::DateTime;
use near_crypto::{PublicKey, Signature};
use near_fmt::{AbbrBytes, Slice};
use near_primitives_core::config::{ActionCosts, ExtCosts, ParameterCost, VMConfig};
use near_primitives_core::runtime::fees::Fee;
use near_vm_runner::logic::CompiledContractCache;
use num_rational::Rational32;
use serde_with::base64::Base64;
use serde_with::serde_as;
use std::collections::HashMap;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;
use strum::IntoEnumIterator;
use validator_stake_view::ValidatorStakeView;
/// A view of the account
#[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct AccountView {
#[serde(with = "dec_format")]
pub amount: Balance,
#[serde(with = "dec_format")]
pub locked: Balance,
pub code_hash: CryptoHash,
pub storage_usage: StorageUsage,
/// TODO(2271): deprecated.
#[serde(default)]
pub storage_paid_at: BlockHeight,
}
/// A view of the contract code.
#[serde_as]
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct ContractCodeView {
#[serde(rename = "code_base64")]
#[serde_as(as = "Base64")]
pub code: Vec<u8>,
pub hash: CryptoHash,
}
/// State for the view call.
#[derive(Debug)]
pub struct ViewApplyState {
/// Currently building block height.
pub block_height: BlockHeight,
/// Prev block hash
pub prev_block_hash: CryptoHash,
/// Currently building block hash
pub block_hash: CryptoHash,
/// Current epoch id
pub epoch_id: EpochId,
/// Current epoch height
pub epoch_height: EpochHeight,
/// The current block timestamp (number of non-leap-nanoseconds since January 1, 1970 0:00:00 UTC).
pub block_timestamp: u64,
/// Current Protocol version when we apply the state transition
pub current_protocol_version: ProtocolVersion,
/// Cache for compiled contracts.
pub cache: Option<Box<dyn CompiledContractCache>>,
}
impl From<&Account> for AccountView {
fn from(account: &Account) -> Self {
AccountView {
amount: account.amount(),
locked: account.locked(),
code_hash: account.code_hash(),
storage_usage: account.storage_usage(),
storage_paid_at: 0,
}
}
}
impl From<Account> for AccountView {
fn from(account: Account) -> Self {
(&account).into()
}
}
impl From<&AccountView> for Account {
fn from(view: &AccountView) -> Self {
Account::new(view.amount, view.locked, view.code_hash, view.storage_usage)
}
}
impl From<AccountView> for Account {
fn from(view: AccountView) -> Self {
(&view).into()
}
}
impl From<ContractCode> for ContractCodeView {
fn from(contract_code: ContractCode) -> Self {
let hash = *contract_code.hash();
let code = contract_code.into_code();
ContractCodeView { code, hash }
}
}
impl From<ContractCodeView> for ContractCode {
fn from(contract_code: ContractCodeView) -> Self {
ContractCode::new(contract_code.code, Some(contract_code.hash))
}
}
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Eq,
PartialEq,
Clone,
serde::Serialize,
serde::Deserialize,
)]
pub enum AccessKeyPermissionView {
FunctionCall {
#[serde(with = "dec_format")]
allowance: Option<Balance>,
receiver_id: String,
method_names: Vec<String>,
},
FullAccess,
}
impl From<AccessKeyPermission> for AccessKeyPermissionView {
fn from(permission: AccessKeyPermission) -> Self {
match permission {
AccessKeyPermission::FunctionCall(func_call) => AccessKeyPermissionView::FunctionCall {
allowance: func_call.allowance,
receiver_id: func_call.receiver_id,
method_names: func_call.method_names,
},
AccessKeyPermission::FullAccess => AccessKeyPermissionView::FullAccess,
}
}
}
impl From<AccessKeyPermissionView> for AccessKeyPermission {
fn from(view: AccessKeyPermissionView) -> Self {
match view {
AccessKeyPermissionView::FunctionCall { allowance, receiver_id, method_names } => {
AccessKeyPermission::FunctionCall(FunctionCallPermission {
allowance,
receiver_id,
method_names,
})
}
AccessKeyPermissionView::FullAccess => AccessKeyPermission::FullAccess,
}
}
}
#[derive(
BorshSerialize,
BorshDeserialize,
Debug,
Eq,
PartialEq,
Clone,
serde::Serialize,
serde::Deserialize,
)]
pub struct AccessKeyView {
pub nonce: Nonce,
pub permission: AccessKeyPermissionView,
}
impl From<AccessKey> for AccessKeyView {
fn from(access_key: AccessKey) -> Self {
Self { nonce: access_key.nonce, permission: access_key.permission.into() }
}
}
impl From<AccessKeyView> for AccessKey {
fn from(view: AccessKeyView) -> Self {
Self { nonce: view.nonce, permission: view.permission.into() }
}
}
/// Item of the state, key and value are serialized in base64 and proof for inclusion of given state item.
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct StateItem {
pub key: StoreKey,
pub value: StoreValue,
}
#[serde_as]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct ViewStateResult {
pub values: Vec<StateItem>,
#[serde_as(as = "Vec<Base64>")]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub proof: Vec<Arc<[u8]>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone, Default)]
pub struct CallResult {
pub result: Vec<u8>,
pub logs: Vec<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct QueryError {
pub error: String,
pub logs: Vec<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct AccessKeyInfoView {
pub public_key: PublicKey,
pub access_key: AccessKeyView,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct AccessKeyList {
pub keys: Vec<AccessKeyInfoView>,
}
impl FromIterator<AccessKeyInfoView> for AccessKeyList {
fn from_iter<I: IntoIterator<Item = AccessKeyInfoView>>(iter: I) -> Self {
Self { keys: iter.into_iter().collect() }
}
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct KnownPeerStateView {
pub peer_id: PeerId,
pub status: String,
pub addr: String,
pub first_seen: i64,
pub last_seen: i64,
pub last_attempt: Option<(i64, String)>,
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct ConnectionInfoView {
pub peer_id: PeerId,
pub addr: String,
pub time_established: i64,
pub time_connected_until: i64,
}
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum QueryResponseKind {
ViewAccount(AccountView),
ViewCode(ContractCodeView),
ViewState(ViewStateResult),
CallResult(CallResult),
AccessKey(AccessKeyView),
AccessKeyList(AccessKeyList),
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
#[serde(tag = "request_type", rename_all = "snake_case")]
pub enum QueryRequest {
ViewAccount {
account_id: AccountId,
},
ViewCode {
account_id: AccountId,
},
ViewState {
account_id: AccountId,
#[serde(rename = "prefix_base64")]
prefix: StoreKey,
#[serde(default, skip_serializing_if = "is_false")]
include_proof: bool,
},
ViewAccessKey {
account_id: AccountId,
public_key: PublicKey,
},
ViewAccessKeyList {
account_id: AccountId,
},
CallFunction {
account_id: AccountId,
method_name: String,
#[serde(rename = "args_base64")]
args: FunctionArgs,
},
}
fn is_false(v: &bool) -> bool {
!*v
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct QueryResponse {
pub kind: QueryResponseKind,
pub block_height: BlockHeight,
pub block_hash: CryptoHash,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct StatusSyncInfo {
pub latest_block_hash: CryptoHash,
pub latest_block_height: BlockHeight,
pub latest_state_root: CryptoHash,
pub latest_block_time: DateTime<chrono::Utc>,
pub syncing: bool,
pub earliest_block_hash: Option<CryptoHash>,
pub earliest_block_height: Option<BlockHeight>,
pub earliest_block_time: Option<DateTime<chrono::Utc>>,
pub epoch_id: Option<EpochId>,
pub epoch_start_height: Option<BlockHeight>,
}
// TODO: add more information to ValidatorInfo
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct ValidatorInfo {
pub account_id: AccountId,
pub is_slashed: bool,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct PeerInfoView {
pub addr: String,
pub account_id: Option<AccountId>,
pub height: Option<BlockHeight>,
pub block_hash: Option<CryptoHash>,
pub is_highest_block_invalid: bool,
pub tracked_shards: Vec<ShardId>,
pub archival: bool,
pub peer_id: PublicKey,
pub received_bytes_per_sec: u64,
pub sent_bytes_per_sec: u64,
pub last_time_peer_requested_millis: u64,
pub last_time_received_message_millis: u64,
pub connection_established_time_millis: u64,
pub is_outbound_peer: bool,
/// Connection nonce.
pub nonce: u64,
}
/// Information about a Producer: its account name, peer_id and a list of connected peers that
/// the node can use to send message for this producer.
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct KnownProducerView {
pub account_id: AccountId,
pub peer_id: PublicKey,
pub next_hops: Option<Vec<PublicKey>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct Tier1ProxyView {
pub addr: std::net::SocketAddr,
pub peer_id: PublicKey,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct AccountDataView {
pub peer_id: PublicKey,
pub proxies: Vec<Tier1ProxyView>,
pub account_key: PublicKey,
pub timestamp: DateTime<chrono::Utc>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct NetworkInfoView {
pub peer_max_count: u32,
pub num_connected_peers: usize,
pub connected_peers: Vec<PeerInfoView>,
pub known_producers: Vec<KnownProducerView>,
pub tier1_accounts_keys: Vec<PublicKey>,
pub tier1_accounts_data: Vec<AccountDataView>,
pub tier1_connections: Vec<PeerInfoView>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub enum SyncStatusView {
/// Initial state. Not enough peers to do anything yet.
AwaitingPeers,
/// Not syncing / Done syncing.
NoSync,
/// Syncing using light-client headers to a recent epoch
// TODO #3488
// Bowen: why do we use epoch ordinal instead of epoch id?
EpochSync { epoch_ord: u64 },
/// Downloading block headers for fast sync.
HeaderSync {
start_height: BlockHeight,
current_height: BlockHeight,
highest_height: BlockHeight,
},
/// State sync, with different states of state sync for different shards.
StateSync(CryptoHash, HashMap<ShardId, ShardSyncDownloadView>),
/// Sync state across all shards is done.
StateSyncDone,
/// Catch up on blocks.
BodySync { start_height: BlockHeight, current_height: BlockHeight, highest_height: BlockHeight },
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct PeerStoreView {
pub peer_states: Vec<KnownPeerStateView>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct RecentOutboundConnectionsView {
pub recent_outbound_connections: Vec<ConnectionInfoView>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct EdgeView {
pub peer0: PeerId,
pub peer1: PeerId,
pub nonce: u64,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct NetworkGraphView {
pub edges: Vec<EdgeView>,
pub next_hops: HashMap<PeerId, Vec<PeerId>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct LabeledEdgeView {
pub peer0: u32,
pub peer1: u32,
pub nonce: u64,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct EdgeCacheView {
pub peer_labels: HashMap<PeerId, u32>,
pub spanning_trees: HashMap<u32, Vec<LabeledEdgeView>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct PeerDistancesView {
pub distance: Vec<Option<u32>>,
pub min_nonce: u64,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct NetworkRoutesView {
pub edge_cache: EdgeCacheView,
pub local_edges: HashMap<PeerId, EdgeView>,
pub peer_distances: HashMap<PeerId, PeerDistancesView>,
pub my_distances: HashMap<PeerId, u32>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct ShardSyncDownloadView {
pub downloads: Vec<DownloadStatusView>,
pub status: String,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct DownloadStatusView {
pub error: bool,
pub done: bool,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct CatchupStatusView {
// This is the first block of the epoch that we are catching up
pub sync_block_hash: CryptoHash,
pub sync_block_height: BlockHeight,
// Status of all shards that need to sync
pub shard_sync_status: HashMap<ShardId, String>,
// Blocks that we need to catchup, if it is empty, it means catching up is done
pub blocks_to_catchup: Vec<BlockStatusView>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct RequestedStatePartsView {
// This is the first block of the epoch that was requested
pub block_hash: CryptoHash,
// All the part ids of the shards that were requested
pub shard_requested_parts: HashMap<ShardId, Vec<PartElapsedTimeView>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq)]
pub struct BlockStatusView {
pub height: BlockHeight,
pub hash: CryptoHash,
}
impl BlockStatusView {
pub fn new(height: &BlockHeight, hash: &CryptoHash) -> BlockStatusView {
Self { height: *height, hash: *hash }
}
}
impl From<Tip> for BlockStatusView {
fn from(tip: Tip) -> Self {
Self { height: tip.height, hash: tip.last_block_hash }
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct PartElapsedTimeView {
pub part_id: u64,
pub elapsed_ms: u128,
}
impl PartElapsedTimeView {
pub fn new(part_id: &u64, elapsed_ms: u128) -> PartElapsedTimeView {
Self { part_id: *part_id, elapsed_ms }
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct BlockByChunksView {
pub height: BlockHeight,
pub hash: CryptoHash,
pub block_status: String,
pub chunk_status: String,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct ChainProcessingInfo {
pub num_blocks_in_processing: usize,
pub num_orphans: usize,
pub num_blocks_missing_chunks: usize,
/// contains processing info of recent blocks, ordered by height high to low
pub blocks_info: Vec<BlockProcessingInfo>,
/// contains processing info of chunks that we don't know which block it belongs to yet
pub floating_chunks_info: Vec<ChunkProcessingInfo>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct BlockProcessingInfo {
pub height: BlockHeight,
pub hash: CryptoHash,
pub received_timestamp: DateTime<chrono::Utc>,
/// Timestamp when block was received.
//pub received_timestamp: DateTime<chrono::Utc>,
/// Time (in ms) between when the block was first received and when it was processed
pub in_progress_ms: u128,
/// Time (in ms) that the block spent in the orphan pool. If the block was never put in the
/// orphan pool, it is None. If the block is still in the orphan pool, it is since the time
/// it was put into the pool until the current time.
pub orphaned_ms: Option<u128>,
/// Time (in ms) that the block spent in the missing chunks pool. If the block was never put in the
/// missing chunks pool, it is None. If the block is still in the missing chunks pool, it is
/// since the time it was put into the pool until the current time.
pub missing_chunks_ms: Option<u128>,
pub block_status: BlockProcessingStatus,
/// Only contains new chunks that belong to this block, if the block doesn't produce a new chunk
/// for a shard, the corresponding item will be None.
pub chunks_info: Vec<Option<ChunkProcessingInfo>>,
}
#[derive(
BorshSerialize,
BorshDeserialize,
Clone,
Debug,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
)]
pub enum BlockProcessingStatus {
Orphan,
WaitingForChunks,
InProcessing,
Accepted,
Error(String),
Dropped(DroppedReason),
Unknown,
}
#[derive(
BorshSerialize,
BorshDeserialize,
Clone,
Debug,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
)]
pub enum DroppedReason {
// If the node has already processed a block at this height
HeightProcessed,
// If the block processing pool is full
TooManyProcessingBlocks,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct ChunkProcessingInfo {
pub height_created: BlockHeight,
pub shard_id: ShardId,
pub chunk_hash: ChunkHash,
pub prev_block_hash: CryptoHash,
/// Account id of the validator who created this chunk
/// Theoretically this field should never be None unless there is some database corruption.
pub created_by: Option<AccountId>,
pub status: ChunkProcessingStatus,
/// Timestamp of first time when we request for this chunk.
pub requested_timestamp: Option<DateTime<chrono::Utc>>,
/// Timestamp of when the chunk is complete
pub completed_timestamp: Option<DateTime<chrono::Utc>>,
/// Time (in millis) that it takes between when the chunk is requested and when it is completed.
pub request_duration: Option<u64>,
pub chunk_parts_collection: Vec<PartCollectionInfo>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct PartCollectionInfo {
pub part_owner: AccountId,
// Time when the part is received through any message
pub received_time: Option<DateTime<chrono::Utc>>,
// Time when we receive a PartialEncodedChunkForward containing this part
pub forwarded_received_time: Option<DateTime<chrono::Utc>>,
// Time when we receive the PartialEncodedChunk message containing this part
pub chunk_received_time: Option<DateTime<chrono::Utc>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub enum ChunkProcessingStatus {
NeedToRequest,
Requested,
Completed,
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct DetailedDebugStatus {
pub network_info: NetworkInfoView,
pub sync_status: String,
pub catchup_status: Vec<CatchupStatusView>,
pub current_head_status: BlockStatusView,
pub current_header_head_status: BlockStatusView,
pub block_production_delay_millis: u64,
}
// TODO: add more information to status.
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct StatusResponse {
/// Binary version.
pub version: Version,
/// Unique chain id.
pub chain_id: String,
/// Currently active protocol version.
pub protocol_version: u32,
/// Latest protocol version that this client supports.
pub latest_protocol_version: u32,
/// Address for RPC server. None if node doesn’t have RPC endpoint enabled.
#[serde(skip_serializing_if = "Option::is_none")]
pub rpc_addr: Option<String>,
/// Current epoch validators.
pub validators: Vec<ValidatorInfo>,
/// Sync status of the node.
pub sync_info: StatusSyncInfo,
/// Validator id of the node
pub validator_account_id: Option<AccountId>,
/// Public key of the validator.
pub validator_public_key: Option<PublicKey>,
/// Public key of the node.
pub node_public_key: PublicKey,
/// Deprecated; same as `validator_public_key` which you should use instead.
pub node_key: Option<PublicKey>,
/// Uptime of the node.
pub uptime_sec: i64,
/// Information about last blocks, network, epoch and chain & chunk info.
#[serde(skip_serializing_if = "Option::is_none")]
pub detailed_debug_status: Option<DetailedDebugStatus>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct ChallengeView {
// TODO: decide how to represent challenges in json.
}
impl From<Challenge> for ChallengeView {
fn from(_challenge: Challenge) -> Self {
Self {}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct BlockHeaderView {
pub height: BlockHeight,
pub prev_height: Option<BlockHeight>,
pub epoch_id: CryptoHash,
pub next_epoch_id: CryptoHash,
pub hash: CryptoHash,
pub prev_hash: CryptoHash,
pub prev_state_root: CryptoHash,
#[cfg(feature = "protocol_feature_block_header_v4")]
pub block_body_hash: Option<CryptoHash>,
pub chunk_receipts_root: CryptoHash,
pub chunk_headers_root: CryptoHash,
pub chunk_tx_root: CryptoHash,
pub outcome_root: CryptoHash,
pub chunks_included: u64,
pub challenges_root: CryptoHash,
/// Legacy json number. Should not be used.
pub timestamp: u64,
#[serde(with = "dec_format")]
pub timestamp_nanosec: u64,
pub random_value: CryptoHash,
pub validator_proposals: Vec<ValidatorStakeView>,
pub chunk_mask: Vec<bool>,
#[serde(with = "dec_format")]
pub gas_price: Balance,
pub block_ordinal: Option<NumBlocks>,
/// TODO(2271): deprecated.
#[serde(with = "dec_format")]
pub rent_paid: Balance,
/// TODO(2271): deprecated.
#[serde(with = "dec_format")]
pub validator_reward: Balance,
#[serde(with = "dec_format")]
pub total_supply: Balance,
pub challenges_result: ChallengesResult,
pub last_final_block: CryptoHash,
pub last_ds_final_block: CryptoHash,
pub next_bp_hash: CryptoHash,
pub block_merkle_root: CryptoHash,
pub epoch_sync_data_hash: Option<CryptoHash>,
pub approvals: Vec<Option<Signature>>,
pub signature: Signature,
pub latest_protocol_version: ProtocolVersion,
}
impl From<BlockHeader> for BlockHeaderView {
fn from(header: BlockHeader) -> Self {
Self {
height: header.height(),
prev_height: header.prev_height(),
epoch_id: header.epoch_id().0,
next_epoch_id: header.next_epoch_id().0,
hash: *header.hash(),
prev_hash: *header.prev_hash(),
prev_state_root: *header.prev_state_root(),
#[cfg(feature = "protocol_feature_block_header_v4")]
block_body_hash: header.block_body_hash(),
chunk_receipts_root: *header.chunk_receipts_root(),
chunk_headers_root: *header.chunk_headers_root(),
chunk_tx_root: *header.chunk_tx_root(),
chunks_included: header.chunks_included(),
challenges_root: *header.challenges_root(),
outcome_root: *header.outcome_root(),
timestamp: header.raw_timestamp(),
timestamp_nanosec: header.raw_timestamp(),
random_value: *header.random_value(),
validator_proposals: header.validator_proposals().map(Into::into).collect(),
chunk_mask: header.chunk_mask().to_vec(),
block_ordinal: if header.block_ordinal() != 0 {
Some(header.block_ordinal())
} else {
None
},
gas_price: header.gas_price(),
rent_paid: 0,
validator_reward: 0,
total_supply: header.total_supply(),
challenges_result: header.challenges_result().clone(),
last_final_block: *header.last_final_block(),
last_ds_final_block: *header.last_ds_final_block(),
next_bp_hash: *header.next_bp_hash(),
block_merkle_root: *header.block_merkle_root(),
epoch_sync_data_hash: header.epoch_sync_data_hash(),
approvals: header.approvals().to_vec(),
signature: header.signature().clone(),
latest_protocol_version: header.latest_protocol_version(),
}
}
}
impl From<BlockHeaderView> for BlockHeader {
fn from(view: BlockHeaderView) -> Self {
let inner_lite = BlockHeaderInnerLite {
height: view.height,
epoch_id: EpochId(view.epoch_id),
next_epoch_id: EpochId(view.next_epoch_id),
prev_state_root: view.prev_state_root,
outcome_root: view.outcome_root,
timestamp: view.timestamp,
next_bp_hash: view.next_bp_hash,
block_merkle_root: view.block_merkle_root,
};
const LAST_HEADER_V2_VERSION: ProtocolVersion =
crate::version::ProtocolFeature::BlockHeaderV3.protocol_version() - 1;
if view.latest_protocol_version <= 29 {
let validator_proposals = view
.validator_proposals
.into_iter()
.map(|v| v.into_validator_stake().into_v1())
.collect();
let mut header = BlockHeaderV1 {
prev_hash: view.prev_hash,
inner_lite,
inner_rest: BlockHeaderInnerRest {
chunk_receipts_root: view.chunk_receipts_root,
chunk_headers_root: view.chunk_headers_root,
chunk_tx_root: view.chunk_tx_root,
chunks_included: view.chunks_included,
challenges_root: view.challenges_root,
random_value: view.random_value,
validator_proposals,
chunk_mask: view.chunk_mask,
gas_price: view.gas_price,
total_supply: view.total_supply,
challenges_result: view.challenges_result,
last_final_block: view.last_final_block,
last_ds_final_block: view.last_ds_final_block,
approvals: view.approvals.clone(),
latest_protocol_version: view.latest_protocol_version,
},
signature: view.signature,
hash: CryptoHash::default(),
};
header.init();
BlockHeader::BlockHeaderV1(Arc::new(header))
} else if view.latest_protocol_version <= LAST_HEADER_V2_VERSION {
let validator_proposals = view
.validator_proposals
.into_iter()
.map(|v| v.into_validator_stake().into_v1())
.collect();
let mut header = BlockHeaderV2 {
prev_hash: view.prev_hash,
inner_lite,
inner_rest: BlockHeaderInnerRestV2 {
chunk_receipts_root: view.chunk_receipts_root,
chunk_headers_root: view.chunk_headers_root,
chunk_tx_root: view.chunk_tx_root,
challenges_root: view.challenges_root,
random_value: view.random_value,
validator_proposals,
chunk_mask: view.chunk_mask,
gas_price: view.gas_price,
total_supply: view.total_supply,
challenges_result: view.challenges_result,
last_final_block: view.last_final_block,
last_ds_final_block: view.last_ds_final_block,
approvals: view.approvals.clone(),
latest_protocol_version: view.latest_protocol_version,
},
signature: view.signature,
hash: CryptoHash::default(),
};
header.init();
BlockHeader::BlockHeaderV2(Arc::new(header))
} else {
#[cfg(feature = "protocol_feature_block_header_v4")]
if checked_feature!(
"protocol_feature_block_header_v4",
BlockHeaderV4,
view.latest_protocol_version
) {
let mut header = BlockHeaderV4 {
prev_hash: view.prev_hash,
inner_lite,
inner_rest: BlockHeaderInnerRestV4 {
block_body_hash: view.block_body_hash.unwrap_or_default(),
chunk_receipts_root: view.chunk_receipts_root,
chunk_headers_root: view.chunk_headers_root,
chunk_tx_root: view.chunk_tx_root,
challenges_root: view.challenges_root,
random_value: view.random_value,
validator_proposals: view
.validator_proposals
.into_iter()
.map(Into::into)
.collect(),
chunk_mask: view.chunk_mask,
gas_price: view.gas_price,
block_ordinal: view.block_ordinal.unwrap_or(0),
total_supply: view.total_supply,
challenges_result: view.challenges_result,
last_final_block: view.last_final_block,
last_ds_final_block: view.last_ds_final_block,
prev_height: view.prev_height.unwrap_or_default(),
epoch_sync_data_hash: view.epoch_sync_data_hash,
approvals: view.approvals.clone(),
latest_protocol_version: view.latest_protocol_version,
},
signature: view.signature,
hash: CryptoHash::default(),
};
header.init();
return BlockHeader::BlockHeaderV4(Arc::new(header));
}
let mut header = BlockHeaderV3 {
prev_hash: view.prev_hash,
inner_lite,
inner_rest: BlockHeaderInnerRestV3 {
chunk_receipts_root: view.chunk_receipts_root,
chunk_headers_root: view.chunk_headers_root,
chunk_tx_root: view.chunk_tx_root,
challenges_root: view.challenges_root,
random_value: view.random_value,
validator_proposals: view
.validator_proposals
.into_iter()
.map(Into::into)
.collect(),
chunk_mask: view.chunk_mask,
gas_price: view.gas_price,
block_ordinal: view.block_ordinal.unwrap_or(0),
total_supply: view.total_supply,
challenges_result: view.challenges_result,
last_final_block: view.last_final_block,
last_ds_final_block: view.last_ds_final_block,
prev_height: view.prev_height.unwrap_or_default(),
epoch_sync_data_hash: view.epoch_sync_data_hash,
approvals: view.approvals.clone(),
latest_protocol_version: view.latest_protocol_version,
},
signature: view.signature,
hash: CryptoHash::default(),
};
header.init();
BlockHeader::BlockHeaderV3(Arc::new(header))
}
}
}
#[derive(
PartialEq,
Eq,
Debug,
Clone,
BorshDeserialize,
BorshSerialize,
serde::Serialize,
serde::Deserialize,
)]
pub struct BlockHeaderInnerLiteView {
pub height: BlockHeight,
pub epoch_id: CryptoHash,
pub next_epoch_id: CryptoHash,
pub prev_state_root: CryptoHash,
pub outcome_root: CryptoHash,
/// Legacy json number. Should not be used.
pub timestamp: u64,
#[serde(with = "dec_format")]
pub timestamp_nanosec: u64,
pub next_bp_hash: CryptoHash,
pub block_merkle_root: CryptoHash,
}
impl From<BlockHeader> for BlockHeaderInnerLiteView {
fn from(header: BlockHeader) -> Self {
let inner_lite = match &header {
BlockHeader::BlockHeaderV1(header) => &header.inner_lite,
BlockHeader::BlockHeaderV2(header) => &header.inner_lite,
BlockHeader::BlockHeaderV3(header) => &header.inner_lite,
BlockHeader::BlockHeaderV4(header) => &header.inner_lite,
};
BlockHeaderInnerLiteView {
height: inner_lite.height,
epoch_id: inner_lite.epoch_id.0,
next_epoch_id: inner_lite.next_epoch_id.0,
prev_state_root: inner_lite.prev_state_root,
outcome_root: inner_lite.outcome_root,