Skip to content

Commit

Permalink
Reduce unwrap()s in code (#960)
Browse files Browse the repository at this point in the history
Reduce unwrap()s in code
  • Loading branch information
dignifiedquire authored Dec 1, 2019
2 parents cf35bb4 + 514a64b commit 5070de9
Show file tree
Hide file tree
Showing 19 changed files with 174 additions and 125 deletions.
2 changes: 1 addition & 1 deletion filecoin-proofs/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ pub fn get_unsealed_range<T: Into<PathBuf> + AsRef<Path>>(
let pp = public_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
);
)?;

let offset_padded: PaddedBytesAmount = UnpaddedBytesAmount::from(offset).into();
let num_bytes_padded: PaddedBytesAmount = num_bytes.into();
Expand Down
8 changes: 4 additions & 4 deletions filecoin-proofs/src/api/seal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,13 @@ pub fn seal_pre_commit<R: AsRef<Path>, T: AsRef<Path>, S: AsRef<Path>>(
// Zero-pad the data to the requested size by extending the underlying file if needed.
f_data.set_len(sector_bytes as u64)?;

let mut data = unsafe { MmapOptions::new().map_mut(&f_data).unwrap() };
let mut data = unsafe { MmapOptions::new().map_mut(&f_data)? };

let compound_setup_params = compound_proof::SetupParams {
vanilla_params: setup_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
),
)?,
partitions: Some(usize::from(PoRepProofPartitions::from(porep_config))),
};

Expand Down Expand Up @@ -219,7 +219,7 @@ pub fn seal_commit<T: AsRef<Path>>(
vanilla_params: setup_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
),
)?,
partitions: Some(usize::from(PoRepProofPartitions::from(porep_config))),
};

Expand Down Expand Up @@ -290,7 +290,7 @@ pub fn verify_seal(
vanilla_params: setup_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
),
)?,
partitions: Some(usize::from(PoRepProofPartitions::from(porep_config))),
};

Expand Down
5 changes: 3 additions & 2 deletions filecoin-proofs/src/bin/paramcache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ fn cache_porep_params(porep_config: PoRepConfig) {
let public_params = public_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
);
)
.unwrap();

{
let circuit = <StackedCompound as CompoundProof<
Expand Down Expand Up @@ -70,7 +71,7 @@ fn cache_post_params(post_config: PoStConfig) {
n
);

let post_public_params = post_public_params(post_config);
let post_public_params = post_public_params(post_config).unwrap();

{
let post_circuit: ElectionPoStCircuit<Bls12, PedersenHasher> =
Expand Down
8 changes: 4 additions & 4 deletions filecoin-proofs/src/caches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub fn get_stacked_params(porep_config: PoRepConfig) -> Result<Arc<groth16::Para
let public_params = public_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
);
)?;

let parameters_generator = || {
<StackedCompound as CompoundProof<
Expand All @@ -102,7 +102,7 @@ pub fn get_stacked_params(porep_config: PoRepConfig) -> Result<Arc<groth16::Para
}

pub fn get_post_params(post_config: PoStConfig) -> Result<Arc<groth16::Parameters<Bls12>>> {
let post_public_params = post_public_params(post_config);
let post_public_params = post_public_params(post_config)?;

let parameters_generator = || {
<ElectionPoStCompound<DefaultTreeHasher> as CompoundProof<
Expand All @@ -126,7 +126,7 @@ pub fn get_stacked_verifying_key(porep_config: PoRepConfig) -> Result<Arc<Bls12V
let public_params = public_params(
PaddedBytesAmount::from(porep_config),
usize::from(PoRepProofPartitions::from(porep_config)),
);
)?;

let vk_generator = || {
<StackedCompound as CompoundProof<
Expand All @@ -147,7 +147,7 @@ pub fn get_stacked_verifying_key(porep_config: PoRepConfig) -> Result<Arc<Bls12V
}

pub fn get_post_verifying_key(post_config: PoStConfig) -> Result<Arc<Bls12VerifyingKey>> {
let post_public_params = post_public_params(post_config);
let post_public_params = post_public_params(post_config)?;

let vk_generator = || {
<ElectionPoStCompound<DefaultTreeHasher> as CompoundProof<
Expand Down
18 changes: 10 additions & 8 deletions filecoin-proofs/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,11 @@ pub type PostPublicParams = election_post::PublicParams;
pub fn public_params(
sector_bytes: PaddedBytesAmount,
partitions: usize,
) -> stacked::PublicParams<DefaultTreeHasher> {
) -> Result<stacked::PublicParams<DefaultTreeHasher>> {
StackedDrg::<DefaultTreeHasher, DefaultPieceHasher>::setup(&setup_params(
sector_bytes,
partitions,
))
.unwrap()
)?)
}

pub fn window_size_nodes_for_sector_bytes(sector_size: PaddedBytesAmount) -> Result<usize> {
Expand All @@ -42,8 +41,8 @@ pub fn window_size_nodes_for_sector_bytes(sector_size: PaddedBytesAmount) -> Res
}
}

pub fn post_public_params(post_config: PoStConfig) -> PostPublicParams {
ElectionPoSt::<DefaultTreeHasher>::setup(&post_setup_params(post_config)).unwrap()
pub fn post_public_params(post_config: PoStConfig) -> Result<PostPublicParams> {
ElectionPoSt::<DefaultTreeHasher>::setup(&post_setup_params(post_config))
}

pub fn post_setup_params(post_config: PoStConfig) -> PostSetupParams {
Expand All @@ -54,7 +53,10 @@ pub fn post_setup_params(post_config: PoStConfig) -> PostSetupParams {
}
}

pub fn setup_params(sector_bytes: PaddedBytesAmount, partitions: usize) -> stacked::SetupParams {
pub fn setup_params(
sector_bytes: PaddedBytesAmount,
partitions: usize,
) -> Result<stacked::SetupParams> {
let window_challenges = select_challenges(partitions, POREP_WINDOW_MINIMUM_CHALLENGES, LAYERS);
let wrapper_challenges =
select_challenges(partitions, POREP_WRAPPER_MINIMUM_CHALLENGES, LAYERS);
Expand All @@ -80,14 +82,14 @@ pub fn setup_params(sector_bytes: PaddedBytesAmount, partitions: usize) -> stack
);

let nodes = sector_bytes / 32;
stacked::SetupParams {
Ok(stacked::SetupParams {
nodes,
degree: BASE_DEGREE,
expansion_degree: EXP_DEGREE,
seed: DRG_SEED,
config,
window_size_nodes,
}
})
}

fn select_challenges(
Expand Down
28 changes: 15 additions & 13 deletions filecoin-proofs/src/types/porep_config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::path::PathBuf;

use anyhow::Result;

use paired::bls12_381::Bls12;
use storage_proofs::circuit::stacked::{StackedCircuit, StackedCompound};
use storage_proofs::drgraph::DefaultTreeHasher;
Expand Down Expand Up @@ -47,29 +49,29 @@ impl From<PoRepConfig> for SectorSize {

impl PoRepConfig {
/// Returns the cache identifier as used by `storage-proofs::paramater_cache`.
pub fn get_cache_identifier(&self) -> String {
pub fn get_cache_identifier(&self) -> Result<String> {
let params =
crate::parameters::public_params(self.sector_size.into(), self.partitions.into());
crate::parameters::public_params(self.sector_size.into(), self.partitions.into())?;

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

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

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

pub fn get_cache_params_path(&self) -> PathBuf {
let id = self.get_cache_identifier();
parameter_cache::parameter_cache_params_path(&id)
pub fn get_cache_params_path(&self) -> Result<PathBuf> {
let id = self.get_cache_identifier()?;
Ok(parameter_cache::parameter_cache_params_path(&id))
}
}
38 changes: 21 additions & 17 deletions filecoin-proofs/src/types/post_config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::path::PathBuf;

use anyhow::Result;

use paired::bls12_381::Bls12;
use storage_proofs::circuit::election_post::{ElectionPoStCircuit, ElectionPoStCompound};
use storage_proofs::drgraph::DefaultTreeHasher;
Expand Down Expand Up @@ -30,28 +32,30 @@ impl From<PoStConfig> for UnpaddedBytesAmount {

impl PoStConfig {
/// Returns the cache identifier as used by `storage-proofs::paramater_cache`.
pub fn get_cache_identifier(self) -> String {
let params = crate::parameters::post_public_params(self);

<ElectionPoStCompound<DefaultTreeHasher> as CacheableParameters<
Bls12,
ElectionPoStCircuit<_, DefaultTreeHasher>,
_,
>>::cache_identifier(&params)
pub fn get_cache_identifier(self) -> Result<String> {
let params = crate::parameters::post_public_params(self)?;

Ok(
<ElectionPoStCompound<DefaultTreeHasher> as CacheableParameters<
Bls12,
ElectionPoStCircuit<_, DefaultTreeHasher>,
_,
>>::cache_identifier(&params),
)
}

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

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

pub fn get_cache_params_path(self) -> PathBuf {
let id = self.get_cache_identifier();
parameter_cache::parameter_cache_params_path(&id)
pub fn get_cache_params_path(self) -> Result<PathBuf> {
let id = self.get_cache_identifier()?;
Ok(parameter_cache::parameter_cache_params_path(&id))
}
}
2 changes: 1 addition & 1 deletion storage-proofs/benches/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ fn encode_single_node<H: Hasher>(

let node_data = H::Domain::try_from_bytes(&data[start..end]).unwrap();
let key_data = H::Domain::try_from_bytes(&key).unwrap();
let encoded = H::sloth_encode(&key_data, &node_data);
let encoded = H::sloth_encode(&key_data, &node_data).unwrap();
encoded.write_bytes(&mut data[start..end]).unwrap();
}

Expand Down
8 changes: 4 additions & 4 deletions storage-proofs/src/circuit/create_label.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ where
let fr = if alloc_bits[0].get_value().is_some() {
let be_bits = alloc_bits
.iter()
.map(|v| v.get_value().unwrap())
.collect::<Vec<bool>>();
.map(|v| v.get_value().ok_or(SynthesisError::AssignmentMissing))
.collect::<Result<Vec<bool>, SynthesisError>>()?;

let le_bits = be_bits
.chunks(8)
Expand Down Expand Up @@ -119,7 +119,7 @@ mod tests {
acc
});

let expected = crypto::create_label::create_label(input_bytes.as_slice(), m);
let expected = crypto::create_label::create_label(input_bytes.as_slice(), m).unwrap();

assert_eq!(
expected,
Expand Down Expand Up @@ -178,7 +178,7 @@ mod tests {
input_bytes.extend_from_slice(parent);
}

let expected = crypto::create_label::create_label(input_bytes.as_slice(), m);
let expected = crypto::create_label::create_label(input_bytes.as_slice(), m).unwrap();

assert_eq!(
expected,
Expand Down
6 changes: 4 additions & 2 deletions storage-proofs/src/circuit/variables.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::fmt;

use anyhow::Result;

use bellperson::gadgets::num::AllocatedNum;
use bellperson::{ConstraintSystem, SynthesisError};
use paired::Engine;
Expand Down Expand Up @@ -39,8 +41,8 @@ impl<E: Engine> Root<E> {
}
}

pub fn var<CS: ConstraintSystem<E>>(cs: CS, fr: E::Fr) -> Self {
Root::Var(AllocatedNum::alloc(cs, || Ok(fr)).unwrap())
pub fn var<CS: ConstraintSystem<E>>(cs: CS, fr: E::Fr) -> Result<Self> {
Ok(Root::Var(AllocatedNum::alloc(cs, || Ok(fr))?))
}

pub fn is_some(&self) -> bool {
Expand Down
7 changes: 4 additions & 3 deletions storage-proofs/src/crypto/create_label.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use anyhow::Result;
use ff::PrimeField;
use paired::bls12_381::Fr;
use sha2::{Digest, Sha256};

use crate::fr32::bytes_into_fr_repr_safe;

/// Key derivation function, based on pedersen hashing.
pub fn create_label(data: &[u8], _m: usize) -> Fr {
pub fn create_label(data: &[u8], _m: usize) -> Result<Fr> {
let hash = Sha256::digest(data);
Fr::from_repr(bytes_into_fr_repr_safe(hash.as_ref())).unwrap()
Ok(Fr::from_repr(bytes_into_fr_repr_safe(hash.as_ref()))?)
}

#[cfg(test)]
Expand All @@ -30,7 +31,7 @@ mod tests {
];
let expected = Fr::from_repr(FrRepr(repr)).unwrap();

let res = create_label(&data, m);
let res = create_label(&data, m).unwrap();
assert_eq!(res, expected);
}
}
2 changes: 1 addition & 1 deletion storage-proofs/src/drgporep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ where
let end = start + NODE_SIZE;

let node_data = H::Domain::try_from_bytes(&data[start..end])?;
let encoded = H::sloth_encode(key.as_ref(), &node_data);
let encoded = H::sloth_encode(key.as_ref(), &node_data)?;

encoded.write_bytes(&mut data[start..end])?;
}
Expand Down
16 changes: 8 additions & 8 deletions storage-proofs/src/hasher/blake2s.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Hasher for Blake2sHasher {
"Blake2sHasher".into()
}

fn create_label(data: &[u8], m: usize) -> Self::Domain {
fn create_label(data: &[u8], m: usize) -> Result<Self::Domain> {
assert_eq!(
data.len(),
32 * (1 + m),
Expand All @@ -35,20 +35,20 @@ impl Hasher for Blake2sHasher {
m
);

<Self::Function as HashFunction<Self::Domain>>::hash(data)
Ok(<Self::Function as HashFunction<Self::Domain>>::hash(data))
}

fn sloth_encode(key: &Self::Domain, ciphertext: &Self::Domain) -> Self::Domain {
fn sloth_encode(key: &Self::Domain, ciphertext: &Self::Domain) -> Result<Self::Domain> {
// TODO: validate this is how sloth should work in this case
let k = (*key).into();
let c = (*ciphertext).into();

sloth::encode::<Bls12>(&k, &c).into()
Ok(sloth::encode::<Bls12>(&k, &c).into())
}

fn sloth_decode(key: &Self::Domain, ciphertext: &Self::Domain) -> Self::Domain {
fn sloth_decode(key: &Self::Domain, ciphertext: &Self::Domain) -> Result<Self::Domain> {
// TODO: validate this is how sloth should work in this case
sloth::decode::<Bls12>(&(*key).into(), &(*ciphertext).into()).into()
Ok(sloth::decode::<Bls12>(&(*key).into(), &(*ciphertext).into()).into())
}
}

Expand Down Expand Up @@ -247,8 +247,8 @@ impl HashFunction<Blake2sDomain> for Blake2sFunction {
Some(_) => {
let bits = alloc_bits
.iter()
.map(|v| v.get_value().unwrap())
.collect::<Vec<bool>>();
.map(|v| v.get_value().ok_or(SynthesisError::AssignmentMissing))
.collect::<std::result::Result<Vec<bool>, SynthesisError>>()?;
// TODO: figure out if we can avoid this
let frs = multipack::compute_multipacking::<E>(&bits);
Ok(frs[0])
Expand Down
Loading

0 comments on commit 5070de9

Please sign in to comment.