diff --git a/vcx/libvcx/src/api/proof.rs b/vcx/libvcx/src/api/proof.rs index 17f0f11d..15af36d3 100644 --- a/vcx/libvcx/src/api/proof.rs +++ b/vcx/libvcx/src/api/proof.rs @@ -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()); }, }; diff --git a/vcx/libvcx/src/connection.rs b/vcx/libvcx/src/connection.rs index 4552723c..55eb409c 100644 --- a/vcx/libvcx/src/connection.rs +++ b/vcx/libvcx/src/connection.rs @@ -384,7 +384,7 @@ pub fn update_agent_profile(handle: u32) -> Result { 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)), @@ -510,11 +510,12 @@ pub fn build_connection_with_invite(source_id: &str, details: &str) -> Result Result { 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)})?; diff --git a/vcx/libvcx/src/credential.rs b/vcx/libvcx/src/credential.rs index 0fc22591..6adab09d 100644 --- a/vcx/libvcx/src/credential.rs +++ b/vcx/libvcx/src/credential.rs @@ -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 = 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()?; @@ -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())?; @@ -276,11 +277,10 @@ impl Credential { fn get_source_id(&self) -> &String {&self.source_id} fn get_payment_txn(&self) -> Result { - 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){ @@ -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)) } @@ -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), CredentialError> { @@ -498,12 +498,7 @@ pub fn parse_json_offer(offer: &str) -> Result<(CredentialOffer, Option Result<(), CredentialError> { diff --git a/vcx/libvcx/src/credential_def.rs b/vcx/libvcx/src/credential_def.rs index cb0f4d1c..c9037b06 100644 --- a/vcx/libvcx/src/credential_def.rs +++ b/vcx/libvcx/src/credential_def.rs @@ -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 { - 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 { Ok(self.payment_txn.clone().ok_or(error::NOT_READY.code_num)?) } fn to_string_with_version(&self) -> String { json!({ @@ -75,15 +69,13 @@ impl CredentialDef { } fn from_string_with_version(data: &str) -> Result { - 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, diff --git a/vcx/libvcx/src/disclosed_proof.rs b/vcx/libvcx/src/disclosed_proof.rs index 8556c709..d829a27a 100644 --- a/vcx/libvcx/src/disclosed_proof.rs +++ b/vcx/libvcx/src/disclosed_proof.rs @@ -17,6 +17,7 @@ use schema::{ LedgerSchema }; use utils::libindy::anoncreds; use utils::libindy::crypto; +use utils::serde_utils; use settings; use utils::httpclient; @@ -85,29 +86,18 @@ fn credential_def_identifiers(credentials: &str) -> Result 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))? + )); } } } @@ -433,7 +423,7 @@ pub fn get_proof_request(connection_handle: u32, msg_id: &str) -> Result Result { diff --git a/vcx/libvcx/src/issuer_credential.rs b/vcx/libvcx/src/issuer_credential.rs index 04994c94..dffa264a 100644 --- a/vcx/libvcx/src/issuer_credential.rs +++ b/vcx/libvcx/src/issuer_credential.rs @@ -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, @@ -328,16 +328,17 @@ impl IssuerCredential { } fn get_payment_txn(&self) -> Result { - 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 { diff --git a/vcx/libvcx/src/messages/agent_utils.rs b/vcx/libvcx/src/messages/agent_utils.rs index c87456b0..04f77dc7 100644 --- a/vcx/libvcx/src/messages/agent_utils.rs +++ b/vcx/libvcx/src/messages/agent_utils.rs @@ -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 => "".to_string(), - }; - - let logo = match logo { - Some(x) => x, - None => "".to_string(), - }; - - let path = match path { - Some(x) => x, - None => "".to_string(), - }; + let seed = seed.unwrap_or("".to_string()); + let name = name.unwrap_or("".to_string()); + let logo = logo.unwrap_or("".to_string()); + let path = path.unwrap_or("".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)?; @@ -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(); @@ -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; @@ -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(()) } diff --git a/vcx/libvcx/src/messages/create_key.rs b/vcx/libvcx/src/messages/create_key.rs index 990ea6ca..4cafa04b 100644 --- a/vcx/libvcx/src/messages/create_key.rs +++ b/vcx/libvcx/src/messages/create_key.rs @@ -138,7 +138,7 @@ impl GeneralMessage for CreateKeyMsg { debug!("create_keys inner bundle: {:?}", data); let msg = Bundled::create(data).encode()?; - let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID).unwrap(); + let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID)?; bundle_for_agency(msg, &to_did) } } @@ -148,7 +148,7 @@ pub fn parse_create_keys_response(response: Vec) -> Result<(String, String), debug!("create keys response inner bundle: {:?}", data[0]); let mut de = Deserializer::new(&data[0][..]); - let response: CreateKeyResponse = Deserialize::deserialize(&mut de).unwrap(); + let response: CreateKeyResponse = Deserialize::deserialize(&mut de).or(Err(error::UNKNOWN_ERROR.code_num))?; Ok((response.for_did, response.for_verkey)) } diff --git a/vcx/libvcx/src/messages/get_message.rs b/vcx/libvcx/src/messages/get_message.rs index 4f87164c..f319605a 100644 --- a/vcx/libvcx/src/messages/get_message.rs +++ b/vcx/libvcx/src/messages/get_message.rs @@ -111,12 +111,12 @@ impl GetMessages{ } self.payload.msg_type.name = "GET_MSGS_BY_CONNS".to_string(); - let data = encode::to_vec_named(&self.payload).unwrap(); + let data = encode::to_vec_named(&self.payload).or(Err(error::UNKNOWN_ERROR.code_num))?; trace!("get_message content: {:?}", data); let msg = Bundled::create(data).encode()?; - let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID).unwrap(); + let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID)?; let data = bundle_for_agency(msg, &to_did)?; match httpclient::post_u8(&data) { @@ -145,7 +145,7 @@ impl GeneralMessage for GetMessages{ return Err(self.validate_rc) } - let data = encode::to_vec_named(&self.payload).unwrap(); + let data = encode::to_vec_named(&self.payload).or(Err(error::UNKNOWN_ERROR.code_num))?; trace!("get_message content: {:?}", data); let msg = Bundled::create(data).encode()?; @@ -213,14 +213,13 @@ impl Message { pub fn decrypt(&self, vk: &str) -> Message { let mut new_message = self.clone(); - if self.payload.is_some() { - let payload = ::messages::to_u8(&self.payload.clone().unwrap()); + if let Some(ref payload) = self.payload { + let payload = ::messages::to_u8(payload); match ::utils::libindy::crypto::parse_msg(&vk, &payload) { Ok(x) => { - new_message.decrypted_payload = match to_json(&x.1) { - Ok(x) => Some(x.to_string()), - Err(_) => None, - }; + new_message.decrypted_payload = to_json(&x.1) + .map(|i| i.to_string()) + .ok(); } Err(_) => (), }; @@ -326,27 +325,24 @@ pub fn get_connection_messages(pw_did: &str, pw_vk: &str, agent_did: &str, agent pub fn get_ref_msg(msg_id: &str, pw_did: &str, pw_vk: &str, agent_did: &str, agent_vk: &str) -> Result<(String, Vec), u32> { let message = get_connection_messages(pw_did, pw_vk, agent_did, agent_vk, Some(vec![msg_id.to_string()]))?; trace!("checking for ref_msg: {:?}", message); - let msg_id; - if message[0].status_code == MessageAccepted.as_string() && !message[0].ref_msg_id.is_none() { - msg_id = message[0].ref_msg_id.clone().unwrap() - } - else { - return Err(error::NOT_READY.code_num); - } - let message = get_connection_messages(pw_did, pw_vk, agent_did, agent_vk, Some(vec![msg_id.to_string()]))?; + let msg_id = match message[0].ref_msg_id.clone() { + Some(ref ref_msg_id) if message[0].status_code == MessageAccepted.as_string() => ref_msg_id.to_string(), + _ => return Err(error::NOT_READY.code_num), + }; + + let message = get_connection_messages(pw_did, pw_vk, agent_did, agent_vk, Some(vec![msg_id]))?; trace!("checking for pending message: {:?}", message); // this will work for both credReq and proof types - if message[0].status_code == MessagePending.as_string() && !message[0].payload.is_none() { - let data = to_u8(message[0].payload.as_ref().unwrap()); - // TOD: check returned verkey - let (_, msg) = crypto::parse_msg(&pw_vk, &data)?; - Ok((message[0].uid.clone(), msg)) - } - else { - Err(error::INVALID_HTTP_RESPONSE.code_num) + match message[0].payload.clone() { + Some(ref payload) if message[0].status_code == MessagePending.as_string() => { + // TODO: check returned verkey + let (_, msg) = crypto::parse_msg(&pw_vk, &to_u8(payload))?; + Ok((message[0].uid.clone(), msg)) + }, + _ => Err(error::INVALID_HTTP_RESPONSE.code_num) } } diff --git a/vcx/libvcx/src/messages/invite.rs b/vcx/libvcx/src/messages/invite.rs index aaef0a6f..eab0cafb 100644 --- a/vcx/libvcx/src/messages/invite.rs +++ b/vcx/libvcx/src/messages/invite.rs @@ -371,8 +371,8 @@ impl GeneralMessage for SendInvite{ self.generate_signature()?; debug!("connection invitation details: {}", serde_json::to_string(&self.payload.msg_detail_payload).unwrap_or("failure".to_string())); - let create = encode::to_vec_named(&self.payload.create_payload).unwrap(); - let details = encode::to_vec_named(&self.payload.msg_detail_payload).unwrap(); + let create = encode::to_vec_named(&self.payload.create_payload).or(Err(error::UNKNOWN_ERROR.code_num))?; + let details = encode::to_vec_named(&self.payload.msg_detail_payload).or(Err(error::UNKNOWN_ERROR.code_num))?; let mut bundle = Bundled::create(create); bundle.bundled.push(details); @@ -407,8 +407,8 @@ impl GeneralMessage for AcceptInvite{ self.generate_signature()?; debug!("connection invitation details: {}", serde_json::to_string(&self.payload.msg_detail_payload).unwrap_or("failure".to_string())); - let create = encode::to_vec_named(&self.payload.create_payload).unwrap(); - let details = encode::to_vec_named(&self.payload.msg_detail_payload).unwrap(); + let create = encode::to_vec_named(&self.payload.create_payload).or(Err(error::UNKNOWN_ERROR.code_num))?; + let details = encode::to_vec_named(&self.payload.msg_detail_payload).or(Err(error::UNKNOWN_ERROR.code_num))?; let mut bundle = Bundled::create(create); bundle.bundled.push(details); diff --git a/vcx/libvcx/src/messages/mod.rs b/vcx/libvcx/src/messages/mod.rs index 101880c6..6151a6b1 100644 --- a/vcx/libvcx/src/messages/mod.rs +++ b/vcx/libvcx/src/messages/mod.rs @@ -188,9 +188,9 @@ pub fn extract_json_payload(data: &Vec) -> Result { } pub fn bundle_for_agency(message: Vec, did: &str) -> Result, u32> { - let agency_vk = settings::get_config_value(settings::CONFIG_AGENCY_VERKEY).unwrap(); - let agent_vk = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_VERKEY).unwrap(); - let my_vk = settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_VERKEY).unwrap(); + let agency_vk = settings::get_config_value(settings::CONFIG_AGENCY_VERKEY)?; + let agent_vk = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_VERKEY)?; + let my_vk = settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_VERKEY)?; trace!("pre encryption msg: {:?}", message); let msg = crypto::prep_msg(wallet::get_wallet_handle(), &my_vk, &agent_vk, &message[..])?; @@ -201,7 +201,7 @@ pub fn bundle_for_agency(message: Vec, did: &str) -> Result, u32> { fwd: did.to_owned(), msg, }; - let outer = encode::to_vec_named(&outer).unwrap(); + let outer = encode::to_vec_named(&outer).or(Err(error::UNKNOWN_ERROR.code_num))?; trace!("forward bundle: {:?}", outer); let msg = Bundled::create(outer).encode()?; @@ -220,18 +220,18 @@ pub fn bundle_for_agent(message: Vec, pw_vk: &str, agent_did: &str, agent_vk fwd: agent_did.to_string(), msg, }; - let inner = encode::to_vec_named(&inner).unwrap(); + let inner = encode::to_vec_named(&inner).or(Err(error::UNKNOWN_ERROR.code_num))?; debug!("inner forward: {:?}", inner); let msg = Bundled::create(inner).encode()?; - let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID).unwrap(); + let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID)?; bundle_for_agency(msg, &to_did) } pub fn unbundle_from_agency(message: Vec) -> Result>, u32> { - let my_vk = settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_VERKEY).unwrap(); + let my_vk = settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_VERKEY)?; let (_, data) = crypto::parse_msg(&my_vk, &message[..])?; diff --git a/vcx/libvcx/src/messages/proofs/proof_message.rs b/vcx/libvcx/src/messages/proofs/proof_message.rs index 597b4211..a14e4fb8 100644 --- a/vcx/libvcx/src/messages/proofs/proof_message.rs +++ b/vcx/libvcx/src/messages/proofs/proof_message.rs @@ -1,6 +1,6 @@ extern crate serde_json; -use utils::{ error }; +use utils::{ error, serde_utils }; use serde_json::Value; use error::proof::ProofError; @@ -52,21 +52,15 @@ impl ProofMessage { .or(Err(ProofError::CommonError(error::INVALID_JSON.code_num)))?; if let Value::Array(ref identifiers) = credentials["identifiers"] { - for identifier in identifiers { - let schema_id = match identifier.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 identifier.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)), - }; - //Todo: handle rev_reg_id - let rev_reg_id = String::new(); - - rtn.push((schema_id.to_string(), cred_def_id.to_string(), rev_reg_id)); + let reg_rev_id = String::new(); + rtn.push(( + serde_utils::get_value_to_string("schema_id", identifier) + .map_err(|e| ProofError::CommonError(e))?, + serde_utils::get_value_to_string("cred_def_id", identifier) + .map_err(|e| ProofError::CommonError(e))?, + reg_rev_id + )); } } diff --git a/vcx/libvcx/src/messages/send_message.rs b/vcx/libvcx/src/messages/send_message.rs index 69c6d6fa..2e483d45 100644 --- a/vcx/libvcx/src/messages/send_message.rs +++ b/vcx/libvcx/src/messages/send_message.rs @@ -157,8 +157,8 @@ impl GeneralMessage for SendMessage{ }; debug!("SendMessage details: {:?}", detail); - let create = encode::to_vec_named(&create).unwrap(); - let detail = encode::to_vec_named(&detail).unwrap(); + let create = encode::to_vec_named(&create).or(Err(error::UNKNOWN_ERROR.code_num))?; + let detail = encode::to_vec_named(&detail).or(Err(error::UNKNOWN_ERROR.code_num))?; let mut bundle = Bundled::create(create); bundle.bundled.push(detail); @@ -184,42 +184,25 @@ fn parse_send_message_response(response: Vec) -> Result { } let mut de = Deserializer::new(&data[1][..]); - let response: SendMessageResponse = match Deserialize::deserialize(&mut de) { - Ok(x) => x, - Err(x) => { - error!("Could not parse messagepack: {}", x); - return Err(error::INVALID_MSGPACK.code_num) - }, - }; + let response: SendMessageResponse = Deserialize::deserialize(&mut de) + .or(Err(error::INVALID_MSGPACK.code_num))?; debug!("messages: {:?}", response); - match serde_json::to_string(&response) { - Ok(x) => Ok(x), - Err(_) => Err(error::INVALID_JSON.code_num), - } + serde_json::to_string(&response).or(Err(error::INVALID_JSON.code_num)) } pub fn parse_msg_uid(response: &str) -> Result { - match serde_json::from_str(response) { - Ok(json) => { - let json: serde_json::Value = json; - match json["uids"].as_array() { - Some(x) => { - Ok(String::from(x[0].as_str().unwrap())) - }, - None => { - info!("response had no uid"); - Err(error::INVALID_JSON.code_num) - }, - } - - }, - Err(_) => { - info!("get_messages called without a valid response from server"); - Err(error::INVALID_JSON.code_num) - } - } + serde_json::from_str::(response) + .or(Err(error::INVALID_JSON.code_num))?["uids"] + .as_array() + .map_or(Err(error::INVALID_JSON.code_num), |uids| { + Ok(uids[0] + .as_str() + .ok_or(error::INVALID_JSON.code_num)? + .to_string() + ) + }) } #[cfg(test)] diff --git a/vcx/libvcx/src/messages/update_connection.rs b/vcx/libvcx/src/messages/update_connection.rs index d9d6ffe9..c9ee2709 100644 --- a/vcx/libvcx/src/messages/update_connection.rs +++ b/vcx/libvcx/src/messages/update_connection.rs @@ -97,8 +97,9 @@ impl DeleteConnection { return Ok(serde_json::to_string(&DeleteConnectionPayload::deserialize(data.to_owned()).unwrap()).unwrap()) } let data = unbundle_from_agency(response.clone())?; - let response = DeleteConnectionPayload::deserialize(data[0].to_owned()).map_err(|e| e.to_error_code())?; - Ok(serde_json::to_string(&response).unwrap()) + let response = DeleteConnectionPayload::deserialize(data[0].to_owned()) + .map_err(|e| e.to_error_code())?; + serde_json::to_string(&response).or(Err(error::INVALID_JSON.code_num)) } fn print_info(&self) { @@ -131,7 +132,7 @@ impl GeneralMessage for DeleteConnection{ if self.validate_rc != error::SUCCESS.code_num { return Err(self.validate_rc) } - let payload = encode::to_vec_named(&self.payload).unwrap(); + let payload = encode::to_vec_named(&self.payload).or(Err(error::INVALID_JSON.code_num))?; let bundle = Bundled::create(payload); diff --git a/vcx/libvcx/src/messages/update_message.rs b/vcx/libvcx/src/messages/update_message.rs index f11b731b..f213e09c 100644 --- a/vcx/libvcx/src/messages/update_message.rs +++ b/vcx/libvcx/src/messages/update_message.rs @@ -37,12 +37,12 @@ struct UpdateMessagesResponse { impl UpdateMessages{ pub fn send_secure(&mut self) -> Result<(), u32> { - let data = encode::to_vec_named(&self).unwrap(); + let data = encode::to_vec_named(&self).or(Err(error::UNKNOWN_ERROR.code_num))?; trace!("update_message content: {:?}", data); let msg = Bundled::create(data).encode()?; - let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID).unwrap(); + let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID)?; let data = bundle_for_agency(msg, &to_did)?; if settings::test_agency_mode_enabled() { diff --git a/vcx/libvcx/src/messages/update_profile.rs b/vcx/libvcx/src/messages/update_profile.rs index ff84dcb1..e8545036 100644 --- a/vcx/libvcx/src/messages/update_profile.rs +++ b/vcx/libvcx/src/messages/update_profile.rs @@ -122,11 +122,11 @@ impl GeneralMessage for UpdateProfileData{ if self.validate_rc != error::SUCCESS.code_num { return Err(self.validate_rc) } - let data = encode::to_vec_named(&self.payload).unwrap(); + let data = encode::to_vec_named(&self.payload).or(Err(error::UNKNOWN_ERROR.code_num))?; trace!("update profile inner bundle: {:?}", data); let msg = Bundled::create(data).encode()?; - let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID).unwrap(); + let to_did = settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID)?; bundle_for_agency(msg, &to_did) } } @@ -135,12 +135,11 @@ fn parse_update_profile_response(response: Vec) -> Result { let data = unbundle_from_agency(response)?; let mut de = Deserializer::new(&data[0][..]); - let response: UpdateProfileResponse = Deserialize::deserialize(&mut de).unwrap(); - match serde_json::to_string(&response) { - Ok(x) => Ok(x), - Err(_) => Err(error::INVALID_JSON.code_num), - } + let response: UpdateProfileResponse = Deserialize::deserialize(&mut de) + .or(Err(error::UNKNOWN_ERROR.code_num))?; + + serde_json::to_string(&response).or(Err(error::INVALID_JSON.code_num)) } #[cfg(test)] diff --git a/vcx/libvcx/src/proof.rs b/vcx/libvcx/src/proof.rs index 6e317299..52891efa 100644 --- a/vcx/libvcx/src/proof.rs +++ b/vcx/libvcx/src/proof.rs @@ -214,7 +214,7 @@ impl Proof { self.proof_request = Some(proof_obj); let data = connection::generate_encrypted_payload(&self.prover_vk, &self.remote_vk, &proof_request, "PROOF_REQUEST").map_err(|_| ProofError::ProofConnectionError())?; - let title = format!("{} wants you to share {}", settings::get_config_value(settings::CONFIG_INSTITUTION_NAME).unwrap(), self.name); + let title = format!("{} wants you to share {}", settings::get_config_value(settings::CONFIG_INSTITUTION_NAME).map_err(|e| ProofError::CommonError(e))?, self.name); match messages::send_message().to(&self.prover_did) .to_vk(&self.prover_vk) @@ -429,7 +429,7 @@ fn get_proof_details(response: &str) -> Result { Ok(json) => { let json: serde_json::Value = json; let detail = match json["uids"].as_array() { - Some(x) => x[0].as_str().unwrap(), + Some(x) => x[0].as_str().ok_or(ProofError::CommonError(error::INVALID_JSON.code_num))?, None => { warn!("response had no uid"); return Err(ProofError::CommonError(error::INVALID_JSON.code_num)) diff --git a/vcx/libvcx/src/schema.rs b/vcx/libvcx/src/schema.rs index 77df0ed4..9fa5722c 100644 --- a/vcx/libvcx/src/schema.rs +++ b/vcx/libvcx/src/schema.rs @@ -167,9 +167,11 @@ impl LedgerSchema { pub fn new_from_ledger(id: &str) -> Result { - //Todo: find out what submitter did needs to be - let submitter_did = &settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let submitter_did = &settings::get_config_value(settings::CONFIG_INSTITUTION_DID) + .map_err(|e| SchemaError::CommonError(e))?; + let (schema_id, schema_json) = LedgerSchema::retrieve_schema(submitter_did, id)?; + Ok(LedgerSchema{ schema_id, schema_json, @@ -188,11 +190,7 @@ impl CreateSchema { pub fn get_schema_id(&self) -> &String { &self.schema_id } fn get_payment_txn(&self) -> Result { - if self.payment_txn.is_some() { - Ok(self.payment_txn.clone().unwrap()) - } else { - Err(error::NOT_READY.code_num) - } + Ok(self.payment_txn.clone().ok_or(error::NOT_READY.code_num)?) } fn to_string_with_version(&self) -> String { @@ -242,11 +240,14 @@ pub fn create_new_schema(source_id: &str, pub fn get_schema_attrs(source_id: String, schema_id: String) -> Result<(u32, String), SchemaError> { - let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID) + .map_err(|e| SchemaError::CommonError(e))?; let (schema_id, schema_json) = LedgerSchema::retrieve_schema(&submitter_did, &schema_id)?; + let schema_data: SchemaData = serde_json::from_str(&schema_json) .or(Err(SchemaError::CommonError(error::INVALID_JSON.code_num)))?; + let new_schema = CreateSchema { source_id, schema_id, @@ -404,7 +405,6 @@ pub mod tests { let (schema_id, _) = ::utils::libindy::anoncreds::tests::create_and_write_test_schema(); let (_, schema_attrs ) = get_schema_attrs("id".to_string(), schema_id.clone()).unwrap(); - assert!(schema_attrs.contains(&schema_id)); } diff --git a/vcx/libvcx/src/settings.rs b/vcx/libvcx/src/settings.rs index 2496ee5f..cb9aedb8 100644 --- a/vcx/libvcx/src/settings.rs +++ b/vcx/libvcx/src/settings.rs @@ -176,18 +176,16 @@ pub fn test_agency_mode_enabled() -> bool { } pub fn process_config_string(config: &str) -> Result { - let configuration: Value = serde_json::from_str(config) - .or(Err(error::INVALID_JSON.code_num))?; + let configuration: Value = serde_json::from_str(config).or(Err(error::INVALID_JSON.code_num))?; if let Value::Object(ref map) = configuration { for (key, value) in map { - if value.is_string() { - set_config_value(key, value.as_str().unwrap()); - } + set_config_value(key, value.as_str().ok_or(error::INVALID_JSON.code_num)?); } } - let config = SETTINGS.read().unwrap(); - validate_config(&config.clone()) + validate_config( + &SETTINGS.read().or(Err(error::INVALID_CONFIGURATION.code_num))?.clone() + ) } pub fn process_config_file(path: &str) -> Result { @@ -200,10 +198,11 @@ pub fn process_config_file(path: &str) -> Result { } pub fn get_config_value(key: &str) -> Result { - match SETTINGS.read().unwrap().get(key) { - None => Err(error::INVALID_CONFIGURATION.code_num), - Some(value) => Ok(value.to_string()), - } + SETTINGS + .read() + .or(Err(error::INVALID_CONFIGURATION.code_num))? + .get(key) + .map_or(Err(error::INVALID_CONFIGURATION.code_num), |v| Ok(v.to_string())) } pub fn set_config_value(key: &str, value: &str) { diff --git a/vcx/libvcx/src/utils/httpclient.rs b/vcx/libvcx/src/utils/httpclient.rs index 0c438bbb..fd0b84ed 100644 --- a/vcx/libvcx/src/utils/httpclient.rs +++ b/vcx/libvcx/src/utils/httpclient.rs @@ -8,16 +8,17 @@ lazy_static!{ static ref NEXT_U8_RESPONSE: Mutex>> = Mutex::new(vec![]); } +//Todo: change this RC to a u32 pub fn post_u8(body_content: &Vec) -> Result,String> { - let url = format!("{}/agency/msg", settings::get_config_value(settings::CONFIG_AGENCY_ENDPOINT).unwrap()); + let url = format!("{}/agency/msg", settings::get_config_value(settings::CONFIG_AGENCY_ENDPOINT).or(Err("Invalid Configuration".to_string()))?); //Setting SSL Certs location. This is needed on android platform. Or openssl will fail to verify the certs if cfg!(target_os = "android") { info!("::Android code"); set_ssl_cert_location(); } - let client = reqwest::ClientBuilder::new().build().unwrap(); + let client = reqwest::ClientBuilder::new().build().or(Err("Preparing Post failed".to_string()))?; debug!("Posting encrypted bundle to: \"{}\"", url); if settings::test_agency_mode_enabled() {return Ok(NEXT_U8_RESPONSE.lock().unwrap().pop().unwrap_or(Vec::new()));} let mut response = match client.post(&url).body(body_content.to_owned()).header(ContentType::octet_stream()).send() { diff --git a/vcx/libvcx/src/utils/libindy/ledger.rs b/vcx/libvcx/src/utils/libindy/ledger.rs index 3d6f3a80..a113c859 100644 --- a/vcx/libvcx/src/utils/libindy/ledger.rs +++ b/vcx/libvcx/src/utils/libindy/ledger.rs @@ -58,7 +58,7 @@ pub fn libindy_parse_get_cred_def_response(get_cred_def_response: &str) -> Resul } pub fn libindy_build_get_credential_def_txn(cred_def_id: &str) -> Result{ - let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let submitter_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; Ledger::build_get_cred_def_request(&submitter_did, cred_def_id).map_err(map_rust_indy_sdk_error_code) } diff --git a/vcx/libvcx/src/utils/libindy/payments.rs b/vcx/libvcx/src/utils/libindy/payments.rs index 96e94a7d..cd090730 100644 --- a/vcx/libvcx/src/utils/libindy/payments.rs +++ b/vcx/libvcx/src/utils/libindy/payments.rs @@ -145,7 +145,7 @@ pub fn get_address_info(address: &str) -> Result { return Ok(AddressInfo { address: address.to_string(), balance: _address_balance(&utxo), utxo}) } - let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID)?; let (txn, _) = Payment::build_get_payment_sources_request(get_wallet_handle() as i32, &did, address) .map_err(map_rust_indy_sdk_error_code)?; @@ -156,10 +156,7 @@ pub fn get_address_info(address: &str) -> Result { .map_err(map_rust_indy_sdk_error_code)?; trace!("indy_parse_get_utxo_response() --> {}", response); - let utxo: Vec = match serde_json::from_str(&response) { - Ok(x) => x, - Err(_) => return Err(error::INVALID_JSON.code_num), - }; + let utxo: Vec = serde_json::from_str(&response).or(Err(error::INVALID_JSON.code_num))?; Ok(AddressInfo { address: address.to_string(), balance: _address_balance(&utxo), utxo }) } @@ -173,15 +170,7 @@ pub fn list_addresses() -> Result, u32> { .map_err(map_rust_indy_sdk_error_code)?; trace!("--> {}", addresses); - let addresses: Value = match serde_json::from_str(&addresses) { - Ok(x) => x, - Err(_) => return Err(error::INVALID_JSON.code_num), - }; - info!("my addresses: {}", addresses); - match addresses.as_array() { - None => Err(error::INVALID_JSON.code_num), - Some(x) => Ok(x.into_iter().map(|address|address.as_str().unwrap().to_string()).collect()), - } + Ok(serde_json::from_str(&addresses).or(Err(error::INVALID_JSON.code_num))?) } pub fn get_wallet_token_info() -> Result { @@ -204,7 +193,7 @@ pub fn get_wallet_token_info() -> Result { pub fn get_ledger_fees() -> Result { if settings::test_indy_mode_enabled() { return Ok(DEFAULT_FEES.to_string()); } - let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).or(Err(error::INVALID_CONFIGURATION.code_num))?; let response = match Payment::build_get_txn_fees_req(get_wallet_handle() as i32, &did, PAYMENT_METHOD_NAME) { Ok(txn) => libindy_sign_and_submit_request(&did, &txn)?, @@ -223,7 +212,7 @@ pub fn pay_for_txn(req: &str, txn_type: &str) -> Result<(Option, Str let txn_price = get_txn_price(txn_type)?; if txn_price == 0 { - let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).or(Err(error::INVALID_CONFIGURATION.code_num))?; let txn_response = libindy_sign_and_submit_request(&did, req)?; Ok((None, txn_response)) } else { @@ -239,7 +228,7 @@ pub fn pay_for_txn(req: &str, txn_type: &str) -> Result<(Option, Str } fn _submit_fees_request(req: &str, inputs: &str, outputs: &str) -> Result<(String, String), u32> { - let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).or(Err(error::INVALID_CONFIGURATION.code_num))?; let req = libindy_sign_request(&did, req)?; @@ -271,7 +260,7 @@ pub fn pay_a_payee(price: u64, address: &str) -> Result<(PaymentTxn, String), Pa let output = outputs(remainder, &refund_address, Some(address.to_string()), Some(price))?; let payment = PaymentTxn::from_parts(&input, &output, price, false).map_err(|e|PaymentError::CommonError(e))?; - let my_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); + let my_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).or(Err(PaymentError::CommonError(error::INVALID_CONFIGURATION.code_num)))?; if settings::test_indy_mode_enabled() { return Ok((PaymentTxn::from_parts(r#"["pay:null:9UFgyjuJxi1i1HD"]"#,r#"[{"amount":4,"extra":null,"recipient":"pay:null:xkIsxem0YNtHrRO"}]"#,1, false).unwrap(), SUBMIT_SCHEMA_RESPONSE.to_string())); } @@ -318,7 +307,7 @@ pub fn inputs(cost: u64) -> Result<(u64, String, String), PaymentError> { refund_address = address.address.clone(); 'inner: for utxo in address.utxo.iter() { if balance < cost { - inputs.push(utxo.source.clone().unwrap().to_string()); + inputs.push(utxo.source.clone().ok_or(PaymentError::InsufficientFunds())?.to_string()); balance += utxo.amount; } else { break 'outer } } @@ -346,7 +335,7 @@ pub fn outputs(remainder: u64, refund_address: &str, payee_address: Option Result<(), u32> { } pub fn get_pool_handle() -> Result { - let h = POOL_HANDLE.read().unwrap(); - if h.is_none() { - Err(error::NO_POOL_OPEN.code_num) - } - else { - Ok(h.unwrap()) - } + Ok(POOL_HANDLE.read().or(Err(error::NO_POOL_OPEN.code_num))?.ok_or(error::NO_POOL_OPEN.code_num)?) } #[cfg(test)] diff --git a/vcx/libvcx/src/utils/mod.rs b/vcx/libvcx/src/utils/mod.rs index 1022ccfc..e2eb3c55 100644 --- a/vcx/libvcx/src/utils/mod.rs +++ b/vcx/libvcx/src/utils/mod.rs @@ -18,6 +18,7 @@ pub mod openssl; pub mod json; pub mod libindy; pub mod threadpool; +pub mod serde_utils; use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; lazy_static! { diff --git a/vcx/libvcx/src/utils/serde_utils.rs b/vcx/libvcx/src/utils/serde_utils.rs new file mode 100644 index 00000000..7e6d2e01 --- /dev/null +++ b/vcx/libvcx/src/utils/serde_utils.rs @@ -0,0 +1,15 @@ +extern crate serde_json; + +use ::utils::error; +use serde_json::{Value}; + +pub fn get_value_to_string(key: &str, map: &Value) -> Result { + Ok( + map.get(key) + .ok_or(error::INVALID_JSON.code_num)? + .as_str() + .ok_or(error::INVALID_JSON.code_num)? + .to_string() + ) +} +