1use std::fmt;
15
16use heika_block::scoring::{self, BlockStatistic};
17use heika_block::statement::BlockStatement;
18use heika_block::{Block, BlockType};
19use heika_core::address::Address;
20use heika_core::hash::Hash256;
21use heika_core::key::{PrivateKey, PublicKey};
22use heika_core::network::NetworkParameters;
23use heika_core::vrf::{self, GenerationHash};
24use heika_transaction::Transaction;
25
26use crate::verify::{
27 MAX_TRANSACTIONS_PER_BLOCK, Tip, VerifyError, verify_next, verify_transaction,
28};
29use heika_state_transition::executor::{ExecError, Executor};
30
31const NORMAL_HEADER_SIZE: usize = 376;
33const IMPORTANCE_HEADER_SIZE: usize = 424;
35const SIGNED_FROM: usize = 108;
37const NORMAL_SIGNED_TO: usize = 372;
39const BLOCK_VERSION: u8 = 1;
41
42pub struct Decisions {
44 pub timestamp: u64,
46 pub transactions: Vec<Vec<u8>>,
48 pub beneficiary: Address,
49 pub fee_multiplier: u32,
50}
51
52#[derive(Clone, Debug)]
54pub struct Slot {
55 pub height: u64,
56 pub timestamp: u64,
58 pub signer: PublicKey,
60 pub harvester: Address,
62 pub beneficiary: Address,
63 pub fee_multiplier: u32,
64 pub inflation: u64,
66 pub beneficiary_percentage: u64,
69}
70
71impl Slot {
72 pub fn beneficiary_amount(&self, transactions: &[Vec<u8>]) -> u64 {
75 let fee: u64 = transactions
76 .iter()
77 .map(|bytes| bytes.len() as u64 * u64::from(self.fee_multiplier))
78 .sum();
79 (fee + self.inflation) * self.beneficiary_percentage / 100
80 }
81}
82
83pub trait Assemble: Send + Sync {
87 fn fee_multiplier(&self, slot: &Slot) -> u32 {
91 slot.fee_multiplier
92 }
93
94 fn assemble(&self, slot: &Slot, chosen: Vec<Vec<u8>>) -> Vec<Vec<u8>>;
96}
97
98pub struct Parent<'a> {
100 pub block: &'a Block,
101 pub generation_hash: GenerationHash,
102 pub recent: &'a [BlockStatistic],
104 pub importance_hash: Hash256,
106}
107
108#[derive(Debug)]
110pub enum ProduceError {
111 Proof,
113 Exec(ExecError),
115 Encode(String),
117 Verify(VerifyError),
120}
121
122impl fmt::Display for ProduceError {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 match self {
125 Self::Proof => write!(f, "VRF の証明が作れません"),
126 Self::Exec(error) => write!(f, "{error}"),
127 Self::Encode(what) => write!(f, "組んだブロックが読めません: {what}"),
128 Self::Verify(error) => write!(f, "組んだブロックが確かめを通りません: {error}"),
129 }
130 }
131}
132
133impl std::error::Error for ProduceError {}
134
135impl From<ExecError> for ProduceError {
136 fn from(error: ExecError) -> Self {
137 Self::Exec(error)
138 }
139}
140
141#[derive(Clone, Debug)]
143pub struct Candidate {
144 pub bytes: Vec<u8>,
145 pub fee_multiplier: u32,
147 count: usize,
149 hash: Hash256,
150}
151
152impl Candidate {
153 pub fn new(
156 parameters: &NetworkParameters,
157 height: u64,
158 bytes: Vec<u8>,
159 ) -> Result<Self, VerifyError> {
160 let count = verify_transaction(parameters, height, 0, &bytes)?;
161 let transaction = Transaction::from_bytes(&bytes)
162 .map_err(|error| VerifyError::Transaction(error.to_string()))?;
163 let fee_multiplier =
164 u32::try_from(transaction.fee / bytes.len() as u64).unwrap_or(u32::MAX);
165 Ok(Self {
166 hash: transaction.hash(¶meters.generation_hash_seed),
167 bytes,
168 fee_multiplier,
169 count,
170 })
171 }
172
173 pub fn hash(&self) -> Hash256 {
174 self.hash
175 }
176}
177
178pub trait Pending {
181 fn candidates(&self, timestamp: u64) -> Vec<Candidate>;
183}
184
185pub fn choose(candidates: &[Candidate], min_fee_multiplier: u32) -> (Vec<Candidate>, u32) {
190 let mut sorted: Vec<&Candidate> = candidates
191 .iter()
192 .filter(|candidate| candidate.fee_multiplier >= min_fee_multiplier)
193 .collect();
194 sorted.sort_by(|a, b| {
195 b.fee_multiplier
196 .cmp(&a.fee_multiplier)
197 .then(a.hash.0.cmp(&b.hash.0))
198 });
199 let (mut best, mut best_fee) = (0, 0u128);
200 let (mut size, mut count) = (0u128, 0);
201 for (index, candidate) in sorted.iter().enumerate() {
202 count += candidate.count;
203 if count > MAX_TRANSACTIONS_PER_BLOCK {
204 break;
205 }
206 size += candidate.bytes.len() as u128;
207 let fee = u128::from(candidate.fee_multiplier) * size;
208 if fee >= best_fee {
209 (best, best_fee) = (index + 1, fee);
210 }
211 }
212 let chosen: Vec<Candidate> = sorted[..best].iter().map(|&c| c.clone()).collect();
213 let fee_multiplier = chosen.last().map_or(0, |last| last.fee_multiplier);
214 (chosen, fee_multiplier)
215}
216
217pub fn produce(
221 executor: &mut Executor,
222 parameters: &NetworkParameters,
223 parent: &Parent,
224 signing: &PrivateKey,
225 vrf_key: &PrivateKey,
226 decisions: &Decisions,
227) -> Result<Block, ProduceError> {
228 produce_with_statement(executor, parameters, parent, signing, vrf_key, decisions)
229 .map(|(block, _)| block)
230}
231
232pub fn produce_with_statement(
234 executor: &mut Executor,
235 parameters: &NetworkParameters,
236 parent: &Parent,
237 signing: &PrivateKey,
238 vrf_key: &PrivateKey,
239 decisions: &Decisions,
240) -> Result<(Block, BlockStatement), ProduceError> {
241 let proof = vrf::prove(vrf_key, &parent.generation_hash.0).ok_or(ProduceError::Proof)?;
242 let (mut bytes, block_type) = assemble(parameters, parent, signing, &proof, decisions)?;
243 let candidate = decode(&bytes)?;
244
245 executor.check_harvester(
247 parent.block,
248 &parent.generation_hash,
249 &candidate,
250 parameters,
251 )?;
252 let produced = executor.apply_produced(&candidate)?;
253 bytes[280..312].copy_from_slice(&produced.receipts_hash.0);
254 bytes[312..344].copy_from_slice(&produced.state_hash.0);
255 if let Some((voting, harvesting, balance)) = produced.footer {
256 bytes[372..376].copy_from_slice(&voting.to_le_bytes());
257 bytes[376..384].copy_from_slice(&harvesting.to_le_bytes());
258 bytes[384..392].copy_from_slice(&balance.to_le_bytes());
259 }
260 let signed_to = match block_type {
261 BlockType::Importance => IMPORTANCE_HEADER_SIZE,
262 _ => NORMAL_SIGNED_TO,
263 };
264 let signature = signing.sign(&[&bytes[SIGNED_FROM..signed_to]]);
265 bytes[8..72].copy_from_slice(&signature.0);
266 let block = decode(&bytes)?;
267
268 let tip = Tip {
270 height: parent.block.height,
271 hash: parent.block.hash(),
272 importance_hash: parent.importance_hash,
273 };
274 verify_next(parameters, Some(tip), &block).map_err(ProduceError::Verify)?;
275 Ok((block, produced.statement))
276}
277
278pub fn draft(
280 parameters: &NetworkParameters,
281 parent: &Parent,
282 signing: &PrivateKey,
283 vrf_key: &PrivateKey,
284 decisions: &Decisions,
285) -> Result<Block, ProduceError> {
286 let proof = vrf::prove(vrf_key, &parent.generation_hash.0).ok_or(ProduceError::Proof)?;
287 let (bytes, _) = assemble(parameters, parent, signing, &proof, decisions)?;
288 decode(&bytes)
289}
290
291pub fn earliest_hit(
295 executor: &Executor,
296 parameters: &NetworkParameters,
297 parent: &Parent,
298 signing: &PrivateKey,
299 vrf_key: &PrivateKey,
300 until: u64,
301) -> Result<Option<u64>, ProduceError> {
302 let gamma = vrf::gamma(vrf_key, &parent.generation_hash.0).ok_or(ProduceError::Proof)?;
303 let hit = scoring::hit(&vrf::proof_hash(&gamma).generation_hash());
304 let importance = executor.signer_importance(
305 &PublicKey::from_private_key(signing),
306 parent.block.height + 1,
307 )?;
308 let seconds = scoring::earliest_hit_seconds(
309 hit,
310 scoring::difficulty(parent.recent, parameters),
311 importance,
312 until.saturating_sub(parent.block.timestamp) / 1000,
313 parameters,
314 );
315 Ok(seconds.map(|seconds| parent.block.timestamp + seconds * 1000))
316}
317
318fn assemble(
320 parameters: &NetworkParameters,
321 parent: &Parent,
322 signing: &PrivateKey,
323 proof: &vrf::VrfProof,
324 decisions: &Decisions,
325) -> Result<(Vec<u8>, BlockType), ProduceError> {
326 let height = parent.block.height + 1;
327 let block_type = if height.is_multiple_of(parameters.importance_grouping) {
328 BlockType::Importance
329 } else {
330 BlockType::Normal
331 };
332 let header_size = match block_type {
333 BlockType::Importance => IMPORTANCE_HEADER_SIZE,
334 _ => NORMAL_HEADER_SIZE,
335 };
336 let mut bytes = vec![0u8; header_size];
337 bytes[72..104].copy_from_slice(&PublicKey::from_private_key(signing).0);
338 bytes[108] = BLOCK_VERSION;
339 bytes[109] = parameters.identifier.0;
340 bytes[110..112].copy_from_slice(&block_type_code(block_type).to_le_bytes());
341 bytes[112..120].copy_from_slice(&height.to_le_bytes());
342 bytes[120..128].copy_from_slice(&decisions.timestamp.to_le_bytes());
343 bytes[128..136].copy_from_slice(&scoring::difficulty(parent.recent, parameters).to_le_bytes());
344 bytes[136..168].copy_from_slice(&proof.gamma);
345 bytes[168..184].copy_from_slice(&proof.verification_hash);
346 bytes[184..216].copy_from_slice(&proof.scalar);
347 bytes[216..248].copy_from_slice(&parent.block.hash().0);
348 bytes[344..368].copy_from_slice(&decisions.beneficiary.0);
349 bytes[368..372].copy_from_slice(&decisions.fee_multiplier.to_le_bytes());
350 if block_type == BlockType::Importance {
351 bytes[392..424].copy_from_slice(&parent.importance_hash.0);
352 }
353 for (index, transaction) in decisions.transactions.iter().enumerate() {
355 bytes.extend_from_slice(transaction);
356 if index + 1 < decisions.transactions.len() {
357 bytes.resize(bytes.len().next_multiple_of(8), 0);
358 }
359 }
360 let size =
361 u32::try_from(bytes.len()).map_err(|_| ProduceError::Encode("大きすぎます".into()))?;
362 bytes[0..4].copy_from_slice(&size.to_le_bytes());
363
364 let candidate = decode(&bytes)?;
365 let transactions_hash = candidate
366 .calculate_transactions_hash(¶meters.generation_hash_seed)
367 .map_err(|error| ProduceError::Encode(error.to_string()))?;
368 bytes[248..280].copy_from_slice(&transactions_hash.0);
369 Ok((bytes, block_type))
370}
371
372fn decode(bytes: &[u8]) -> Result<Block, ProduceError> {
373 Block::from_bytes(bytes).map_err(|error| ProduceError::Encode(error.to_string()))
374}
375
376fn block_type_code(block_type: BlockType) -> u16 {
378 match block_type {
379 BlockType::Nemesis => 0x8043,
380 BlockType::Normal => 0x8143,
381 BlockType::Importance => 0x8243,
382 }
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 fn candidate(fee_multiplier: u32, size: usize, tag: u8) -> Candidate {
390 Candidate {
391 bytes: vec![0; size],
392 fee_multiplier,
393 count: 1,
394 hash: Hash256([tag; 32]),
395 }
396 }
397
398 #[test]
399 fn beneficiary_amount_matches_the_harvest_fee_split() {
400 let slot = Slot {
401 height: 2,
402 timestamp: 0,
403 signer: PublicKey([1; 32]),
404 harvester: Address([2; 24]),
405 beneficiary: Address([3; 24]),
406 fee_multiplier: 100,
407 inflation: 73_210_170,
408 beneficiary_percentage: 25,
409 };
410 let transactions = [vec![0; 176], vec![0; 200]];
412 assert_eq!(slot.beneficiary_amount(&transactions), 18_311_942);
413 let alone = Slot {
415 beneficiary_percentage: 0,
416 ..slot
417 };
418 assert_eq!(alone.beneficiary_amount(&transactions), 0);
419 }
420
421 #[test]
422 fn chooses_the_prefix_with_the_largest_total_fee() {
423 let candidates = [
425 candidate(50, 1000, 1),
426 candidate(100, 200, 2),
427 candidate(10, 100, 3),
428 ];
429 let (chosen, multiplier) = choose(&candidates, 0);
430 let tags: Vec<u8> = chosen.iter().map(|c| c.hash.0[0]).collect();
431 assert_eq!((tags, multiplier), (vec![2, 1], 50));
432 let (chosen, multiplier) = choose(&candidates, 60);
434 assert_eq!((chosen.len(), multiplier), (1, 100));
435 assert_eq!(choose(&[], 0).1, 0);
437 }
438
439 #[test]
440 fn stops_at_the_transaction_count_limit() {
441 let candidates: Vec<_> = (0..MAX_TRANSACTIONS_PER_BLOCK + 5)
442 .map(|index| Candidate {
443 hash: Hash256([0; 32].map(|_: u8| (index % 251) as u8)),
444 ..candidate(100, 100, 0)
445 })
446 .collect();
447 assert_eq!(choose(&candidates, 0).0.len(), MAX_TRANSACTIONS_PER_BLOCK);
448 }
449}