Skip to content

Commit

Permalink
Merge branch 'eshel-ibc' of github.com:scrtlabs/SecretNetwork into es…
Browse files Browse the repository at this point in the history
…hel-ibc
  • Loading branch information
eshelB committed Aug 30, 2022
2 parents 8152de2 + b7ab07f commit dfd161b
Show file tree
Hide file tree
Showing 16 changed files with 820 additions and 243 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ pub fn init(
let ValidatedMessage {
validated_msg,
reply_params,
} = validate_msg(&decrypted_msg, &contract_hash, None)?;
} = validate_msg(&decrypted_msg, &contract_hash, None, None)?;

let mut engine = start_engine(
context,
Expand Down Expand Up @@ -186,15 +186,16 @@ pub fn handle(
let ParsedMessage {
should_validate_sig_info,
was_msg_encrypted,
should_encrypt_output,
secret_msg,
decrypted_msg,
contract_hash_for_validation,
} = parse_message(msg, &parsed_sig_info, &parsed_handle_type)?;

let mut canonical_sender_address = CanonicalAddr::from_vec(vec![]);
if should_validate_sig_info || was_msg_encrypted {
canonical_sender_address = to_canonical(sender)?;
}
let canonical_sender_address = match to_canonical(sender) {
Ok(can) => can,
Err(_) => CanonicalAddr::from_vec(vec![]),
};

// There is no signature to verify when the input isn't signed.
// Receiving unsigned messages is only possible in Handle. (Init tx are always signed)
Expand All @@ -215,7 +216,12 @@ pub fn handle(
let mut validated_msg = decrypted_msg.clone();
let mut reply_params: Option<ReplyParams> = None;
if was_msg_encrypted {
let x = validate_msg(&decrypted_msg, &contract_hash, contract_hash_for_validation)?;
let x = validate_msg(
&decrypted_msg,
&contract_hash,
contract_hash_for_validation,
Some(parsed_handle_type.clone()),
)?;
validated_msg = x.validated_msg;
reply_params = x.reply_params;
}
Expand Down Expand Up @@ -257,7 +263,7 @@ pub fn handle(
secret_msg.nonce, secret_msg.user_public_key
);

if was_msg_encrypted {
if should_encrypt_output {
output = encrypt_output(
output,
&secret_msg,
Expand Down Expand Up @@ -337,7 +343,7 @@ pub fn query(
let decrypted_msg = secret_msg.decrypt()?;

let ValidatedMessage { validated_msg, .. } =
validate_msg(&decrypted_msg, &contract_hash, None)?;
validate_msg(&decrypted_msg, &contract_hash, None, None)?;

let mut engine = start_engine(
context,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
use cw_types_v1::ibc::IbcPacketReceiveMsg;
use cw_types_v1::results::REPLY_ENCRYPTION_MAGIC_BYTES;
use log::*;

use enclave_ffi_types::EnclaveError;

use cw_types_v010::types::{CanonicalAddr, Coin, HumanAddr};
use enclave_cosmos_types::traits::CosmosAminoPubkey;
use enclave_cosmos_types::types::{
ContractCode, CosmWasmMsg, CosmosPubKey, SigInfo, SignDoc, StdSignDoc,
ContractCode, CosmWasmMsg, CosmosPubKey, HandleType, SigInfo, SignDoc, StdSignDoc,
};
use enclave_crypto::traits::VerifyingKey;
use enclave_crypto::{sha_256, AESKey, Hmac, Kdf, HASH_SIZE, KEY_MANAGER};
use enclave_ffi_types::EnclaveError;

use crate::io::create_callback_signature;
use crate::message::is_ibc_msg;
use crate::types::SecretMessage;

pub type ContractKey = [u8; CONTRACT_KEY_LENGTH];
Expand Down Expand Up @@ -121,6 +122,64 @@ pub fn validate_msg(
msg: &[u8],
contract_hash: &[u8; HASH_SIZE],
contract_hash_for_validation: Option<Vec<u8>>,
handle_type: Option<HandleType>,
) -> Result<ValidatedMessage, EnclaveError> {
match handle_type {
None => validate_basic_msg(msg, contract_hash, contract_hash_for_validation),
Some(h) => match is_ibc_msg(h.clone()) {
false => validate_basic_msg(msg, contract_hash, contract_hash_for_validation),
true => validate_ibc_msg(msg, contract_hash, contract_hash_for_validation, h),
},
}
}

pub fn validate_ibc_msg(
msg: &[u8],
contract_hash: &[u8; HASH_SIZE],
contract_hash_for_validation: Option<Vec<u8>>,
handle_type: HandleType,
) -> Result<ValidatedMessage, EnclaveError> {
match handle_type {
HandleType::HANDLE_TYPE_IBC_PACKET_RECEIVE => {
let mut parsed_ibc_packet: IbcPacketReceiveMsg =
serde_json::from_slice(&msg.to_vec()).map_err(|err| {
warn!(
"IbcPacketReceive msg got an error while trying to deserialize msg input bytes into json {:?}: {}",
String::from_utf8_lossy(&msg),
err
);
EnclaveError::FailedToDeserialize
})?;

let validated_msg = validate_basic_msg(
parsed_ibc_packet.packet.data.as_slice(),
contract_hash,
contract_hash_for_validation,
)?;
parsed_ibc_packet.packet.data = validated_msg.validated_msg.as_slice().into();

Ok(ValidatedMessage{
validated_msg: serde_json::to_vec(&parsed_ibc_packet).map_err(|err| {
warn!(
"got an error while trying to serialize parsed_ibc_packet msg into bytes {:?}: {}",
parsed_ibc_packet, err
);
EnclaveError::FailedToSerialize
})?,
reply_params: validated_msg.reply_params,
})
}
_ => {
warn!("Malformed message - in IBC, only packet receive message can be encrypted");
Err(EnclaveError::ValidationFailure)
}
}
}

pub fn validate_basic_msg(
msg: &[u8],
contract_hash: &[u8; HASH_SIZE],
contract_hash_for_validation: Option<Vec<u8>>,
) -> Result<ValidatedMessage, EnclaveError> {
if contract_hash_for_validation.is_none() && msg.len() < HEX_ENCODED_HASH_SIZE {
warn!("Malformed message - expected contract code hash to be prepended to the msg");
Expand Down
15 changes: 12 additions & 3 deletions cosmwasm/enclaves/shared/contract-engine/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,10 @@ pub fn encrypt_output(
// More info in: https://github.com/CosmWasm/cosmwasm/blob/v1.0.0/packages/std/src/results/submessages.rs#L192-L198
let encryption_key = calc_encryption_key(&secret_msg.nonce, &secret_msg.user_public_key);
trace!(
"Output before encryption: {:?}",
String::from_utf8_lossy(&output)
"Output before encryption: {:?} {:?} {:?}",
String::from_utf8_lossy(&output),
secret_msg.nonce,
secret_msg.user_public_key
);

let mut output: RawWasmOutput = serde_json::from_slice(&output).map_err(|err| {
Expand Down Expand Up @@ -449,6 +451,7 @@ pub fn encrypt_output(
let reply = Reply {
id: msg_id.unwrap(),
result: SubMsgResult::Err(encrypted_err),
was_msg_encrypted: true,
};
let reply_as_vec = serde_json::to_vec(&reply).map_err(|err| {
warn!(
Expand Down Expand Up @@ -537,6 +540,7 @@ pub fn encrypt_output(
events,
data: ok.data.clone(),
}),
was_msg_encrypted: true,
};

let reply_as_vec = serde_json::to_vec(&reply).map_err(|err| {
Expand Down Expand Up @@ -580,6 +584,8 @@ pub fn encrypt_output(
// We don't encrypt it here to remain with the same type (u64)
sub_msg.id = 0;
}

sub_msg.was_msg_encrypted = true;
}

// v1: The attributes that will be emitted as part of a "wasm" event.
Expand All @@ -598,7 +604,7 @@ pub fn encrypt_output(

if let Some(data) = &mut ok.data {
if is_ibc_output {
warn!("IBC output should not containt any data");
warn!("IBC output should not contain any data");
return Err(EnclaveError::InternalError);
}

Expand Down Expand Up @@ -649,6 +655,7 @@ pub fn encrypt_output(
events,
data: ok.data.clone(),
}),
was_msg_encrypted: true,
};

let reply_as_vec = serde_json::to_vec(&reply).map_err(|err| {
Expand Down Expand Up @@ -689,6 +696,8 @@ pub fn encrypt_output(
// We don't encrypt it here to remain with the same type (u64)
sub_msg.id = 0;
}

sub_msg.was_msg_encrypted = true;
}

// v1: The attributes that will be emitted as part of a "wasm" event.
Expand Down
Loading

0 comments on commit dfd161b

Please sign in to comment.