1use std::fmt::Debug;
4
5use crate::beacon::BeaconSchedule;
6use crate::blocks::{Block, Tipset};
7use crate::chain::{Error as ChainStoreError, Weight};
8use crate::prelude::*;
9use crate::state_manager::{Error as StateManagerError, StateManager};
10use anyhow::anyhow;
11use fvm_ipld_encoding::Error as ForestEncodingError;
12use nunny::Vec as NonEmpty;
13use thiserror::Error;
14
15mod validation;
16mod weight;
17
18#[derive(Debug, Error)]
19pub enum FilecoinConsensusError {
20 #[error("Block must have an election proof included in tipset")]
21 BlockWithoutElectionProof,
22 #[error("Block without ticket")]
23 BlockWithoutTicket,
24 #[error("Block height {current} not greater than parent height {parent}")]
25 BlockHeightNotGreaterThanParentHeight { current: i64, parent: i64 },
26 #[error("Block had the wrong timestamp: {0} != {1}")]
27 UnequalBlockTimestamps(u64, u64),
28 #[error("Tipset without ticket to verify")]
29 TipsetWithoutTicket,
30 #[error("Block is not claiming to be a winner")]
31 NotClaimingWin,
32 #[error("Block miner was slashed or is invalid")]
33 InvalidOrSlashedMiner,
34 #[error("Miner claimed wrong number of wins: miner = {0}, computed = {1}")]
35 MinerWinClaimsIncorrect(i64, i64),
36 #[error("Drawing chain randomness failed: {0}")]
37 DrawingChainRandomness(String),
38 #[error("Miner isn't elligible to mine")]
39 MinerNotEligibleToMine,
40 #[error("Querying miner power failed: {0}")]
41 MinerPowerUnavailable(String),
42 #[error("Power actor not found")]
43 PowerActorUnavailable,
44 #[error("Verifying VRF failed: {0}")]
45 VrfValidation(String),
46 #[error("Failed to validate blocks random beacon values: {0}")]
47 BeaconValidation(String),
48 #[error("Failed to verify winning PoSt: {0}")]
49 WinningPoStValidation(String),
50 #[error("Chain store error: {0}")]
51 ChainStore(#[from] ChainStoreError),
52 #[error("StateManager error: {0}")]
53 StateManager(#[from] StateManagerError),
54 #[error("Encoding error: {0}")]
55 ForestEncoding(#[from] ForestEncodingError),
56}
57
58#[derive(derive_more::Constructor)]
59pub struct FilecoinConsensus {
60 beacon: Arc<BeaconSchedule>,
66}
67
68impl FilecoinConsensus {
69 pub async fn validate_block(
70 &self,
71 state_manager: StateManager,
72 block: Arc<Block>,
73 ) -> Result<(), NonEmpty<FilecoinConsensusError>> {
74 validation::validate_block(state_manager, self.beacon.clone(), block).await
75 }
76}
77
78impl Debug for FilecoinConsensus {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 f.debug_struct("FilecoinConsensus")
81 .field("beacon", &self.beacon.0.len())
82 .finish()
83 }
84}
85
86pub fn weight<DB>(db: &DB, ts: &Tipset) -> anyhow::Result<Weight>
87where
88 DB: Blockstore + ShallowClone,
89{
90 weight::weight(db, ts).map_err(|s| anyhow!(s))
91}