-
Notifications
You must be signed in to change notification settings - Fork 332
/
foreign_client.rs
1789 lines (1594 loc) · 63.2 KB
/
foreign_client.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
//! Queries and methods for interfacing with foreign clients.
//!
//! The term "foreign client" refers to IBC light clients that are running on-chain,
//! i.e. they are *foreign* to the relayer. In contrast, the term "local client"
//! refers to light clients running *locally* as part of the relayer.
use core::{fmt, time::Duration};
use std::thread;
use std::time::Instant;
use ibc_proto::google::protobuf::Any;
use itertools::Itertools;
use tracing::{debug, error, info, instrument, trace, warn};
use flex_error::define_error;
use ibc_relayer_types::applications::ics28_ccv::msgs::ccv_misbehaviour::MsgSubmitIcsConsumerMisbehaviour;
use ibc_relayer_types::clients::ics07_tendermint::misbehaviour::Misbehaviour;
use ibc_relayer_types::core::ics02_client::client_state::ClientState;
use ibc_relayer_types::core::ics02_client::error::Error as ClientError;
use ibc_relayer_types::core::ics02_client::events::UpdateClient;
use ibc_relayer_types::core::ics02_client::header::Header;
use ibc_relayer_types::core::ics02_client::msgs::create_client::MsgCreateClient;
use ibc_relayer_types::core::ics02_client::msgs::misbehaviour::MsgSubmitMisbehaviour;
use ibc_relayer_types::core::ics02_client::msgs::update_client::MsgUpdateClient;
use ibc_relayer_types::core::ics02_client::msgs::upgrade_client::MsgUpgradeClient;
use ibc_relayer_types::core::ics02_client::trust_threshold::TrustThreshold;
use ibc_relayer_types::core::ics24_host::identifier::{ChainId, ClientId};
use ibc_relayer_types::downcast;
use ibc_relayer_types::events::{IbcEvent, IbcEventType, WithBlockDataType};
use ibc_relayer_types::timestamp::{Timestamp, TimestampOverflowError};
use ibc_relayer_types::tx_msg::Msg;
use ibc_relayer_types::Height;
use crate::chain::client::ClientSettings;
use crate::chain::handle::ChainHandle;
use crate::chain::requests::*;
use crate::chain::tracking::TrackedMsgs;
use crate::client_state::AnyClientState;
use crate::consensus_state::AnyConsensusState;
use crate::error::Error as RelayerError;
use crate::event::IbcEventWithHeight;
use crate::light_client::AnyHeader;
use crate::misbehaviour::{AnyMisbehaviour, MisbehaviourEvidence};
use crate::telemetry;
use crate::util::collate::CollatedIterExt;
use crate::util::pretty::{PrettyDuration, PrettySlice};
const MAX_MISBEHAVIOUR_CHECK_DURATION: Duration = Duration::from_secs(120);
const MAX_RETRIES: usize = 5;
define_error! {
ForeignClientError {
ClientCreate
{
chain_id: ChainId,
description: String
}
[ RelayerError ]
|e| {
format_args!("error raised while creating client for chain {0}: {1}",
e.chain_id, e.description)
},
Client
[ ClientError ]
|_| { "ICS02 client error" },
HeaderInTheFuture
{
src_chain_id: ChainId,
src_header_height: Height,
src_header_time: Timestamp,
dst_chain_id: ChainId,
dst_latest_header_height: Height,
dst_latest_header_time: Timestamp,
max_drift: Duration
}
|e| {
format_args!("update header from {} with height {} and time {} is in the future compared with latest header on {} with height {} and time {}, adjusted with drift {:?}",
e.src_chain_id, e.src_header_height, e.src_header_time, e.dst_chain_id, e.dst_latest_header_height, e.dst_latest_header_time, e.max_drift)
},
ClientUpdate
{
chain_id: ChainId,
description: String
}
[ RelayerError ]
|e| {
format_args!("error raised while updating client on chain {0}: {1}", e.chain_id, e.description)
},
ClientUpdateTiming
{
chain_id: ChainId,
clock_drift: Duration,
description: String
}
[ TimestampOverflowError ]
|e| {
format_args!("error raised while updating client on chain {0}: {1}", e.chain_id, e.description)
},
ClientAlreadyUpToDate
{
client_id: ClientId,
chain_id: ChainId,
height: Height,
}
|e| {
format_args!("client {} is already up-to-date with chain {}@{}",
e.client_id, e.chain_id, e.height)
},
MissingSmallerTrustedHeight
{
chain_id: ChainId,
target_height: Height,
}
|e| {
format_args!("chain {} is missing trusted state smaller than target height {}",
e.chain_id, e.target_height)
},
MissingTrustedHeight
{
chain_id: ChainId,
target_height: Height,
}
|e| {
format_args!("chain {} is missing trusted state at target height {}",
e.chain_id, e.target_height)
},
ClientRefresh
{
client_id: ClientId,
reason: String
}
[ RelayerError ]
|e| {
format_args!("error raised while trying to refresh client {0}: {1}",
e.client_id, e.reason)
},
ClientQuery
{
client_id: ClientId,
chain_id: ChainId,
}
[ RelayerError ]
|e| {
format_args!("failed while querying for client {0} on chain id {1}",
e.client_id, e.chain_id)
},
ClientConsensusQuery
{
client_id: ClientId,
chain_id: ChainId,
height: Height
}
[ RelayerError ]
|e| {
format_args!("failed while querying for client consensus state {0} on chain id {1} for height {2}",
e.client_id, e.chain_id, e.height)
},
ClientUpgrade
{
client_id: ClientId,
chain_id: ChainId,
description: String,
}
[ RelayerError ]
|e| {
format_args!("failed while trying to upgrade client id {0} for chain {1}: {2}: {3}",
e.client_id, e.chain_id, e.description, e.source)
},
ClientUpgradeNoSource
{
client_id: ClientId,
chain_id: ChainId,
description: String,
}
|e| {
format_args!("failed while trying to upgrade client id {0} for chain {1}: {2}",
e.client_id, e.chain_id, e.description)
},
ClientEventQuery
{
client_id: ClientId,
chain_id: ChainId,
consensus_height: Height
}
[ RelayerError ]
|e| {
format_args!("failed while querying Tx for client {0} on chain id {1} at consensus height {2}",
e.client_id, e.chain_id, e.consensus_height)
},
UnexpectedEvent
{
client_id: ClientId,
chain_id: ChainId,
event: String,
}
|e| {
format_args!("failed while querying Tx for client {0} on chain id {1}: query Tx-es returned unexpected event: {2}",
e.client_id, e.chain_id, e.event)
},
MismatchChainId
{
client_id: ClientId,
expected_chain_id: ChainId,
actual_chain_id: ChainId,
}
|e| {
format_args!("failed while finding client {0}: expected chain_id in client state: {1}; actual chain_id: {2}",
e.client_id, e.expected_chain_id, e.actual_chain_id)
},
ExpiredOrFrozen
{
client_id: ClientId,
chain_id: ChainId,
description: String,
}
|e| {
format_args!("client {0} on chain id {1} is expired or frozen: {2}",
e.client_id, e.chain_id, e.description)
},
ConsensusStateNotTrusted
{
height: Height,
elapsed: Duration,
}
|e| {
format_args!("the consensus state at height {} is outside of trusting period: elapsed {:?}",
e.height, e.elapsed)
},
Misbehaviour
{
description: String,
}
[ RelayerError ]
|e| {
format_args!("error raised while checking for misbehaviour evidence: {0}", e.description)
},
MisbehaviourExit
{ reason: String }
|e| {
format_args!("cannot run misbehaviour: {0}", e.reason)
},
SameChainId
{
chain_id: ChainId
}
|e| {
format_args!("the chain ID ({}) at the source and destination chains must be different", e.chain_id)
},
MissingClientIdFromEvent
{ event: IbcEvent }
|e| {
format_args!("cannot extract client_id from result: {:?}",
e.event)
},
ChainErrorEvent
{
chain_id: ChainId,
event: IbcEvent
}
|e| {
format_args!("failed to update client on destination {} because of error event: {}",
e.chain_id, e.event)
},
}
}
pub trait HasExpiredOrFrozenError {
fn is_expired_or_frozen_error(&self) -> bool;
}
impl HasExpiredOrFrozenError for ForeignClientErrorDetail {
fn is_expired_or_frozen_error(&self) -> bool {
matches!(self, Self::ExpiredOrFrozen(_))
}
}
impl HasExpiredOrFrozenError for ForeignClientError {
fn is_expired_or_frozen_error(&self) -> bool {
self.detail().is_expired_or_frozen_error()
}
}
/// User-supplied options for the [`ForeignClient::build_create_client`] operation.
///
/// Currently, the parameters are specific to the Tendermint-based chains.
/// A future revision will bring differentiated options for other chain types.
#[derive(Debug, Default)]
pub struct CreateOptions {
pub max_clock_drift: Option<Duration>,
pub trusting_period: Option<Duration>,
pub trust_threshold: Option<TrustThreshold>,
}
/// Captures the diagnostic of verifying whether a certain
/// consensus state is within the trusting period (i.e., trusted)
/// or it's not within the trusting period (not trusted).
pub enum ConsensusStateTrusted {
NotTrusted {
elapsed: Duration,
network_timestamp: Timestamp,
consensus_state_timestmap: Timestamp,
},
Trusted {
elapsed: Duration,
},
}
#[derive(Clone, Debug)]
pub struct ForeignClient<DstChain: ChainHandle, SrcChain: ChainHandle> {
/// The identifier of this client. The host chain determines this id upon client creation,
/// so we may be using the default value temporarily.
pub id: ClientId,
/// A handle to the chain hosting this client, i.e., destination chain.
pub dst_chain: DstChain,
/// A handle to the chain whose headers this client is verifying, aka the source chain.
pub src_chain: SrcChain,
}
/// Used in Output messages.
/// Provides a concise description of a [`ForeignClient`],
/// using the format:
/// {CHAIN-ID}->{CHAIN-ID}:{CLIENT}
/// where the first chain identifier is for the source
/// chain, and the second chain identifier is the
/// destination (which hosts the client) chain.
impl<DstChain: ChainHandle, SrcChain: ChainHandle> fmt::Display
for ForeignClient<DstChain, SrcChain>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}->{}:{}",
self.src_chain.id(),
self.dst_chain.id(),
self.id
)
}
}
impl<DstChain: ChainHandle, SrcChain: ChainHandle> ForeignClient<DstChain, SrcChain> {
/// Creates a new foreign client on `dst_chain`. Blocks until the client is created, or
/// an error occurs.
/// Post-condition: `dst_chain` hosts an IBC client for `src_chain`.
pub fn new(
dst_chain: DstChain,
src_chain: SrcChain,
) -> Result<ForeignClient<DstChain, SrcChain>, ForeignClientError> {
// Sanity check
if src_chain.id().eq(&dst_chain.id()) {
return Err(ForeignClientError::same_chain_id(src_chain.id()));
}
let mut client = ForeignClient {
id: ClientId::default(),
dst_chain,
src_chain,
};
client.create()?;
Ok(client)
}
pub fn restore(
id: ClientId,
dst_chain: DstChain,
src_chain: SrcChain,
) -> ForeignClient<DstChain, SrcChain> {
ForeignClient {
id,
dst_chain,
src_chain,
}
}
/// Queries `host_chain` to verify that a client with identifier `client_id` exists.
/// If the client does not exist, returns an error. If the client exists, cross-checks that the
/// identifier for the target chain of this client (i.e., the chain whose headers this client is
/// verifying) is consistent with `expected_target_chain`, and if so, return a new
/// `ForeignClient` representing this client.
pub fn find(
expected_target_chain: SrcChain,
host_chain: DstChain,
client_id: &ClientId,
) -> Result<ForeignClient<DstChain, SrcChain>, ForeignClientError> {
match host_chain.query_client_state(
QueryClientStateRequest {
client_id: client_id.clone(),
height: QueryHeight::Latest,
},
IncludeProof::No,
) {
Ok((cs, _)) => {
if cs.chain_id() != expected_target_chain.id() {
Err(ForeignClientError::mismatch_chain_id(
client_id.clone(),
expected_target_chain.id(),
cs.chain_id(),
))
} else {
// TODO: Any additional checks?
Ok(ForeignClient::restore(
client_id.clone(),
host_chain,
expected_target_chain,
))
}
}
Err(e) => Err(ForeignClientError::client_query(
client_id.clone(),
host_chain.id(),
e,
)),
}
}
/// Create and send a transaction to perform a client upgrade.
/// src_upgrade_height: The height on the source chain at which the chain will halt for the upgrade.
#[instrument(
name = "foreign_client.upgrade",
level = "error",
skip(self),
fields(client = %self)
)]
pub fn upgrade(&self, src_upgrade_height: Height) -> Result<Vec<IbcEvent>, ForeignClientError> {
let msgs = self
.build_update_client_with_trusted(src_upgrade_height, None)
.map_err(|_| {
ForeignClientError::client_upgrade_no_source(
self.id.clone(),
self.dst_chain.id(),
format!(
"is chain {} halted at height {}?",
self.src_chain().id(),
src_upgrade_height
),
)
})?;
let mut msgs: Vec<Any> = msgs.into_iter().map(Msg::to_any).collect();
// Query the host chain for the upgraded client state, consensus state & their proofs.
let (client_state, proof_upgrade_client) = self
.src_chain
.query_upgraded_client_state(QueryUpgradedClientStateRequest {
upgrade_height: src_upgrade_height,
})
.map_err(|e| {
ForeignClientError::client_upgrade(
self.id.clone(),
self.src_chain.id(),
format!("failed while fetching from chain the upgraded client state. The upgrade height `{src_upgrade_height}` might be too low"),
e,
)
})?;
debug!("upgraded client state {:?}", client_state);
let (consensus_state, proof_upgrade_consensus_state) = self
.src_chain
.query_upgraded_consensus_state(QueryUpgradedConsensusStateRequest {
upgrade_height: src_upgrade_height,
})
.map_err(|e| {
ForeignClientError::client_upgrade(
self.id.clone(),
self.src_chain.id(),
"failed while fetching from chain the upgraded client consensus state"
.to_string(),
e,
)
})?;
debug!("upgraded client consensus state {:?}", consensus_state);
// Get signer
let signer = self.dst_chain.get_signer().map_err(|e| {
ForeignClientError::client_upgrade(
self.id.clone(),
self.dst_chain.id(),
"failed while fetching the destination chain signer".to_string(),
e,
)
})?;
let msg_upgrade = MsgUpgradeClient {
client_id: self.id.clone(),
client_state: client_state.into(),
consensus_state: consensus_state.into(),
proof_upgrade_client: proof_upgrade_client.into(),
proof_upgrade_consensus_state: proof_upgrade_consensus_state.into(),
signer,
}
.to_any();
msgs.push(msg_upgrade);
let tm = TrackedMsgs::new_static(msgs, "upgrade client");
let res = self
.dst_chain
.send_messages_and_wait_commit(tm)
.map_err(|e| {
ForeignClientError::client_upgrade(
self.id.clone(),
self.dst_chain.id(),
"failed while sending message to destination chain".to_string(),
e,
)
})?;
Ok(res
.into_iter()
.map(|ev_with_height| ev_with_height.event)
.collect())
}
/// Returns a handle to the chain hosting this client.
pub fn dst_chain(&self) -> DstChain {
self.dst_chain.clone()
}
/// Returns a handle to the chain whose headers this client is sourcing (the source chain).
pub fn src_chain(&self) -> SrcChain {
self.src_chain.clone()
}
pub fn id(&self) -> &ClientId {
&self.id
}
/// Lower-level interface for preparing a message to create a client.
pub fn build_create_client(
&self,
options: CreateOptions,
) -> Result<MsgCreateClient, ForeignClientError> {
// Get signer
let signer = self.dst_chain.get_signer().map_err(|e| {
ForeignClientError::client_create(
self.src_chain.id(),
format!(
"failed while fetching the dst chain ({}) signer",
self.dst_chain.id()
),
e,
)
})?;
// Build client create message with the data from source chain at latest height.
let latest_height = self.src_chain.query_latest_height().map_err(|e| {
ForeignClientError::client_create(
self.src_chain.id(),
"failed while querying src chain for latest height".to_string(),
e,
)
})?;
// Calculate client state settings from the chain configurations and
// optional user overrides.
let src_config = self.src_chain.config().map_err(|e| {
ForeignClientError::client_create(
self.src_chain.id(),
"failed while querying the source chain for configuration".to_string(),
e,
)
})?;
let dst_config = self.dst_chain.config().map_err(|e| {
ForeignClientError::client_create(
self.dst_chain.id(),
"failed while querying the destination chain for configuration".to_string(),
e,
)
})?;
let settings = ClientSettings::for_create_command(options, &src_config, &dst_config);
let client_state: AnyClientState = self
.src_chain
.build_client_state(latest_height, settings)
.map_err(|e| {
ForeignClientError::client_create(
self.src_chain.id(),
"failed when building client state".to_string(),
e,
)
})?;
let consensus_state = self
.src_chain
.build_consensus_state(
client_state.latest_height(),
latest_height,
client_state.clone(),
)
.map_err(|e| {
ForeignClientError::client_create(
self.src_chain.id(),
"failed while building client consensus state from src chain".to_string(),
e,
)
})?;
//TODO Get acct_prefix
let msg = MsgCreateClient::new(client_state.into(), consensus_state.into(), signer)
.map_err(ForeignClientError::client)?;
Ok(msg)
}
/// Returns the identifier of the newly created client.
pub fn build_create_client_and_send(
&self,
options: CreateOptions,
) -> Result<IbcEventWithHeight, ForeignClientError> {
let new_msg = self.build_create_client(options)?;
let res = self
.dst_chain
.send_messages_and_wait_commit(TrackedMsgs::new_single(
new_msg.to_any(),
"create client",
))
.map_err(|e| {
ForeignClientError::client_create(
self.dst_chain.id(),
"failed sending message to dst chain ".to_string(),
e,
)
})?;
assert!(!res.is_empty());
Ok(res[0].clone())
}
/// Sends the client creation transaction & subsequently sets the id of this ForeignClient
#[instrument(
name = "foreign_client.create",
level = "error",
skip(self),
fields(client = %self)
)]
fn create(&mut self) -> Result<(), ForeignClientError> {
let event_with_height = self
.build_create_client_and_send(CreateOptions::default())
.map_err(|e| {
error!("failed to create client: {}", e);
e
})?;
self.id = extract_client_id(&event_with_height.event)?.clone();
info!(id = %self.id, "🍭 client was created successfully");
debug!(id = %self.id, ?event_with_height.event, "event emitted after creation");
Ok(())
}
#[instrument(
name = "foreign_client.validated_client_state",
level = "error",
skip(self),
fields(client = %self)
)]
pub fn validated_client_state(
&self,
) -> Result<(AnyClientState, Option<Duration>), ForeignClientError> {
let (client_state, _) = {
self.dst_chain
.query_client_state(
QueryClientStateRequest {
client_id: self.id().clone(),
height: QueryHeight::Latest,
},
IncludeProof::No,
)
.map_err(|e| {
ForeignClientError::client_refresh(
self.id().clone(),
"failed querying client state on dst chain".to_string(),
e,
)
})?
};
if client_state.is_frozen() {
return Err(ForeignClientError::expired_or_frozen(
self.id().clone(),
self.dst_chain.id(),
"client state reports that client is frozen".into(),
));
}
match self
.check_consensus_state_trusting_period(&client_state, &client_state.latest_height())?
{
ConsensusStateTrusted::NotTrusted {
elapsed,
network_timestamp,
consensus_state_timestmap,
} => {
error!(
latest_height = %client_state.latest_height(),
network_timestmap = %network_timestamp,
consensus_state_timestamp = %consensus_state_timestmap,
elapsed = ?elapsed,
"client state is not valid: latest height is outside of trusting period!",
);
return Err(ForeignClientError::expired_or_frozen(
self.id().clone(),
self.dst_chain.id(),
format!("expired: time elapsed since last client update: {elapsed:?}"),
));
}
ConsensusStateTrusted::Trusted { elapsed } => Ok((client_state, Some(elapsed))),
}
}
/// Verifies if the consensus state at given [`Height`]
/// is within or outside of the client's trusting period.
#[instrument(
name = "foreign_client.check_consensus_state_trusting_period",
level = "error",
skip_all,
fields(client = %self, %height)
)]
fn check_consensus_state_trusting_period(
&self,
client_state: &AnyClientState,
height: &Height,
) -> Result<ConsensusStateTrusted, ForeignClientError> {
// Safety check
if client_state.chain_id() != self.src_chain.id() {
warn!("the chain id in the client state ('{}') is inconsistent with the client's source chain id ('{}')",
client_state.chain_id(), self.src_chain.id());
}
let consensus_state_timestamp = self.fetch_consensus_state(*height)?.timestamp();
let current_src_network_time = self
.src_chain
.query_application_status()
.map_err(|e| {
ForeignClientError::client_refresh(
self.id().clone(),
"failed querying the application status of source chain".to_string(),
e,
)
})?
.timestamp;
// Compute the duration of time elapsed since this consensus state was installed
let elapsed = current_src_network_time
.duration_since(&consensus_state_timestamp)
.unwrap_or_default();
if client_state.expired(elapsed) {
Ok(ConsensusStateTrusted::NotTrusted {
elapsed,
network_timestamp: current_src_network_time,
consensus_state_timestmap: consensus_state_timestamp,
})
} else {
Ok(ConsensusStateTrusted::Trusted { elapsed })
}
}
pub fn is_expired_or_frozen(&self) -> bool {
match self.validated_client_state() {
Ok(_) => false,
Err(e) => e.is_expired_or_frozen_error(),
}
}
#[instrument(
name = "foreign_client.refresh",
level = "error",
skip_all,
fields(client = %self)
)]
pub fn refresh(&mut self) -> Result<Option<Vec<IbcEvent>>, ForeignClientError> {
fn check_no_errors(
ibc_events: &[IbcEvent],
dst_chain_id: ChainId,
) -> Result<(), ForeignClientError> {
// The assumption is that only one IbcEventType::ChainError will be
// in the resulting Vec<IbcEvent> if an error occurred.
let chain_error = ibc_events
.iter()
.find(|&e| e.event_type() == IbcEventType::ChainError);
match chain_error {
None => Ok(()),
Some(ev) => Err(ForeignClientError::chain_error_event(
dst_chain_id,
ev.to_owned(),
)),
}
}
// If elapsed < refresh_window for the client, `try_refresh()` will
// be successful with an empty vector.
if let Some(events) = self.try_refresh()? {
check_no_errors(&events, self.dst_chain().id())?;
Ok(Some(events))
} else {
Ok(None)
}
}
fn try_refresh(&mut self) -> Result<Option<Vec<IbcEvent>>, ForeignClientError> {
let (client_state, elapsed) = self.validated_client_state()?;
// The refresh_window is the maximum duration
// we can backoff between subsequent client updates.
let refresh_window = client_state.refresh_period();
match (elapsed, refresh_window) {
(None, _) | (_, None) => Ok(None),
(Some(elapsed), Some(refresh_window)) => {
if elapsed > refresh_window {
info!(?elapsed, ?refresh_window, "client needs to be refreshed");
self.build_latest_update_client_and_send()
.map_or_else(Err, |ev| Ok(Some(ev)))
} else {
Ok(None)
}
}
}
}
/// Wrapper for build_update_client_with_trusted.
pub fn wait_and_build_update_client(
&self,
target_height: Height,
) -> Result<Vec<Any>, ForeignClientError> {
self.wait_and_build_update_client_with_trusted(target_height, None)
}
/// Returns a trusted height that is lower than the target height, so
/// that the relayer can update the client to the target height based
/// on the returned trusted height.
#[instrument(
name = "foreign_client.solve_trusted_height",
level = "error",
skip_all,
fields(client = %self, %target_height)
)]
fn solve_trusted_height(
&self,
target_height: Height,
client_state: &AnyClientState,
) -> Result<Height, ForeignClientError> {
let client_latest_height = client_state.latest_height();
if client_latest_height < target_height {
// If the latest height of the client is already lower than the
// target height, we can simply use it.
Ok(client_latest_height)
} else {
// The only time when the above is false is when for some reason,
// the command line user wants to submit a client update at an
// older height even when the relayer already have an up-to-date
// client at a newer height.
// In production, this should rarely happen unless there is another
// relayer racing to update the client state, and that we so happen
// to get the the latest client state that was updated between
// the time the target height was determined, and the time
// the client state was fetched.
warn!(
"resolving trusted height from the full list of consensus state \
heights for target height {}; this may take a while",
target_height
);
// Potential optimization: cache the list of consensus heights
// so that subsequent fetches can be fast.
let cs_heights = self.fetch_consensus_state_heights()?;
// Iterate through the available consesnsus heights and find one
// that is lower than the target height.
cs_heights
.into_iter()
.find(|h| h < &target_height)
.ok_or_else(|| {
ForeignClientError::missing_smaller_trusted_height(
self.dst_chain().id(),
target_height,
)
})
}
}
/// Validate a non-zero trusted height to make sure that there is a corresponding
/// consensus state at the given trusted height on the destination chain's client.
#[instrument(
name = "foreign_client.validate_trusted_height",
level = "error",
skip_all,
fields(client = %self, %trusted_height)
)]
fn validate_trusted_height(
&self,
trusted_height: Height,
client_state: &AnyClientState,
) -> Result<(), ForeignClientError> {
if client_state.latest_height() != trusted_height {
// There should be no need to validate a trusted height in production,
// Since it is always fetched from some client state. The only use is
// from the command line when the trusted height is manually specified.
// We should consider skipping the validation entirely and only validate
// it from the command line itself.
self.fetch_consensus_state(trusted_height)?;
}
Ok(())
}
/// Given a client state and header it adds, if required, a delay such that the header will
/// not be considered in the future when submitted in an update client:
/// - determine the `dst_timestamp` as the time of the latest block on destination chain
/// - return if `header.timestamp <= dst_timestamp + client_state.max_clock_drift`
/// - wait for the destination chain to reach `dst_timestamp + 1`
/// Note: This is mostly to help with existing clients where the `max_clock_drift` did
/// not take into account the block time.
/// - return error if header.timestamp < dst_timestamp + client_state.max_clock_drift
///
/// Ref: https://github.com/informalsystems/hermes/issues/1445.
#[instrument(
name = "foreign_client.wait_for_header_validation_delay",
level = "error",
skip_all,
fields(client = %self)
)]
fn wait_for_header_validation_delay(
&self,
client_state: &AnyClientState,
header: &AnyHeader,
) -> Result<(), ForeignClientError> {
// Get latest height and time on destination chain
let mut status = self.dst_chain().query_application_status().map_err(|e| {
ForeignClientError::client_update(
self.dst_chain.id(),
"failed querying latest status of the destination chain".to_string(),
e,
)
})?;
let ts_adjusted = (status.timestamp + client_state.max_clock_drift()).map_err(|e| {
ForeignClientError::client_update_timing(
self.dst_chain.id(),
client_state.max_clock_drift(),
"failed to adjust timestamp of destination chain with clock drift".to_string(),
e,
)
})?;
if header.timestamp().after(&ts_adjusted) {
// Header would be considered in the future, wait for destination chain to
// advance to the next height.
warn!(
"src header {} is after dst latest header {} + client state drift {},\
wait for next height on {}",
header.timestamp(),
status.timestamp,
PrettyDuration(&client_state.max_clock_drift()),
self.dst_chain().id()
);
let target_dst_height = status.height.increment();
loop {
thread::sleep(Duration::from_millis(300));
status = self.dst_chain().query_application_status().map_err(|e| {
ForeignClientError::client_update(