ibc_testkit/fixtures/clients/
tendermint.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
use core::str::FromStr;
use core::time::Duration;

use basecoin_store::avl::get_proof_spec as basecoin_proof_spec;
use bon::Builder;
use ibc::clients::tendermint::client_state::ClientState as TmClientState;
use ibc::clients::tendermint::types::error::TendermintClientError;
use ibc::clients::tendermint::types::proto::v1::{ClientState as RawTmClientState, Fraction};
#[cfg(feature = "serde")]
use ibc::clients::tendermint::types::Header;
use ibc::clients::tendermint::types::{
    AllowUpdate, ClientState as ClientStateType, TrustThreshold,
};
use ibc::core::client::types::proto::v1::Height as RawHeight;
use ibc::core::client::types::Height;
use ibc::core::commitment_types::specs::ProofSpecs;
use ibc::core::host::types::error::DecodingError;
use ibc::core::host::types::identifiers::ChainId;
use ibc::core::primitives::prelude::*;
use tendermint::block::Header as TmHeader;

/// Returns a dummy tendermint `ClientState` by given `frozen_height`, for testing purposes only!
pub fn dummy_tm_client_state_from_raw(
    frozen_height: RawHeight,
) -> Result<TmClientState, DecodingError> {
    ClientStateType::try_from(dummy_raw_tm_client_state(frozen_height)).map(TmClientState::from)
}

/// Returns a dummy tendermint `ClientState` from a `TmHeader`, for testing purposes only!
pub fn dummy_tm_client_state_from_header(tm_header: TmHeader) -> TmClientState {
    let chain_id = ChainId::from_str(tm_header.chain_id.as_str()).expect("Never fails");
    let client_state = ClientStateType::new(
        chain_id.clone(),
        TrustThreshold::ONE_THIRD,
        Duration::from_secs(64000),
        Duration::from_secs(128_000),
        Duration::from_millis(3000),
        Height::new(chain_id.revision_number(), u64::from(tm_header.height)).expect("Never fails"),
        ProofSpecs::cosmos(),
        Vec::new(),
        AllowUpdate {
            after_expiry: false,
            after_misbehaviour: false,
        },
    )
    .expect("Never fails");

    TmClientState::from(client_state)
}

/// Returns a dummy tendermint `RawTmClientState` by given `frozen_height`, for testing purposes only!
pub fn dummy_raw_tm_client_state(frozen_height: RawHeight) -> RawTmClientState {
    #[allow(deprecated)]
    RawTmClientState {
        chain_id: ChainId::new("ibc-0").expect("Never fails").to_string(),
        trust_level: Some(Fraction {
            numerator: 1,
            denominator: 3,
        }),
        trusting_period: Some(Duration::from_secs(64000).try_into().expect("no error")),
        unbonding_period: Some(Duration::from_secs(128_000).try_into().expect("no error")),
        max_clock_drift: Some(Duration::from_millis(3000).try_into().expect("no error")),
        latest_height: Some(Height::new(0, 10).expect("Never fails").into()),
        proof_specs: ProofSpecs::cosmos().into(),
        upgrade_path: Vec::new(),
        frozen_height: Some(frozen_height),
        allow_update_after_expiry: false,
        allow_update_after_misbehaviour: false,
    }
}

#[derive(Debug, Builder)]
pub struct ClientStateConfig {
    #[builder(default = TrustThreshold::ONE_THIRD)]
    pub trust_level: TrustThreshold,
    #[builder(default = Duration::from_secs(64000))]
    pub trusting_period: Duration,
    #[builder(default = Duration::from_secs(128_000))]
    pub unbonding_period: Duration,
    #[builder(default = Duration::from_millis(3000))]
    pub max_clock_drift: Duration,
    #[builder(default = vec![basecoin_proof_spec(); 2].try_into().expect("no error"))]
    pub proof_specs: ProofSpecs,
    #[builder(default)]
    pub upgrade_path: Vec<String>,
    #[builder(default = AllowUpdate { after_expiry: false, after_misbehaviour: false })]
    allow_update: AllowUpdate,
}

impl Default for ClientStateConfig {
    fn default() -> Self {
        Self::builder().build()
    }
}

impl ClientStateConfig {
    pub fn into_client_state(
        self,
        chain_id: ChainId,
        latest_height: Height,
    ) -> Result<TmClientState, TendermintClientError> {
        Ok(ClientStateType::new(
            chain_id,
            self.trust_level,
            self.trusting_period,
            self.unbonding_period,
            self.max_clock_drift,
            latest_height,
            self.proof_specs,
            self.upgrade_path,
            self.allow_update,
        )?
        .into())
    }
}

#[cfg(feature = "serde")]
pub fn dummy_valid_tendermint_header() -> tendermint::block::Header {
    use tendermint::block::signed_header::SignedHeader;

    serde_json::from_str::<SignedHeader>(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/data/json/valid_signed_header.json"
    )))
    .expect("Never fails")
    .header
}

#[cfg(feature = "serde")]
pub fn dummy_expired_tendermint_header() -> tendermint::block::Header {
    use tendermint::block::signed_header::SignedHeader;

    serde_json::from_str::<SignedHeader>(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/data/json/expired_signed_header.json"
    )))
    .expect("Never fails")
    .header
}

// TODO: This should be replaced with a ::default() or ::produce().
// The implementation of this function comprises duplicate code (code borrowed from
// `tendermint-rs` for assembling a Header).
// See https://github.com/informalsystems/tendermint-rs/issues/381.
//
// The normal flow is:
// - get the (trusted) signed header and the `trusted_validator_set` at a `trusted_height`
// - get the `signed_header` and the `validator_set` at latest height
// - build the ics07 Header
// For testing purposes this function does:
// - get the `signed_header` from a .json file
// - create the `validator_set` with a single validator that is also the proposer
// - assume a `trusted_height` of 1 and no change in the validator set since height 1,
//   i.e. `trusted_validator_set` = `validator_set`
#[cfg(feature = "serde")]
pub fn dummy_ics07_header() -> Header {
    use subtle_encoding::hex;
    use tendermint::block::signed_header::SignedHeader;
    use tendermint::validator::{Info as ValidatorInfo, Set as ValidatorSet};
    use tendermint::PublicKey;

    // Build a SignedHeader from a JSON file.
    let shdr = serde_json::from_str::<SignedHeader>(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/data/json/valid_signed_header.json"
    )))
    .expect("Never fails");

    // Build a set of validators.
    // Below are test values inspired form `test_validator_set()` in tendermint-rs.
    let v1 = ValidatorInfo::new(
        PublicKey::from_raw_ed25519(
            &hex::decode_upper("F349539C7E5EF7C49549B09C4BFC2335318AB0FE51FBFAA2433B4F13E816F4A7")
                .expect("Never fails"),
        )
        .expect("Never fails"),
        281_815_u64.try_into().expect("Never fails"),
    );

    let vs = ValidatorSet::new(vec![v1.clone()], Some(v1));

    Header {
        signed_header: shdr,
        validator_set: vs.clone(),
        trusted_height: Height::min(0),
        trusted_next_validator_set: vs,
    }
}

#[cfg(all(test, feature = "serde"))]
mod tests {
    use ibc::primitives::proto::Any;
    use rstest::rstest;

    use super::*;

    #[rstest]
    // try conversions for when the client is not frozen
    #[case::valid_client(0, 0, false)]
    // try conversions for when the client is frozen
    #[case::frozen_client(0, 1, true)]
    fn tm_client_state_conversions_healthy(
        #[case] revision_number: u64,
        #[case] revision_height: u64,
        #[case] is_frozen: bool,
    ) {
        let frozen_height = RawHeight {
            revision_number,
            revision_height,
        };

        // check client state creation path from a proto type
        let tm_client_state_from_raw = dummy_tm_client_state_from_raw(frozen_height);
        assert!(tm_client_state_from_raw.is_ok());

        let any_from_tm_client_state = Any::from(
            tm_client_state_from_raw
                .as_ref()
                .expect("Never fails")
                .clone(),
        );
        let tm_client_state_from_any = ClientStateType::try_from(any_from_tm_client_state);
        assert!(tm_client_state_from_any.is_ok());
        assert_eq!(
            Some(is_frozen),
            tm_client_state_from_any
                .as_ref()
                .map(|x| x.is_frozen())
                .ok()
        );
        assert_eq!(
            tm_client_state_from_raw.expect("Never fails"),
            tm_client_state_from_any.expect("Never fails").into()
        );
    }

    #[test]
    fn tm_client_state_from_header_healthy() {
        // check client state creation path from a tendermint header
        let tm_header = dummy_valid_tendermint_header();
        let tm_client_state_from_header = dummy_tm_client_state_from_header(tm_header);
        let any_from_header = Any::from(tm_client_state_from_header.clone());
        let tm_client_state_from_any = ClientStateType::try_from(any_from_header);
        assert!(tm_client_state_from_any.is_ok());
        assert_eq!(
            tm_client_state_from_header,
            tm_client_state_from_any.expect("Never fails").into()
        );
    }
}