-
Notifications
You must be signed in to change notification settings - Fork 90
/
header.rs
338 lines (297 loc) · 12.3 KB
/
header.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
//! Defines the domain type for tendermint headers
use alloc::string::ToString;
use core::fmt::{Display, Error as FmtError, Formatter};
use core::str::FromStr;
use bytes::Buf;
use ibc_proto::google::protobuf::Any;
use ibc_proto::ibc::lightclients::tendermint::v1::Header as RawHeader;
use ibc_proto::protobuf::Protobuf;
use pretty::{PrettySignedHeader, PrettyValidatorSet};
use prost::Message;
use tendermint::block::signed_header::SignedHeader;
use tendermint::chain::Id as TmChainId;
use tendermint::validator::Set as ValidatorSet;
use tendermint_light_client_verifier::types::{TrustedBlockState, UntrustedBlockState};
use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState;
use crate::clients::ics07_tendermint::error::Error;
use crate::core::ics02_client::error::ClientError;
use crate::core::ics24_host::identifier::ChainId;
use crate::core::timestamp::Timestamp;
use crate::prelude::*;
use crate::Height;
pub(crate) const TENDERMINT_HEADER_TYPE_URL: &str = "/ibc.lightclients.tendermint.v1.Header";
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Tendermint consensus header
#[derive(Clone, PartialEq, Eq)]
pub struct Header {
pub signed_header: SignedHeader, // contains the commitment root
pub validator_set: ValidatorSet, // the validator set that signed Header
pub trusted_height: Height, // the height of a trusted header seen by client less than or equal to Header
pub trusted_next_validator_set: ValidatorSet, // the last trusted validator set at trusted height
}
impl core::fmt::Debug for Header {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, " Header {{...}}")
}
}
impl Display for Header {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "Header {{ signed_header: {}, validator_set: {}, trusted_height: {}, trusted_validator_set: {} }}", PrettySignedHeader(&self.signed_header), PrettyValidatorSet(&self.validator_set), self.trusted_height, PrettyValidatorSet(&self.trusted_next_validator_set))
}
}
impl Header {
pub fn timestamp(&self) -> Timestamp {
self.signed_header.header.time.into()
}
pub fn height(&self) -> Height {
Height::new(
ChainId::from_str(self.signed_header.header.chain_id.as_str())
.expect("chain id")
.revision_number(),
u64::from(self.signed_header.header.height),
)
.expect("malformed tendermint header domain type has an illegal height of 0")
}
pub(crate) fn as_untrusted_block_state(&self) -> UntrustedBlockState<'_> {
UntrustedBlockState {
signed_header: &self.signed_header,
validators: &self.validator_set,
next_validators: None,
}
}
pub(crate) fn as_trusted_block_state<'a>(
&'a self,
consensus_state: &TmConsensusState,
chain_id: &'a TmChainId,
) -> Result<TrustedBlockState<'a>, Error> {
Ok(TrustedBlockState {
chain_id,
header_time: consensus_state.timestamp,
height: self
.trusted_height
.revision_height()
.try_into()
.map_err(|_| Error::InvalidHeaderHeight {
height: self.trusted_height.revision_height(),
})?,
next_validators: &self.trusted_next_validator_set,
next_validators_hash: consensus_state.next_validators_hash,
})
}
pub fn verify_chain_id_version_matches_height(&self, chain_id: &ChainId) -> Result<(), Error> {
if self.height().revision_number() != chain_id.revision_number() {
return Err(Error::MismatchHeaderChainId {
given: self.signed_header.header.chain_id.to_string(),
expected: chain_id.to_string(),
});
}
Ok(())
}
/// Checks if the fields of a given header are consistent with the trusted fields of this header.
pub fn validate_basic(&self) -> Result<(), Error> {
if self.height().revision_number() != self.trusted_height.revision_number() {
return Err(Error::MismatchHeightRevisions {
trusted_revision: self.trusted_height.revision_number(),
header_revision: self.height().revision_number(),
});
}
// We need to ensure that the trusted height (representing the
// height of the header already on chain for which this client update is
// based on) must be smaller than height of the new header that we're
// installing.
if self.trusted_height >= self.height() {
return Err(Error::InvalidHeaderHeight {
height: self.height().revision_height(),
});
}
if self.validator_set.hash() != self.signed_header.header.validators_hash {
return Err(Error::MismatchValidatorsHashes {
signed_header_validators_hash: self.signed_header.header.validators_hash,
validators_hash: self.validator_set.hash(),
});
}
if self.trusted_next_validator_set.hash() != self.signed_header.header.next_validators_hash
{
return Err(Error::MismatchValidatorsHashes {
signed_header_validators_hash: self.signed_header.header.next_validators_hash,
validators_hash: self.trusted_next_validator_set.hash(),
});
}
Ok(())
}
}
impl Protobuf<RawHeader> for Header {}
impl TryFrom<RawHeader> for Header {
type Error = Error;
fn try_from(raw: RawHeader) -> Result<Self, Self::Error> {
let header = Self {
signed_header: raw
.signed_header
.ok_or(Error::MissingSignedHeader)?
.try_into()
.map_err(|e| Error::InvalidHeader {
reason: "signed header conversion".to_string(),
error: e,
})?,
validator_set: raw
.validator_set
.ok_or(Error::MissingValidatorSet)?
.try_into()
.map_err(Error::InvalidRawHeader)?,
trusted_height: raw
.trusted_height
.and_then(|raw_height| raw_height.try_into().ok())
.ok_or(Error::MissingTrustedHeight)?,
trusted_next_validator_set: raw
.trusted_validators
.ok_or(Error::MissingTrustedNextValidatorSet)?
.try_into()
.map_err(Error::InvalidRawHeader)?,
};
Ok(header)
}
}
impl Protobuf<Any> for Header {}
impl TryFrom<Any> for Header {
type Error = ClientError;
fn try_from(raw: Any) -> Result<Self, Self::Error> {
use core::ops::Deref;
match raw.type_url.as_str() {
TENDERMINT_HEADER_TYPE_URL => decode_header(raw.value.deref()).map_err(Into::into),
_ => Err(ClientError::UnknownHeaderType {
header_type: raw.type_url,
}),
}
}
}
impl From<Header> for Any {
fn from(header: Header) -> Self {
Any {
type_url: TENDERMINT_HEADER_TYPE_URL.to_string(),
value: Protobuf::<RawHeader>::encode_vec(&header),
}
}
}
fn decode_header<B: Buf>(buf: B) -> Result<Header, Error> {
RawHeader::decode(buf).map_err(Error::Decode)?.try_into()
}
impl From<Header> for RawHeader {
fn from(value: Header) -> Self {
RawHeader {
signed_header: Some(value.signed_header.into()),
validator_set: Some(value.validator_set.into()),
trusted_height: Some(value.trusted_height.into()),
trusted_validators: Some(value.trusted_next_validator_set.into()),
}
}
}
mod pretty {
pub use super::*;
use crate::utils::pretty::PrettySlice;
pub struct PrettySignedHeader<'a>(pub &'a SignedHeader);
impl Display for PrettySignedHeader<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(
f,
"SignedHeader {{ header: {{ chain_id: {}, height: {} }}, commit: {{ height: {} }} }}",
self.0.header.chain_id, self.0.header.height, self.0.commit.height
)
}
}
pub struct PrettyValidatorSet<'a>(pub &'a ValidatorSet);
impl Display for PrettyValidatorSet<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
let validator_addresses: Vec<_> = self
.0
.validators()
.iter()
.map(|validator| validator.address)
.collect();
if let Some(proposer) = self.0.proposer() {
match &proposer.name {
Some(name) => write!(f, "PrettyValidatorSet {{ validators: {}, proposer: {}, total_voting_power: {} }}", PrettySlice(&validator_addresses), name, self.0.total_voting_power()),
None => write!(f, "PrettyValidatorSet {{ validators: {}, proposer: None, total_voting_power: {} }}", PrettySlice(&validator_addresses), self.0.total_voting_power()),
}
} else {
write!(
f,
"PrettyValidatorSet {{ validators: {}, proposer: None, total_voting_power: {} }}",
PrettySlice(&validator_addresses),
self.0.total_voting_power()
)
}
}
}
}
#[cfg(any(test, feature = "mocks"))]
pub mod test_util {
use alloc::vec;
use subtle_encoding::hex;
use tendermint::block::signed_header::SignedHeader;
use tendermint::validator::{Info as ValidatorInfo, Set as ValidatorSet};
use tendermint::PublicKey;
use crate::clients::ics07_tendermint::header::Header;
use crate::mock::host::SyntheticTmBlock;
use crate::Height;
pub fn get_dummy_tendermint_header() -> tendermint::block::Header {
serde_json::from_str::<SignedHeader>(include_str!(
"../../../tests/support/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`
pub fn get_dummy_ics07_header() -> Header {
// Build a SignedHeader from a JSON file.
let shdr = serde_json::from_str::<SignedHeader>(include_str!(
"../../../tests/support/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 = 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,
}
}
impl From<SyntheticTmBlock> for Header {
fn from(light_block: SyntheticTmBlock) -> Self {
let SyntheticTmBlock {
trusted_height,
light_block,
} = light_block;
Self {
signed_header: light_block.signed_header,
validator_set: light_block.validators,
trusted_height,
trusted_next_validator_set: light_block.next_validators,
}
}
}
}