Skip to main content

drive_proof_verifier/block_proof/
block.rs

1//! The quorum's signature over a block.
2
3use super::header::check_header;
4use super::header::header_time_ms;
5use super::BlockProofError;
6use crate::verify::{quorum_public_key, verify_quorum_signature};
7use crate::{ContextProvider, Error};
8use dapi_grpc::platform::v0::get_blocks_response::get_blocks_response_v0::Block;
9use dapi_grpc::platform::v0::tenderdash_block_proof::{BlockId, Header};
10use dapi_grpc::platform::v0::TenderdashBlockProof;
11use tenderdash_abci::proto::types::{BlockId as SignedBlockId, Commit, PartSetHeader};
12use tenderdash_abci::signatures::Signable;
13
14/// The header and block id of a proof, which a well-formed one always carries.
15pub fn proof_parts(proof: &TenderdashBlockProof) -> Result<(&Header, &BlockId), BlockProofError> {
16    let header = proof
17        .header
18        .as_ref()
19        .ok_or(BlockProofError::MissingHeader)?;
20    let block_id = proof
21        .block_id
22        .as_ref()
23        .ok_or(BlockProofError::MissingBlockId)?;
24    Ok((header, block_id))
25}
26
27/// Check that the fields a `getBlocks` block repeats from its header are the ones in
28/// `proof`. Only the header is signed, and a node reads those fields from another
29/// Tenderdash answer than the proof, so nothing else ties them to it.
30pub fn check_block_fields(
31    proof: &TenderdashBlockProof,
32    block: &Block,
33) -> Result<(), BlockProofError> {
34    let (header, block_id) = proof_parts(proof)?;
35
36    let fields = [
37        ("height", block.height == header.height),
38        ("hash", block.hash == block_id.hash),
39        ("time", block.time_ms == header_time_ms(header)?),
40        (
41            "core chain locked height",
42            block.core_chain_locked_height == header.core_chain_locked_height,
43        ),
44        ("app hash", block.app_hash == header.app_hash),
45        (
46            "proposer",
47            block.proposer_pro_tx_hash == header.proposer_pro_tx_hash,
48        ),
49    ];
50    match fields.iter().find(|(_, matches)| !matches) {
51        Some((field, _)) => Err(BlockProofError::FieldMismatch {
52            height: header.height,
53            field,
54        }),
55        None => Ok(()),
56    }
57}
58
59/// Verify that a quorum committed the block `proof` describes, and return that block's
60/// header, every field of which the quorum's signature then covers.
61///
62/// The header must hash to the block hash and the state id of the proof's block id, and
63/// the proof's signature must be the quorum's threshold signature over the precommit vote
64/// for that block id at the header's chain, height and the proof's round. The quorum's key
65/// comes from `provider`, looked up by the quorum type and hash the proof names and the
66/// header's Core height.
67///
68/// Once the signature verifies, and only then, that Core height is reported to
69/// [ContextProvider::core_height_verified]: the state id covers it, so the quorum signed it.
70///
71/// What this does not show: that the block is recent, or that `provider`'s quorum was the
72/// validator set of that height. Any quorum of the named type whose key `provider` returns
73/// is accepted, as for every other Platform proof.
74pub fn verify_block_proof<'a>(
75    proof: &'a TenderdashBlockProof,
76    provider: &dyn ContextProvider,
77) -> Result<&'a Header, Error> {
78    let (header, block_id) = proof_parts(proof)?;
79    check_header(header, block_id)?;
80
81    let out_of_range = |field| BlockProofError::VoteFieldOutOfRange {
82        height: header.height,
83        field,
84    };
85    let height = i64::try_from(header.height).map_err(|_| out_of_range("height"))?;
86    let round = i32::try_from(proof.round).map_err(|_| out_of_range("round"))?;
87    let quorum_type = u8::try_from(proof.quorum_type).map_err(|_| out_of_range("quorum type"))?;
88    let quorum_hash = <[u8; 32]>::try_from(proof.quorum_hash.as_slice()).map_err(|e| {
89        Error::ResponseDecodeError {
90            error: "invalid quorum hash size: ".to_string() + &e.to_string(),
91        }
92    })?;
93
94    let public_key = quorum_public_key(
95        provider,
96        proof.quorum_type,
97        quorum_hash,
98        header.core_chain_locked_height,
99    )?;
100
101    // The commit Tenderdash stored for the block, as far as its signature covers it
102    let commit = Commit {
103        height,
104        round,
105        block_id: Some(SignedBlockId {
106            hash: block_id.hash.clone(),
107            part_set_header: Some(PartSetHeader {
108                total: block_id.part_set_total,
109                hash: block_id.part_set_hash.clone(),
110            }),
111            state_id: block_id.state_id.clone(),
112        }),
113        quorum_hash: quorum_hash.to_vec(),
114        ..Default::default()
115    };
116    let sign_digest = commit
117        .calculate_sign_hash(&header.chain_id, quorum_type, &quorum_hash, height, round)
118        .map_err(|e| Error::SignDigestFailed {
119            error: e.to_string(),
120        })?;
121
122    verify_quorum_signature(
123        provider,
124        proof.quorum_type,
125        quorum_hash,
126        header.core_chain_locked_height,
127        &public_key,
128        &sign_digest,
129        &proof.signature,
130    )?;
131
132    Ok(header)
133}
134
135#[cfg(test)]
136mod tests {
137    use super::super::fixtures::{
138        block_id_of, header_of, sign, signed_proof, TestQuorum, CORE_HEIGHT, QUORUM_HASH,
139        QUORUM_TYPE,
140    };
141    use super::*;
142
143    fn proof() -> TenderdashBlockProof {
144        signed_proof(header_of(7, &[]))
145    }
146
147    /// Verify `proof` against the test quorum, expecting no Core height to be reported.
148    fn refused(proof: &TenderdashBlockProof) -> Error {
149        let quorum = TestQuorum::new();
150        let error = verify_block_proof(proof, &quorum).unwrap_err();
151        assert!(quorum.verified.lock().unwrap().is_empty());
152        error
153    }
154
155    #[test]
156    fn should_accept_a_block_the_quorum_signed() {
157        let proof = proof();
158        let quorum = TestQuorum::new();
159
160        let header = verify_block_proof(&proof, &quorum).unwrap();
161
162        assert_eq!(Some(header), proof.header.as_ref());
163        assert_eq!(
164            *quorum.verified.lock().unwrap(),
165            [(QUORUM_TYPE, QUORUM_HASH, CORE_HEIGHT)]
166        );
167    }
168
169    #[test]
170    fn should_refuse_a_proof_without_its_parts() {
171        let mut proof = proof();
172        proof.header = None;
173        assert!(matches!(
174            refused(&proof),
175            Error::InvalidBlockProof(BlockProofError::MissingHeader)
176        ));
177
178        let mut proof = self::proof();
179        proof.block_id = None;
180        assert!(matches!(
181            refused(&proof),
182            Error::InvalidBlockProof(BlockProofError::MissingBlockId)
183        ));
184    }
185
186    #[test]
187    fn should_refuse_a_header_that_does_not_hash_to_the_block_id() {
188        let mut proof = proof();
189        proof.header.as_mut().unwrap().data_hash[0] ^= 1;
190
191        assert!(matches!(
192            refused(&proof),
193            Error::InvalidBlockProof(BlockProofError::HeaderHashMismatch { height: 7 })
194        ));
195    }
196
197    #[test]
198    fn should_refuse_a_header_that_does_not_hash_to_the_state_id() {
199        // The block hash leaves the Core height out, so only the state id catches it
200        let mut proof = proof();
201        proof.header.as_mut().unwrap().core_chain_locked_height += 1;
202        assert!(matches!(
203            refused(&proof),
204            Error::InvalidBlockProof(BlockProofError::StateIdMismatch { height: 7 })
205        ));
206
207        let mut proof = self::proof();
208        proof.block_id.as_mut().unwrap().state_id[0] ^= 1;
209        assert!(matches!(
210            refused(&proof),
211            Error::InvalidBlockProof(BlockProofError::StateIdMismatch { height: 7 })
212        ));
213    }
214
215    /// A node can change a header and derive a matching block id from it, but not sign it.
216    #[test]
217    fn should_refuse_a_consistent_header_the_quorum_did_not_sign() {
218        let changes: [fn(&mut Header); 4] = [
219            |header| header.data_hash[0] ^= 1,
220            |header| header.results_hash[0] ^= 1,
221            |header| header.core_chain_locked_height += 1,
222            |header| header.chain_id.push('x'),
223        ];
224        for change in changes {
225            let mut proof = proof();
226            let header = proof.header.as_mut().unwrap();
227            change(header);
228            proof.block_id = Some(block_id_of(header));
229
230            assert!(matches!(refused(&proof), Error::InvalidSignature { .. }));
231        }
232    }
233
234    #[test]
235    fn should_refuse_the_signature_of_another_block() {
236        let mut proof = proof();
237        proof.signature = signed_proof(header_of(8, &[])).signature;
238
239        assert!(matches!(refused(&proof), Error::InvalidSignature { .. }));
240    }
241
242    #[test]
243    fn should_refuse_a_signature_when_what_the_vote_covers_changes() {
244        let changes: [fn(&mut TenderdashBlockProof); 3] = [
245            |proof| proof.round += 1,
246            |proof| proof.block_id.as_mut().unwrap().part_set_total += 1,
247            |proof| proof.block_id.as_mut().unwrap().part_set_hash[0] ^= 1,
248        ];
249        for change in changes {
250            let mut proof = proof();
251            change(&mut proof);
252
253            assert!(matches!(refused(&proof), Error::InvalidSignature { .. }));
254        }
255    }
256
257    #[test]
258    fn should_refuse_a_signature_of_another_key() {
259        let quorum = TestQuorum::with_another_key();
260
261        assert!(matches!(
262            verify_block_proof(&proof(), &quorum),
263            Err(Error::InvalidSignature { .. })
264        ));
265        assert!(quorum.verified.lock().unwrap().is_empty());
266    }
267
268    #[test]
269    fn should_refuse_a_malformed_signature() {
270        let mut proof = proof();
271        proof.signature[5] ^= 1;
272        assert!(matches!(
273            refused(&proof),
274            Error::InvalidSignature { .. } | Error::SignatureVerificationError { .. }
275        ));
276
277        proof.signature = vec![0; 96];
278        assert!(matches!(
279            refused(&proof),
280            Error::SignatureVerificationError { .. }
281        ));
282
283        proof.signature = vec![1; 95];
284        assert!(matches!(
285            refused(&proof),
286            Error::InvalidSignatureFormat { .. }
287        ));
288    }
289
290    #[test]
291    fn should_ask_for_the_key_of_the_quorum_the_proof_names() {
292        // Signed for the quorum it names, which the provider does not know
293        let mut proof = proof();
294        proof.quorum_hash = vec![8; 32];
295        sign(&mut proof);
296        assert!(matches!(
297            refused(&proof),
298            Error::QuorumKeyUnavailable {
299                quorum_type: QUORUM_TYPE,
300                quorum_hash,
301                core_chain_locked_height: CORE_HEIGHT,
302                ..
303            } if quorum_hash == [8; 32]
304        ));
305
306        let mut proof = self::proof();
307        proof.quorum_type = 100;
308        sign(&mut proof);
309        assert!(matches!(
310            refused(&proof),
311            Error::QuorumKeyUnavailable {
312                quorum_type: 100,
313                ..
314            }
315        ));
316    }
317
318    #[test]
319    fn should_refuse_fields_no_vote_can_carry() {
320        let mut proof = proof();
321        proof.quorum_hash.pop();
322        assert!(matches!(refused(&proof), Error::ResponseDecodeError { .. }));
323
324        let mut proof = self::proof();
325        proof.quorum_type = 256;
326        assert!(matches!(
327            refused(&proof),
328            Error::InvalidBlockProof(BlockProofError::VoteFieldOutOfRange {
329                field: "quorum type",
330                ..
331            })
332        ));
333
334        let mut proof = self::proof();
335        proof.round = u32::MAX;
336        assert!(matches!(
337            refused(&proof),
338            Error::InvalidBlockProof(BlockProofError::VoteFieldOutOfRange { field: "round", .. })
339        ));
340    }
341}