Skip to content
This repository has been archived by the owner on Jul 31, 2019. It is now read-only.

Commit

Permalink
took unwraps out of libvcx (#503)
Browse files Browse the repository at this point in the history
  • Loading branch information
rytmarsh authored and glowkey committed Sep 11, 2018
1 parent 9f23d18 commit e0fc5ad
Show file tree
Hide file tree
Showing 25 changed files with 211 additions and 257 deletions.
4 changes: 2 additions & 2 deletions vcx/libvcx/src/api/proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,11 +345,11 @@ pub extern fn vcx_get_proof(command_handle: u32,
Ok(x) => {
info!("vcx_get_proof_cb(command_handle: {}, proof_handle: {}, rc: {}, proof: {})", command_handle, proof_handle, 0, x);
let msg = CStringUtils::string_to_cstring(x);
cb(command_handle, error::SUCCESS.code_num, proof::get_proof_state(proof_handle).unwrap(), msg.as_ptr());
cb(command_handle, error::SUCCESS.code_num, proof::get_proof_state(proof_handle).unwrap_or(0), msg.as_ptr());
},
Err(x) => {
warn!("vcx_get_proof_cb(command_handle: {}, proof_handle: {}, rc: {}, proof: {})", command_handle, proof_handle, x.to_error_code(), "null");
cb(command_handle, x.to_error_code(), proof::get_proof_state(proof_handle).unwrap(), ptr::null_mut());
cb(command_handle, x.to_error_code(), proof::get_proof_state(proof_handle).unwrap_or(0), ptr::null_mut());
},
};

Expand Down
13 changes: 7 additions & 6 deletions vcx/libvcx/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ pub fn update_agent_profile(handle: u32) -> Result<u32, ConnectionError> {
match messages::update_data()
.to(&pw_did)
.name(&name)
.logo_url(&settings::get_config_value(settings::CONFIG_INSTITUTION_LOGO_URL).unwrap())
.logo_url(&settings::get_config_value(settings::CONFIG_INSTITUTION_LOGO_URL).map_err(|e| ConnectionError::CommonError(e))?)
.send_secure() {
Ok(_) => Ok(error::SUCCESS.code_num),
Err(ec) => Err(ConnectionError::CommonError(ec)),
Expand Down Expand Up @@ -510,11 +510,12 @@ pub fn build_connection_with_invite(source_id: &str, details: &str) -> Result<u3
pub fn parse_acceptance_details(handle: u32, message: &Message) -> Result<SenderDetail, ConnectionError> {

debug!("parsing acceptance details for message {:?}", message);
if message.payload.is_none() {
return Err(ConnectionError::CommonError(error::INVALID_MSGPACK.code_num)) }

let my_vk = settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_VERKEY).unwrap();
let payload = messages::to_u8(message.payload.as_ref().unwrap());
let my_vk = settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_VERKEY).map_err(|e| ConnectionError::CommonError(e))?;
let payload = messages::to_u8(
message.payload
.as_ref()
.ok_or(ConnectionError::CommonError(error::INVALID_MSGPACK.code_num))?
);
// TODO: check returned verkey
let (_, payload) = crypto::parse_msg(&my_vk,&payload).map_err(|e| {ConnectionError::CommonError(e)})?;

Expand Down
27 changes: 11 additions & 16 deletions vcx/libvcx/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ impl Credential {
self.credential_request = Some(req.clone());
let req = serde_json::to_string(&req).or(Err(CredentialError::InvalidCredentialJson()))?;
let data: Vec<u8> = connection::generate_encrypted_payload(local_my_vk, local_their_vk, &req, "CRED_REQ").map_err(|e| CredentialError::CommonError(e.to_error_code()))?;
let offer_msg_id = self.credential_offer.as_ref().unwrap().msg_ref_id.as_ref().ok_or(CredentialError::CommonError(error::CREATE_CREDENTIAL_REQUEST_ERROR.code_num))?;
let offer_msg_id = self.credential_offer.as_ref().ok_or(CredentialError::CommonError(error::CREATE_CREDENTIAL_REQUEST_ERROR.code_num))?
.msg_ref_id.as_ref().ok_or(CredentialError::CommonError(error::CREATE_CREDENTIAL_REQUEST_ERROR.code_num))?;

if self.payment_info.is_some() {
let (payment_txn, _) = self.submit_payment()?;
Expand Down Expand Up @@ -184,7 +185,7 @@ impl Credential {
let credential = extract_json_payload(&payload)?;

let credential_msg: CredentialMessage = serde_json::from_str(&credential)
.or(Err(error::INVALID_CREDENTIAL_JSON.code_num)).unwrap();
.or(Err(error::INVALID_CREDENTIAL_JSON.code_num))?;

let cred_req: &CredentialRequest = self.credential_request.as_ref()
.ok_or(CredentialError::InvalidCredentialJson().to_error_code())?;
Expand Down Expand Up @@ -276,11 +277,10 @@ impl Credential {
fn get_source_id(&self) -> &String {&self.source_id}

fn get_payment_txn(&self) -> Result<PaymentTxn, u32> {
if self.payment_info.is_none() || self.payment_txn.is_none() {
return Err(error::NO_PAYMENT_INFORMATION.code_num);
match self.payment_txn {
Some(ref payment_txn) if self.payment_info.is_some() => Ok(payment_txn.clone()),
_ => Err(error::NO_PAYMENT_INFORMATION.code_num)
}

Ok(self.payment_txn.clone().unwrap())
}

fn set_credential_offer(&mut self, offer: CredentialOffer){
Expand Down Expand Up @@ -432,9 +432,9 @@ pub fn get_credential_offer_msg(connection_handle: u32, msg_id: &str) -> Result<
offer.msg_ref_id = Some(message[0].uid.to_owned());
let mut payload = Vec::new();
payload.push(json!(offer));
if payment_info.is_some() { payload.push(json!(payment_info.unwrap())); }
if let Some(p) = payment_info { payload.push(json!(p)); }

Ok(serde_json::to_string_pretty(&payload).unwrap())
Ok(serde_json::to_string_pretty(&payload).or(Err(CredentialError::CommonError(error::INVALID_MESSAGES.code_num)))?)
} else {
Err(CredentialError::CommonError(error::INVALID_MESSAGES.code_num))
}
Expand Down Expand Up @@ -472,13 +472,13 @@ pub fn get_credential_offer_messages(connection_handle: u32, match_name: Option<
offer.msg_ref_id = Some(msg.uid.to_owned());
let mut payload = Vec::new();
payload.push(json!(offer));
if payment_info.is_some() { payload.push(json!(payment_info.unwrap())); }
if let Some(p) = payment_info { payload.push(json!(p)); }

messages.push(payload);
}
}

Ok(serde_json::to_string_pretty(&messages).unwrap())
Ok(serde_json::to_string_pretty(&messages).or(Err(CredentialError::CommonError(error::INVALID_MESSAGES.code_num)))?)
}

pub fn parse_json_offer(offer: &str) -> Result<(CredentialOffer, Option<PaymentInfo>), CredentialError> {
Expand All @@ -498,12 +498,7 @@ pub fn parse_json_offer(offer: &str) -> Result<(CredentialOffer, Option<PaymentI
}
}
}
if offer.is_some() {
Ok((offer.unwrap(), payment))
}
else {
Err(CredentialError::InvalidCredentialJson())
}
Ok((offer.ok_or(CredentialError::InvalidCredentialJson())?, payment))
}

pub fn release(handle: u32) -> Result<(), CredentialError> {
Expand Down
12 changes: 2 additions & 10 deletions vcx/libvcx/src/credential_def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,7 @@ impl CredentialDef {

pub fn set_source_id(&mut self, source_id: String) { self.source_id = source_id.clone(); }

fn get_payment_txn(&self) -> Result<PaymentTxn, u32> {
if self.payment_txn.is_some() {
Ok(self.payment_txn.clone().unwrap())
} else {
Err(error::NOT_READY.code_num)
}
}
fn get_payment_txn(&self) -> Result<PaymentTxn, u32> { Ok(self.payment_txn.clone().ok_or(error::NOT_READY.code_num)?) }

fn to_string_with_version(&self) -> String {
json!({
Expand All @@ -75,15 +69,13 @@ impl CredentialDef {
}

fn from_string_with_version(data: &str) -> Result<CredentialDef, CredDefError> {
let values:serde_json::Value = serde_json::from_str(data).unwrap();
let values:serde_json::Value = serde_json::from_str(data).or(Err(CredDefError::CommonError(error::INVALID_JSON.code_num)))?;
let version = values["version"].to_string();
let data = values["data"].to_string();
serde_json::from_str(&data).or(Err(CredDefError::CreateCredDefError()))
}
}

//Todo: Add a get_cred_def_id call

pub fn create_new_credentialdef(source_id: String,
name: String,
issuer_did: String,
Expand Down
40 changes: 15 additions & 25 deletions vcx/libvcx/src/disclosed_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use schema::{ LedgerSchema };

use utils::libindy::anoncreds;
use utils::libindy::crypto;
use utils::serde_utils;

use settings;
use utils::httpclient;
Expand Down Expand Up @@ -85,29 +86,18 @@ fn credential_def_identifiers(credentials: &str) -> Result<Vec<(String, String,
let credentials: Value = serde_json::from_str(credentials)
.or(Err(ProofError::CommonError(error::INVALID_JSON.code_num)))?;

if let Value::Object(ref map) = credentials["attrs"] {
for (requested_attr, value) in map {
if let Value::Object(ref attr_obj) = value["cred_info"] {

let cred_uuid = match attr_obj.get("referent") {
Some(i) => if i.is_string() { i.as_str().unwrap() } else { return Err(ProofError::CommonError(error::INVALID_JSON.code_num))},
None => return Err(ProofError::CommonError(error::INVALID_JSON.code_num)),
};

let schema_id = match attr_obj.get("schema_id") {
Some(i) => if i.is_string() { i.as_str().unwrap() } else { return Err(ProofError::CommonError(error::INVALID_JSON.code_num))},
None => return Err(ProofError::CommonError(error::INVALID_JSON.code_num)),
};

let cred_def_id = match attr_obj.get("cred_def_id") {
Some(i) => if i.is_string() { i.as_str().unwrap() } else { return Err(ProofError::CommonError(error::INVALID_JSON.code_num))},
None => return Err(ProofError::CommonError(error::INVALID_JSON.code_num)),
};

rtn.push((requested_attr.to_string(),
cred_uuid.to_string(),
schema_id.to_string(),
cred_def_id.to_string()))
if let Value::Object(ref attrs) = credentials["attrs"] {
for (requested_attr, value) in attrs {
if let Some(ref attr_obj) = value.get("cred_info") {
rtn.push((
requested_attr.to_string(),
serde_utils::get_value_to_string("referent", attr_obj)
.map_err(|e| ProofError::CommonError(e))?,
serde_utils::get_value_to_string("schema_id", attr_obj)
.map_err(|e| ProofError::CommonError(e))?,
serde_utils::get_value_to_string("cred_def_id", attr_obj)
.map_err(|e| ProofError::CommonError(e))?
));
}
}
}
Expand Down Expand Up @@ -433,7 +423,7 @@ pub fn get_proof_request(connection_handle: u32, msg_id: &str) -> Result<String,
.or(Err(ProofError::CommonError(error::INVALID_HTTP_RESPONSE.code_num)))?;

request.msg_ref_id = Some(message[0].uid.to_owned());
Ok(serde_json::to_string_pretty(&request).unwrap())
Ok(serde_json::to_string_pretty(&request).or(Err(ProofError::InvalidJson()))?)
} else {
Err(ProofError::CommonError(error::INVALID_MESSAGES.code_num))
}
Expand Down Expand Up @@ -479,7 +469,7 @@ pub fn get_proof_request_messages(connection_handle: u32, match_name: Option<&st
}
}

Ok(serde_json::to_string_pretty(&messages).unwrap())
Ok(serde_json::to_string_pretty(&messages).or(Err(ProofError::InvalidJson()))?)
}

pub fn get_source_id(handle: u32) -> Result<String, u32> {
Expand Down
23 changes: 12 additions & 11 deletions vcx/libvcx/src/issuer_credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl IssuerCredential {
let cred_json = json!(credential_offer);
let mut payload = Vec::new();

if payment.is_some() { payload.push(json!(payment.unwrap())); }
if let Some(x) = payment { payload.push(json!(x)); }
payload.push(cred_json);
let payload = match serde_json::to_string(&payload) {
Ok(p) => p,
Expand Down Expand Up @@ -328,16 +328,17 @@ impl IssuerCredential {
}

fn get_payment_txn(&self) -> Result<payments::PaymentTxn, u32> {
if self.price == 0 || self.payment_address.is_none() { return Err(error::NO_PAYMENT_INFORMATION.code_num); }

let payment_address = self.payment_address.clone().unwrap();

Ok(payments::PaymentTxn {
amount: self.price,
credit: true,
inputs: vec![payment_address],
outputs: Vec::new(),
})
match self.payment_address {
Some(ref payment_address) if self.price > 0 => {
Ok(payments::PaymentTxn {
amount: self.price,
credit: true,
inputs: vec![payment_address.to_string()],
outputs: Vec::new(),
})
},
_ => Err(error::NO_PAYMENT_INFORMATION.code_num)
}
}

pub fn to_string(&self) -> String {
Expand Down
79 changes: 41 additions & 38 deletions vcx/libvcx/src/messages/agent_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,34 +94,15 @@ pub fn connect_register_provision(endpoint: &str,
Err(_) => (), // If MS is already in wallet then just continue
};

let seed = match seed {
Some(x) => x,
None => "".to_string(),
};

let name = match name {
Some(x) => x,
None => "<CHANGE_ME>".to_string(),
};

let logo = match logo {
Some(x) => x,
None => "<CHANGE_ME>".to_string(),
};

let path = match path {
Some(x) => x,
None => "<CHANGE_ME>".to_string(),
};
let seed = seed.unwrap_or("".to_string());
let name = name.unwrap_or("<CHANGE_ME>".to_string());
let logo = logo.unwrap_or("<CHANGE_ME>".to_string());
let path = path.unwrap_or("<CHANGE_ME>".to_string());

let seed_opt = if seed.len() > 0 {Some(seed.as_ref())} else {None};
let (my_did, my_vk) = create_and_store_my_did(seed_opt)?;

let issuer_seed = match issuer_seed {
Some(x) => x,
None => "".to_string(),
};

let issuer_seed = issuer_seed.unwrap_or("".to_string());
let issuer_seed_opt = if issuer_seed.len() > 0 {Some(issuer_seed.as_ref())} else {None};
let (issuer_did, issuer_vk) = create_and_store_my_did(issuer_seed_opt)?;

Expand All @@ -142,13 +123,17 @@ pub fn connect_register_provision(endpoint: &str,
from_did: my_did.to_string(),
from_vk: my_vk.to_string(),
};
let data = Bundled::create(encode::to_vec_named(&payload).unwrap()).encode()?;
let data = Bundled::create(
encode::to_vec_named(&payload).or(Err(error::UNKNOWN_ERROR.code_num))?
).encode()?;
let data = bundle_for_agency(data, &agency_did)?;
let data = unbundle_from_agency(httpclient::post_u8(&data).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num).unwrap())?;
let data = unbundle_from_agency(
httpclient::post_u8(&data).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num)?
)?;

trace!("deserializing connect response: {:?}", data);
let mut de = Deserializer::new(&data[0][..]);
let response: ConnectResponseMsg = Deserialize::deserialize(&mut de).map_err(|ec| {error::INVALID_OPTION.code_num}).unwrap();
let response: ConnectResponseMsg = Deserialize::deserialize(&mut de).map_err(|ec| {error::INVALID_OPTION.code_num})?;
//self.my_vk = Some(connection::get_pw_verkey(connection_handle).map_err(|ec| CredentialError::CommonError(ec.to_error_code()))?);
let agency_pw_vk = response.from_vk.to_owned();
let agency_pw_did = response.from_did.to_owned();
Expand All @@ -161,28 +146,39 @@ pub fn connect_register_provision(endpoint: &str,
msg_type: MsgType { name: "SIGNUP".to_string(), ver: "1.0".to_string(), },
};

let data = encode::to_vec_named(&payload).unwrap();
let data = Bundled::create(data).encode().unwrap();
let data = encode::to_vec_named(&payload)
.or(Err(error::UNKNOWN_ERROR.code_num))?;
let data = Bundled::create(data)
.encode()
.or(Err(error::UNKNOWN_ERROR.code_num))?;
let data = bundle_for_agency(data, &agency_pw_did)?;
let data = unbundle_from_agency(httpclient::post_u8(&data).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num).unwrap())?;
let data = unbundle_from_agency(
httpclient::post_u8(&data).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num)?
)?;

trace!("deserializing register response: {:?}", data);
let mut de = Deserializer::new(&data[0][..]);
let response: RegisterResponse = Deserialize::deserialize(&mut de).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num).unwrap();
let response: RegisterResponse = Deserialize::deserialize(&mut de)
.map_err(|e|error::INVALID_HTTP_RESPONSE.code_num)?;

/* STEP 3 - CREATE AGENT */
let payload = GenericMsg {
msg_type: MsgType { name: "CREATE_AGENT".to_string(), ver: "1.0".to_string(), },
};

let data = encode::to_vec_named(&payload).unwrap();
let data = Bundled::create(data).encode().unwrap();
let data = encode::to_vec_named(&payload)
.or(Err(error::UNKNOWN_ERROR.code_num))?;
let data = Bundled::create(data).encode()
.or(Err(error::UNKNOWN_ERROR.code_num))?;
let data = bundle_for_agency(data, &agency_pw_did)?;
let data = unbundle_from_agency(httpclient::post_u8(&data).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num).unwrap())?;
let data = unbundle_from_agency(
httpclient::post_u8(&data).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num)?
)?;

trace!("deserializing provision response: {:?}", data);
let mut de = Deserializer::new(&data[0][..]);
let response: ConnectResponseMsg = Deserialize::deserialize(&mut de).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num).unwrap();
let response: ConnectResponseMsg = Deserialize::deserialize(&mut de)
.map_err(|e|error::INVALID_HTTP_RESPONSE.code_num)?;
let agent_did = response.from_did;
let agent_vk = response.from_vk;

Expand Down Expand Up @@ -235,10 +231,17 @@ pub fn update_agent_info(id: &str, value: &str) -> Result<(), u32> {
let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID)?;
let endpoint = settings::get_config_value(settings::CONFIG_AGENCY_ENDPOINT)?;

let data = encode::to_vec_named(&new_config).unwrap();
let data = Bundled::create(data).encode().unwrap();
let data = encode::to_vec_named(&new_config)
.or(Err(error::UNKNOWN_ERROR.code_num))?;

let data = Bundled::create(data).encode()
.or(Err(error::UNKNOWN_ERROR.code_num))?;

let data = bundle_for_agency(data, &to_did)?;
let data = unbundle_from_agency(httpclient::post_u8(&data).map_err(|e|error::INVALID_HTTP_RESPONSE.code_num).unwrap())?;

let data = unbundle_from_agency(
httpclient::post_u8(&data) .map_err(|e|error::INVALID_HTTP_RESPONSE.code_num)?
)?;

Ok(())
}
Expand Down
Loading

0 comments on commit e0fc5ad

Please sign in to comment.