unc-client-primitives 0.12.2

This crate hosts UNC client-related error types
Documentation
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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
use actix::Message;
use chrono::DateTime;
use chrono::Utc;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tracing::debug_span;
use unc_chain_configs::{ClientConfig, ProtocolConfigView};
use unc_primitives::errors::EpochError;
use unc_primitives::hash::CryptoHash;
use unc_primitives::merkle::{MerklePath, PartialMerkleTree};
use unc_primitives::network::PeerId;
use unc_primitives::sharding::ChunkHash;
use unc_primitives::types::{
    AccountId, BlockHeight, BlockReference, EpochId, EpochReference, MaybeBlockId, ShardId,
    TransactionOrReceiptId,
};
use unc_primitives::views::validator_power_and_pledge_view::ValidatorPowerAndPledgeView;
use unc_primitives::views::{
    AllMinersView, BlockView, ChunkView, DownloadStatusView, EpochValidatorInfo,
    ExecutionOutcomeWithIdView, GasPriceView, LightClientBlockLiteView, LightClientBlockView,
    MaintenanceWindowsView, QueryRequest, QueryResponse, ReceiptView, ShardSyncDownloadView,
    SplitStorageInfoView, StateChangesKindsView, StateChangesRequestView, StateChangesView,
    SyncStatusView, TxStatusView,
};
pub use unc_primitives::views::{StatusResponse, StatusSyncInfo};
use yansi::Color::Magenta;
use yansi::Style;

/// Combines errors coming from chain, tx pool and block producer.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("Chain: {0}")]
    Chain(#[from] unc_chain_primitives::Error),
    #[error("Chunk: {0}")]
    Chunk(#[from] unc_chunks_primitives::Error),
    #[error("Block Producer: {0}")]
    BlockProducer(String),
    #[error("Chunk Producer: {0}")]
    ChunkProducer(String),
    #[error("Other: {0}")]
    Other(String),
}

impl From<unc_primitives::errors::EpochError> for Error {
    fn from(err: unc_primitives::errors::EpochError) -> Self {
        Error::Chain(err.into())
    }
}

#[derive(Debug, serde::Serialize)]
pub struct DownloadStatus {
    pub start_time: DateTime<Utc>,
    pub prev_update_time: DateTime<Utc>,
    pub run_me: Arc<AtomicBool>,
    pub error: bool,
    pub done: bool,
    pub state_requests_count: u64,
    pub last_target: Option<PeerId>,
}

impl DownloadStatus {
    pub fn new(now: DateTime<Utc>) -> Self {
        Self {
            start_time: now,
            prev_update_time: now,
            run_me: Arc::new(AtomicBool::new(true)),
            error: false,
            done: false,
            state_requests_count: 0,
            last_target: None,
        }
    }
}

impl Clone for DownloadStatus {
    /// Clones an object, but it clones the value of `run_me` instead of the
    /// `Arc` that wraps that value.
    fn clone(&self) -> Self {
        DownloadStatus {
            start_time: self.start_time,
            prev_update_time: self.prev_update_time,
            // Creates a new `Arc` holding the same value.
            run_me: Arc::new(AtomicBool::new(self.run_me.load(Ordering::SeqCst))),
            error: self.error,
            done: self.done,
            state_requests_count: self.state_requests_count,
            last_target: self.last_target.clone(),
        }
    }
}

/// Various status of syncing a specific shard.
#[derive(Clone, Debug)]
pub enum ShardSyncStatus {
    StateDownloadHeader,
    StateDownloadParts,
    StateDownloadScheduling,
    StateDownloadApplying,
    StateDownloadComplete,
    ReshardingScheduling,
    ReshardingApplying,
    StateSyncDone,
}

impl ShardSyncStatus {
    pub fn repr(&self) -> u8 {
        match self {
            ShardSyncStatus::StateDownloadHeader => 0,
            ShardSyncStatus::StateDownloadParts => 1,
            ShardSyncStatus::StateDownloadScheduling => 2,
            ShardSyncStatus::StateDownloadApplying => 3,
            ShardSyncStatus::StateDownloadComplete => 4,
            ShardSyncStatus::ReshardingScheduling => 5,
            ShardSyncStatus::ReshardingApplying => 6,
            ShardSyncStatus::StateSyncDone => 7,
        }
    }
}

/// Manually implement compare for ShardSyncStatus to compare only based on variant name
impl PartialEq<Self> for ShardSyncStatus {
    fn eq(&self, other: &Self) -> bool {
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }
}

impl Eq for ShardSyncStatus {}

impl ToString for ShardSyncStatus {
    fn to_string(&self) -> String {
        match self {
            ShardSyncStatus::StateDownloadHeader => "header".to_string(),
            ShardSyncStatus::StateDownloadParts => "parts".to_string(),
            ShardSyncStatus::StateDownloadScheduling => "scheduling".to_string(),
            ShardSyncStatus::StateDownloadApplying => "applying".to_string(),
            ShardSyncStatus::StateDownloadComplete => "download complete".to_string(),
            ShardSyncStatus::ReshardingScheduling => "resharding scheduling".to_string(),
            ShardSyncStatus::ReshardingApplying => "resharding applying".to_string(),
            ShardSyncStatus::StateSyncDone => "done".to_string(),
        }
    }
}

impl From<&DownloadStatus> for DownloadStatusView {
    fn from(status: &DownloadStatus) -> Self {
        DownloadStatusView { done: status.done, error: status.error }
    }
}

impl From<ShardSyncDownload> for ShardSyncDownloadView {
    fn from(download: ShardSyncDownload) -> Self {
        ShardSyncDownloadView {
            downloads: download.downloads.iter().map(|x| x.into()).collect(),
            status: download.status.to_string(),
        }
    }
}

/// Stores status of shard sync and statuses of downloading shards.
#[derive(Clone, Debug)]
pub struct ShardSyncDownload {
    /// Stores all download statuses. If we are downloading state parts, its
    /// length equals the number of state parts. Otherwise it is 1, since we
    /// have only one piece of data to download, like shard state header. It
    /// could be 0 when we are not downloading anything but rather splitting a
    /// shard as part of resharding.
    pub downloads: Vec<DownloadStatus>,
    pub status: ShardSyncStatus,
}

impl ShardSyncDownload {
    /// Creates a instance of self which includes initial statuses for shard state header download at the given time.
    pub fn new_download_state_header(now: DateTime<Utc>) -> Self {
        Self {
            downloads: vec![DownloadStatus::new(now)],
            status: ShardSyncStatus::StateDownloadHeader,
        }
    }

    /// Creates a instance of self which includes initial statuses for shard state parts download at the given time.
    pub fn new_download_state_parts(now: DateTime<Utc>, num_parts: u64) -> Self {
        // Avoid using `vec![x; num_parts]`, because each element needs to have
        // its own independent value of `response`.
        let mut downloads = Vec::with_capacity(num_parts as usize);
        for _ in 0..num_parts {
            downloads.push(DownloadStatus::new(now));
        }
        Self { downloads, status: ShardSyncStatus::StateDownloadParts }
    }
}

pub fn format_shard_sync_phase_per_shard(
    new_shard_sync: &HashMap<ShardId, ShardSyncDownload>,
    use_colour: bool,
) -> Vec<(ShardId, String)> {
    new_shard_sync
        .iter()
        .map(|(&shard_id, shard_progress)| {
            (shard_id, format_shard_sync_phase(shard_progress, use_colour))
        })
        .collect::<Vec<(_, _)>>()
}

/// Applies style if `use_colour` is enabled.
fn paint(s: &str, style: Style, use_style: bool) -> String {
    if use_style {
        style.paint(s).to_string()
    } else {
        s.to_string()
    }
}

/// Formats the given ShardSyncDownload for logging.
pub fn format_shard_sync_phase(
    shard_sync_download: &ShardSyncDownload,
    use_colour: bool,
) -> String {
    match &shard_sync_download.status {
        ShardSyncStatus::StateDownloadHeader => format!(
            "{} requests sent {}, last target {:?}",
            paint("HEADER", Magenta.style().bold(), use_colour),
            shard_sync_download.downloads.get(0).map_or(0, |x| x.state_requests_count),
            shard_sync_download.downloads.get(0).map_or(None, |x| x.last_target.as_ref()),
        ),
        ShardSyncStatus::StateDownloadParts => {
            let mut num_parts_done = 0;
            let mut num_parts_not_done = 0;
            for download in shard_sync_download.downloads.iter() {
                if download.done {
                    num_parts_done += 1;
                } else {
                    num_parts_not_done += 1;
                }
            }
            format!("num_parts_done={num_parts_done} num_parts_not_done={num_parts_not_done}")
        }
        status => format!("{status:?}"),
    }
}

#[derive(Clone)]
pub struct StateSyncStatus {
    pub sync_hash: CryptoHash,
    pub sync_status: HashMap<ShardId, ShardSyncDownload>,
}

/// If alternate flag was specified, write formatted sync_status per shard.
impl std::fmt::Debug for StateSyncStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if f.alternate() {
            write!(
                f,
                "StateSyncStatus {{ sync_hash: {:?}, shard_sync: {:?} }}",
                self.sync_hash,
                format_shard_sync_phase_per_shard(&self.sync_status, false)
            )
        } else {
            write!(
                f,
                "StateSyncStatus {{ sync_hash: {:?}, sync_status: {:?} }}",
                self.sync_hash, self.sync_status
            )
        }
    }
}

/// Various status sync can be in, whether it's fast sync or archival.
#[derive(Clone, Debug, strum::AsRefStr)]
pub enum SyncStatus {
    /// 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 {
        /// Head height at the beginning. Not the header head height!
        /// Used only for reporting the progress of the sync.
        start_height: BlockHeight,
        /// Current header head height.
        current_height: BlockHeight,
        /// Highest height of our peers.
        highest_height: BlockHeight,
    },
    /// State sync, with different states of state sync for different shards.
    StateSync(StateSyncStatus),
    /// Sync state across all shards is done.
    StateSyncDone,
    /// Download and process blocks until the head reaches the head of the network.
    BlockSync {
        /// Header head height at the beginning.
        /// Used only for reporting the progress of the sync.
        start_height: BlockHeight,
        /// Current head height.
        current_height: BlockHeight,
        /// Highest height of our peers.
        highest_height: BlockHeight,
    },
}

impl SyncStatus {
    /// Get a string representation of the status variant
    pub fn as_variant_name(&self) -> &str {
        self.as_ref()
    }

    /// True if currently engaged in syncing the chain.
    pub fn is_syncing(&self) -> bool {
        match self {
            SyncStatus::NoSync => false,
            _ => true,
        }
    }

    pub fn repr(&self) -> u8 {
        match self {
            // Represent NoSync as 0 because it is the state of a normal well-behaving node.
            SyncStatus::NoSync => 0,
            SyncStatus::AwaitingPeers => 1,
            SyncStatus::EpochSync { .. } => 2,
            SyncStatus::HeaderSync { .. } => 3,
            SyncStatus::StateSync(_) => 4,
            SyncStatus::StateSyncDone => 5,
            SyncStatus::BlockSync { .. } => 6,
        }
    }

    pub fn start_height(&self) -> Option<BlockHeight> {
        match self {
            SyncStatus::HeaderSync { start_height, .. } => Some(*start_height),
            SyncStatus::BlockSync { start_height, .. } => Some(*start_height),
            _ => None,
        }
    }

    pub fn update(&mut self, new_value: Self) {
        let _span =
            debug_span!(target: "sync", "update_sync_status", old_value = ?self, ?new_value)
                .entered();
        *self = new_value;
    }
}

impl From<SyncStatus> for SyncStatusView {
    fn from(status: SyncStatus) -> Self {
        match status {
            SyncStatus::AwaitingPeers => SyncStatusView::AwaitingPeers,
            SyncStatus::NoSync => SyncStatusView::NoSync,
            SyncStatus::EpochSync { epoch_ord } => SyncStatusView::EpochSync { epoch_ord },
            SyncStatus::HeaderSync { start_height, current_height, highest_height } => {
                SyncStatusView::HeaderSync { start_height, current_height, highest_height }
            }
            SyncStatus::StateSync(state_sync_status) => SyncStatusView::StateSync(
                state_sync_status.sync_hash,
                state_sync_status
                    .sync_status
                    .into_iter()
                    .map(|(shard_id, shard_sync)| (shard_id, shard_sync.into()))
                    .collect(),
            ),
            SyncStatus::StateSyncDone => SyncStatusView::StateSyncDone,
            SyncStatus::BlockSync { start_height, current_height, highest_height } => {
                SyncStatusView::BlockSync { start_height, current_height, highest_height }
            }
        }
    }
}

/// Actor message requesting block provider by EpochId and BlockHeight.
#[derive(Debug)]
pub struct GetProvider(pub EpochId, pub BlockHeight);

#[derive(thiserror::Error, Debug)]
pub enum GetProviderError {
    #[error("IO Error: {error_message}")]
    IOError { error_message: String },
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    #[error("There are no fully synchronized blocks yet")]
    NotSyncedYet,
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::Error> for crate::types::GetProviderError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => {
                Self::IOError { error_message: error.to_string() }
            }
            unc_chain_primitives::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

impl From<EpochError> for GetProviderError {
    fn from(error: EpochError) -> Self {
        Self::IOError { error_message: error.to_string() }
    }
}

impl Message for crate::types::GetProvider {
    type Result = Result<AccountId, crate::types::GetProviderError>;
}

/// Actor message requesting block provider by EpochId and BlockHeight.
#[derive(Debug)]
pub struct GetAllMiners(pub CryptoHash);

#[derive(thiserror::Error, Debug)]
pub enum GetAllMinersError {
    #[error("IO Error: {error_message}")]
    IOError { error_message: String },
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::Error> for crate::types::GetAllMinersError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => {
                Self::IOError { error_message: error.to_string() }
            }
            unc_chain_primitives::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

impl From<EpochError> for crate::types::GetAllMinersError {
    fn from(error: EpochError) -> Self {
        Self::IOError { error_message: error.to_string() }
    }
}

impl Message for crate::types::GetAllMiners {
    type Result = Result<AllMinersView, crate::types::GetAllMinersError>;
}

/// Actor message requesting block by id, hash or sync state.
#[derive(Debug)]
pub struct GetBlock(pub BlockReference);

#[derive(thiserror::Error, Debug)]
pub enum GetBlockError {
    #[error("IO Error: {error_message}")]
    IOError { error_message: String },
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    #[error("There are no fully synchronized blocks yet")]
    NotSyncedYet,
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::Error> for GetBlockError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => {
                Self::IOError { error_message: error.to_string() }
            }
            unc_chain_primitives::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

impl GetBlock {
    pub fn latest() -> Self {
        Self(BlockReference::latest())
    }
}

impl Message for GetBlock {
    type Result = Result<BlockView, GetBlockError>;
}

/// Get block with the block merkle tree. Used for testing
#[derive(Debug)]
pub struct GetBlockWithMerkleTree(pub BlockReference);

impl GetBlockWithMerkleTree {
    pub fn latest() -> Self {
        Self(BlockReference::latest())
    }
}

impl Message for GetBlockWithMerkleTree {
    type Result = Result<(BlockView, Arc<PartialMerkleTree>), GetBlockError>;
}

/// Actor message requesting a chunk by chunk hash and block hash + shard id.
#[derive(Debug)]
pub enum GetChunk {
    Height(BlockHeight, ShardId),
    BlockHash(CryptoHash, ShardId),
    ChunkHash(ChunkHash),
}

impl Message for GetChunk {
    type Result = Result<ChunkView, GetChunkError>;
}

#[derive(thiserror::Error, Debug)]
pub enum GetChunkError {
    #[error("IO Error: {error_message}")]
    IOError { error_message: String },
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    #[error("Shard ID {shard_id} is invalid")]
    InvalidShardId { shard_id: u64 },
    #[error("Chunk with hash {chunk_hash:?} has never been observed on this node")]
    UnknownChunk { chunk_hash: ChunkHash },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::Error> for GetChunkError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => {
                Self::IOError { error_message: error.to_string() }
            }
            unc_chain_primitives::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            unc_chain_primitives::Error::InvalidShardId(shard_id) => {
                Self::InvalidShardId { shard_id }
            }
            unc_chain_primitives::Error::ChunkMissing(chunk_hash) => {
                Self::UnknownChunk { chunk_hash }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

/// Queries client for given path / data.
#[derive(Clone, Debug)]
pub struct Query {
    pub block_reference: BlockReference,
    pub request: QueryRequest,
}

impl Query {
    pub fn new(block_reference: BlockReference, request: QueryRequest) -> Self {
        Query { block_reference, request }
    }
}

impl Message for Query {
    type Result = Result<QueryResponse, QueryError>;
}

#[derive(thiserror::Error, Debug)]
pub enum QueryError {
    #[error("There are no fully synchronized blocks on the node yet")]
    NoSyncedBlocks,
    #[error("The node does not track the shard ID {requested_shard_id}")]
    UnavailableShard { requested_shard_id: unc_primitives::types::ShardId },
    #[error("Account ID {requested_account_id} is invalid")]
    InvalidAccount {
        requested_account_id: unc_primitives::types::AccountId,
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error(
        "Account {requested_account_id} does not exist while viewing at block #{block_height}"
    )]
    UnknownAccount {
        requested_account_id: unc_primitives::types::AccountId,
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error("Chip {public_key} does not exist while viewing at block #{block_height}")]
    UnknownChip {
        public_key: unc_crypto::PublicKey,
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error(
        "Contract code for contract ID {contract_account_id} has never been observed on the node at block #{block_height}"
    )]
    NoContractCode {
        contract_account_id: unc_primitives::types::AccountId,
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error("State of contract {contract_account_id} is too large to be viewed")]
    TooLargeContractState {
        contract_account_id: unc_primitives::types::AccountId,
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error("Access key for public key {public_key} has never been observed on the node at block #{block_height}")]
    UnknownAccessKey {
        public_key: unc_crypto::PublicKey,
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error("Function call returned an error: {vm_error}")]
    ContractExecutionError {
        vm_error: String,
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error("The node reached its limits. Try again later. More details: {error_message}")]
    InternalError { error_message: String },
    #[error(
        "The data for block #{block_height} is garbage collected on this node, use an archival node to fetch historical data"
    )]
    GarbageCollectedBlock {
        block_height: unc_primitives::types::BlockHeight,
        block_hash: unc_primitives::hash::CryptoHash,
    },
    #[error("Block either has never been observed on the node or has been garbage collected: {block_reference:?}")]
    UnknownBlock { block_reference: unc_primitives::types::BlockReference },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

#[derive(Debug)]
pub struct Status {
    pub is_health_check: bool,
    // If true - return more detailed information about the current status (recent blocks etc).
    pub detailed: bool,
}

#[derive(thiserror::Error, Debug)]
pub enum StatusError {
    #[error("Node is syncing")]
    NodeIsSyncing,
    #[error("No blocks for {elapsed:?}")]
    NoNewBlocks { elapsed: std::time::Duration },
    #[error("Epoch Out Of Bounds {epoch_id:?}")]
    EpochOutOfBounds { epoch_id: unc_primitives::types::EpochId },
    #[error("The node reached its limits. Try again later. More details: {error_message}")]
    InternalError { error_message: String },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::error::Error> for StatusError {
    fn from(error: unc_chain_primitives::error::Error) -> Self {
        match error {
            unc_chain_primitives::error::Error::IOErr(error) => {
                Self::InternalError { error_message: error.to_string() }
            }
            unc_chain_primitives::error::Error::DBNotFoundErr(error_message)
            | unc_chain_primitives::error::Error::ValidatorError(error_message) => {
                Self::InternalError { error_message }
            }
            unc_chain_primitives::error::Error::EpochOutOfBounds(epoch_id) => {
                Self::EpochOutOfBounds { epoch_id }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

impl Message for Status {
    type Result = Result<StatusResponse, StatusError>;
}

#[derive(Debug)]
pub struct GetNextLightClientBlock {
    pub last_block_hash: CryptoHash,
}

#[derive(thiserror::Error, Debug)]
pub enum GetNextLightClientBlockError {
    #[error("Internal error: {error_message}")]
    InternalError { error_message: String },
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    #[error("Epoch Out Of Bounds {epoch_id:?}")]
    EpochOutOfBounds { epoch_id: unc_primitives::types::EpochId },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::error::Error> for GetNextLightClientBlockError {
    fn from(error: unc_chain_primitives::error::Error) -> Self {
        match error {
            unc_chain_primitives::error::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            unc_chain_primitives::error::Error::IOErr(error) => {
                Self::InternalError { error_message: error.to_string() }
            }
            unc_chain_primitives::error::Error::EpochOutOfBounds(epoch_id) => {
                Self::EpochOutOfBounds { epoch_id }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

impl Message for GetNextLightClientBlock {
    type Result = Result<Option<Arc<LightClientBlockView>>, GetNextLightClientBlockError>;
}

#[derive(Debug)]
pub struct GetNetworkInfo {}

impl Message for GetNetworkInfo {
    type Result = Result<NetworkInfoResponse, String>;
}

#[derive(Debug)]
pub struct GetGasPrice {
    pub block_id: MaybeBlockId,
}

impl Message for GetGasPrice {
    type Result = Result<GasPriceView, GetGasPriceError>;
}

#[derive(thiserror::Error, Debug)]
pub enum GetGasPriceError {
    #[error("Internal error: {error_message}")]
    InternalError { error_message: String },
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::Error> for GetGasPriceError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => {
                Self::InternalError { error_message: error.to_string() }
            }
            unc_chain_primitives::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

#[derive(Clone, Debug)]
pub struct PeerInfo {
    pub id: PeerId,
    pub addr: Option<std::net::SocketAddr>,
    pub account_id: Option<AccountId>,
}

#[derive(Clone, Debug)]
pub struct KnownProducer {
    pub account_id: AccountId,
    pub addr: Option<std::net::SocketAddr>,
    pub peer_id: PeerId,
    pub next_hops: Option<Vec<PeerId>>,
}

#[derive(Debug)]
pub struct NetworkInfoResponse {
    pub connected_peers: Vec<PeerInfo>,
    pub num_connected_peers: usize,
    pub peer_max_count: u32,
    pub sent_bytes_per_sec: u64,
    pub received_bytes_per_sec: u64,
    /// Accounts of known block and chunk producers from routing table.
    pub known_producers: Vec<KnownProducer>,
}

/// Status of given transaction including all the subsequent receipts.
#[derive(Debug)]
pub struct TxStatus {
    pub tx_hash: CryptoHash,
    pub signer_account_id: AccountId,
    pub fetch_receipt: bool,
}

#[derive(Debug)]
pub enum TxStatusError {
    ChainError(unc_chain_primitives::Error),
    MissingTransaction(CryptoHash),
    InternalError(String),
    TimeoutError,
}

impl From<unc_chain_primitives::Error> for TxStatusError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        Self::ChainError(error)
    }
}

impl Message for TxStatus {
    type Result = Result<TxStatusView, TxStatusError>;
}

#[derive(Debug)]
pub struct GetValidatorInfo {
    pub epoch_reference: EpochReference,
}

impl Message for GetValidatorInfo {
    type Result = Result<EpochValidatorInfo, GetValidatorInfoError>;
}

#[derive(thiserror::Error, Debug)]
pub enum GetProviderInfoError {
    #[error("IO Error: {0}")]
    IOError(String),
    #[error("Unknown block")]
    UnknownBlock,
    #[error("Provider info unavailable")]
    ProviderInfoUnavailable,
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {0}")]
    Unreachable(String),
}

impl From<unc_chain_primitives::Error> for crate::types::GetProviderInfoError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::DBNotFoundErr(_)
            | unc_chain_primitives::Error::BlockOutOfBounds(_) => Self::UnknownBlock,
            unc_chain_primitives::Error::IOErr(s) => Self::IOError(s.to_string()),
            _ => Self::Unreachable(error.to_string()),
        }
    }
}
#[derive(thiserror::Error, Debug)]
pub enum GetValidatorInfoError {
    #[error("IO Error: {0}")]
    IOError(String),
    #[error("Unknown epoch")]
    UnknownEpoch,
    #[error("Validator info unavailable")]
    ValidatorInfoUnavailable,
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {0}")]
    Unreachable(String),
}

impl From<unc_chain_primitives::Error> for GetValidatorInfoError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::DBNotFoundErr(_)
            | unc_chain_primitives::Error::EpochOutOfBounds(_) => Self::UnknownEpoch,
            unc_chain_primitives::Error::IOErr(s) => Self::IOError(s.to_string()),
            _ => Self::Unreachable(error.to_string()),
        }
    }
}

#[derive(Debug)]
pub struct GetValidatorOrdered {
    pub block_id: MaybeBlockId,
}

impl Message for GetValidatorOrdered {
    type Result = Result<Vec<ValidatorPowerAndPledgeView>, GetValidatorInfoError>;
}

#[derive(Debug)]
pub struct GetStateChanges {
    pub block_hash: CryptoHash,
    pub state_changes_request: StateChangesRequestView,
}

#[derive(thiserror::Error, Debug)]
pub enum GetStateChangesError {
    #[error("IO Error: {error_message}")]
    IOError { error_message: String },
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    #[error("There are no fully synchronized blocks yet")]
    NotSyncedYet,
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::Error> for GetStateChangesError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => {
                Self::IOError { error_message: error.to_string() }
            }
            unc_chain_primitives::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

impl Message for GetStateChanges {
    type Result = Result<StateChangesView, GetStateChangesError>;
}

#[derive(Debug)]
pub struct GetStateChangesInBlock {
    pub block_hash: CryptoHash,
}

impl Message for GetStateChangesInBlock {
    type Result = Result<StateChangesKindsView, GetStateChangesError>;
}

#[derive(Debug)]
pub struct GetStateChangesWithCauseInBlock {
    pub block_hash: CryptoHash,
}

impl Message for GetStateChangesWithCauseInBlock {
    type Result = Result<StateChangesView, GetStateChangesError>;
}

#[derive(Debug)]
pub struct GetStateChangesWithCauseInBlockForTrackedShards {
    pub block_hash: CryptoHash,
    pub epoch_id: EpochId,
}

impl Message for GetStateChangesWithCauseInBlockForTrackedShards {
    type Result = Result<HashMap<ShardId, StateChangesView>, GetStateChangesError>;
}

#[derive(Debug)]
pub struct GetExecutionOutcome {
    pub id: TransactionOrReceiptId,
}

#[derive(thiserror::Error, Debug)]
pub enum GetExecutionOutcomeError {
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    #[error("Inconsistent state. Total number of shards is {number_or_shards} but the execution outcome is in shard {execution_outcome_shard_id}")]
    InconsistentState {
        number_or_shards: usize,
        execution_outcome_shard_id: unc_primitives::types::ShardId,
    },
    #[error("{transaction_or_receipt_id} has not been confirmed")]
    NotConfirmed { transaction_or_receipt_id: unc_primitives::hash::CryptoHash },
    #[error("{transaction_or_receipt_id} does not exist")]
    UnknownTransactionOrReceipt { transaction_or_receipt_id: unc_primitives::hash::CryptoHash },
    #[error("Node doesn't track the shard where {transaction_or_receipt_id} is executed")]
    UnavailableShard {
        transaction_or_receipt_id: unc_primitives::hash::CryptoHash,
        shard_id: unc_primitives::types::ShardId,
    },
    #[error("Internal error: {error_message}")]
    InternalError { error_message: String },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<TxStatusError> for GetExecutionOutcomeError {
    fn from(error: TxStatusError) -> Self {
        match error {
            TxStatusError::ChainError(err) => {
                Self::InternalError { error_message: err.to_string() }
            }
            _ => Self::Unreachable { error_message: format!("{:?}", error) },
        }
    }
}

impl From<unc_chain_primitives::error::Error> for GetExecutionOutcomeError {
    fn from(error: unc_chain_primitives::error::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => {
                Self::InternalError { error_message: error.to_string() }
            }
            unc_chain_primitives::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            _ => Self::Unreachable { error_message: error.to_string() },
        }
    }
}

pub struct GetExecutionOutcomeResponse {
    pub outcome_proof: ExecutionOutcomeWithIdView,
    pub outcome_root_proof: MerklePath,
}

impl Message for GetExecutionOutcome {
    type Result = Result<GetExecutionOutcomeResponse, GetExecutionOutcomeError>;
}

#[derive(Debug)]
pub struct GetExecutionOutcomesForBlock {
    pub block_hash: CryptoHash,
}

impl Message for GetExecutionOutcomesForBlock {
    type Result = Result<HashMap<ShardId, Vec<ExecutionOutcomeWithIdView>>, String>;
}

#[derive(Debug)]
pub struct GetBlockProof {
    pub block_hash: CryptoHash,
    pub head_block_hash: CryptoHash,
}

pub struct GetBlockProofResponse {
    pub block_header_lite: LightClientBlockLiteView,
    pub proof: MerklePath,
}

#[derive(thiserror::Error, Debug)]
pub enum GetBlockProofError {
    #[error("Block either has never been observed on the node or has been garbage collected: {error_message}")]
    UnknownBlock { error_message: String },
    #[error("Internal error: {error_message}")]
    InternalError { error_message: String },
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {error_message}")]
    Unreachable { error_message: String },
}

impl From<unc_chain_primitives::error::Error> for GetBlockProofError {
    fn from(error: unc_chain_primitives::error::Error) -> Self {
        match error {
            unc_chain_primitives::error::Error::DBNotFoundErr(error_message) => {
                Self::UnknownBlock { error_message }
            }
            unc_chain_primitives::error::Error::Other(error_message) => {
                Self::InternalError { error_message }
            }
            err => Self::Unreachable { error_message: err.to_string() },
        }
    }
}

impl Message for GetBlockProof {
    type Result = Result<GetBlockProofResponse, GetBlockProofError>;
}

#[derive(Debug)]
pub struct GetReceipt {
    pub receipt_id: CryptoHash,
}

#[derive(thiserror::Error, Debug)]
pub enum GetReceiptError {
    #[error("IO Error: {0}")]
    IOError(String),
    #[error("Receipt with id {0} has never been observed on this node")]
    UnknownReceipt(unc_primitives::hash::CryptoHash),
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {0}")]
    Unreachable(String),
}

impl From<unc_chain_primitives::Error> for GetReceiptError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => Self::IOError(error.to_string()),
            _ => Self::Unreachable(error.to_string()),
        }
    }
}

impl Message for GetReceipt {
    type Result = Result<Option<ReceiptView>, GetReceiptError>;
}

#[derive(Debug)]
pub struct GetProtocolConfig(pub BlockReference);

impl Message for GetProtocolConfig {
    type Result = Result<ProtocolConfigView, GetProtocolConfigError>;
}

#[derive(thiserror::Error, Debug)]
pub enum GetProtocolConfigError {
    #[error("IO Error: {0}")]
    IOError(String),
    #[error("Block has never been observed: {0}")]
    UnknownBlock(String),
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {0}")]
    Unreachable(String),
}

impl From<unc_chain_primitives::Error> for GetProtocolConfigError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => Self::IOError(error.to_string()),
            unc_chain_primitives::Error::DBNotFoundErr(s) => Self::UnknownBlock(s),
            _ => Self::Unreachable(error.to_string()),
        }
    }
}

#[derive(Debug)]
pub struct GetMaintenanceWindows {
    pub account_id: AccountId,
}

impl Message for GetMaintenanceWindows {
    type Result = Result<MaintenanceWindowsView, GetMaintenanceWindowsError>;
}

#[derive(thiserror::Error, Debug)]
pub enum GetMaintenanceWindowsError {
    #[error("IO Error: {0}")]
    IOError(String),
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {0}")]
    Unreachable(String),
}

impl From<unc_chain_primitives::Error> for GetMaintenanceWindowsError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => Self::IOError(error.to_string()),
            _ => Self::Unreachable(error.to_string()),
        }
    }
}

#[derive(Debug)]
pub struct GetClientConfig {}

impl Message for GetClientConfig {
    type Result = Result<ClientConfig, GetClientConfigError>;
}

#[derive(thiserror::Error, Debug)]
pub enum GetClientConfigError {
    #[error("IO Error: {0}")]
    IOError(String),
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {0}")]
    Unreachable(String),
}

impl From<unc_chain_primitives::Error> for GetClientConfigError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => Self::IOError(error.to_string()),
            _ => Self::Unreachable(error.to_string()),
        }
    }
}

#[derive(Debug)]
pub struct GetSplitStorageInfo {}

impl Message for GetSplitStorageInfo {
    type Result = Result<SplitStorageInfoView, GetSplitStorageInfoError>;
}

#[derive(thiserror::Error, Debug)]
pub enum GetSplitStorageInfoError {
    #[error("IO Error: {0}")]
    IOError(String),
    // NOTE: Currently, the underlying errors are too broad, and while we tried to handle
    // expected cases, we cannot statically guarantee that no other errors will be returned
    // in the future.
    // TODO #3851: Remove this variant once we can exhaustively match all the underlying errors
    #[error("It is a bug if you receive this error type, please, report this incident: https://github.com/utnet-org/utility/issues/new/choose. Details: {0}")]
    Unreachable(String),
}

impl From<unc_chain_primitives::Error> for GetSplitStorageInfoError {
    fn from(error: unc_chain_primitives::Error) -> Self {
        match error {
            unc_chain_primitives::Error::IOErr(error) => Self::IOError(error.to_string()),
            _ => Self::Unreachable(error.to_string()),
        }
    }
}

impl From<std::io::Error> for GetSplitStorageInfoError {
    fn from(error: std::io::Error) -> Self {
        Self::IOError(error.to_string())
    }
}

#[cfg(feature = "sandbox")]
#[derive(Debug)]
pub enum SandboxMessage {
    SandboxPatchState(Vec<unc_primitives::state_record::StateRecord>),
    SandboxPatchStateStatus,
    SandboxFastForward(unc_primitives::types::BlockHeightDelta),
    SandboxFastForwardStatus,
}

#[cfg(feature = "sandbox")]
#[derive(Eq, PartialEq, Debug, actix::MessageResponse)]
pub enum SandboxResponse {
    SandboxPatchStateFinished(bool),
    SandboxFastForwardFinished(bool),
    SandboxFastForwardFailed(String),
    SandboxNoResponse,
}
#[cfg(feature = "sandbox")]
impl Message for SandboxMessage {
    type Result = SandboxResponse;
}