Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanting Zhang committed Mar 20, 2024
1 parent 37615c7 commit 98e5152
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 47 deletions.
65 changes: 53 additions & 12 deletions src/data.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
//! Very minimal utilities for reading/writing general arecibo data in disk.
use camino::{Utf8Path, Utf8PathBuf};
use camino::Utf8Path;
#[cfg(not(target_arch = "wasm32"))]
use camino::Utf8PathBuf;
use once_cell::sync::OnceCell;
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Mutex;
#[cfg(not(target_arch = "wasm32"))]
use std::{
collections::HashMap,
fs::{self, File, OpenOptions},
Expand All @@ -16,33 +20,46 @@ pub static ARECIBO_DATA: &str = ".arecibo_data";

/// Global configuration for Arecibo data storage, including root directory and counters.
/// This configuration is initialized on first use.
pub static mut ARECIBO_CONFIG: OnceCell<DataConfig> = OnceCell::new();
pub static ARECIBO_CONFIG: OnceCell<Mutex<DataConfig>> = OnceCell::new();

/// Configuration for managing Arecibo data files, including the root directory,
/// witness counter, and cross-term counter for organizing files.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Default)]
pub struct DataConfig {
#[cfg(not(target_arch = "wasm32"))]
root_dir: Utf8PathBuf,
#[cfg(not(target_arch = "wasm32"))]
section_counters: HashMap<String, usize>,
write_data: bool,
}

#[cfg(not(target_arch = "wasm32"))]
/// Initializes the global configuration for Arecibo data storage, setting up the root directory
/// and initializing counters. We create the root directory if it does not already exist.
pub fn init_config() -> DataConfig {
pub fn init_config() -> Mutex<DataConfig> {
let root_dir = home::home_dir().unwrap().join(ARECIBO_DATA);
let root_dir = Utf8PathBuf::from_path_buf(root_dir).unwrap();
if !root_dir.exists() {
fs::create_dir_all(&root_dir).expect("Failed to create arecibo data directory");
}

DataConfig {
let config = DataConfig {
root_dir,
section_counters: HashMap::new(),
write_data: WRITE,
}
};

Mutex::new(config)
}

#[cfg(target_arch = "wasm32")]
/// Initializes the global configuration for Arecibo data storage, setting up the root directory
/// and initializing counters. We create the root directory if it does not already exist.
pub fn init_config() -> Mutex<DataConfig> {
Mutex::new(DataConfig::default())
}

#[cfg(not(target_arch = "wasm32"))]
/// Writes Arecibo data to disk, organizing it into sections and labeling it with a unique identifier.
/// This function serializes the given payload and writes it into the appropriate section and file.
/// For now, we just increment the relevant counter to ensure uniqueness.
Expand All @@ -51,8 +68,8 @@ pub fn write_arecibo_data<T: Serialize>(
label: impl AsRef<Utf8Path>,
payload: &T,
) {
let _ = unsafe { ARECIBO_CONFIG.set(init_config()) };
let config = unsafe { ARECIBO_CONFIG.get_mut().unwrap() };
let mutex = ARECIBO_CONFIG.get_or_init(init_config);
let mut config = mutex.lock().unwrap();

let section_path = config.root_dir.join(section.as_ref());
if !section_path.exists() {
Expand All @@ -77,12 +94,26 @@ pub fn write_arecibo_data<T: Serialize>(
bincode::serialize_into(writer, payload).expect("Failed to write data");
}

#[cfg(target_arch = "wasm32")]
/// Writes Arecibo data to disk, organizing it into sections and labeling it with a unique identifier.
/// This function serializes the given payload and writes it into the appropriate section and file.
/// For now, we just increment the relevant counter to ensure uniqueness.
pub fn write_arecibo_data<T: Serialize>(
_section: impl AsRef<Utf8Path>,
_label: impl AsRef<Utf8Path>,
_payload: &T,
) {
// Do nothing
}

#[cfg(not(target_arch = "wasm32"))]
/// Reads and deserializes data from a specified section and label.
pub fn read_arecibo_data<T: DeserializeOwned>(
section: impl AsRef<Utf8Path>,
label: impl AsRef<Utf8Path>,
) -> T {
let config = unsafe { ARECIBO_CONFIG.get_or_init(init_config) };
let mutex = ARECIBO_CONFIG.get_or_init(init_config);
let config = mutex.lock().unwrap();

let section_path = config.root_dir.join(section.as_ref());
assert!(section_path.exists(), "Section directory does not exist");
Expand All @@ -97,15 +128,25 @@ pub fn read_arecibo_data<T: DeserializeOwned>(
bincode::deserialize_from(reader).expect("Failed to read data")
}

#[cfg(target_arch = "wasm32")]
/// Reads and deserializes data from a specified section and label.
pub fn read_arecibo_data<T: DeserializeOwned>(
_section: impl AsRef<Utf8Path>,
_label: impl AsRef<Utf8Path>,
) -> T {
unimplemented!("not supported on wasm yet")
}

/// Are we configured to write data?
pub fn write_data() -> bool {
let config = unsafe { ARECIBO_CONFIG.get_or_init(init_config) };
let mutex = ARECIBO_CONFIG.get_or_init(init_config);
let config = mutex.lock().unwrap();
config.write_data
}

/// Set the configuration for writing data.
pub fn set_write_data(write_data: bool) {
let _ = unsafe { ARECIBO_CONFIG.set(init_config()) };
let config = unsafe { ARECIBO_CONFIG.get_mut().unwrap() };
let mutex = ARECIBO_CONFIG.get_or_init(init_config);
let mut config = mutex.lock().unwrap();
config.write_data = write_data;
}
42 changes: 7 additions & 35 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,15 @@ mod nifs;

// public modules
pub mod constants;
pub mod data;
pub mod errors;
pub mod gadgets;
pub mod provider;
pub mod r1cs;
pub mod spartan;
pub mod traits;

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
pub mod data;
pub mod supernova;
pub mod traits;

use once_cell::sync::OnceCell;
use traits::{CurveCycleEquipped, Dual};

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
use crate::data::{write_arecibo_data, write_data};
use crate::digest::{DigestComputer, SimpleDigestible};
use crate::{
Expand All @@ -52,6 +46,7 @@ use errors::NovaError;
use ff::{Field, PrimeField};
use gadgets::scalar_as_base;
use nifs::NIFS;
use once_cell::sync::OnceCell;
use r1cs::{
CommitmentKeyHint, R1CSInstance, R1CSShape, R1CSWitness, RelaxedR1CSInstance, RelaxedR1CSWitness,
};
Expand All @@ -63,6 +58,7 @@ use traits::{
snark::RelaxedR1CSSNARKTrait,
AbsorbInROTrait, Engine, ROConstants, ROConstantsCircuit, ROTrait,
};
use traits::{CurveCycleEquipped, Dual};

/// A type that holds parameters for the primary and secondary circuits of Nova and SuperNova
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Abomonation)]
Expand Down Expand Up @@ -358,13 +354,6 @@ pub struct ResourceBuffer<E: Engine> {
T: Vec<E::Scalar>,
}

/// A very simple config for [`RecursiveSNARK`] in charge of logging behavior.
/// To be fleshed out and extended in the future.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RecursiveSNARKConfig {
write_data: bool,
}

/// A SNARK that proves the correct execution of an incremental computation
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
Expand All @@ -389,8 +378,6 @@ where
i: usize,
zi_primary: Vec<E1::Scalar>,
zi_secondary: Vec<<Dual<E1> as Engine>::Scalar>,

config: RecursiveSNARKConfig,
}

impl<E1> RecursiveSNARK<E1>
Expand Down Expand Up @@ -502,20 +489,8 @@ where
T: r1cs::default_T::<Dual<E1>>(r1cs_secondary.num_cons),
};

let config = RecursiveSNARKConfig {
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
write_data: write_data(),
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
write_data: false,
};

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
if config.write_data {
write_arecibo_data(
format!("r1cs_primary_{:?}", pp.digest()),
"",
&r1cs_primary,
);
if write_data() {
write_arecibo_data(format!("r1cs_primary_{:?}", pp.digest()), "", &r1cs_primary);
}

Ok(Self {
Expand All @@ -534,8 +509,6 @@ where
i: 0,
zi_primary,
zi_secondary,

config,
})
}

Expand Down Expand Up @@ -625,8 +598,7 @@ where
&mut self.buffer_primary.ABC_Z_2,
)?;

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
if self.config.write_data {
if write_data() {
let W = l_w_primary.W;
write_arecibo_data(
format!("witness_{:?}", pp.digest()),
Expand Down

0 comments on commit 98e5152

Please sign in to comment.