Skip to main content

drive_proof_verifier/block_proof/
fixtures.rs

1//! Blocks signed by test quorums, and the answers a node would give for them, for tests of
2//! this crate and of the crates that verify block proofs through it.
3//!
4//! A test quorum's key is derived from its hash, so these are synthetic blocks, never
5//! network trust anchors: a verifier accepts them only from a provider that answers a test
6//! quorum's key, as [`TestQuorum`] does. The sign hash is built here by hand, from
7//! Tenderdash's definition of it, so the verifier is checked against that definition and
8//! not against itself.
9
10use super::header::{header_hash, header_time_ms, state_id_hash};
11use super::merkle::{merkle_root, MerkleTree};
12use super::transaction::{result_leaf, transaction_hash};
13use crate::{ContextProvider, ContextProviderError};
14use dapi_grpc::platform::v0::get_blocks_response::get_blocks_response_v0::{Block, Transaction};
15use dapi_grpc::platform::v0::get_owner_transactions_in_block_response::get_owner_transactions_in_block_response_v0::OwnerTransaction;
16use dapi_grpc::platform::v0::get_owner_transactions_in_block_response::GetOwnerTransactionsInBlockResponseV0;
17use dapi_grpc::platform::v0::tenderdash_block_proof::{BlockId, Header};
18use dapi_grpc::platform::v0::{TenderdashBlockProof, TenderdashTransactionProof};
19use dapi_grpc::Message;
20use dpp::bls::SecretKey;
21use dpp::data_contract::TokenConfiguration;
22use dpp::prelude::{CoreBlockHeight, DataContract, Identifier};
23use dpp::version::PlatformVersion;
24use sha2::{Digest, Sha256};
25use std::sync::{Arc, Mutex};
26use tenderdash_abci::proto::types::{CanonicalBlockId, CanonicalPartSetHeader};
27
28/// The LLMQ type of the test quorums.
29pub const QUORUM_TYPE: u32 = 106;
30/// The quorum that signs a block unless a test names another.
31pub const QUORUM_HASH: [u8; 32] = [2; 32];
32/// The Core height the test blocks are chain locked at.
33pub const CORE_HEIGHT: u32 = 2_300_000;
34/// The chain of the test blocks.
35pub const CHAIN_ID: &str = "dash-test-1";
36
37/// A transaction of a test block: its bytes, and the code, data and gas of its result.
38pub type TestTransaction = (Vec<u8>, u32, Vec<u8>, i64);
39
40/// The key of the test quorum `quorum_hash`, derived from the first byte of its hash.
41fn secret_key(quorum_hash: &[u8]) -> SecretKey {
42    // Kept in 1..=0x73, so the repeated byte is a scalar below the order of the curve
43    let seed = quorum_hash.first().copied().unwrap_or_default() % 0x73 + 1;
44    SecretKey::from_be_bytes(&[seed; 32]).expect("a scalar below the curve order is a key")
45}
46
47/// The public key of the test quorum `quorum_hash`.
48pub fn quorum_public_key(quorum_hash: [u8; 32]) -> [u8; 48] {
49    secret_key(&quorum_hash).public_key().to_bytes()
50}
51
52/// A provider that knows the test quorum [`QUORUM_HASH`] and records the Core heights
53/// reported to it as verified.
54pub struct TestQuorum {
55    public_key: [u8; 48],
56    /// The quorum type, quorum hash and Core height of each verified signature.
57    pub verified: Mutex<Vec<(u32, [u8; 32], u32)>>,
58}
59
60impl TestQuorum {
61    /// Knows the quorum by the key it signs with.
62    pub fn new() -> Self {
63        Self {
64            public_key: quorum_public_key(QUORUM_HASH),
65            verified: Mutex::new(Vec::new()),
66        }
67    }
68
69    /// Knows the quorum by another key than the one it signs with.
70    pub fn with_another_key() -> Self {
71        Self {
72            public_key: quorum_public_key([9; 32]),
73            verified: Mutex::new(Vec::new()),
74        }
75    }
76}
77
78impl Default for TestQuorum {
79    fn default() -> Self {
80        Self::new()
81    }
82}
83
84impl ContextProvider for TestQuorum {
85    fn get_data_contract(
86        &self,
87        _: &Identifier,
88        _: &PlatformVersion,
89    ) -> Result<Option<Arc<DataContract>>, ContextProviderError> {
90        Ok(None)
91    }
92
93    fn get_token_configuration(
94        &self,
95        _: &Identifier,
96    ) -> Result<Option<TokenConfiguration>, ContextProviderError> {
97        Ok(None)
98    }
99
100    fn get_quorum_public_key(
101        &self,
102        quorum_type: u32,
103        quorum_hash: [u8; 32],
104        _: u32,
105    ) -> Result<[u8; 48], ContextProviderError> {
106        if (quorum_type, quorum_hash) != (QUORUM_TYPE, QUORUM_HASH) {
107            return Err(ContextProviderError::InvalidQuorum(
108                "not the test quorum".to_string(),
109            ));
110        }
111        Ok(self.public_key)
112    }
113
114    fn get_platform_activation_height(&self) -> Result<CoreBlockHeight, ContextProviderError> {
115        Ok(1)
116    }
117
118    fn core_height_verified(
119        &self,
120        quorum_type: u32,
121        quorum_hash: [u8; 32],
122        core_chain_locked_height: u32,
123    ) {
124        if let Ok(mut verified) = self.verified.lock() {
125            verified.push((quorum_type, quorum_hash, core_chain_locked_height));
126        }
127    }
128}
129
130fn sha256(bytes: &[u8]) -> Vec<u8> {
131    Sha256::digest(bytes).to_vec()
132}
133
134fn reversed(mut bytes: Vec<u8>) -> Vec<u8> {
135    bytes.reverse();
136    bytes
137}
138
139/// The hash a quorum signs for a precommit vote, as Tenderdash defines it.
140fn vote_sign_hash(proof: &TenderdashBlockProof) -> Vec<u8> {
141    let header = proof.header.clone().unwrap_or_default();
142    let block_id = proof.block_id.clone().unwrap_or_default();
143    let height = header.height as i64;
144    const PRECOMMIT: i32 = 2;
145
146    let canonical_block_id = CanonicalBlockId {
147        hash: block_id.hash,
148        part_set_header: Some(CanonicalPartSetHeader {
149            total: block_id.part_set_total,
150            hash: block_id.part_set_hash,
151        }),
152    };
153    let mut sign_bytes = Vec::new();
154    sign_bytes.extend(PRECOMMIT.to_le_bytes());
155    sign_bytes.extend(height.to_le_bytes());
156    sign_bytes.extend(i64::from(proof.round).to_le_bytes());
157    sign_bytes.extend(sha256(&canonical_block_id.encode_length_delimited_to_vec()));
158    sign_bytes.extend(&block_id.state_id);
159    sign_bytes.extend(header.chain_id.as_bytes());
160
161    let mut request = b"dpbvote".to_vec();
162    request.extend(height.to_le_bytes());
163    request.extend((proof.round as i32).to_le_bytes());
164
165    let mut message = vec![proof.quorum_type as u8];
166    message.extend(reversed(proof.quorum_hash.clone()));
167    message.extend(reversed(sha256(&request)));
168    message.extend(reversed(sha256(&sign_bytes)));
169    sha256(&sha256(&message))
170}
171
172/// Sign `proof` as it stands, as the test quorum it names.
173pub fn sign(proof: &mut TenderdashBlockProof) {
174    proof.signature = secret_key(&proof.quorum_hash)
175        .sign(&vote_sign_hash(proof))
176        .expect("a test key signs any digest")
177        .to_bytes()
178        .to_vec();
179}
180
181/// The block id Tenderdash derives from `header`.
182pub fn block_id_of(header: &Header) -> BlockId {
183    BlockId {
184        hash: header_hash(header).to_vec(),
185        part_set_total: 1,
186        part_set_hash: vec![0xdd; 32],
187        state_id: state_id_hash(header)
188            .expect("a test header has a time a state id can carry")
189            .to_vec(),
190    }
191}
192
193/// The proof of the block of `header`, signed by the test quorum `quorum_hash`.
194pub fn signed_proof_by(quorum_hash: [u8; 32], header: Header) -> TenderdashBlockProof {
195    let mut proof = TenderdashBlockProof {
196        block_id: Some(block_id_of(&header)),
197        header: Some(header),
198        round: 3,
199        quorum_hash: quorum_hash.to_vec(),
200        quorum_type: QUORUM_TYPE,
201        signature: Vec::new(),
202    };
203    sign(&mut proof);
204    proof
205}
206
207/// The proof of the block of `header`, signed by the test quorum [`QUORUM_HASH`].
208pub fn signed_proof(header: Header) -> TenderdashBlockProof {
209    signed_proof_by(QUORUM_HASH, header)
210}
211
212fn transaction_hashes(transactions: &[TestTransaction]) -> Vec<[u8; 32]> {
213    transactions
214        .iter()
215        .map(|(transaction, ..)| transaction_hash(transaction))
216        .collect()
217}
218
219fn result_leaves(transactions: &[TestTransaction]) -> Vec<Vec<u8>> {
220    transactions
221        .iter()
222        .map(|(_, code, data, gas_used)| result_leaf(*code, data, *gas_used))
223        .collect()
224}
225
226/// The header of a block at `height` that holds `transactions`, executed under the latest
227/// protocol version.
228pub fn header_of(height: u64, transactions: &[TestTransaction]) -> Header {
229    Header {
230        block_version: 14,
231        app_version: u64::from(PlatformVersion::latest().protocol_version),
232        chain_id: CHAIN_ID.to_string(),
233        height,
234        core_chain_locked_height: CORE_HEIGHT,
235        time_seconds: 1_722_265_200 + height as i64,
236        time_nanos: 123_456_789,
237        last_block_id: Some(BlockId {
238            hash: vec![0xaa; 32],
239            part_set_total: 2,
240            part_set_hash: vec![0xbb; 32],
241            state_id: vec![0xcc; 32],
242        }),
243        last_commit_hash: vec![1; 32],
244        data_hash: merkle_root(&transaction_hashes(transactions)).to_vec(),
245        validators_hash: vec![3; 32],
246        next_validators_hash: vec![4; 32],
247        consensus_hash: vec![5; 32],
248        next_consensus_hash: vec![6; 32],
249        app_hash: vec![7; 32],
250        results_hash: merkle_root(&result_leaves(transactions)).to_vec(),
251        evidence_hash: vec![9; 32],
252        proposer_pro_tx_hash: vec![10; 32],
253        proposed_app_version: 15,
254    }
255}
256
257/// The block an honest node returns from `getBlocks` when asked to prove the block of
258/// `header`, which holds `transactions`, signed by the test quorum `quorum_hash`. Start
259/// from [`header_of`] to give the block another protocol version or Core height.
260pub fn block_answer_of(
261    quorum_hash: [u8; 32],
262    header: Header,
263    transactions: &[TestTransaction],
264) -> Block {
265    let time_ms = header_time_ms(&header).expect("a test header has a time in milliseconds");
266    let block_id = block_id_of(&header);
267
268    Block {
269        height: header.height,
270        hash: block_id.hash,
271        time_ms,
272        core_chain_locked_height: header.core_chain_locked_height,
273        app_hash: header.app_hash.clone(),
274        proposer_pro_tx_hash: header.proposer_pro_tx_hash.clone(),
275        transactions: transactions
276            .iter()
277            .cloned()
278            .map(|(bytes, code, result_data, gas_used)| Transaction {
279                hash: transaction_hash(&bytes).to_vec(),
280                state_transition: bytes,
281                code,
282                result_data,
283                gas_used,
284            })
285            .collect(),
286        proof: Some(signed_proof_by(quorum_hash, header)),
287    }
288}
289
290/// [`block_answer_of`] the block at `height` under the latest protocol version.
291pub fn block_answer_by(
292    quorum_hash: [u8; 32],
293    height: u64,
294    transactions: &[TestTransaction],
295) -> Block {
296    block_answer_of(quorum_hash, header_of(height, transactions), transactions)
297}
298
299/// [`block_answer_by`] the test quorum [`QUORUM_HASH`].
300pub fn block_answer(height: u64, transactions: &[TestTransaction]) -> Block {
301    block_answer_by(QUORUM_HASH, height, transactions)
302}
303
304/// What an honest node answers `getOwnerTransactionsInBlock` with when asked to prove the
305/// transactions at `indexes` of the block of `header`, which holds `transactions`. The
306/// answer lists them in the order of `indexes`, each with the paths of its own position.
307pub fn owner_answer_of(
308    header: Header,
309    transactions: &[TestTransaction],
310    indexes: &[usize],
311) -> GetOwnerTransactionsInBlockResponseV0 {
312    let total = transactions.len() as u32;
313    let hashes = transaction_hashes(transactions);
314    let leaves = result_leaves(transactions);
315
316    let answered = indexes
317        .iter()
318        .filter_map(|&index| {
319            let (bytes, code, result_data, gas_used) = transactions.get(index)?.clone();
320            Some(OwnerTransaction {
321                hash: transaction_hash(&bytes).to_vec(),
322                state_transition: bytes,
323                code,
324                result_data,
325                gas_used,
326                proof: Some(TenderdashTransactionProof {
327                    index: index as u32,
328                    total,
329                    transaction_path: MerkleTree::new(&hashes, &[index]).paths.pop()?,
330                    result_path: MerkleTree::new(&leaves, &[index]).paths.pop()?,
331                }),
332            })
333        })
334        .collect();
335
336    GetOwnerTransactionsInBlockResponseV0 {
337        transactions: answered,
338        proof: Some(signed_proof(header)),
339    }
340}
341
342/// [`owner_answer_of`] the block at `height` under the latest protocol version.
343pub fn owner_answer(
344    height: u64,
345    transactions: &[TestTransaction],
346    indexes: &[usize],
347) -> GetOwnerTransactionsInBlockResponseV0 {
348    owner_answer_of(header_of(height, transactions), transactions, indexes)
349}