nimiq-consensus 2.2.0

Consensus logic of Nimiq's Albatross implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! Contains implementations of request handlers for consensus-related message types.
//!
//! Each handler defines how to respond to a specific request (e.g., block, head, macro chain,
//! missing blocks, history chunk) by interacting with the local blockchain state.
//! These handlers are registered to process incoming network requests during consensus and syncing operations.

#[cfg(feature = "full")]
use std::convert::TryFrom;
#[cfg(feature = "full")]
use std::sync::Arc;
use std::{cmp, collections::HashSet};

use nimiq_block::Block;
#[cfg(feature = "full")]
use nimiq_block::BlockInclusionProof;
#[cfg(feature = "full")]
use nimiq_blockchain::interface::{HistoryIndexInterface, HistoryInterface};
#[cfg(feature = "full")]
use nimiq_blockchain::{Blockchain, CHUNK_SIZE};
#[cfg(feature = "full")]
use nimiq_blockchain_interface::BlockchainError;
use nimiq_blockchain_interface::{AbstractBlockchain, Direction};
use nimiq_blockchain_proxy::BlockchainProxy;
use nimiq_network_interface::{network::Network, request::Handle};
use nimiq_primitives::policy::Policy;
#[cfg(feature = "full")]
use nimiq_primitives::trie::error::IncompleteTrie;
#[cfg(feature = "full")]
use parking_lot::RwLock;

use crate::messages::*;
#[cfg(feature = "full")]
use crate::sync::live::{
    diff_queue::{RequestTrieDiff, ResponseTrieDiff},
    state_queue::{Chunk, RequestChunk, ResponseChunk},
};

impl RequestMacroChain {
    const MAX_LOCATORS: usize = 100;
    const MAX_EPOCHS: u32 = 255;
}
impl<N: Network> Handle<N, BlockchainProxy> for RequestMacroChain {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &BlockchainProxy,
    ) -> Result<MacroChain, MacroChainError> {
        // Validate request.
        if self.locators.len() > Self::MAX_LOCATORS {
            return Err(MacroChainError::TooManyLocators);
        }

        // A peer has the macro chain. Check all block locator hashes in the given order and pick
        // the first hash that is found on our main chain, ignore the rest.
        let blockchain = blockchain.read();
        let mut start_block_hash = None;
        for locator in self.locators.iter() {
            let chain_info = blockchain.get_chain_info(locator, false);
            if let Ok(chain_info) = chain_info
                && chain_info.on_main_chain
            {
                // Validate that the locator is a macro block before using it.
                // This prevents panics when get_macro_blocks() is called with a micro block hash.
                if let Ok(block) = blockchain.get_block(locator, false)
                    && block.is_macro()
                {
                    // We found a macro block on the main chain, use it.
                    start_block_hash = Some(locator.clone());
                    break;
                }
                // Skip micro blocks and continue searching for a macro block.
            }
        }
        let Some(start_block_hash) = start_block_hash else {
            return Err(MacroChainError::UnknownLocators);
        };
        // Get up to `self.max_blocks` macro blocks from our chain starting at `start_block_hash`.
        // TODO We don't need the actual macro block headers here, the hash of each block would suffice.
        let election_blocks = blockchain
            .get_macro_blocks(
                &start_block_hash,
                u32::min(self.max_epochs as u32, Self::MAX_EPOCHS),
                false,
                Direction::Forward,
                true,
            )
            .unwrap(); // Safe: We validated that start_block_hash is a macro block on our chain.
        let epochs: Vec<_> = election_blocks.iter().map(|block| block.hash()).collect();

        // Add latest checkpoint block if all of the following conditions are met:
        // * the latest macro block is a checkpoint block.
        // * the latest macro block is not the locator given by the requester.
        // * the requester has caught up, i.e. it already knows the most recent epoch (epochs.is_empty())
        //   or we are returning the most recent epoch as part of this response.
        let checkpoint_block = blockchain.macro_head();
        let checkpoint_hash = blockchain.macro_head_hash();
        let caught_up = epochs.is_empty()
            || *epochs.last().unwrap() == checkpoint_block.header.parent_election_hash;
        let checkpoint = if !checkpoint_block.is_election()
            && checkpoint_hash != start_block_hash
            && caught_up
        {
            Some(Checkpoint {
                block_number: checkpoint_block.block_number(),
                hash: checkpoint_hash,
            })
        } else {
            None
        };

        Ok(MacroChain { epochs, checkpoint })
    }
}

#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestBatchSet {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &Arc<RwLock<Blockchain>>,
    ) -> Result<BatchSetInfo, BatchSetError> {
        let blockchain = blockchain.read();

        // Fetch the block corresponding to the given hash and ensure it is a macro block.
        // Return an error if it is a micro block or the hash is not found.
        let block = match blockchain.get_block(&self.hash, true, None) {
            Ok(Block::Macro(block)) => block,
            Ok(Block::Micro(_)) => return Err(BatchSetError::MicroBlockGiven),
            Err(_) => return Err(BatchSetError::TargetHashNotFound),
        };

        let prove_history_len =
            |batch_set_hash: &Blake2bHash, block_number: u32| -> Result<_, BatchSetError> {
                blockchain
                    .history_store
                    .prove_num_leaves(block_number, None)
                    .map_err(|error| {
                        log::error!(
                            error = ?error,
                            requested_hash = %self.hash,
                            batch_set_hash = %batch_set_hash,
                            block_number,
                            "Failed to prove history size for batch set request"
                        );
                        BatchSetError::CouldntProduceHistorySizeProof
                    })
            };

        // Try to get the epoch chunk hashes following the given macro block.
        // For each hash, fetch the macro block and its history length, and build a batch set.
        // If there are no chunks, create a single batch set with the provided block.
        let batch_sets = if let Ok(macro_hashes) = blockchain
            .chain_store
            .get_epoch_chunks(block.block_number(), None)
        {
            // Build a list of batch sets for the given macro blocks.
            // For each macro block in the current epoch, retrieve the full block and its associated history length.
            // These are bundled into `BatchSet` items and collected into a vector.
            let mut batch_sets = vec![];
            for macro_hash in macro_hashes {
                let macro_block = blockchain
                    .get_block(&macro_hash, true, None)
                    .expect("Macro block must exist since it can't be pruned");

                let history_len = prove_history_len(&macro_hash, macro_block.block_number())?;

                let batch_set = BatchSet {
                    macro_block: macro_block.unwrap_macro(),
                    history_len,
                };
                batch_sets.push(batch_set);
            }
            batch_sets
        } else {
            // If there are no epoch chunks, create a single batch set from the given macro block.
            let history_len = prove_history_len(&self.hash, block.block_number())?;

            let batch_set = BatchSet {
                macro_block: block.clone(),
                history_len,
            };
            vec![batch_set]
        };

        // FIXME Don't send the same macro block twice.
        let election_macro_block = if block.is_election() {
            Some(block)
        } else {
            None
        };

        Ok(BatchSetInfo {
            election_macro_block,
            batch_sets,
        })
    }
}

#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestHistoryChunk {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &Arc<RwLock<Blockchain>>,
    ) -> Result<HistoryChunk, HistoryChunkError> {
        let Ok(chunk_index) = usize::try_from(self.chunk_index) else {
            return Err(HistoryChunkError::CouldntProduceProof);
        };

        // Attempt to retrieve a proof for the requested history chunk.
        if let Some(chunk) = blockchain.read().history_store.prove_chunk(
            self.epoch_number,
            self.block_number,
            CHUNK_SIZE,
            chunk_index,
            None,
        ) {
            // Return the chunk if the proof was successfully generated.
            Ok(HistoryChunk { chunk })
        } else {
            // Return an error if the proof could not be produced.
            Err(HistoryChunkError::CouldntProduceProof)
        }
    }
}

impl<N: Network> Handle<N, BlockchainProxy> for RequestBlock {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &BlockchainProxy,
    ) -> Result<Block, BlockError> {
        // Attempt to retrieve the requested block from the blockchain.
        // The block body is included if `include_body` is true.
        // If the block is not found, return an error.
        blockchain
            .read()
            .get_block(&self.hash, self.include_body)
            .map_err(|_| BlockError::TargetHashNotFound)
    }
}

impl<N: Network> Handle<N, BlockchainProxy> for RequestMissingBlocks {
    fn handle(
        &self,
        peer_id: N::PeerId,
        blockchain: &BlockchainProxy,
    ) -> Result<ResponseBlocks, ResponseBlocksError> {
        // Validate request.
        if self.locators.len() > Self::MAX_LOCATORS {
            return Err(ResponseBlocksError::TooManyLocators);
        }

        match self.direction {
            Direction::Forward => self.handle_forward::<N>(peer_id, blockchain),
            Direction::Backward => self.handle_backward::<N>(peer_id, blockchain),
        }
    }
}
impl RequestMissingBlocks {
    const MAX_LOCATORS: usize = 100;

    fn handle_backward<N: Network>(
        &self,
        _request_id: N::PeerId,
        blockchain: &BlockchainProxy,
    ) -> Result<ResponseBlocks, ResponseBlocksError> {
        // TODO We might want to do a sanity check on the locator hashes and reject the request if
        //  they they don't match up with the given target hash.

        // Build a HashSet from the given locator hashes.
        let locators = HashSet::<Blake2bHash>::from_iter(self.locators.iter().cloned());

        // Walk the chain backwards from the target block until we find one of the locators or
        // encounter a macro block. Return all blocks between the locator block (exclusive) and the
        // target block (inclusive). If we stopped at a macro block instead of a locator, the macro
        // block is included in the result.
        let mut blocks = Vec::new();
        let mut block_hash = self.target_hash.clone();

        // Take a blockchain read lock.
        let blockchain = blockchain.read();

        while !locators.contains(&block_hash) {
            let block = blockchain.get_block(&block_hash, self.include_body);
            if let Ok(block) = block {
                let is_macro = block.is_macro();

                block_hash = block.parent_hash().clone();
                blocks.push(block);

                if is_macro {
                    break;
                }
            } else {
                // This can only happen if the target hash is unknown or after the chain was pruned.
                debug!(
                    blocks_found = blocks.len(),
                    unknown_block_hash = %block_hash,
                    "ResponseBlocks - unknown target block/predecessor",
                );
                return Err(ResponseBlocksError::TargetHashNotFound);
            }
        }

        // Blocks are returned in ascending (forward) order.
        blocks.reverse();

        Ok(ResponseBlocks { blocks })
    }

    fn handle_forward<N: Network>(
        &self,
        _peer_id: N::PeerId,
        blockchain: &BlockchainProxy,
    ) -> Result<ResponseBlocks, ResponseBlocksError> {
        let blockchain = blockchain.read();

        // Check that we know the target hash and that it is located on our main chain.
        let target_block = match blockchain.get_chain_info(&self.target_hash, false) {
            Ok(target_block) => {
                if !target_block.on_main_chain {
                    debug!(
                        target_hash = %self.target_hash,
                        "ResponseBlocks - target block not on main chain",
                    );
                    return Err(ResponseBlocksError::TargetBlockNotOnMainChain);
                }
                target_block
            }
            Err(error) => {
                debug!(
                    %error,
                    target_hash = %self.target_hash,
                    "ResponseBlocks - target hash not found",
                );
                return Err(ResponseBlocksError::TargetHashNotFound);
            }
        };

        // Find the first locator that is on our main chain.
        // The locators are ordered from newest to oldest block.
        let mut start_hash = None;
        let mut start_block_number = None;
        for locator in self.locators.iter() {
            if let Ok(chain_info) = blockchain.get_chain_info(locator, false)
                && chain_info.on_main_chain
            {
                start_hash = Some(locator.clone());
                start_block_number = Some(chain_info.head.block_number());
                break;
            }
        }

        // If there is no match, reject the request.
        if start_hash.is_none() {
            debug!("ResponseBlocks - unknown locators",);
            return Err(ResponseBlocksError::UnknownLocators);
        }
        let start_block_number = start_block_number.unwrap();
        let start_hash = start_hash.unwrap();

        // Get at most one batch of blocks from there.
        let next_macro_block = Policy::macro_block_after(start_block_number);
        let num_blocks = cmp::min(
            next_macro_block - start_block_number,
            target_block
                .head
                .block_number()
                .saturating_sub(start_block_number),
        );

        // If the number of blocks to return is 0, we return early.
        if num_blocks == 0 {
            return Ok(ResponseBlocks { blocks: vec![] });
        }

        // Fetch the requested blocks from the chain.
        let blocks = match blockchain.get_blocks(
            &start_hash,
            num_blocks,
            self.include_body,
            Direction::Forward,
        ) {
            Ok(blocks) => blocks,
            Err(error) => {
                debug!(
                    %error,
                    start_hash = %start_hash,
                    num_blocks,
                    "ResponseBlocks - Failed to get blocks",
                );
                return Err(ResponseBlocksError::FailedToGetBlocks);
            }
        };

        Ok(ResponseBlocks { blocks })
    }
}

impl<N: Network> Handle<N, BlockchainProxy> for RequestHead {
    fn handle(&self, _peer_id: N::PeerId, blockchain: &BlockchainProxy) -> ResponseHead {
        let blockchain = blockchain.read();
        // Read blockchain state and return the current head information
        ResponseHead {
            block_number: blockchain.block_number(),
            block_hash: blockchain.head_hash(),
            macro_hash: blockchain.macro_head_hash(),
            election_hash: blockchain.election_head_hash(),
        }
    }
}

#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestChunk {
    fn handle(&self, _peer_id: N::PeerId, blockchain: &Arc<RwLock<Blockchain>>) -> ResponseChunk {
        let blockchain_rg = blockchain.read();

        // Check if our state is complete.
        let txn = blockchain_rg.read_transaction();
        if !blockchain_rg.state.accounts.is_complete(Some(&txn)) {
            return ResponseChunk::IncompleteState;
        }

        // Request a chunk of the accounts state starting at the specified key,
        // up to the defined limit (bounded by the protocol maximum).
        let chunk = blockchain_rg.state.accounts.get_chunk(
            self.start_key.clone(),
            cmp::min(self.limit, Policy::state_chunks_max_size()) as usize,
            Some(&txn),
        );
        ResponseChunk::Chunk(Chunk {
            block_number: blockchain_rg.block_number(),
            block_hash: blockchain_rg.head_hash(),
            chunk,
        })
    }
}

#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestTrieDiff {
    fn handle(&self, _peer_id: N::PeerId, context: &Arc<RwLock<Blockchain>>) -> ResponseTrieDiff {
        // TODO return the requested range only
        let blockchain = context.read();
        let txn = blockchain.read_transaction();
        match blockchain
            .chain_store
            .get_accounts_diff(&self.block_hash, Some(&txn))
        {
            Ok(diff) => ResponseTrieDiff::PartialDiff(diff),
            Err(BlockchainError::BlockNotFound(..)) => ResponseTrieDiff::UnknownBlockHash,
            Err(BlockchainError::AccountsDiffNotFound) => ResponseTrieDiff::IncompleteState,
            Err(e) => {
                error!("unexpected error while querying accounts diff: {}", e);
                ResponseTrieDiff::IncompleteState
            }
        }
    }
}

impl RequestTransactionsProof {
    const MAX_TRANSACTIONS: usize = 255;

    #[cfg(feature = "full")]
    /// Proves inclusion of transactions for a specific block number.
    fn prove_txns_with_block_number(
        blockchain: &Arc<RwLock<Blockchain>>,
        transactions: &[Blake2bHash],
        block_number: u32,
    ) -> Result<ResponseTransactionsProof, ResponseTransactionProofError> {
        let blockchain = blockchain.read();
        let Some(history_index) = blockchain.history_store.history_index() else {
            log::info!("Cannot create transaction proof without history index");
            return Err(ResponseTransactionProofError::Other);
        };
        let hashes: Vec<&Blake2bHash> = transactions.iter().collect();

        // There are three possible scenarios for creating a transaction inclusion proof:
        // A- The block number is located in a finalized epoch:
        //    We use the epoch's finalization block (election block)
        // B- The block number is located in an incomplete epoch with an already finalized checkpoint block
        //    We use the batch's checkpoint block, with the current transaction count to construct the proof
        // C- The block number is located in the current batch:
        //    We use the current transaction count to construct the proof

        let mut verifier_state = None;
        let election_head = blockchain.election_head().block_number();
        let macro_head = blockchain.macro_head().block_number();
        let current_head = blockchain.head().block_number();

        // We cannot prove transactions from the future
        if block_number > current_head {
            log::info!(
                current_head,
                requested_block_number = block_number,
                "Requested txn proof from the future",
            );
            return Err(ResponseTransactionProofError::RequestedTxnProofFromFuture(
                block_number,
                current_head,
            ));
        }

        let proving_block_number = if Policy::is_election_block_at(block_number) {
            // If we were provided the block number of an election block it has to be already finalized
            log::info!(
                election_block_number = block_number,
                len = hashes.len(),
                "Requested txn proof from finalized epoch",
            );
            block_number
        } else if Policy::is_macro_block_at(block_number) {
            log::info!(
                checkpoint_block_number = block_number,
                len = hashes.len(),
                "Requested txn proof from finalized checkpoint block",
            );
            // If we were provided a block number corresponding to a checkpoint block, it needs to correspond to the current epoch
            // Otherwise, the requester should use the latest epoch number.
            if block_number < election_head {
                log::info!(
                block_number,
                "Requested txn proof that corresponds to a finalized epoch, should use the election block instead",
            );
                return Err(
                    ResponseTransactionProofError::RequestedTxnProofFromFinalizedEpoch(
                        block_number,
                    ),
                );
            }
            block_number
        } else {
            log::info!(
                block_number = block_number,
                len = hashes.len(),
                "Requested txn proof from current batch",
            );
            // If we were provided a block number corresponding to a micro block,
            // it needs to correspond to at least the previous batch (we allow the
            // previous batch also, to not fail when the client is a few blocks behind
            // and we are already at or over a macro block).
            // If the requested block is older than the previous batch, the requester
            // should use the latest checkpoint block number instead.
            if block_number < macro_head - Policy::blocks_per_batch() {
                log::info!(
                block_number,
                "Requested txn proof from finalized batch, should use a checkpoint block instead",
            );
                return Err(
                    ResponseTransactionProofError::RequestedTxnProofFromFinalizedBatch(
                        block_number,
                    ),
                );
            }
            block_number
        };

        let block = blockchain
            .chain_store
            .get_block_at(proving_block_number, false, None)
            .ok();

        let block = if let Some(block) = block {
            // We have some extra work in the current epoch, if the block we are proving is not our current head
            if block.block_number() > election_head && block.block_number() < current_head {
                let chain_info = blockchain.get_chain_info(&block.hash(), false, None);
                let history_tree_len = chain_info.unwrap().history_tree_len;
                verifier_state = Some(history_tree_len as usize);
            }
            block
        } else {
            log::info!("Could not find the desired block to create the txn proof");
            return Err(ResponseTransactionProofError::BlockNotFound(
                proving_block_number,
            ));
        };

        let proof = match history_index.prove(
            Policy::epoch_at(proving_block_number),
            hashes,
            verifier_state,
            None,
        ) {
            Some(proof) => proof,
            None => {
                log::info!("Could not generate the txn inclusion proof");
                return Err(ResponseTransactionProofError::CouldntProveInclusion);
            }
        };

        Ok(ResponseTransactionsProof { proof, block })
    }

    #[cfg(feature = "full")]
    /// Attempts to prove inclusion of a single transaction by hash.
    fn prove_transaction(
        blockchain: &Arc<RwLock<Blockchain>>,
        transaction: &Blake2bHash,
    ) -> Result<ResponseTransactionsProof, ResponseTransactionProofError> {
        let blockchain = blockchain.read();
        let Some(history_index) = blockchain.history_store.history_index() else {
            log::info!("Cannot create transaction proof without history index");
            return Err(ResponseTransactionProofError::Other);
        };

        let mut verifier_state = None;
        let election_head = blockchain.election_head().block_number();
        let macro_head = blockchain.macro_head().block_number();
        let current_head = blockchain.head().block_number();

        // Get the historic transaction from the history store
        let historic_transaction = history_index.get_hist_tx_by_hash(transaction, None);

        if let Some(hist_txn) = historic_transaction {
            let block_number = hist_txn.block_number;

            let proving_block_number = if block_number <= election_head {
                // If the txn is in a finalized epoch, we use the election block of that epoch
                Policy::election_block_after(block_number)
            } else if block_number <= macro_head {
                // If the txn is in a finalized batch in the current epoch, we use the last checkpoint block
                macro_head
            } else {
                // If the txn is in the current batch, we use the transaction's block
                hist_txn.block_number
            };

            let block = if let Ok(block) =
                blockchain
                    .chain_store
                    .get_block_at(proving_block_number, false, None)
            {
                block
            } else {
                return Err(ResponseTransactionProofError::BlockNotFound(
                    proving_block_number,
                ));
            };

            // We have some extra work in the current epoch, if the block we are proving is not our current head
            if proving_block_number > election_head && proving_block_number < current_head {
                let chain_info = blockchain.get_chain_info(&block.hash(), false, None);
                let history_tree_len = chain_info.unwrap().history_tree_len;
                verifier_state = Some(history_tree_len as usize);
            }

            // Prove the transaction
            let proof = match history_index.prove(
                Policy::epoch_at(proving_block_number),
                vec![transaction],
                verifier_state,
                None,
            ) {
                Some(proof) => proof,
                None => {
                    log::info!("Could not generate the txn inclusion proof");
                    return Err(ResponseTransactionProofError::CouldntProveInclusion);
                }
            };

            Ok(ResponseTransactionsProof { proof, block })
        } else {
            // If we couldn't find the transaction in our history store, then we cannot prove it.
            Err(ResponseTransactionProofError::TransactionNotFound)
        }
    }
}

#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestTransactionsProof {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &Arc<RwLock<Blockchain>>,
    ) -> Result<ResponseTransactionsProof, ResponseTransactionProofError> {
        // Validate request.
        if self.hashes.len() > Self::MAX_TRANSACTIONS {
            // Reject request that exceed the tx limit
            return Err(ResponseTransactionProofError::TooManyTransactionsProvided);
        }

        if self.hashes.is_empty() {
            // If we are not given a list of transactions then there is nothing to do
            return Err(ResponseTransactionProofError::NoTransactionsProvided);
        }

        // Handle the different cases: if we are provided a block number (to generate the proof) or not
        if let Some(block_number) = self.block_number {
            Self::prove_txns_with_block_number(blockchain, &self.hashes, block_number)
        } else {
            Self::prove_transaction(blockchain, &self.hashes[0])
        }
    }
}

impl RequestTransactionReceiptsByAddress {
    const MAX_RECEIPTS: u16 = 500;
}
#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestTransactionReceiptsByAddress {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &Arc<RwLock<Blockchain>>,
    ) -> ResponseTransactionReceiptsByAddress {
        let blockchain = blockchain.read();
        let Some(history_index) = blockchain.history_store.history_index() else {
            log::info!("Cannot fetch transaction receipts by address without history index");
            return ResponseTransactionReceiptsByAddress { receipts: vec![] };
        };

        // Get the transaction hashes for this address.
        let raw_tx_hashes = history_index.get_tx_hashes_by_address(
            &self.address,
            self.max
                .unwrap_or(Self::MAX_RECEIPTS)
                .min(Self::MAX_RECEIPTS),
            self.start_at.clone(),
            None,
        );

        let mut receipts = vec![];

        for hash in raw_tx_hashes {
            // Get all the historic transactions that correspond to this hash.
            receipts.extend(
                history_index
                    .get_hist_tx_by_hash(&hash, None)
                    .iter()
                    .map(|hist_tx| (hist_tx.tx_hash().into(), hist_tx.block_number)),
            );
        }

        ResponseTransactionReceiptsByAddress { receipts }
    }
}

impl RequestTrieProof {
    const MAX_KEYS: usize = 255;
}
#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestTrieProof {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &Arc<RwLock<Blockchain>>,
    ) -> Result<ResponseTrieProof, ResponseTrieProofError> {
        // Validate request.
        if self.keys.is_empty() {
            return Err(ResponseTrieProofError::EmptyKeys);
        }
        if self.keys.len() > Self::MAX_KEYS {
            return Err(ResponseTrieProofError::TooManyKeys);
        }
        let unique_keys: std::collections::BTreeSet<_> = self.keys.iter().collect();
        if unique_keys.len() != self.keys.len() {
            return Err(ResponseTrieProofError::DuplicateKeys);
        }

        // We only prove accounts that exist in our current state
        let blockchain = blockchain.read();
        match blockchain.get_accounts_proof(self.keys.iter().collect()) {
            Err(IncompleteTrie) => Err(ResponseTrieProofError::IncompleteTrie),
            Ok(proof) => Ok(ResponseTrieProof {
                proof,
                block_hash: blockchain.head_hash(),
            }),
        }
    }
}

impl RequestBlocksProof {
    const MAX_BLOCKS: usize = 255;
}
#[cfg(feature = "full")]
impl<N: Network> Handle<N, Arc<RwLock<Blockchain>>> for RequestBlocksProof {
    fn handle(
        &self,
        _peer_id: N::PeerId,
        blockchain: &Arc<RwLock<Blockchain>>,
    ) -> Result<ResponseBlocksProof, ResponseBlocksProofError> {
        // Validate request.
        if self.blocks.len() > Self::MAX_BLOCKS {
            return Err(ResponseBlocksProofError::TooManyBlocks);
        }

        // Check if the request is sane and we can answer it
        let blockchain = blockchain.read();
        for &block_number in &self.blocks {
            if !Policy::is_election_block_at(block_number)
                || block_number > self.election_head
                || self.election_head > blockchain.election_head().block_number()
                || block_number == Policy::genesis_block_number()
            {
                return Err(ResponseBlocksProofError::BadBlockNumber(block_number));
            }
        }

        // Collect all election blocks needed for the proof
        let mut election_numbers = Vec::new();
        let mut block_proof = Vec::new();
        for block_number in &self.blocks {
            let hops = BlockInclusionProof::get_interlink_hops(*block_number, self.election_head);
            let mut hop_blocks = Vec::new();
            for &hop in &hops {
                if !election_numbers.contains(&hop) {
                    if let Ok(Block::Macro(hop_block)) = blockchain.get_block_at(hop, false, None) {
                        hop_blocks.push(hop_block);
                    } else {
                        continue;
                    }
                }
            }
            election_numbers.extend_from_slice(&hops);
            block_proof.append(&mut hop_blocks);
        }

        Ok(ResponseBlocksProof {
            proof: BlockInclusionProof { proof: block_proof },
        })
    }
}