-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathclient_state.rs
1277 lines (1141 loc) · 45.9 KB
/
client_state.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::prelude::*;
use core::convert::{TryFrom, TryInto};
use core::time::Duration;
use ibc_proto::google::protobuf::Any;
use ibc_proto::ibc::core::client::v1::Height as RawHeight;
use ibc_proto::ibc::core::commitment::v1::{MerklePath, MerkleProof as RawMerkleProof};
use ibc_proto::ibc::lightclients::tendermint::v1::{
ClientState as RawTmClientState, ConsensusState as RawTmConsensusState,
};
use ibc_proto::protobuf::Protobuf;
use prost::Message;
use tendermint::chain::id::MAX_LENGTH as MaxChainIdLen;
use tendermint::trust_threshold::TrustThresholdFraction as TendermintTrustThresholdFraction;
use tendermint_light_client_verifier::options::Options;
use tendermint_light_client_verifier::types::{TrustedBlockState, UntrustedBlockState};
use tendermint_light_client_verifier::{ProdVerifier, Verifier};
use crate::clients::ics07_tendermint::client_state::ClientState as TmClientState;
use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState;
use crate::clients::ics07_tendermint::error::{Error, IntoResult};
use crate::clients::ics07_tendermint::header::{Header as TmHeader, Header};
use crate::clients::ics07_tendermint::misbehaviour::Misbehaviour as TmMisbehaviour;
use crate::core::ics02_client::client_state::{ClientState as Ics2ClientState, UpdatedState};
use crate::core::ics02_client::client_type::ClientType;
use crate::core::ics02_client::consensus_state::ConsensusState;
use crate::core::ics02_client::error::ClientError;
use crate::core::ics02_client::trust_threshold::TrustThreshold;
use crate::core::ics23_commitment::commitment::{
CommitmentPrefix, CommitmentProofBytes, CommitmentRoot,
};
use crate::core::ics23_commitment::merkle::{apply_prefix, MerkleProof};
use crate::core::ics23_commitment::specs::ProofSpecs;
use crate::core::ics24_host::identifier::{ChainId, ClientId};
use crate::core::ics24_host::path::{ClientConsensusStatePath, ClientUpgradePath};
use crate::core::ics24_host::Path;
use crate::timestamp::{Timestamp, ZERO_DURATION};
use crate::Height;
use super::client_type as tm_client_type;
use crate::core::context::ContextError;
use crate::core::ValidationContext;
pub const TENDERMINT_CLIENT_STATE_TYPE_URL: &str = "/ibc.lightclients.tendermint.v1.ClientState";
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClientState {
pub chain_id: ChainId,
pub trust_level: TrustThreshold,
pub trusting_period: Duration,
pub unbonding_period: Duration,
max_clock_drift: Duration,
latest_height: Height,
pub proof_specs: ProofSpecs,
pub upgrade_path: Vec<String>,
allow_update: AllowUpdate,
frozen_height: Option<Height>,
#[cfg_attr(feature = "serde", serde(skip))]
verifier: ProdVerifier,
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct AllowUpdate {
pub after_expiry: bool,
pub after_misbehaviour: bool,
}
impl ClientState {
#[allow(clippy::too_many_arguments)]
pub fn new(
chain_id: ChainId,
trust_level: TrustThreshold,
trusting_period: Duration,
unbonding_period: Duration,
max_clock_drift: Duration,
latest_height: Height,
proof_specs: ProofSpecs,
upgrade_path: Vec<String>,
allow_update: AllowUpdate,
frozen_height: Option<Height>,
) -> Result<ClientState, Error> {
if chain_id.as_str().len() > MaxChainIdLen {
return Err(Error::ChainIdTooLong {
chain_id: chain_id.clone(),
len: chain_id.as_str().len(),
max_len: MaxChainIdLen,
});
}
// `TrustThreshold` is guaranteed to be in the range `[0, 1)`, but a `TrustThreshold::ZERO`
// value is invalid in this context
if trust_level == TrustThreshold::ZERO {
return Err(Error::InvalidTrustThreshold {
reason: "ClientState trust-level cannot be zero".to_string(),
});
}
let _ = TendermintTrustThresholdFraction::new(
trust_level.numerator(),
trust_level.denominator(),
)
.map_err(Error::InvalidTendermintTrustThreshold)?;
// Basic validation of trusting period and unbonding period: each should be non-zero.
if trusting_period <= Duration::new(0, 0) {
return Err(Error::InvalidTrustThreshold {
reason: format!(
"ClientState trusting period ({trusting_period:?}) must be greater than zero"
),
});
}
if unbonding_period <= Duration::new(0, 0) {
return Err(Error::InvalidTrustThreshold {
reason: format!(
"ClientState unbonding period ({unbonding_period:?}) must be greater than zero"
),
});
}
if trusting_period >= unbonding_period {
return Err(Error::InvalidTrustThreshold {
reason: format!(
"ClientState trusting period ({trusting_period:?}) must be smaller than unbonding period ({unbonding_period:?})"
),
});
}
if max_clock_drift <= Duration::new(0, 0) {
return Err(Error::InvalidMaxClockDrift {
reason: "ClientState max-clock-drift must be greater than zero".to_string(),
});
}
if latest_height.revision_number() != chain_id.version() {
return Err(Error::InvalidLatestHeight {
reason: "ClientState latest-height revision number must match chain-id version"
.to_string(),
});
}
// Disallow empty proof-specs
if proof_specs.is_empty() {
return Err(Error::Validation {
reason: "ClientState proof-specs cannot be empty".to_string(),
});
}
// `upgrade_path` itself may be empty, but if not then each key must be non-empty
for (idx, key) in upgrade_path.iter().enumerate() {
if key.trim().is_empty() {
return Err(Error::Validation {
reason: format!(
"ClientState upgrade-path key at index {idx:?} cannot be empty"
),
});
}
}
Ok(Self {
chain_id,
trust_level,
trusting_period,
unbonding_period,
max_clock_drift,
latest_height,
proof_specs,
upgrade_path,
allow_update,
frozen_height,
verifier: ProdVerifier::default(),
})
}
pub fn with_header(self, h: TmHeader) -> Result<Self, Error> {
Ok(ClientState {
latest_height: Height::new(
self.latest_height.revision_number(),
h.signed_header.header.height.into(),
)
.map_err(|_| Error::InvalidHeaderHeight {
height: h.signed_header.header.height.value(),
})?,
..self
})
}
pub fn with_frozen_height(self, h: Height) -> Self {
Self {
frozen_height: Some(h),
..self
}
}
/// Get the refresh time to ensure the state does not expire
pub fn refresh_time(&self) -> Option<Duration> {
Some(2 * self.trusting_period / 3)
}
/// Helper method to produce a [`Options`] struct for use in
/// Tendermint-specific light client verification.
pub fn as_light_client_options(&self) -> Result<Options, Error> {
Ok(Options {
trust_threshold: self.trust_level.try_into().map_err(|e: ClientError| {
Error::InvalidTrustThreshold {
reason: e.to_string(),
}
})?,
trusting_period: self.trusting_period,
clock_drift: self.max_clock_drift,
})
}
fn check_header_validator_set(
trusted_consensus_state: &TmConsensusState,
header: &Header,
) -> Result<(), ClientError> {
let trusted_val_hash = header.trusted_validator_set.hash();
if trusted_consensus_state.next_validators_hash != trusted_val_hash {
return Err(Error::MisbehaviourTrustedValidatorHashMismatch {
trusted_validator_set: header.trusted_validator_set.validators().clone(),
next_validators_hash: trusted_consensus_state.next_validators_hash,
trusted_val_hash,
}
.into());
}
Ok(())
}
fn check_header_and_validator_set(
&self,
header: &Header,
consensus_state: &TmConsensusState,
current_timestamp: Timestamp,
) -> Result<(), ClientError> {
Self::check_header_validator_set(consensus_state, header)?;
let duration_since_consensus_state = current_timestamp
.duration_since(&consensus_state.timestamp())
.ok_or_else(|| ClientError::InvalidConsensusStateTimestamp {
time1: consensus_state.timestamp(),
time2: current_timestamp,
})?;
if duration_since_consensus_state >= self.trusting_period {
return Err(Error::ConsensusStateTimestampGteTrustingPeriod {
duration_since_consensus_state,
trusting_period: self.trusting_period,
}
.into());
}
let untrusted_state = header.as_untrusted_block_state();
let chain_id = self.chain_id.clone().into();
let trusted_state = header.as_trusted_block_state(consensus_state, &chain_id)?;
let options = self.as_light_client_options()?;
self.verifier
.validate_against_trusted(
&untrusted_state,
&trusted_state,
&options,
current_timestamp.into_tm_time().unwrap(),
)
.into_result()?;
Ok(())
}
fn verify_header_commit_against_trusted(
&self,
header: &Header,
consensus_state: &TmConsensusState,
) -> Result<(), ClientError> {
let untrusted_state = header.as_untrusted_block_state();
let chain_id = self.chain_id.clone().into();
let trusted_state = Header::as_trusted_block_state(header, consensus_state, &chain_id)?;
let options = self.as_light_client_options()?;
self.verifier
.verify_commit_against_trusted(&untrusted_state, &trusted_state, &options)
.into_result()?;
Ok(())
}
}
impl Ics2ClientState for ClientState {
fn chain_id(&self) -> ChainId {
self.chain_id.clone()
}
fn client_type(&self) -> ClientType {
tm_client_type()
}
fn latest_height(&self) -> Height {
self.latest_height
}
fn validate_proof_height(&self, proof_height: Height) -> Result<(), ClientError> {
if self.latest_height() < proof_height {
return Err(ClientError::InvalidProofHeight {
latest_height: self.latest_height(),
proof_height,
});
}
Ok(())
}
fn confirm_not_frozen(&self) -> Result<(), ClientError> {
if let Some(frozen_height) = self.frozen_height {
return Err(ClientError::ClientFrozen {
description: format!("the client is frozen at height {frozen_height}"),
});
}
Ok(())
}
fn zero_custom_fields(&mut self) {
// Reset custom fields to zero values
self.trusting_period = ZERO_DURATION;
self.trust_level = TrustThreshold::ZERO;
self.allow_update.after_expiry = false;
self.allow_update.after_misbehaviour = false;
self.frozen_height = None;
self.max_clock_drift = ZERO_DURATION;
}
fn expired(&self, elapsed: Duration) -> bool {
elapsed > self.trusting_period
}
fn initialise(&self, consensus_state: Any) -> Result<Box<dyn ConsensusState>, ClientError> {
TmConsensusState::try_from(consensus_state).map(TmConsensusState::into_box)
}
fn check_misbehaviour_and_update_state(
&self,
ctx: &dyn ValidationContext,
client_id: ClientId,
misbehaviour: Any,
) -> Result<Box<dyn Ics2ClientState>, ContextError> {
let misbehaviour = TmMisbehaviour::try_from(misbehaviour)?;
let header_1 = misbehaviour.header1();
let header_2 = misbehaviour.header2();
if header_1.height() == header_2.height() {
// Fork
if header_1.signed_header.commit.block_id.hash
== header_2.signed_header.commit.block_id.hash
{
return Err(ContextError::ClientError(
Error::MisbehaviourHeadersBlockHashesEqual.into(),
));
}
} else {
// BFT time violation
if header_1.signed_header.header.time > header_2.signed_header.header.time {
return Err(ContextError::ClientError(
Error::MisbehaviourHeadersNotAtSameHeight.into(),
));
}
}
let client_cons_state_path_1 =
ClientConsensusStatePath::new(&client_id, &header_1.trusted_height);
let consensus_state_1 = {
let cs = ctx.consensus_state(&client_cons_state_path_1)?;
downcast_tm_consensus_state(cs.as_ref())
}?;
let client_cons_state_path_2 =
ClientConsensusStatePath::new(&client_id, &header_2.trusted_height);
let consensus_state_2 = {
let cs = ctx.consensus_state(&client_cons_state_path_2)?;
downcast_tm_consensus_state(cs.as_ref())
}?;
let chain_id = self
.chain_id
.clone()
.with_version(header_1.height().revision_number());
if !misbehaviour.chain_id_matches(&chain_id) {
return Err(ContextError::ClientError(
Error::MisbehaviourHeadersChainIdMismatch {
header_chain_id: header_1.signed_header.header.chain_id.to_string(),
chain_id: self.chain_id.to_string(),
}
.into(),
));
}
let current_timestamp = ctx.host_timestamp()?;
self.check_header_and_validator_set(header_1, &consensus_state_1, current_timestamp)?;
self.check_header_and_validator_set(header_2, &consensus_state_2, current_timestamp)?;
self.verify_header_commit_against_trusted(header_1, &consensus_state_1)?;
self.verify_header_commit_against_trusted(header_2, &consensus_state_2)?;
let client_state = downcast_tm_client_state(self)?.clone();
Ok(client_state
.with_frozen_height(Height::new(0, 1).unwrap())
.into_box())
}
fn check_header_and_update_state(
&self,
ctx: &dyn ValidationContext,
client_id: ClientId,
header: Any,
) -> Result<UpdatedState, ClientError> {
fn maybe_consensus_state(
ctx: &dyn ValidationContext,
client_cons_state_path: &ClientConsensusStatePath,
) -> Result<Option<Box<dyn ConsensusState>>, ClientError> {
match ctx.consensus_state(client_cons_state_path) {
Ok(cs) => Ok(Some(cs)),
Err(e) => match e {
ContextError::ClientError(ClientError::ConsensusStateNotFound {
client_id: _,
height: _,
}) => Ok(None),
ContextError::ClientError(e) => Err(e),
_ => Err(ClientError::Other {
description: e.to_string(),
}),
},
}
}
let client_state = downcast_tm_client_state(self)?.clone();
let header = TmHeader::try_from(header)?;
if header.height().revision_number() != client_state.chain_id().version() {
return Err(ClientError::ClientSpecific {
description: Error::MismatchedRevisions {
current_revision: client_state.chain_id().version(),
update_revision: header.height().revision_number(),
}
.to_string(),
});
}
// Check if a consensus state is already installed; if so it should
// match the untrusted header.
let header_consensus_state = TmConsensusState::from(header.clone());
let client_cons_state_path = ClientConsensusStatePath::new(&client_id, &header.height());
let existing_consensus_state = match maybe_consensus_state(ctx, &client_cons_state_path)? {
Some(cs) => {
let cs = downcast_tm_consensus_state(cs.as_ref())?;
// If this consensus state matches, skip verification
// (optimization)
if cs == header_consensus_state {
// Header is already installed and matches the incoming
// header (already verified)
return Ok(UpdatedState {
client_state: client_state.into_box(),
consensus_state: cs.into_box(),
});
}
Some(cs)
}
None => None,
};
let trusted_client_cons_state_path =
ClientConsensusStatePath::new(&client_id, &header.trusted_height);
let trusted_consensus_state = downcast_tm_consensus_state(
ctx.consensus_state(&trusted_client_cons_state_path)
.map_err(|e| match e {
ContextError::ClientError(e) => e,
_ => ClientError::Other {
description: e.to_string(),
},
})?
.as_ref(),
)?;
let trusted_state = TrustedBlockState {
chain_id: &self.chain_id.clone().into(),
header_time: trusted_consensus_state.timestamp,
height: header
.trusted_height
.revision_height()
.try_into()
.map_err(|_| ClientError::ClientSpecific {
description: Error::InvalidHeaderHeight {
height: header.trusted_height.revision_height(),
}
.to_string(),
})?,
next_validators: &header.trusted_validator_set,
next_validators_hash: trusted_consensus_state.next_validators_hash,
};
let untrusted_state = UntrustedBlockState {
signed_header: &header.signed_header,
validators: &header.validator_set,
// NB: This will skip the
// VerificationPredicates::next_validators_match check for the
// untrusted state.
next_validators: None,
};
let options = client_state.as_light_client_options()?;
let now = ctx
.host_timestamp()
.map_err(|e| ClientError::Other {
description: e.to_string(),
})?
.into_tm_time()
.unwrap();
self.verifier
.verify(untrusted_state, trusted_state, &options, now)
.into_result()?;
// If the header has verified, but its corresponding consensus state
// differs from the existing consensus state for that height, freeze the
// client and return the installed consensus state.
if let Some(cs) = existing_consensus_state {
if cs != header_consensus_state {
return Ok(UpdatedState {
client_state: client_state.with_frozen_height(header.height()).into_box(),
consensus_state: cs.into_box(),
});
}
}
// Monotonicity checks for timestamps for in-the-middle updates
// (cs-new, cs-next, cs-latest)
if header.height() < client_state.latest_height() {
let maybe_next_cs = ctx
.next_consensus_state(&client_id, &header.height())
.map_err(|e| match e {
ContextError::ClientError(e) => e,
_ => ClientError::Other {
description: e.to_string(),
},
})?
.as_ref()
.map(|cs| downcast_tm_consensus_state(cs.as_ref()))
.transpose()?;
if let Some(next_cs) = maybe_next_cs {
// New (untrusted) header timestamp cannot occur after next
// consensus state's height
if header.signed_header.header().time > next_cs.timestamp {
return Err(ClientError::ClientSpecific {
description: Error::HeaderTimestampTooHigh {
actual: header.signed_header.header().time.to_string(),
max: next_cs.timestamp.to_string(),
}
.to_string(),
});
}
}
}
// (cs-trusted, cs-prev, cs-new)
if header.trusted_height < header.height() {
let maybe_prev_cs = ctx
.prev_consensus_state(&client_id, &header.height())
.map_err(|e| match e {
ContextError::ClientError(e) => e,
_ => ClientError::Other {
description: e.to_string(),
},
})?
.as_ref()
.map(|cs| downcast_tm_consensus_state(cs.as_ref()))
.transpose()?;
if let Some(prev_cs) = maybe_prev_cs {
// New (untrusted) header timestamp cannot occur before the
// previous consensus state's height
if header.signed_header.header().time < prev_cs.timestamp {
return Err(ClientError::ClientSpecific {
description: Error::HeaderTimestampTooLow {
actual: header.signed_header.header().time.to_string(),
min: prev_cs.timestamp.to_string(),
}
.to_string(),
});
}
}
}
Ok(UpdatedState {
client_state: client_state.with_header(header.clone())?.into_box(),
consensus_state: TmConsensusState::from(header).into_box(),
})
}
/// Perform client-specific verifications and check all data in the new
/// client state to be the same across all valid Tendermint clients for the
/// new chain.
///
/// You can learn more about how to upgrade IBC-connected SDK chains in
/// [this](https://ibc.cosmos.network/main/ibc/upgrades/quick-guide.html)
/// guide
fn verify_upgrade_client(
&self,
upgraded_client_state: Any,
upgraded_consensus_state: Any,
proof_upgrade_client: RawMerkleProof,
proof_upgrade_consensus_state: RawMerkleProof,
root: &CommitmentRoot,
) -> Result<(), ClientError> {
// Make sure that the client type is of Tendermint type `ClientState`
let mut upgraded_tm_client_state = TmClientState::try_from(upgraded_client_state)?;
// Make sure that the consensus type is of Tendermint type `ConsensusState`
let upgraded_tm_cons_state = TmConsensusState::try_from(upgraded_consensus_state)?;
// Note: verification of proofs that unmarshalled correctly has been done
// while decoding the proto message into a `MsgEnvelope` domain type
let merkle_proof_upgrade_client = MerkleProof::from(proof_upgrade_client);
let merkle_proof_upgrade_cons_state = MerkleProof::from(proof_upgrade_consensus_state);
// Make sure the latest height of the current client is not greater then
// the upgrade height This condition checks both the revision number and
// the height
if self.latest_height() >= upgraded_tm_client_state.latest_height() {
return Err(ClientError::LowUpgradeHeight {
upgraded_height: self.latest_height(),
client_height: upgraded_tm_client_state.latest_height(),
});
}
// Check to see if the upgrade path is set
let mut upgrade_path = self.upgrade_path.clone();
if upgrade_path.pop().is_none() {
return Err(ClientError::ClientSpecific {
description: "cannot upgrade client as no upgrade path has been set".to_string(),
});
};
let last_height = self.latest_height().revision_height();
// Construct the merkle path for the client state
let mut client_upgrade_path = upgrade_path.clone();
client_upgrade_path.push(ClientUpgradePath::UpgradedClientState(last_height).to_string());
let client_upgrade_merkle_path = MerklePath {
key_path: client_upgrade_path,
};
upgraded_tm_client_state.zero_custom_fields();
let client_state_value =
Protobuf::<RawTmClientState>::encode_vec(&upgraded_tm_client_state)
.map_err(ClientError::Encode)?;
// Verify the proof of the upgraded client state
merkle_proof_upgrade_client
.verify_membership(
&self.proof_specs,
root.clone().into(),
client_upgrade_merkle_path,
client_state_value,
0,
)
.map_err(ClientError::Ics23Verification)?;
// Construct the merkle path for the consensus state
let mut cons_upgrade_path = upgrade_path;
cons_upgrade_path
.push(ClientUpgradePath::UpgradedClientConsensusState(last_height).to_string());
let cons_upgrade_merkle_path = MerklePath {
key_path: cons_upgrade_path,
};
let cons_state_value = Protobuf::<RawTmConsensusState>::encode_vec(&upgraded_tm_cons_state)
.map_err(ClientError::Encode)?;
// Verify the proof of the upgraded consensus state
merkle_proof_upgrade_cons_state
.verify_membership(
&self.proof_specs,
root.clone().into(),
cons_upgrade_merkle_path,
cons_state_value,
0,
)
.map_err(ClientError::Ics23Verification)?;
Ok(())
}
// Commit the new client state and consensus state to the store
fn update_state_with_upgrade_client(
&self,
upgraded_client_state: Any,
upgraded_consensus_state: Any,
) -> Result<UpdatedState, ClientError> {
let upgraded_tm_client_state = TmClientState::try_from(upgraded_client_state)?;
let upgraded_tm_cons_state = TmConsensusState::try_from(upgraded_consensus_state)?;
// Frozen height is set to None fo the new client state
let new_frozen_height = None;
// Construct new client state and consensus state relayer chosen client
// parameters are ignored. All chain-chosen parameters come from
// committed client, all client-chosen parameters come from current
// client.
let new_client_state = TmClientState::new(
upgraded_tm_client_state.chain_id,
self.trust_level,
self.trusting_period,
upgraded_tm_client_state.unbonding_period,
self.max_clock_drift,
upgraded_tm_client_state.latest_height,
upgraded_tm_client_state.proof_specs,
upgraded_tm_client_state.upgrade_path,
self.allow_update,
new_frozen_height,
)?;
// The new consensus state is merely used as a trusted kernel against
// which headers on the new chain can be verified. The root is just a
// stand-in sentinel value as it cannot be known in advance, thus no
// proof verification will pass. The timestamp and the
// NextValidatorsHash of the consensus state is the blocktime and
// NextValidatorsHash of the last block committed by the old chain. This
// will allow the first block of the new chain to be verified against
// the last validators of the old chain so long as it is submitted
// within the TrustingPeriod of this client.
// NOTE: We do not set processed time for this consensus state since
// this consensus state should not be used for packet verification as
// the root is empty. The next consensus state submitted using update
// will be usable for packet-verification.
let sentinel_root = "sentinel_root".as_bytes().to_vec();
let new_consensus_state = TmConsensusState::new(
sentinel_root.into(),
upgraded_tm_cons_state.timestamp,
upgraded_tm_cons_state.next_validators_hash,
);
Ok(UpdatedState {
client_state: new_client_state.into_box(),
consensus_state: new_consensus_state.into_box(),
})
}
fn verify_membership(
&self,
prefix: &CommitmentPrefix,
proof: &CommitmentProofBytes,
root: &CommitmentRoot,
path: Path,
value: Vec<u8>,
) -> Result<(), ClientError> {
let client_state = downcast_tm_client_state(self)?;
let merkle_path = apply_prefix(prefix, vec![path.to_string()]);
let merkle_proof: MerkleProof = RawMerkleProof::try_from(proof.clone())
.map_err(ClientError::InvalidCommitmentProof)?
.into();
merkle_proof
.verify_membership(
&client_state.proof_specs,
root.clone().into(),
merkle_path,
value,
0,
)
.map_err(ClientError::Ics23Verification)
}
fn verify_non_membership(
&self,
prefix: &CommitmentPrefix,
proof: &CommitmentProofBytes,
root: &CommitmentRoot,
path: Path,
) -> Result<(), ClientError> {
let client_state = downcast_tm_client_state(self)?;
let merkle_path = apply_prefix(prefix, vec![path.to_string()]);
let merkle_proof: MerkleProof = RawMerkleProof::try_from(proof.clone())
.map_err(ClientError::InvalidCommitmentProof)?
.into();
merkle_proof
.verify_non_membership(&client_state.proof_specs, root.clone().into(), merkle_path)
.map_err(ClientError::Ics23Verification)
}
}
fn downcast_tm_client_state(cs: &dyn Ics2ClientState) -> Result<&ClientState, ClientError> {
cs.as_any()
.downcast_ref::<ClientState>()
.ok_or_else(|| ClientError::ClientArgsTypeMismatch {
client_type: tm_client_type(),
})
}
fn downcast_tm_consensus_state(cs: &dyn ConsensusState) -> Result<TmConsensusState, ClientError> {
cs.as_any()
.downcast_ref::<TmConsensusState>()
.ok_or_else(|| ClientError::ClientArgsTypeMismatch {
client_type: tm_client_type(),
})
.map(Clone::clone)
}
impl Protobuf<RawTmClientState> for ClientState {}
impl TryFrom<RawTmClientState> for ClientState {
type Error = Error;
fn try_from(raw: RawTmClientState) -> Result<Self, Self::Error> {
let chain_id = ChainId::from_string(raw.chain_id.as_str());
let trust_level = {
let trust_level = raw
.trust_level
.clone()
.ok_or(Error::MissingTrustingPeriod)?;
trust_level
.try_into()
.map_err(|e| Error::InvalidTrustThreshold {
reason: format!("{e}"),
})?
};
let trusting_period = raw
.trusting_period
.ok_or(Error::MissingTrustingPeriod)?
.try_into()
.map_err(|_| Error::MissingTrustingPeriod)?;
let unbonding_period = raw
.unbonding_period
.ok_or(Error::MissingUnbondingPeriod)?
.try_into()
.map_err(|_| Error::MissingUnbondingPeriod)?;
let max_clock_drift = raw
.max_clock_drift
.ok_or(Error::NegativeMaxClockDrift)?
.try_into()
.map_err(|_| Error::NegativeMaxClockDrift)?;
let latest_height = raw
.latest_height
.ok_or(Error::MissingLatestHeight)?
.try_into()
.map_err(|_| Error::MissingLatestHeight)?;
// In `RawClientState`, a `frozen_height` of `0` means "not frozen".
// See:
// https://github.com/cosmos/ibc-go/blob/8422d0c4c35ef970539466c5bdec1cd27369bab3/modules/light-clients/07-tendermint/types/client_state.go#L74
let frozen_height = raw
.frozen_height
.and_then(|raw_height| raw_height.try_into().ok());
// We use set this deprecated field just so that we can properly convert
// it back in its raw form
#[allow(deprecated)]
let allow_update = AllowUpdate {
after_expiry: raw.allow_update_after_expiry,
after_misbehaviour: raw.allow_update_after_misbehaviour,
};
let client_state = ClientState::new(
chain_id,
trust_level,
trusting_period,
unbonding_period,
max_clock_drift,
latest_height,
raw.proof_specs.into(),
raw.upgrade_path,
allow_update,
frozen_height,
)?;
Ok(client_state)
}
}
impl From<ClientState> for RawTmClientState {
fn from(value: ClientState) -> Self {
#[allow(deprecated)]
Self {
chain_id: value.chain_id.to_string(),
trust_level: Some(value.trust_level.into()),
trusting_period: Some(value.trusting_period.into()),
unbonding_period: Some(value.unbonding_period.into()),
max_clock_drift: Some(value.max_clock_drift.into()),
frozen_height: Some(value.frozen_height.map(|height| height.into()).unwrap_or(
RawHeight {
revision_number: 0,
revision_height: 0,
},
)),
latest_height: Some(value.latest_height.into()),
proof_specs: value.proof_specs.into(),
upgrade_path: value.upgrade_path,
allow_update_after_expiry: value.allow_update.after_expiry,
allow_update_after_misbehaviour: value.allow_update.after_misbehaviour,
}
}
}
impl Protobuf<Any> for ClientState {}
impl TryFrom<Any> for ClientState {
type Error = ClientError;
fn try_from(raw: Any) -> Result<Self, Self::Error> {
use bytes::Buf;
use core::ops::Deref;
fn decode_client_state<B: Buf>(buf: B) -> Result<ClientState, Error> {
RawTmClientState::decode(buf)
.map_err(Error::Decode)?
.try_into()
}
match raw.type_url.as_str() {
TENDERMINT_CLIENT_STATE_TYPE_URL => {
decode_client_state(raw.value.deref()).map_err(Into::into)
}
_ => Err(ClientError::UnknownClientStateType {
client_state_type: raw.type_url,
}),
}
}
}
impl From<ClientState> for Any {
fn from(client_state: ClientState) -> Self {
Any {
type_url: TENDERMINT_CLIENT_STATE_TYPE_URL.to_string(),
value: Protobuf::<RawTmClientState>::encode_vec(&client_state)
.expect("encoding to `Any` from `TmClientState`"),
}
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
use crate::Height;
use core::time::Duration;
use test_log::test;
use ibc_proto::ics23::ProofSpec as Ics23ProofSpec;
use crate::clients::ics07_tendermint::client_state::{
AllowUpdate, ClientState as TmClientState,
};
use crate::core::ics02_client::client_state::ClientState;
use crate::core::ics02_client::trust_threshold::TrustThreshold;
use crate::core::ics23_commitment::specs::ProofSpecs;
use crate::core::ics24_host::identifier::ChainId;
use crate::timestamp::ZERO_DURATION;
#[derive(Clone, Debug, PartialEq)]
struct ClientStateParams {
id: ChainId,
trust_level: TrustThreshold,
trusting_period: Duration,
unbonding_period: Duration,
max_clock_drift: Duration,
latest_height: Height,
proof_specs: ProofSpecs,
upgrade_path: Vec<String>,
allow_update: AllowUpdate,
}
#[test]
fn client_state_new() {
// Define a "default" set of parameters to reuse throughout these tests.
let default_params: ClientStateParams = ClientStateParams {
id: ChainId::default(),
trust_level: TrustThreshold::ONE_THIRD,
trusting_period: Duration::new(64000, 0),
unbonding_period: Duration::new(128000, 0),
max_clock_drift: Duration::new(3, 0),
latest_height: Height::new(0, 10).unwrap(),
proof_specs: ProofSpecs::default(),
upgrade_path: Default::default(),
allow_update: AllowUpdate {
after_expiry: false,
after_misbehaviour: false,
},
};