1use heika_block::{Block, BlockType};
7use heika_core::hash::Hash256;
8use heika_core::patricia;
9use heika_core::vrf::GenerationHash;
10use serde::{Deserialize, Serialize};
11
12use crate::transaction::TransactionInfo;
13use crate::{RestError, hex, hex_array, number};
14
15#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
17pub struct BlockInfo {
18 pub meta: BlockMeta,
19 pub block: BlockHeader,
20}
21
22#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct BlockMeta {
26 pub hash: String,
27 pub generation_hash: String,
28 pub total_fee: String,
29 pub state_hash_sub_cache_merkle_roots: Vec<String>,
31 pub total_transactions_count: u32,
32 pub transactions_count: u32,
33 pub statements_count: u32,
34}
35
36#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
38#[serde(rename_all = "camelCase")]
39pub struct BlockHeader {
40 pub size: u32,
42 pub signature: String,
43 pub signer_public_key: String,
44 pub version: u8,
45 pub network: u8,
46 #[serde(rename = "type")]
47 pub block_type: u16,
48 pub height: String,
49 pub timestamp: String,
50 pub difficulty: String,
51 pub proof_gamma: String,
52 pub proof_verification_hash: String,
53 pub proof_scalar: String,
54 pub previous_block_hash: String,
55 pub transactions_hash: String,
56 pub receipts_hash: String,
57 pub state_hash: String,
58 pub beneficiary_address: String,
59 pub fee_multiplier: u32,
60 #[serde(skip_serializing_if = "Option::is_none")]
61 pub voting_eligible_accounts_count: Option<u32>,
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub harvesting_eligible_accounts_count: Option<String>,
64 #[serde(skip_serializing_if = "Option::is_none")]
65 pub total_voting_balance: Option<String>,
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub previous_importance_block_hash: Option<String>,
68}
69
70impl BlockHeader {
71 pub fn to_header_bytes(&self) -> Result<Vec<u8>, RestError> {
73 let mut bytes = vec![0; 8];
74 bytes.extend_from_slice(&hex_array::<64>(&self.signature, "signature")?);
75 bytes.extend_from_slice(&hex_array::<32>(
76 &self.signer_public_key,
77 "signerPublicKey",
78 )?);
79 bytes.extend_from_slice(&[0; 4]);
80 bytes.push(self.version);
81 bytes.push(self.network);
82 bytes.extend_from_slice(&self.block_type.to_le_bytes());
83 for (text, field) in [
84 (&self.height, "height"),
85 (&self.timestamp, "timestamp"),
86 (&self.difficulty, "difficulty"),
87 ] {
88 bytes.extend_from_slice(&number(text, field)?.to_le_bytes());
89 }
90 bytes.extend_from_slice(&hex_array::<32>(&self.proof_gamma, "proofGamma")?);
91 bytes.extend_from_slice(&hex_array::<16>(
92 &self.proof_verification_hash,
93 "proofVerificationHash",
94 )?);
95 bytes.extend_from_slice(&hex_array::<32>(&self.proof_scalar, "proofScalar")?);
96 for (text, field) in [
97 (&self.previous_block_hash, "previousBlockHash"),
98 (&self.transactions_hash, "transactionsHash"),
99 (&self.receipts_hash, "receiptsHash"),
100 (&self.state_hash, "stateHash"),
101 ] {
102 bytes.extend_from_slice(&hex_array::<32>(text, field)?);
103 }
104 bytes.extend_from_slice(&hex_array::<24>(
105 &self.beneficiary_address,
106 "beneficiaryAddress",
107 )?);
108 bytes.extend_from_slice(&self.fee_multiplier.to_le_bytes());
109 match (
110 self.voting_eligible_accounts_count,
111 &self.harvesting_eligible_accounts_count,
112 &self.total_voting_balance,
113 &self.previous_importance_block_hash,
114 ) {
115 (Some(voting), Some(harvesting), Some(balance), Some(previous)) => {
116 bytes.extend_from_slice(&voting.to_le_bytes());
117 bytes.extend_from_slice(
118 &number(harvesting, "harvestingEligibleAccountsCount")?.to_le_bytes(),
119 );
120 bytes.extend_from_slice(&number(balance, "totalVotingBalance")?.to_le_bytes());
121 bytes.extend_from_slice(&hex_array::<32>(previous, "previousImportanceBlockHash")?);
122 }
123 (None, None, None, None) => bytes.extend_from_slice(&[0; 4]),
124 _ => {
125 return Err(RestError::InvalidValue {
126 field: "previousImportanceBlockHash",
127 });
128 }
129 }
130 let size = bytes.len() as u32;
131 bytes[..4].copy_from_slice(&size.to_le_bytes());
132 Ok(bytes)
133 }
134}
135
136impl TryFrom<&BlockHeader> for Block {
138 type Error = RestError;
139
140 fn try_from(header: &BlockHeader) -> Result<Self, Self::Error> {
141 Block::from_bytes(&header.to_header_bytes()?).map_err(RestError::InvalidBlock)
142 }
143}
144
145impl BlockInfo {
146 pub fn verify(&self) -> Result<Block, RestError> {
153 let block = Block::try_from(&self.block)?;
154 if !block.verify_signature() {
155 return Err(RestError::Mismatch { field: "signature" });
156 }
157 if block.hash() != Hash256(hex_array(&self.meta.hash, "meta.hash")?) {
158 return Err(RestError::Mismatch { field: "meta.hash" });
159 }
160 let generation_hash = GenerationHash(hex_array(
161 &self.meta.generation_hash,
162 "meta.generationHash",
163 )?);
164 if block.generation_hash() != generation_hash {
165 return Err(RestError::Mismatch {
166 field: "meta.generationHash",
167 });
168 }
169 if block.state_hash != self.state_hash()? {
170 return Err(RestError::Mismatch { field: "stateHash" });
171 }
172 Ok(block)
173 }
174
175 pub fn assemble(&self, found: &[TransactionInfo]) -> Result<Vec<u8>, RestError> {
185 let height = number(&self.block.height, "height")?;
186 let mut outer = Vec::new();
187 for entry in found {
188 if entry.meta.aggregate_hash.is_some() {
189 continue;
190 }
191 let at = entry.meta.height.as_deref().ok_or(RestError::Missing {
192 field: "meta.height",
193 })?;
194 if number(at, "meta.height")? == height {
195 outer.push(entry);
196 }
197 }
198 outer.sort_by_key(|entry| entry.meta.index);
199 if outer.len() != self.meta.transactions_count as usize
200 || outer
201 .iter()
202 .enumerate()
203 .any(|(index, entry)| entry.meta.index != Some(index as u32))
204 {
205 return Err(RestError::Mismatch {
206 field: "meta.transactionsCount",
207 });
208 }
209
210 let mut bytes = self.block.to_header_bytes()?;
211 for (index, entry) in outer.iter().enumerate() {
212 if index > 0 {
213 bytes.resize(bytes.len().next_multiple_of(8), 0);
214 }
215 let transaction = if matches!(entry.transaction.transaction_type, 0x4141 | 0x4241) {
216 entry.with_embedded(found)?.transaction.to_bytes()?
217 } else {
218 entry.transaction.to_bytes()?
219 };
220 bytes.extend_from_slice(&transaction);
221 }
222 let size = self.block.size as usize;
224 if bytes.len() < size && size - bytes.len() < 8 {
225 bytes.resize(size, 0);
226 }
227 if bytes.len() != size {
228 return Err(RestError::Mismatch {
229 field: "block.size",
230 });
231 }
232 bytes[..4].copy_from_slice(&self.block.size.to_le_bytes());
233 Ok(bytes)
234 }
235
236 pub fn sub_cache_merkle_roots(&self) -> Result<Vec<Hash256>, RestError> {
238 self.meta
239 .state_hash_sub_cache_merkle_roots
240 .iter()
241 .map(|root| hex_array(root, "meta.stateHashSubCacheMerkleRoots").map(Hash256))
242 .collect()
243 }
244
245 fn state_hash(&self) -> Result<Hash256, RestError> {
247 let roots = self.sub_cache_merkle_roots()?;
248 if roots.is_empty() {
249 return Ok(Hash256([0; 32]));
250 }
251 let roots: [Hash256; 9] = roots.try_into().map_err(|_| RestError::InvalidValue {
252 field: "meta.stateHashSubCacheMerkleRoots",
253 })?;
254 Ok(patricia::state_hash(&roots))
255 }
256}
257
258impl From<&Block> for BlockHeader {
260 fn from(block: &Block) -> Self {
261 let footer = block.importance_footer.as_ref();
262 Self {
263 size: block.as_bytes().len() as u32,
264 signature: block.signature.to_string(),
265 signer_public_key: block.signer_public_key.to_string(),
266 version: block.version,
267 network: block.network.0,
268 block_type: match block.block_type {
269 BlockType::Nemesis => 0x8043,
270 BlockType::Normal => 0x8143,
271 BlockType::Importance => 0x8243,
272 },
273 height: block.height.to_string(),
274 timestamp: block.timestamp.to_string(),
275 difficulty: block.difficulty.to_string(),
276 proof_gamma: hex(&block.generation_hash_proof.gamma),
277 proof_verification_hash: hex(&block.generation_hash_proof.verification_hash),
278 proof_scalar: hex(&block.generation_hash_proof.scalar),
279 previous_block_hash: block.previous_block_hash.to_string(),
280 transactions_hash: block.transactions_hash.to_string(),
281 receipts_hash: block.receipts_hash.to_string(),
282 state_hash: block.state_hash.to_string(),
283 beneficiary_address: block.beneficiary_address.to_hex(),
284 fee_multiplier: block.fee_multiplier,
285 voting_eligible_accounts_count: footer
286 .map(|footer| footer.voting_eligible_accounts_count),
287 harvesting_eligible_accounts_count: footer
288 .map(|footer| footer.harvesting_eligible_accounts_count.to_string()),
289 total_voting_balance: footer.map(|footer| footer.total_voting_balance.to_string()),
290 previous_importance_block_hash: footer
291 .map(|footer| footer.previous_importance_block_hash.to_string()),
292 }
293 }
294}