Skip to content

Commit

Permalink
load generator config for confidential markets
Browse files Browse the repository at this point in the history
  • Loading branch information
akshay111meher committed Nov 18, 2024
1 parent 8609fc6 commit 17026b3
Show file tree
Hide file tree
Showing 8 changed files with 274 additions and 7 deletions.
2 changes: 1 addition & 1 deletion generator_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ pub mod client;
mod handler;
mod handler_funcs;
mod kalypso;
mod model;
pub mod model;
mod supervisord;
10 changes: 5 additions & 5 deletions helper/src/response.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use actix_web::http::StatusCode;
use actix_web::HttpResponse;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Serialize)]
struct JsonResponse {
message: String,
data: Option<Value>,
#[derive(Serialize, Deserialize, Debug)]
pub struct JsonResponse {
pub message: String,
pub data: Option<Value>,
}

struct ResponseOptions {
Expand Down
3 changes: 2 additions & 1 deletion kalypso-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ bytes = "1.0"
bindings = { path = "../bindings", package = "foundry-contracts" }
dotenv = "0.15.0"
dialoguer = "0.10.3"
ethers = { version = "2", features = ["rustls"] }
env_logger = "0.11"
flate2 = "1.0.28"
futures = "0.3"
ethers = { version = "2", features = ["rustls"] }
generator_client = {path = "../generator_client", package = "generator_client"}
hex = "0.4.3"
kalypso_helper = {path = "../helper", package = "helper"}
log = "0.4"
Expand Down
126 changes: 126 additions & 0 deletions kalypso-cli/src/common_deps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1121,3 +1121,129 @@ impl CommonDeps {
})
}
}

pub struct LoadGeneratorConfigInfo {
pub config: generator_client::model::GeneratorConfigSetupRequestBody,
pub generator_client_url: String,
}

impl CommonDeps {
pub fn load_operator_config_info(
config: &std::collections::HashMap<String, String>,
) -> Result<LoadGeneratorConfigInfo, String> {
get_config_ref!(config, "generator_client_url", generator_client_url);
get_config_ref!(config, "operator_address", operator_address);
get_config_ref!(config, "market_id", market_id);
get_config_ref!(config, "rpc_url", rpc_url);
get_config_ref!(config, "private_key", private_key);
get_config_ref!(config, "proof_marketplace", proof_marketplace_address);
get_config_ref!(config, "generator_registry", generator_registry_address);
get_config_ref!(config, "start_block", start_block);
get_config_ref!(config, "chain_id", chain_id);
get_config_ref!(config, "payment_token", payment_token);
get_config_ref!(config, "staking_token", staking_token);
get_config_ref!(config, "attestation_verifier", attestation_verifier_address);
get_config_ref!(config, "entity_registry", entity_key_registry_address);
get_config_ref!(config, "internal_prover_port", internal_prover_port);
get_config_ref!(config, "input_verification_url", input_verification_url);

let operator_address = operator_address
.parse::<Address>()
.map_err(|e| format!("Invalid Operator Address: {}", e))?;

let market_id = U256::from_dec_str(market_id.as_str())
.map_err(|e| format!("Invalid Market Id: {}", e))?;

let proof_marketplace_address = proof_marketplace_address
.parse::<Address>()
.map_err(|e| format!("Invalid Proof Marketplace address: {}", e))?;

let generator_registry_address = generator_registry_address
.parse::<Address>()
.map_err(|e| format!("Invalid Generator Registry address: {}", e))?;

let start_block = U256::from_dec_str(&start_block.as_str())
.map_err(|e| format!("Invalid Start Block: {}", e))?;

let chain_id = U256::from_dec_str(&&chain_id.as_str())
.map_err(|e| format!("Invalid Chain ID: {}", e))?;

let payment_token = payment_token
.parse::<Address>()
.map_err(|e| format!("Invalid Payment Token Address: {}", e))?;

let staking_token = staking_token
.parse::<Address>()
.map_err(|e| format!("Invalid Staking Token Address: {}", e))?;

let attestation_verifier_address = attestation_verifier_address
.parse::<Address>()
.map_err(|e| format!("Invalid Attestation Verifier Address: {}", e))?;

let entity_key_registry_address = entity_key_registry_address
.parse::<Address>()
.map_err(|e| format!("Invalid Entity Key Registry Address: {}", e))?;

let internal_prover_port = U256::from_dec_str(&&internal_prover_port.as_str())
.map_err(|e| format!("Internal Prover Port: {}", e))?;

Ok(LoadGeneratorConfigInfo {
config: generator_client::model::GeneratorConfigSetupRequestBody {
generator_config: Some(vec![
generator_client::model::SetupRequestBodyGeneratorConfig {
address: Some(format!(
"0x{}",
hex::encode(operator_address.as_bytes().to_vec())
)),
data: Some("Some Data".into()),
supported_markets: Some(vec![market_id.to_string()]),
},
]),
runtime_config: Some(generator_client::model::SetupRequestBodyRuntimeConfig {
ws_url: Some("wss:://not_used_so_using_some_dummy_value_to_pass".into()),
http_url: Some(rpc_url.to_string()),
private_key: Some(private_key.to_string()),
proof_market_place: Some(format!(
"0x{}",
hex::encode(proof_marketplace_address.as_bytes().to_vec())
)),
generator_registry: Some(format!(
"0x{}",
hex::encode(generator_registry_address.as_bytes().to_vec())
)),
start_block: Some(start_block.as_u32() as i32),
chain_id: Some(chain_id.as_u32() as i32),
payment_token: Some(format!(
"0x{}",
hex::encode(payment_token.as_bytes().to_vec())
)),
staking_token: Some(format!(
"0x{}",
hex::encode(staking_token.as_bytes().to_vec())
)),
attestation_verifier: Some(format!(
"0x{}",
hex::encode(attestation_verifier_address.as_bytes().to_vec())
)),
entity_registry: Some(format!(
"0x{}",
hex::encode(entity_key_registry_address.as_bytes().to_vec())
)),
markets: {
let mut markets = std::collections::HashMap::new();
// add market details and other info related to it here
markets.insert(
market_id.to_string(),
generator_client::model::MarketDetails {
port: internal_prover_port.to_string(),
ivs_url: input_verification_url.to_string(),
},
);
markets
},
}),
},
generator_client_url: generator_client_url.to_string(),
})
}
}
54 changes: 54 additions & 0 deletions kalypso-cli/src/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,42 @@
"prompt": "Enter the URL or kalypso indexer",
"secret": false,
"env_var": "INDEXER_URL"
},
{
"field": "generator_client_url",
"prompt": "Generator Client URL",
"secret": false,
"env_var": "GENERATOR_CLIENT_URL"
},
{
"field": "gas_key",
"prompt": "Enter gas key. This key will be used to spend gas on chain",
"secret": true,
"env_var": "GAS_KEY"
},
{
"field": "start_block",
"prompt": "Enter Start from which the operations should start",
"secret": false,
"env_var": "START_BLOCK"
},
{
"field": "attestation_verifier",
"prompt": "Enter Attestation Verifier Contract Address",
"secret": false,
"env_var": "ATTESTATION_VERIFIER_ADDRESS"
},
{
"field": "internal_prover_port",
"prompt": "Internal Port number on which proving server is running. It depeneds on market to market",
"secret": false,
"env_var": "INTERNAL_PROVER_PORT"
},
{
"field": "input_verification_url",
"prompt": "Enter input verification enclave URL. This url helps prover determine whether given inputs are valid using IVS service",
"secret": false,
"env_var": "INPUT_VERIFICATION_URL"
}
],
"operations": [
Expand Down Expand Up @@ -462,6 +498,24 @@
"network_opt_in_service",
"network_address"
]
},
{
"name": "Load Generator Config",
"description": "Load config in confidential generator. (Only works in testnet right now)",
"required_prompts": [
"generator_client_url",
"operator_address",
"rpc_url",
"market_id",
"proof_marketplace",
"generator_registry",
"chain_id",
"payment_token",
"staking_token",
"attestation_verifier",
"entity_registry",
"internal_prover_port"
]
}
]
}
78 changes: 78 additions & 0 deletions kalypso-cli/src/operations/generator_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use std::{collections::HashMap, error::Error};

use async_trait::async_trait;

use crate::common_deps::CommonDeps;

use super::Operation;

pub struct GeneratorConfig;

#[async_trait]
impl Operation for GeneratorConfig {
async fn execute(&self, config: HashMap<String, String>) -> Result<(), String> {
let load_generator_config_info = CommonDeps::load_operator_config_info(&config)?;
load_config(
load_generator_config_info.generator_client_url,
load_generator_config_info.config,
)
.await
.map_err(|_| "Failed loading generator config into the enclave.".to_string())?;

Ok(())
}
}

async fn load_config(
generator_client_url: String,
config: generator_client::model::GeneratorConfigSetupRequestBody,
) -> Result<(), Box<dyn Error>> {
// Initialize the HTTP client with a timeout (optional but recommended)
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()?;
let full_url = format!("{}/api/generatorConfigSetup", generator_client_url);

// Prepare the headers
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(reqwest::header::CONTENT_TYPE, "application/json".parse()?);

// Send the POST request
let response = client
.post(&full_url)
.headers(headers)
.json(&config)
.send()
.await?;

// Capture the HTTP status before moving the response
let status = response.status();

// Read the response body as text
let response_text = response.text().await?;

let json_response: kalypso_helper::response::JsonResponse =
match serde_json::from_str(&response_text) {
Ok(resp) => resp,
Err(e) => {
return Err(format!(
"Failed to parse JSON response. HTTP Status: {}, Body: {}, Error: {}",
status, response_text, e
)
.into())
}
};

// Check the HTTP status and the JSON message
if status.is_success() {
println!("{:?}", json_response);
Ok(())
} else {
// Return error with message
Err(format!(
"Failed to load config. HTTP Status: {}, Message: {}",
status, json_response.message
)
.into())
}
}
2 changes: 2 additions & 0 deletions kalypso-cli/src/operations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod complete_registration;
pub mod compute_pcrs;
pub mod create_marketplace;
pub mod create_request;
pub mod generator_config;
pub mod join_marketplace;
pub mod leave_or_request_leave_marketplace;
pub mod read_proof;
Expand Down Expand Up @@ -74,6 +75,7 @@ pub fn get_operation(name: &str) -> Option<Box<dyn Operation>> {
"Add IVS Key" => Some(Box::new(update_encryption_key::AddIvsKey)),
"Read Proof Bytes" => Some(Box::new(read_proof::ReadProof)),
"Request Symbiotic Stake" => Some(Box::new(symbiotic_opt_in::SymbioticOptIn)),
"Load Generator Config" => Some(Box::new(generator_config::GeneratorConfig)),
_ => unimplemented!(),
}
}
6 changes: 6 additions & 0 deletions kalypso-cli/src/prompts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ impl<'a> Prompter<'a> {
validators.insert("vault_address".to_string(), validate_eth_address);
validators.insert("network_address".to_string(), validate_eth_address);
validators.insert("indexer_url".to_string(), validate_rpc_url);
validators.insert("generator_client_url".to_string(), validate_rpc_url);
validators.insert("gas_key".to_string(), validate_private_key as Validator);
validators.insert("start_block".to_string(), validate_dec_str_id);
validators.insert("attestation_verifier".to_string(), validate_eth_address);
validators.insert("internal_prover_port".to_string(), validate_dec_str_id);
validators.insert("input_verification_url".to_string(), validate_rpc_url);

validators.insert(
"confirmation".to_string(),
Expand Down

0 comments on commit 17026b3

Please sign in to comment.