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
use core::result::Result;
use std::{marker::PhantomData, sync::Arc, time::Instant};

use log::{debug, warn};
use sc_client_api::{Backend, Finalizer, HeaderBackend, LockImportRun};
use sp_blockchain::Error;
use sp_runtime::{
    traits::{Block, Header},
    Justification,
};

use crate::{
    phron_primitives::{BlockHash, BlockNumber},
    metrics::Checkpoint,
    BlockId, TimingBlockMetrics,
};

pub trait BlockFinalizer {
    fn finalize_block(&self, block: BlockId, justification: Justification) -> Result<(), Error>;
}

pub struct PhronFinalizer<B, BE, C>
where
    B: Block,
    BE: Backend<B>,
    C: HeaderBackend<B> + LockImportRun<B, BE> + Finalizer<B, BE>,
{
    client: Arc<C>,
    metrics: TimingBlockMetrics,
    phantom: PhantomData<(B, BE)>,
}

impl<B, BE, C> PhronFinalizer<B, BE, C>
where
    B: Block,
    BE: Backend<B>,
    C: HeaderBackend<B> + LockImportRun<B, BE> + Finalizer<B, BE>,
{
    pub(crate) fn new(client: Arc<C>, metrics: TimingBlockMetrics) -> Self {
        PhronFinalizer {
            client,
            metrics,
            phantom: PhantomData,
        }
    }
}

impl<B, BE, C> BlockFinalizer for PhronFinalizer<B, BE, C>
where
    B: Block<Hash = BlockHash>,
    B::Header: Header<Number = BlockNumber>,
    BE: Backend<B>,
    C: HeaderBackend<B> + LockImportRun<B, BE> + Finalizer<B, BE>,
{
    fn finalize_block(&self, block: BlockId, justification: Justification) -> Result<(), Error> {
        let BlockId { number, hash } = block;

        let status = self.client.info();
        if status.finalized_number >= number {
            warn!(target: "phron-finality", "trying to finalize a block with hash {} and number {}
               that is not greater than already finalized {}", hash, number, status.finalized_number);
        }

        debug!(target: "phron-finality", "Finalizing block with hash {:?} and number {:?}. Previous best: #{:?}.", hash, number, status.finalized_number);

        let update_res = self.client.lock_import_and_run(|import_op| {
            // NOTE: all other finalization logic should come here, inside the lock
            self.client
                .apply_finality(import_op, hash, Some(justification), true)
        });

        let status = self.client.info();
        match &update_res {
            Ok(_) => {
                debug!(target: "phron-finality", "Successfully finalized block with hash {:?} and number {:?}. Current best: #{:?}.", hash, number, status.best_number);
                self.metrics
                    .report_block(hash, Instant::now(), Checkpoint::Finalized);
            }
            Err(_) => {
                debug!(target: "phron-finality", "Failed to finalize block with hash {:?} and number {:?}. Current best: #{:?}.", hash, number, status.best_number)
            }
        }

        update_res
    }
}