Fix cipher parsing issue + refactoring

This commit is contained in:
Sosthene 2024-10-14 13:24:57 +02:00
parent caf620dd65
commit 8b65463cd3

View File

@ -13,7 +13,7 @@ use rand::{thread_rng, Fill, Rng, RngCore};
use sdk_common::aes_gcm::aead::generic_array::GenericArray; use sdk_common::aes_gcm::aead::generic_array::GenericArray;
use sdk_common::aes_gcm::aes::cipher::ArrayLength; use sdk_common::aes_gcm::aes::cipher::ArrayLength;
use sdk_common::aes_gcm::Nonce; use sdk_common::aes_gcm::Nonce;
use sdk_common::log::{debug, warn}; use sdk_common::log::{debug, warn, info};
use anyhow::Context; use anyhow::Context;
use anyhow::Error as AnyhowError; use anyhow::Error as AnyhowError;
@ -303,14 +303,17 @@ pub fn login(previous_login_tx: String, fee_rate: u32) -> ApiResult<ApiReturn> {
let mut shared_secrets = Vec::new(); let mut shared_secrets = Vec::new();
for address in other_addresses { for address in other_addresses {
let shared_secret = process.get_shared_secret_for_address(&SilentPaymentAddress::try_from(address)?); let shared_secret =
process.get_shared_secret_for_address(&SilentPaymentAddress::try_from(address)?);
if let Some(shared_secret) = shared_secret { if let Some(shared_secret) = shared_secret {
shared_secrets.push(shared_secret); shared_secrets.push(shared_secret);
} }
} }
let mut decrypted_pcd = Map::new(); let mut decrypted_pcd = Map::new();
state.encrypted_pcd.decrypt_fields(&state.keys, &mut decrypted_pcd)?; state
.encrypted_pcd
.decrypt_fields(&state.keys, &mut decrypted_pcd)?;
let pairing_tx = decrypted_pcd.get("pairing_tx").unwrap().as_str().unwrap(); let pairing_tx = decrypted_pcd.get("pairing_tx").unwrap().as_str().unwrap();
@ -318,13 +321,17 @@ pub fn login(previous_login_tx: String, fee_rate: u32) -> ApiResult<ApiReturn> {
let freezed_utxos = lock_freezed_utxos()?; let freezed_utxos = lock_freezed_utxos()?;
let recipients: Vec<Recipient> = device.to_member().unwrap().get_addresses().iter().map(|a| { let recipients: Vec<Recipient> = device
Recipient { .to_member()
address: a.clone(), .unwrap()
amount: DEFAULT_AMOUNT, .get_addresses()
nb_outputs: 1, .iter()
} .map(|a| Recipient {
}).collect(); address: a.clone(),
amount: DEFAULT_AMOUNT,
nb_outputs: 1,
})
.collect();
let mut mandatory_inputs = Vec::new(); let mut mandatory_inputs = Vec::new();
for i in 0u32..nb_outputs.try_into().unwrap() { for i in 0u32..nb_outputs.try_into().unwrap() {
@ -490,8 +497,7 @@ fn handle_transaction(
tx: &Transaction, tx: &Transaction,
tweak_data: PublicKey, tweak_data: PublicKey,
) -> AnyhowResult<ApiReturn> { ) -> AnyhowResult<ApiReturn> {
let device = lock_local_device()?; let b_scan = lock_local_device()?.get_wallet().get_client().get_scan_key();
let sp_wallet = device.get_wallet();
let op_return: Vec<&sdk_common::sp_client::bitcoin::TxOut> = tx let op_return: Vec<&sdk_common::sp_client::bitcoin::TxOut> = tx
.output .output
@ -518,7 +524,7 @@ fn handle_transaction(
if utxo_destroyed.is_empty() { if utxo_destroyed.is_empty() {
let shared_point = sp_utils::receiving::calculate_ecdh_shared_secret( let shared_point = sp_utils::receiving::calculate_ecdh_shared_secret(
&tweak_data, &tweak_data,
&sp_wallet.get_client().get_scan_key(), &b_scan,
); );
let shared_secret = AnkSharedSecretHash::from_shared_point(shared_point); let shared_secret = AnkSharedSecretHash::from_shared_point(shared_point);
@ -535,58 +541,16 @@ fn handle_transaction(
return false; return false;
} }
}) { }) {
// Calling this check that the prd we found check with the hashed commitment in transaction
// We also check the signed proof that is included in the prd
let prd = Prd::extract_from_message_with_commitment(&plaintext, &commitment)?; let prd = Prd::extract_from_message_with_commitment(&plaintext, &commitment)?;
let proof_key = prd.proof.ok_or(AnyhowError::msg("Missing proof"))?.get_key(); // for now the previous method doesn't error if proof is missing,
let mut actual_sender = String::default(); // We must define if there are cases where a valid prd doesn't have proof
for sp_address in serde_json::from_str::<Member>(&prd.sender)?.get_addresses() {
if proof_key
== SilentPaymentAddress::try_from(sp_address.as_str())
.unwrap()
.get_spend_key()
.x_only_public_key()
.0
{
actual_sender = sp_address;
} else {
continue;
}
break;
}
let outpoint = OutPoint::from_str(&prd.root_commitment)?; let outpoint = OutPoint::from_str(&prd.root_commitment)?;
let updated_process: Process; handle_decrypted_message(plaintext, Some(shared_secret), Some(outpoint))
let mut processes = lock_processes()?;
if let Some(process) = processes.get_mut(&outpoint) {
process.insert_shared_secret(
SilentPaymentAddress::try_from(actual_sender.as_str()).unwrap(),
shared_secret,
);
updated_process = process.clone();
} else {
let mut shared_secrets = HashMap::new();
shared_secrets.insert(
SilentPaymentAddress::try_from(actual_sender.as_str()).unwrap(),
shared_secret,
);
let new_process = Process::new(vec![], shared_secrets, vec![]);
processes.insert(outpoint, new_process.clone());
updated_process = new_process;
}
// We don't need the cached message anymore
let id_to_rm = message.id;
*message = CachedMessage {
id: id_to_rm,
..Default::default()
};
return Ok(ApiReturn {
updated_cached_msg: vec![message.clone()],
updated_process: Some((outpoint.to_string(), updated_process)),
..Default::default()
});
} else { } else {
// store it and wait for the message // store it and wait for the message
let mut new_msg = CachedMessage::new(); let mut new_msg = CachedMessage::new();
@ -611,7 +575,7 @@ fn handle_transaction(
} }
} }
/// If the transaction has anything to do with us, we create/update the relevant `CachedMessage` /// If the transaction has anything to do with us, we create/update the relevant process
/// and return it to caller for persistent storage /// and return it to caller for persistent storage
fn process_transaction( fn process_transaction(
tx_hex: String, tx_hex: String,
@ -852,8 +816,6 @@ fn decrypt_with_cached_messages(
cipher: &[u8], cipher: &[u8],
messages: &mut MutexGuard<Vec<CachedMessage>> messages: &mut MutexGuard<Vec<CachedMessage>>
) -> anyhow::Result<Option<(Vec<u8>, AnkSharedSecretHash)>> { ) -> anyhow::Result<Option<(Vec<u8>, AnkSharedSecretHash)>> {
debug!("cached messages: {:#?}", messages);
let nonce = Nonce::from_slice(&cipher[..12]); let nonce = Nonce::from_slice(&cipher[..12]);
for message in messages.iter_mut() { for message in messages.iter_mut() {
@ -897,7 +859,7 @@ fn decrypt_with_cached_messages(
return Ok(Some(( return Ok(Some((
plain, plain,
AnkSharedSecretHash::from_str(message.shared_secrets.first().unwrap())?, aes_key,
))); )));
} }
} }