Skip to content
This repository has been archived by the owner on Nov 23, 2023. It is now read-only.

Commit

Permalink
Loading params
Browse files Browse the repository at this point in the history
  • Loading branch information
lazovicff committed Sep 12, 2023
1 parent 554ea1a commit a33e930
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 61 deletions.
4 changes: 2 additions & 2 deletions eigentrust-cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl FromStr for Action {
/// Handle `attestations` command.
pub async fn handle_attestations(config: ClientConfig) -> Result<(), EigenError> {
let mnemonic = load_mnemonic();
let client = Client::new(config, mnemonic);
let client = Client::new(config, mnemonic, Vec::new());

let attestations = client.get_attestations().await?;

Expand Down Expand Up @@ -266,7 +266,7 @@ pub async fn handle_scores(
config: ClientConfig, origin: AttestationsOrigin,
) -> Result<(), EigenError> {
let mnemonic = load_mnemonic();
let client = Client::new(config, mnemonic);
let client = Client::new(config, mnemonic, Vec::new());

let att_fp = get_file_path("attestations", FileType::Csv)?;

Expand Down
14 changes: 13 additions & 1 deletion eigentrust-cli/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use dotenv::{dotenv, var};
use eigentrust::{
error::EigenError,
storage::{JSONFileStorage, Storage},
storage::{BinFileStorage, JSONFileStorage, Storage},
ClientConfig,
};
use log::warn;
Expand All @@ -19,6 +19,8 @@ pub enum FileType {
Csv,
/// JSON file.
Json,
/// Binary file.
Bin,
}

impl FileType {
Expand All @@ -27,6 +29,7 @@ impl FileType {
match self {
FileType::Csv => "csv",
FileType::Json => "json",
FileType::Bin => "bin",
}
}
}
Expand Down Expand Up @@ -69,3 +72,12 @@ pub fn load_mnemonic() -> String {
DEFAULT_MNEMONIC.to_string()
})
}

/// Loads the parameter for constructing proving and veirifying keys
pub fn load_params() -> Result<Vec<u8>, EigenError> {
let k = 20;
let filepath = get_file_path(&format!("params-{}", k), FileType::Bin)?;
let bin_storage = BinFileStorage::new(filepath);

bin_storage.load()
}
8 changes: 5 additions & 3 deletions eigentrust-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use cli::*;
use dotenv::dotenv;
use eigentrust::{error::EigenError, eth::deploy_as, Client, ClientConfig};
use env_logger::{init_from_env, Env};
use fs::{load_config, load_mnemonic};
use fs::{load_config, load_mnemonic, load_params};
use log::{debug, info};

#[tokio::main]
Expand All @@ -48,14 +48,16 @@ async fn main() -> Result<(), EigenError> {
debug!("Attesting:{:?}", attestation);

let mnemonic = load_mnemonic();
let client = Client::new(config, mnemonic);
let params = load_params()?;
let client = Client::new(config, mnemonic, params);
client.attest(attestation).await?;
},
Mode::Attestations => handle_attestations(config).await?,
Mode::Bandada(bandada_data) => handle_bandada(&config, bandada_data).await?,
Mode::Deploy => {
let mnemonic = load_mnemonic();
let client = Client::new(config, mnemonic);
let params = load_params()?;
let client = Client::new(config, mnemonic, params);
let as_address = deploy_as(client.get_signer()).await?;
info!("AttestationStation deployed at {:?}", as_address);
},
Expand Down
2 changes: 1 addition & 1 deletion eigentrust/src/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ mod tests {
domain: "0x0000000000000000000000000000000000000000".to_string(),
node_url: anvil.endpoint().to_string(),
};
let client = Client::new(config, TEST_MNEMONIC.to_string());
let client = Client::new(config, TEST_MNEMONIC.to_string(), Vec::new());

// Deploy
let res = deploy_as(client.signer).await;
Expand Down
40 changes: 22 additions & 18 deletions eigentrust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,19 @@ use eigentrust_zk::{
PoseidonNativeSponge, HASHER_WIDTH, MIN_PEER_COUNT, NUM_BITS, NUM_LIMBS,
},
ecdsa::native::{EcdsaKeypair, PublicKey, Signature},
halo2::halo2curves::{
bn256::{self, Bn256},
secp256k1::{Fq, Secp256k1Affine},
halo2::{
halo2curves::{
bn256::{self, Bn256},
secp256k1::{Fq, Secp256k1Affine},
},
poly::{commitment::Params as KZGParams, kzg::commitment::ParamsKZG},
},
params::{
ecc::secp256k1::Secp256k1Params, hasher::poseidon_bn254_5x5::Params,
rns::secp256k1::Secp256k1_4_68,
},
poseidon::native::Poseidon,
utils::{generate_params, prove},
utils::{generate_params, keygen, prove},
};
use error::EigenError;
use eth::{address_from_ecdsa_key, ecdsa_keypairs_from_mnemonic, scalar_from_address};
Expand Down Expand Up @@ -159,11 +162,12 @@ pub struct Client {
signer: Arc<ClientSigner>,
config: ClientConfig,
mnemonic: String,
params: ParamsKZG<Bn256>,
}

impl Client {
/// Creates a new Client instance.
pub fn new(config: ClientConfig, mnemonic: String) -> Self {
pub fn new(config: ClientConfig, mnemonic: String, params_bytes: Vec<u8>) -> Self {
// Setup provider
let provider = Provider::<Http>::try_from(&config.node_url)
.expect("Failed to create provider from config node url");
Expand All @@ -181,7 +185,10 @@ impl Client {
// Arc for thread-safe sharing of signer
let shared_signer = Arc::new(signer);

Self { signer: shared_signer, config, mnemonic }
let mut params_slice = params_bytes.as_slice();
let params = ParamsKZG::read(&mut params_slice).expect("Failed to read KZG params");

Self { signer: shared_signer, config, mnemonic, params }
}

/// Submits an attestation to the attestation station.
Expand Down Expand Up @@ -455,8 +462,8 @@ impl Client {
}

// Add participants to set
for participant in scalar_set {
eigen_trust_set.add_member(participant);
for participant in &scalar_set {
eigen_trust_set.add_member(*participant);
}

// Update the set with the opinions of each participant
Expand All @@ -469,7 +476,7 @@ impl Client {
}

// Build public inputs
let public_inputs = Vec::new();
let mut public_inputs = Vec::new();

// Insert scalar set
for scalar in scalar_set {
Expand All @@ -485,15 +492,12 @@ impl Client {
// Insert Domain
public_inputs.push(domain);

let k = 20;
let rng = &mut rand::thread_rng();
let params = generate_params(k);

// TODO: Build new circuit

// TODO: Get pk
// let pk = keygen(&self.params, circuit)

let proof = prove::<Bn256, _, _>(&params, et_circuit, &[&public_inputs], &pk, rng).unwrap();
// let proof = prove::<Bn256, _, _>(&params, et_circuit, &[&public_inputs], &pk, rng).unwrap();

Ok(())
}
Expand Down Expand Up @@ -590,7 +594,7 @@ mod lib_tests {
domain: "0x0000000000000000000000000000000000000000".to_string(),
node_url: anvil.endpoint().to_string(),
};
let client = Client::new(config, TEST_MNEMONIC.to_string());
let client = Client::new(config, TEST_MNEMONIC.to_string(), Vec::new());

// Deploy attestation station
let as_address = deploy_as(client.get_signer()).await.unwrap();
Expand All @@ -606,7 +610,7 @@ mod lib_tests {
node_url: anvil.endpoint().to_string(),
};

let updated_client = Client::new(updated_config, TEST_MNEMONIC.to_string());
let updated_client = Client::new(updated_config, TEST_MNEMONIC.to_string(), Vec::new());

// Attest
let attestation = AttestationRaw::new([0; 20], [0; 20], 5, [0; 32]);
Expand All @@ -627,7 +631,7 @@ mod lib_tests {
domain: "0x0000000000000000000000000000000000000000".to_string(),
node_url: anvil.endpoint().to_string(),
};
let client = Client::new(config, TEST_MNEMONIC.to_string());
let client = Client::new(config, TEST_MNEMONIC.to_string(), Vec::new());

// Deploy attestation station
let as_address = deploy_as(client.get_signer()).await.unwrap();
Expand All @@ -642,7 +646,7 @@ mod lib_tests {
domain: "0x0000000000000000000000000000000000000000".to_string(),
node_url: anvil.endpoint().to_string(),
};
let client = Client::new(config, TEST_MNEMONIC.to_string());
let client = Client::new(config, TEST_MNEMONIC.to_string(), Vec::new());

// Build Attestation
let about_bytes = [
Expand Down
105 changes: 69 additions & 36 deletions eigentrust/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,75 @@ impl<T: Serialize + DeserializeOwned + Clone> Storage<Vec<T>> for CSVFileStorage
}
}

/// The `JSONFileStorage` struct provides a mechanism for persisting
/// and retrieving structured data to and from JSON files.
pub struct JSONFileStorage<T> {
filepath: PathBuf,
phantom: PhantomData<T>,
}

impl<T> JSONFileStorage<T> {
/// Creates a new JSONFileStorage.
pub fn new(filepath: PathBuf) -> Self {
Self { filepath, phantom: PhantomData }
}

/// Returns the path to the file.
pub fn filepath(&self) -> &PathBuf {
&self.filepath
}
}

impl<T: Serialize + DeserializeOwned + Clone> Storage<T> for JSONFileStorage<T> {
type Err = EigenError;

fn load(&self) -> Result<T, Self::Err> {
let file = File::open(&self.filepath).map_err(EigenError::IOError)?;
let reader = BufReader::new(file);
from_reader(reader).map_err(|e| EigenError::ParsingError(e.to_string()))
}

fn save(&mut self, data: T) -> Result<(), Self::Err> {
let json_str = to_string(&data).map_err(|e| EigenError::ParsingError(e.to_string()))?;

let mut file = File::create(&self.filepath).map_err(EigenError::IOError)?;
file.write_all(json_str.as_bytes()).map_err(EigenError::IOError)
}
}

/// The `BinFileStorage` struct provides a mechanism for persisting
/// and retrieving data to and from bin files.
pub struct BinFileStorage {
filepath: PathBuf,
}

impl BinFileStorage {
/// Creates a new JSONFileStorage.
pub fn new(filepath: PathBuf) -> Self {
Self { filepath }
}

/// Returns the path to the file.
pub fn filepath(&self) -> &PathBuf {
&self.filepath
}
}

impl Storage<Vec<u8>> for BinFileStorage {
type Err = EigenError;

fn load(&self) -> Result<Vec<u8>, Self::Err> {
let file = File::open(&self.filepath).map_err(EigenError::IOError)?;
let reader = BufReader::new(file);
from_reader(reader).map_err(|e| EigenError::ParsingError(e.to_string()))
}

fn save(&mut self, data: Vec<u8>) -> Result<(), Self::Err> {
let mut file = File::create(&self.filepath).map_err(EigenError::IOError)?;
file.write_all(&data).map_err(EigenError::IOError)
}
}

/// Score record
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScoreRecord {
Expand Down Expand Up @@ -247,42 +316,6 @@ pub fn str_to_32_byte_array(hex: &str) -> Result<[u8; 32], EigenError> {
.map_err(|e| EigenError::ConversionError(e.to_string()))
}

/// The `JSONFileStorage` struct provides a mechanism for persisting
/// and retrieving structured data to and from JSON files.
pub struct JSONFileStorage<T> {
filepath: PathBuf,
phantom: PhantomData<T>,
}

impl<T> JSONFileStorage<T> {
/// Creates a new JSONFileStorage.
pub fn new(filepath: PathBuf) -> Self {
Self { filepath, phantom: PhantomData }
}

/// Returns the path to the file.
pub fn filepath(&self) -> &PathBuf {
&self.filepath
}
}

impl<T: Serialize + DeserializeOwned + Clone> Storage<T> for JSONFileStorage<T> {
type Err = EigenError;

fn load(&self) -> Result<T, Self::Err> {
let file = File::open(&self.filepath).map_err(EigenError::IOError)?;
let reader = BufReader::new(file);
from_reader(reader).map_err(|e| EigenError::ParsingError(e.to_string()))
}

fn save(&mut self, data: T) -> Result<(), Self::Err> {
let json_str = to_string(&data).map_err(|e| EigenError::ParsingError(e.to_string()))?;

let mut file = File::create(&self.filepath).map_err(EigenError::IOError)?;
file.write_all(json_str.as_bytes()).map_err(EigenError::IOError)
}
}

#[cfg(test)]
mod tests {
use crate::storage::*;
Expand Down

0 comments on commit a33e930

Please sign in to comment.