Skip to content

Commit

Permalink
Fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
grarco committed Nov 15, 2022
1 parent 268bc83 commit 8aa15d6
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 63 deletions.
33 changes: 25 additions & 8 deletions phase1-cli/src/bin/namada-ts.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use phase1_coordinator::{
authentication::{KeyPair, Production, Signature},
commands::{Computation, RandomSource, SEED_LENGTH},
io::{self, KeyPairUser, verify_signature},
io::{self, verify_signature, KeyPairUser},
objects::{ContributionFileSignature, ContributionInfo, ContributionState, TrimmedContributionInfo},
rest_utils::{ContributorStatus, PostChunkRequest, TOKENS_ZIP_FILE, UPDATE_TIME},
storage::Object,
Expand All @@ -23,7 +23,8 @@ use phase1_cli::{
requests,
CeremonyOpt,
CoordinatorUrl,
Token, VerifySignatureContribution,
Token,
VerifySignatureContribution,
};
use serde_json;
use setup_utils::calculate_hash;
Expand Down Expand Up @@ -549,14 +550,24 @@ async fn contribution_loop(
println!("{}\n", ASCII_CONTRIBUTION_DONE.bright_yellow());

// Attestation
if "n" == io::get_user_input("Would you like to provide an attestation of your contribution? [y/n]".bright_yellow(), Some(&Regex::new(r"^(?i)[yn]$").unwrap())).unwrap() {
if "n"
== io::get_user_input(
"Would you like to provide an attestation of your contribution? [y/n]".bright_yellow(),
Some(&Regex::new(r"^(?i)[yn]$").unwrap()),
)
.unwrap()
{
break;
} else {
loop {
let attestation_url = io::get_user_input("Please enter a valid url for your attestation:".bright_yellow(), None).unwrap();
let attestation_url =
io::get_user_input("Please enter a valid url for your attestation:".bright_yellow(), None)
.unwrap();
if Url::parse(attestation_url.as_str()).is_ok() {
// Send attestation to coordinator
requests::post_attestation(&client, &coordinator, &keypair, &attestation_url).await.expect(&format!("{}", "Failed attestation upload".red().bold()));
requests::post_attestation(&client, &coordinator, &keypair, &attestation_url)
.await
.expect(&format!("{}", "Failed attestation upload".red().bold()));
return;
}
}
Expand Down Expand Up @@ -720,7 +731,9 @@ async fn main() {
match opt {
CeremonyOpt::Contribute(branch) => {
match branch {
phase1_cli::Branches::AnotherMachine { request } => contribution_prelude(request.url, request.token, Branch::AnotherMachine).await,
phase1_cli::Branches::AnotherMachine { request } => {
contribution_prelude(request.url, request.token, Branch::AnotherMachine).await
}
phase1_cli::Branches::Default { request, custom_seed } => {
contribution_prelude(request.url, request.token, Branch::Default(custom_seed)).await
}
Expand Down Expand Up @@ -858,13 +871,17 @@ async fn main() {
let client = Client::new();
update_coordinator(&client, &url.coordinator, &keypair).await;
}
CeremonyOpt::VerifySignature(VerifySignatureContribution { pubkey, message, signature }) => {
CeremonyOpt::VerifySignature(VerifySignatureContribution {
pubkey,
message,
signature,
}) => {
let result = verify_signature(pubkey, signature, message);
if result {
println!("The contribution signature is correct.")
} else {
println!("The contribution signature is not correct.")
}
}
}
}
}
2 changes: 1 addition & 1 deletion phase1-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ pub struct VerifySignatureContribution {
#[structopt(about = "The contribution message hash")]
pub message: String,
#[structopt(about = "The contribution signature")]
pub signature: String
pub signature: String,
}

#[derive(Debug, StructOpt)]
Expand Down
22 changes: 14 additions & 8 deletions phase1-coordinator/src/coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1710,22 +1710,28 @@ impl Coordinator {
}

/// Updates the contribution attestation and summary to storage at the appropriate locator.
pub(crate) fn update_contribution_info_attestation(&mut self, round: u64, attestation: String) -> Result<(), CoordinatorError> {
pub(crate) fn update_contribution_info_attestation(
&mut self,
round: u64,
attestation: String,
) -> Result<(), CoordinatorError> {
// Retrieve current file to update
let updated_info = match self.storage.get(&Locator::ContributionInfoFile{
round_height: round,
})? {
let updated_info = match self
.storage
.get(&Locator::ContributionInfoFile { round_height: round })?
{
Object::ContributionInfoFile(info) => ContributionInfo {
attestation: Some(attestation),
..info
},
_ => return Err(CoordinatorError::StorageFailed)
_ => return Err(CoordinatorError::StorageFailed),
};

// Persist update to storage
self.storage.update(&Locator::ContributionInfoFile{
round_height: round,
}, Object::ContributionInfoFile(updated_info.clone()))?;
self.storage.update(
&Locator::ContributionInfoFile { round_height: round },
Object::ContributionInfoFile(updated_info.clone()),
)?;

// Update the summary
let mut summary = match self.storage.get(&Locator::ContributionsInfoSummary)? {
Expand Down
16 changes: 5 additions & 11 deletions phase1-coordinator/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,17 +211,11 @@ pub fn verify_signature(pubkey: String, signature: String, message: String) -> b
let signature = ed25519_compact::Signature::from_slice(&hex::decode(signature).unwrap());

match (pk, signature) {
(Ok(pk), Ok(signature)) => {
match pk.verify(&message, &signature) {
Ok(_) => true,
Err(_) => {
false
},
}
}
_ => {
false
}
(Ok(pk), Ok(signature)) => match pk.verify(&message, &signature) {
Ok(_) => true,
Err(_) => false,
},
_ => false,
}
}

Expand Down
73 changes: 42 additions & 31 deletions phase1-coordinator/src/rest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ use crate::{
TOKENS_ZIP_FILE,
},
s3::S3Ctx,
storage::{Locator, Object},
CoordinatorState,
Participant, storage::{Locator, Object},
Participant,
};
use rocket::{
get,
Expand Down Expand Up @@ -59,7 +60,8 @@ pub async fn join_queue(
token.clone(),
10,
)
}).await?
})
.await?
.map_err(|e| ResponseError::CoordinatorError(e))?;

Ok(Json(cohort))
Expand Down Expand Up @@ -350,41 +352,50 @@ pub async fn post_contribution_info(

/// Uploads the attestation for a contribution
#[post("/contributor/attestation", format = "json", data = "<request>")]
pub async fn post_attestation( coordinator: &State<Coordinator>,
pub async fn post_attestation(
coordinator: &State<Coordinator>,
participant: Participant,
request: LazyJson<(u64, String)>,) -> Result<()> {
let (round, attestation) = request.0;
request: LazyJson<(u64, String)>,
) -> Result<()> {
let (round, attestation) = request.0;

// Check url format
if let Err(e) = Url::parse(attestation.as_str()) {
return Err(ResponseError::IoError(e.to_string()))
// Check url format
if let Err(e) = Url::parse(attestation.as_str()) {
return Err(ResponseError::IoError(e.to_string()));
}

let read_lock = (*coordinator).clone().read_owned().await;
task::spawn_blocking(move || {
if !read_lock.is_current_contributor(&participant) && !read_lock.is_finished_contributor(&participant) {
// Only current or finished contributors are allowed to query this endpoint
return Err(crate::CoordinatorError::ParticipantUnauthorized);
}

let read_lock = (*coordinator).clone().read_owned().await;
task::spawn_blocking(move || {
if !read_lock.is_current_contributor(&participant) && !read_lock.is_finished_contributor(&participant) {
// Only current or finished contributors are allowed to query this endpoint
return Err(crate::CoordinatorError::ParticipantUnauthorized);
// Check the provided round height matches the signing participant
match read_lock
.storage()
.get(&Locator::ContributionInfoFile { round_height: round })?
{
Object::ContributionInfoFile(f) => {
if f.public_key == participant.address() {
Ok(())
} else {
Err(crate::CoordinatorError::ParticipantRoundHeightInvalid)
}
}
_ => Err(crate::CoordinatorError::StorageFailed),
}
})
.await?
.map_err(|e| ResponseError::CoordinatorError(e))?;

// Check the provided round height matches the signing participant
match read_lock.storage().get(&Locator::ContributionInfoFile{ round_height: round })? {
Object::ContributionInfoFile(f) => {
if f.public_key == participant.address() {
Ok(())
} else {
Err(crate::CoordinatorError::ParticipantRoundHeightInvalid)
}
},
_ => Err(crate::CoordinatorError::StorageFailed)
}})
.await?.map_err(|e| ResponseError::CoordinatorError(e))?;

// Update the contribution info and the summary with the attestation
let mut write_lock = (*coordinator).clone().write_owned().await;

task::spawn_blocking(move || write_lock.update_contribution_info_attestation(round, attestation)).await?.map_err(|e| ResponseError::CoordinatorError(e))
}
// Update the contribution info and the summary with the attestation
let mut write_lock = (*coordinator).clone().write_owned().await;

task::spawn_blocking(move || write_lock.update_contribution_info_attestation(round, attestation))
.await?
.map_err(|e| ResponseError::CoordinatorError(e))
}

/// Retrieve the contributions' info. This endpoint is accessible by anyone and does not require a signed request.
#[cfg(debug_assertions)]
Expand Down
10 changes: 8 additions & 2 deletions phase1-coordinator/src/rest_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -686,12 +686,18 @@ pub async fn perform_verify_chunks(coordinator: Coordinator, s3_ctx: &S3Ctx) ->
}
}

write_lock.storage().get_contributions_summary().map_err(|e| ResponseError::CoordinatorError(e))
write_lock
.storage()
.get_contributions_summary()
.map_err(|e| ResponseError::CoordinatorError(e))
})
.await??;

// Upload json file to S3
s3_ctx.upload_contributions_info(contributions_info).await.map_err(|e| ResponseError::CoordinatorError(CoordinatorError::Error(anyhow!(e.to_string()))))
s3_ctx
.upload_contributions_info(contributions_info)
.await
.map_err(|e| ResponseError::CoordinatorError(CoordinatorError::Error(anyhow!(e.to_string()))))
}

/// Performs the update of the [Coordinator](`crate::Coordinator`)
Expand Down
5 changes: 3 additions & 2 deletions phase1-coordinator/src/s3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ use rusoto_core::{region::Region, request::TlsError};
use rusoto_credential::{AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials};
use rusoto_s3::{
util::{PreSignedRequest, PreSignedRequestOption},
DeleteObjectRequest,
GetObjectRequest,
HeadObjectRequest,
PutObjectRequest,
S3Client,
StreamingBody,
S3, DeleteObjectRequest,
S3,
};
use std::str::FromStr;
use thiserror::Error;
Expand Down Expand Up @@ -89,7 +90,7 @@ impl S3Ctx {
.delete_object(delete_object_request)
.await
.map_or_else(|e| Err(S3Error::UploadError(e.to_string())), |_| Ok(()))?;

// Upload the updated file
let put_object_request = PutObjectRequest {
bucket: self.bucket.clone(),
Expand Down

0 comments on commit 8aa15d6

Please sign in to comment.