Skip to main content

drive_proof_verifier/block_proof/
header.rs

1//! The two hashes Tenderdash derives from a block header and a quorum signs: the block
2//! hash and the state id.
3
4use super::merkle::merkle_root;
5use super::BlockProofError;
6use dapi_grpc::platform::v0::tenderdash_block_proof::{BlockId, Header};
7use dapi_grpc::Message;
8use tenderdash_abci::proto::google::protobuf::Timestamp;
9use tenderdash_abci::proto::types::{BlockId as HashedBlockId, PartSetHeader, StateId};
10use tenderdash_abci::proto::version::Consensus;
11use tenderdash_abci::signatures::Hashable;
12
13/// Tenderdash hashes an absent app hash into a state id as this many zero bytes.
14const APP_HASH_SIZE: usize = 32;
15
16/// The hash Tenderdash gives a block: the Merkle root of its header's fields, each in its
17/// protobuf encoding. A string, number or hash is wrapped in a one-field message first, so
18/// one that is empty or zero is an empty leaf.
19///
20/// The core chain locked height is an empty leaf whatever its value: the state id is what
21/// commits to it.
22pub fn header_hash(header: &Header) -> [u8; 32] {
23    let last_block_id = header.last_block_id.clone().unwrap_or_default();
24
25    merkle_root(&[
26        Consensus {
27            block: header.block_version,
28            app: header.app_version,
29        }
30        .encode_to_vec(),
31        header.chain_id.encode_to_vec(),
32        header.height.encode_to_vec(),
33        Vec::new(),
34        Timestamp {
35            seconds: header.time_seconds,
36            nanos: header.time_nanos,
37        }
38        .encode_to_vec(),
39        HashedBlockId {
40            hash: last_block_id.hash,
41            part_set_header: Some(PartSetHeader {
42                total: last_block_id.part_set_total,
43                hash: last_block_id.part_set_hash,
44            }),
45            state_id: last_block_id.state_id,
46        }
47        .encode_to_vec(),
48        header.last_commit_hash.encode_to_vec(),
49        header.data_hash.encode_to_vec(),
50        header.validators_hash.encode_to_vec(),
51        header.next_validators_hash.encode_to_vec(),
52        header.consensus_hash.encode_to_vec(),
53        header.next_consensus_hash.encode_to_vec(),
54        header.app_hash.encode_to_vec(),
55        header.results_hash.encode_to_vec(),
56        header.evidence_hash.encode_to_vec(),
57        header.proposer_pro_tx_hash.encode_to_vec(),
58        header.proposed_app_version.encode_to_vec(),
59    ])
60}
61
62/// A header's time in milliseconds since the Unix epoch, the precision a state id keeps.
63pub fn header_time_ms(header: &Header) -> Result<u64, BlockProofError> {
64    header
65        .time_seconds
66        .checked_mul(1000)
67        .and_then(|ms| ms.checked_add(i64::from(header.time_nanos / 1_000_000)))
68        .and_then(|ms| u64::try_from(ms).ok())
69        .ok_or(BlockProofError::TimeOutOfRange {
70            height: header.height,
71        })
72}
73
74/// The state id Tenderdash derives from a header, which the quorum signs next to the
75/// block hash: the hash of these fields as Tenderdash's `StateID`.
76pub fn state_id_hash(header: &Header) -> Result<[u8; 32], BlockProofError> {
77    let app_hash = if header.app_hash.is_empty() {
78        vec![0; APP_HASH_SIZE]
79    } else {
80        header.app_hash.clone()
81    };
82    let state_id = StateId {
83        app_version: header.app_version,
84        height: header.height,
85        app_hash,
86        core_chain_locked_height: header.core_chain_locked_height,
87        time: header_time_ms(header)?,
88    };
89
90    // A state id is hashed the same way whatever the chain, height and round
91    state_id
92        .calculate_msg_hash(&header.chain_id, 0, 0)
93        .ok()
94        .and_then(|hash| <[u8; 32]>::try_from(hash).ok())
95        .ok_or(BlockProofError::StateIdNotHashed {
96            height: header.height,
97        })
98}
99
100/// Check that `header` is the one behind `block_id`: that it hashes to the block hash and
101/// to the state id, the two values of a block id a quorum's signature covers.
102pub fn check_header(header: &Header, block_id: &BlockId) -> Result<(), BlockProofError> {
103    if header_hash(header).as_slice() != block_id.hash {
104        return Err(BlockProofError::HeaderHashMismatch {
105            height: header.height,
106        });
107    }
108    if state_id_hash(header)?.as_slice() != block_id.state_id {
109        return Err(BlockProofError::StateIdMismatch {
110            height: header.height,
111        });
112    }
113    Ok(())
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    use sha2::{Digest, Sha256};
120
121    /// The header of the "Generates expected hash" case of `TestHeaderHash` in Tenderdash's
122    /// `types/block_test.go`, which sets every field.
123    fn tenderdash_header() -> Header {
124        let hash_of = |seed: &str| Sha256::digest(seed).to_vec();
125        let last_block = Header {
126            app_version: 1,
127            height: 3,
128            core_chain_locked_height: 1,
129            // 2022-03-04T05:06:07.000000008Z
130            time_seconds: 1_646_370_367,
131            time_nanos: 8,
132            app_hash: hash_of("app_hash"),
133            ..Default::default()
134        };
135
136        Header {
137            block_version: 1,
138            app_version: 2,
139            chain_id: "chainId".to_string(),
140            height: 3,
141            core_chain_locked_height: 1,
142            // 2019-10-13T16:14:44Z
143            time_seconds: 1_570_983_284,
144            time_nanos: 0,
145            last_block_id: Some(BlockId {
146                hash: vec![0; 32],
147                part_set_total: 6,
148                part_set_hash: vec![0; 32],
149                state_id: state_id_hash(&last_block).unwrap().to_vec(),
150            }),
151            last_commit_hash: hash_of("last_commit_hash"),
152            data_hash: hash_of("data_hash"),
153            validators_hash: hash_of("validators_hash"),
154            next_validators_hash: hash_of("next_validators_hash"),
155            consensus_hash: hash_of("consensus_hash"),
156            next_consensus_hash: hash_of("next_consensus_hash"),
157            app_hash: hash_of("app_hash"),
158            results_hash: hash_of("last_results_hash"),
159            evidence_hash: hash_of("evidence_hash"),
160            proposer_pro_tx_hash: hash_of("proposer_pro_tx_hash"),
161            proposed_app_version: 1,
162        }
163    }
164
165    fn block_id_of(header: &Header) -> BlockId {
166        BlockId {
167            hash: header_hash(header).to_vec(),
168            part_set_total: 1,
169            part_set_hash: vec![0xdd; 32],
170            state_id: state_id_hash(header).unwrap().to_vec(),
171        }
172    }
173
174    #[test]
175    fn should_hash_a_header_as_tenderdash_does() {
176        assert_eq!(
177            hex::encode(header_hash(&tenderdash_header())),
178            "ff24ddab9e1550beb40ab7ad432a4d577560e9b87a80c7bb86e75263974b87e0"
179        );
180    }
181
182    /// `TestHeaderHashVector` of the same file: no last block, a time before 1970 with
183    /// nanoseconds, and hashes that are the text of a hex string.
184    #[test]
185    fn should_hash_a_header_with_empty_fields_as_tenderdash_does() {
186        let text = b"f2564c78071e26643ae9b3e2a19fa0dc10d4d9e873aa0be808660123f11a1e78".to_vec();
187        let header = Header {
188            block_version: 1,
189            app_version: 1,
190            chain_id: "test".to_string(),
191            height: 50,
192            // what Go's `time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)`
193            // wraps around to: 0291-03-10T13:13:40.854775807Z
194            time_seconds: -52_978_185_980,
195            time_nanos: 854_775_807,
196            last_block_id: Some(BlockId::default()),
197            last_commit_hash: text.clone(),
198            data_hash: text.clone(),
199            validators_hash: text.clone(),
200            next_validators_hash: text.clone(),
201            consensus_hash: text.clone(),
202            next_consensus_hash: text.clone(),
203            app_hash: text.clone(),
204            results_hash: text.clone(),
205            evidence_hash: text.clone(),
206            proposer_pro_tx_hash: text,
207            ..Default::default()
208        };
209
210        assert_eq!(
211            hex::encode(header_hash(&header)),
212            "1476e858bfe231d7cd767a9693f63fe6a8757e8c07aba432f338a5ecba2b0342"
213        );
214    }
215
216    #[test]
217    fn should_leave_the_core_chain_locked_height_to_the_state_id() {
218        let header = tenderdash_header();
219        let mut other = header.clone();
220        other.core_chain_locked_height += 1;
221
222        assert_eq!(header_hash(&other), header_hash(&header));
223        assert_ne!(
224            state_id_hash(&other).unwrap(),
225            state_id_hash(&header).unwrap()
226        );
227    }
228
229    #[test]
230    fn should_hash_an_absent_app_hash_into_the_state_id_as_zeros() {
231        let mut header = tenderdash_header();
232        header.app_hash = Vec::new();
233        let mut zeros = header.clone();
234        zeros.app_hash = vec![0; 32];
235
236        assert_eq!(
237            state_id_hash(&header).unwrap(),
238            state_id_hash(&zeros).unwrap()
239        );
240    }
241
242    #[test]
243    fn should_keep_milliseconds_of_the_time_in_the_state_id() {
244        let mut header = tenderdash_header();
245        header.time_nanos = 123_999_999;
246
247        assert_eq!(header_time_ms(&header), Ok(1_570_983_284_123));
248    }
249
250    #[test]
251    fn should_refuse_a_state_id_for_a_time_before_1970() {
252        let mut header = tenderdash_header();
253        header.time_seconds = -1;
254
255        assert_eq!(
256            state_id_hash(&header),
257            Err(BlockProofError::TimeOutOfRange { height: 3 })
258        );
259    }
260
261    #[test]
262    fn should_accept_a_header_that_hashes_to_its_block_id() {
263        let header = tenderdash_header();
264
265        assert_eq!(check_header(&header, &block_id_of(&header)), Ok(()));
266    }
267
268    /// The block hash leaves the core chain locked height out, so that field is the one
269    /// only the state id catches.
270    #[test]
271    fn should_tell_which_hash_every_header_field_changes() {
272        let signed = tenderdash_header();
273        let block_id = block_id_of(&signed);
274        let block_hash = Err(BlockProofError::HeaderHashMismatch { height: 3 });
275        type Change = (&'static str, fn(&mut Header));
276        let changes: [Change; 18] = [
277            ("block_version", |header| header.block_version += 1),
278            ("app_version", |header| header.app_version += 1),
279            ("chain_id", |header| header.chain_id.push('x')),
280            ("time_seconds", |header| header.time_seconds += 1),
281            ("time_nanos", |header| header.time_nanos += 1),
282            ("last_block_id", |header| {
283                header.last_block_id.as_mut().unwrap().part_set_total += 1
284            }),
285            ("last_commit_hash", |header| header.last_commit_hash[0] ^= 1),
286            ("data_hash", |header| header.data_hash[0] ^= 1),
287            ("validators_hash", |header| header.validators_hash[0] ^= 1),
288            ("next_validators_hash", |header| {
289                header.next_validators_hash[0] ^= 1
290            }),
291            ("consensus_hash", |header| header.consensus_hash[0] ^= 1),
292            ("next_consensus_hash", |header| {
293                header.next_consensus_hash[0] ^= 1
294            }),
295            ("app_hash", |header| header.app_hash[0] ^= 1),
296            ("results_hash", |header| header.results_hash[0] ^= 1),
297            ("evidence_hash", |header| header.evidence_hash[0] ^= 1),
298            ("proposer_pro_tx_hash", |header| {
299                header.proposer_pro_tx_hash[0] ^= 1
300            }),
301            ("proposed_app_version", |header| {
302                header.proposed_app_version += 1
303            }),
304            ("last_block_id.state_id", |header| {
305                header.last_block_id.as_mut().unwrap().state_id[0] ^= 1
306            }),
307        ];
308
309        for (field, change) in changes {
310            let mut header = signed.clone();
311            change(&mut header);
312            assert_eq!(check_header(&header, &block_id), block_hash, "{field}");
313        }
314
315        let mut header = signed.clone();
316        header.core_chain_locked_height += 1;
317        assert_eq!(
318            check_header(&header, &block_id),
319            Err(BlockProofError::StateIdMismatch { height: 3 })
320        );
321    }
322
323    #[test]
324    fn should_refuse_a_header_under_another_height() {
325        let signed = tenderdash_header();
326        let block_id = block_id_of(&signed);
327        let mut header = signed;
328        header.height += 1;
329
330        assert_eq!(
331            check_header(&header, &block_id),
332            Err(BlockProofError::HeaderHashMismatch { height: 4 })
333        );
334    }
335}