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
use std::path::PathBuf;

use anyhow::{anyhow, Result};
use storage_proofs_core::{
    api_version::{ApiFeature, ApiVersion},
    merkle::MerkleTreeTrait,
    parameter_cache::{
        parameter_cache_metadata_path, parameter_cache_params_path,
        parameter_cache_verifying_key_path, CacheableParameters,
    },
};
use storage_proofs_porep::stacked::{StackedCircuit, StackedCompound};

use crate::{
    constants::{self, DefaultPieceHasher},
    parameters::public_params,
    types::{PaddedBytesAmount, PoRepProofPartitions, SectorSize, UnpaddedBytesAmount},
    POREP_PARTITIONS,
};

#[derive(Clone, Debug)]
pub struct PoRepConfig {
    pub sector_size: SectorSize,
    pub partitions: PoRepProofPartitions,
    pub porep_id: [u8; 32],
    pub api_version: ApiVersion,
    pub api_features: Vec<ApiFeature>,
}

impl From<PoRepConfig> for PaddedBytesAmount {
    fn from(x: PoRepConfig) -> Self {
        let PoRepConfig { sector_size, .. } = x;
        PaddedBytesAmount::from(sector_size)
    }
}

impl From<PoRepConfig> for UnpaddedBytesAmount {
    fn from(x: PoRepConfig) -> Self {
        let PoRepConfig { sector_size, .. } = x;
        PaddedBytesAmount::from(sector_size).into()
    }
}

impl From<PoRepConfig> for PoRepProofPartitions {
    fn from(x: PoRepConfig) -> Self {
        let PoRepConfig { partitions, .. } = x;
        partitions
    }
}

impl From<PoRepConfig> for SectorSize {
    fn from(cfg: PoRepConfig) -> Self {
        let PoRepConfig { sector_size, .. } = cfg;
        sector_size
    }
}

impl PoRepConfig {
    /// construct PoRepConfig by groth16
    pub fn new_groth16(sector_size: u64, porep_id: [u8; 32], api_version: ApiVersion) -> Self {
        Self {
            sector_size: SectorSize(sector_size),
            partitions: PoRepProofPartitions(
                *POREP_PARTITIONS
                    .read()
                    .expect("POREP_PARTITIONS poisoned")
                    .get(&sector_size)
                    .expect("unknown sector size"),
            ),
            porep_id,
            api_version,
            api_features: vec![],
        }
    }

    pub fn new_groth16_with_features(
        sector_size: u64,
        porep_id: [u8; 32],
        api_version: ApiVersion,
        api_features: Vec<ApiFeature>,
    ) -> Result<Self> {
        let mut config = Self {
            sector_size: SectorSize(sector_size),
            partitions: PoRepProofPartitions(
                *POREP_PARTITIONS
                    .read()
                    .expect("POREP_PARTITIONS poisoned")
                    .get(&sector_size)
                    .expect("unknown sector size"),
            ),
            porep_id,
            api_version,
            api_features: vec![],
        };
        for feature in api_features {
            config.enable_feature(feature)?;
        }
        Ok(config)
    }

    #[inline]
    pub fn enable_feature(&mut self, feat: ApiFeature) -> Result<()> {
        for conflict in feat.conflicting_features() {
            if self.feature_enabled(*conflict) {
                return Err(anyhow!(
                    "Cannot enable feature `{feat}` when `{conflict}` is already enabled"
                ));
            }
        }

        match feat {
            ApiFeature::SyntheticPoRep => {
                self.partitions = PoRepProofPartitions(
                    *POREP_PARTITIONS
                        .read()
                        .expect("POREP_PARTITIONS poisoned")
                        .get(&self.sector_size.into())
                        .expect("unknown sector size"),
                );
            }
            ApiFeature::NonInteractivePoRep => {
                self.partitions = PoRepProofPartitions(
                    constants::get_porep_non_interactive_partitions(self.sector_size.into()),
                );
            }
        }

        if !self.feature_enabled(feat) {
            self.api_features.push(feat);
        }

        Ok(())
    }

    #[inline]
    pub fn feature_enabled(&self, feat: ApiFeature) -> bool {
        self.api_features.contains(&feat)
    }

    #[inline]
    pub fn padded_bytes_amount(&self) -> PaddedBytesAmount {
        PaddedBytesAmount::from(self.sector_size)
    }

    #[inline]
    pub fn unpadded_bytes_amount(&self) -> UnpaddedBytesAmount {
        self.padded_bytes_amount().into()
    }

    pub fn minimum_challenges(&self) -> usize {
        if self.feature_enabled(ApiFeature::NonInteractivePoRep) {
            constants::get_porep_non_interactive_minimum_challenges(u64::from(self.sector_size))
        } else {
            constants::get_porep_interactive_minimum_challenges(u64::from(self.sector_size))
        }
    }

    /// Returns the cache identifier as used by `storage-proofs::parameter_cache`.
    pub fn get_cache_identifier<Tree: 'static + MerkleTreeTrait>(&self) -> Result<String> {
        let params = public_params::<Tree>(self)?;

        Ok(
            <StackedCompound<Tree, DefaultPieceHasher> as CacheableParameters<
                StackedCircuit<Tree, DefaultPieceHasher>,
                _,
            >>::cache_identifier(&params),
        )
    }

    pub fn get_cache_metadata_path<Tree: 'static + MerkleTreeTrait>(&self) -> Result<PathBuf> {
        let id = self.get_cache_identifier::<Tree>()?;
        Ok(parameter_cache_metadata_path(&id))
    }

    pub fn get_cache_verifying_key_path<Tree: 'static + MerkleTreeTrait>(&self) -> Result<PathBuf> {
        let id = self.get_cache_identifier::<Tree>()?;
        Ok(parameter_cache_verifying_key_path(&id))
    }

    pub fn get_cache_params_path<Tree: 'static + MerkleTreeTrait>(&self) -> Result<PathBuf> {
        let id = self.get_cache_identifier::<Tree>()?;
        Ok(parameter_cache_params_path(&id))
    }
}