Skip to content

Commit

Permalink
fix: remove reply handling from xcall
Browse files Browse the repository at this point in the history
  • Loading branch information
sherpalden committed Oct 23, 2024
1 parent cc5545b commit 4678082
Show file tree
Hide file tree
Showing 8 changed files with 26 additions and 258 deletions.
3 changes: 0 additions & 3 deletions contracts/cosmwasm-vm/cw-cluster-connection/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ cw-xcall-lib = { path="../cw-xcall-lib" }
hex = "0.4.3"
serde-json-wasm = {workspace=true}
sha2 = { version = "0.10.6", default-features = false }
sha3 = { version = "0.10.6", default-features = false }
ripemd = "0.1.3"
bech32 = "0.9.1"
k256 = "0.11.6"

[dev-dependencies]
Expand Down
88 changes: 8 additions & 80 deletions contracts/cosmwasm-vm/cw-cluster-connection/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cosmwasm_std::{coins, Addr, BankMsg, Event, SubMsgResult, Uint128};
use cosmwasm_std::{coins, Addr, BankMsg, Event, Uint128};
use cw_xcall_lib::network_address::NetId;

use super::*;
Expand Down Expand Up @@ -87,7 +87,7 @@ impl<'a> ClusterConnection<'a> {

let validators_set = self.get_validators(deps.storage)?;

if threshold as usize > validators_set.len() {
if validators_set.len() < threshold as usize {
return Err(ContractError::InvalidThreshold {
msg: "threshold should be at most the size of validators".to_string(),
});
Expand Down Expand Up @@ -132,29 +132,6 @@ impl<'a> ClusterConnection<'a> {
))
}

pub fn recv_message(
&mut self,
deps: DepsMut,
info: MessageInfo,
src_network: NetId,
conn_sn: u128,
msg: String,
) -> Result<Response, ContractError> {
self.ensure_relayer(deps.storage, info.sender)?;

let vec_msg: Vec<u8> = self.hex_decode(msg)?;

if self.get_receipt(deps.as_ref().storage, src_network.clone(), conn_sn) {
return Err(ContractError::DuplicateMessage);
}
self.store_receipt(deps.storage, src_network.clone(), conn_sn)?;

let xcall_submessage =
self.call_xcall_handle_message(deps.storage, &src_network, vec_msg)?;

Ok(Response::new().add_submessage(xcall_submessage))
}

pub fn set_signature_threshold(
&mut self,
deps: DepsMut,
Expand All @@ -168,7 +145,7 @@ impl<'a> ClusterConnection<'a> {
Ok(Response::new().add_attribute("action", "set_signature_threshold"))
}

pub fn recv_message_with_signatures(
pub fn recv_message(
&mut self,
deps: DepsMut,
info: MessageInfo,
Expand All @@ -179,22 +156,16 @@ impl<'a> ClusterConnection<'a> {
) -> Result<Response, ContractError> {
self.ensure_relayer(deps.storage, info.sender)?;

if self.get_receipt(deps.as_ref().storage, src_network.clone(), conn_sn) {
return Err(ContractError::DuplicateMessage);
}

let vec_msg: Vec<u8> = self.hex_decode(msg)?;

let threshold = self.get_signature_threshold(deps.storage);
let validators = self.get_validators(deps.storage)?;

self.verify_signatures(
deps.as_ref(),
threshold,
validators,
vec_msg.clone(),
signatures,
)?;
self.verify_signatures(deps.as_ref(), threshold, vec_msg.clone(), signatures)?;

if self.get_receipt(deps.as_ref().storage, src_network.clone(), conn_sn) {
return Err(ContractError::DuplicateMessage);
}
self.store_receipt(deps.storage, src_network.clone(), conn_sn)?;

let xcall_submessage =
Expand Down Expand Up @@ -246,49 +217,6 @@ impl<'a> ClusterConnection<'a> {
Ok(fee.into())
}

fn xcall_handle_message_reply(
&self,
_deps: DepsMut,
message: Reply,
) -> Result<Response, ContractError> {
match message.result {
SubMsgResult::Ok(_) => Ok(Response::new()
.add_attribute("action", "call_message")
.add_attribute("method", "xcall_handle_message_reply")),
SubMsgResult::Err(error) => Err(ContractError::ReplyError {
code: message.id,
msg: error,
}),
}
}

fn xcall_handle_error_reply(
&self,
_deps: DepsMut,
message: Reply,
) -> Result<Response, ContractError> {
match message.result {
SubMsgResult::Ok(_) => Ok(Response::new()
.add_attribute("action", "call_message")
.add_attribute("method", "xcall_handle_error_reply")),
SubMsgResult::Err(error) => Err(ContractError::ReplyError {
code: message.id,
msg: error,
}),
}
}

pub fn reply(&self, deps: DepsMut, _env: Env, msg: Reply) -> Result<Response, ContractError> {
match msg.id {
XCALL_HANDLE_MESSAGE_REPLY_ID => self.xcall_handle_message_reply(deps, msg),
XCALL_HANDLE_ERROR_REPLY_ID => self.xcall_handle_error_reply(deps, msg),
_ => Err(ContractError::ReplyError {
code: msg.id,
msg: "Unknown".to_string(),
}),
}
}

pub fn migrate(
&self,
deps: DepsMut,
Expand Down
64 changes: 9 additions & 55 deletions contracts/cosmwasm-vm/cw-cluster-connection/src/helper.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use std::collections::HashMap;

use crate::utils::sha256;
use cosmwasm_std::{ensure_eq, Addr, BalanceResponse, BankQuery, Coin};
use cw_xcall_lib::network_address::NetId;
use k256::ecdsa::VerifyingKey;

pub const XCALL_HANDLE_MESSAGE_REPLY_ID: u64 = 1;
pub const XCALL_HANDLE_ERROR_REPLY_ID: u64 = 2;
use super::*;

pub fn sha256(data: &[u8]) -> Vec<u8> {
use sha2::Digest;
sha2::Sha256::digest(&data).to_vec()
}

impl<'a> ClusterConnection<'a> {
pub fn ensure_admin(&self, store: &dyn Storage, address: Addr) -> Result<(), ContractError> {
let admin = self.get_admin(store)?;
Expand Down Expand Up @@ -78,33 +80,14 @@ impl<'a> ClusterConnection<'a> {
msg: to_json_binary(&xcall_msg).unwrap(),
funds: vec![],
});
let sub_msg: SubMsg = SubMsg::reply_always(call_message, XCALL_HANDLE_MESSAGE_REPLY_ID);
Ok(sub_msg)
}

pub fn call_xcall_handle_error(
&self,
store: &dyn Storage,
sn: u128,
) -> Result<SubMsg, ContractError> {
let xcall_host = self.get_xcall(store)?;
let xcall_msg = cw_xcall_lib::xcall_msg::ExecuteMsg::HandleError {
sn: sn.try_into().unwrap(),
};
let call_message: CosmosMsg<Empty> = CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: xcall_host.to_string(),
msg: to_json_binary(&xcall_msg).unwrap(),
funds: vec![],
});
let sub_msg: SubMsg = SubMsg::reply_always(call_message, XCALL_HANDLE_ERROR_REPLY_ID);
let sub_msg: SubMsg = SubMsg::new(call_message);
Ok(sub_msg)
}

pub fn verify_signatures(
&self,
deps: Deps,
threshold: u8,
relayers: Vec<String>,
data: Vec<u8>,
signatures: Vec<Vec<u8>>,
) -> Result<(), ContractError> {
Expand All @@ -129,12 +112,13 @@ impl<'a> ClusterConnection<'a> {
.map_err(|_| ContractError::InvalidSignature)?;

let pk_hex = hex::encode(pk.to_bytes());
if relayers.contains(&pk_hex) && !signers.contains_key(&pk_hex) {
if self.is_validator(deps.storage, pk_hex.clone())
&& !signers.contains_key(&pk_hex)
{
signers.insert(pk_hex, true);
if signers.len() >= threshold.into() {
return Ok(());
}
break;
}
}
Err(_) => continue,
Expand All @@ -144,33 +128,3 @@ impl<'a> ClusterConnection<'a> {
return Err(ContractError::InsufficientSignatures);
}
}

#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::testing::mock_dependencies;
#[test]
fn test_verify_signatures_simple() {
let deps = mock_dependencies();
let connection = ClusterConnection::new();
let message = b"hello";
let threshold = 1;
let relayers =
vec!["02e5e9769497fbc7c7ee57ab39ccedcb612018577d30ca090033dc67ba5d68b8ab".to_string()];

let hex_sign = "62249c41d09297800f35174e041ad53ec85c5dcad6a6bd0db3267d36a56eb92d7645b7a64c22ae7e1f93c6c3867d2a33e6534e64093600861916e3299e4cc922";
let mut signature = hex::decode(hex_sign).expect("Failed to decode hex signature");
signature.push(1);
let signatures = vec![signature];

let result = connection.verify_signatures(
deps.as_ref(),
threshold,
relayers,
message.to_vec(),
signatures,
);

assert!(result.is_ok());
}
}
17 changes: 2 additions & 15 deletions contracts/cosmwasm-vm/cw-cluster-connection/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ pub mod helper;
pub mod msg;
pub mod state;
pub mod types;
pub mod utils;

use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
entry_point, to_json_binary, Binary, CosmosMsg, Deps, DepsMut, Empty, Env, MessageInfo, Reply,
entry_point, to_json_binary, Binary, CosmosMsg, Deps, DepsMut, Empty, Env, MessageInfo,
Response, StdError, StdResult, Storage, SubMsg, WasmMsg,
};

Expand Down Expand Up @@ -68,14 +67,8 @@ pub fn execute(
src_network,
conn_sn,
msg,
} => conn.recv_message(deps, info, src_network, conn_sn, msg),

ExecuteMsg::RecvMessageWithSignatures {
src_network,
conn_sn,
msg,
signatures,
} => conn.recv_message_with_signatures(deps, info, src_network, conn_sn, msg, signatures),
} => conn.recv_message(deps, info, src_network, conn_sn, msg, signatures),
}
}

Expand Down Expand Up @@ -116,12 +109,6 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
}
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> Result<Response, ContractError> {
let conn = ClusterConnection::default();
conn.reply(deps, env, msg)
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
let conn = ClusterConnection::default();
Expand Down
6 changes: 0 additions & 6 deletions contracts/cosmwasm-vm/cw-cluster-connection/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,6 @@ pub enum ExecuteMsg {
src_network: NetId,
conn_sn: u128,
msg: String,
},

RecvMessageWithSignatures {
src_network: NetId,
conn_sn: u128,
msg: String,
signatures: Vec<Vec<u8>>,
},
}
Expand Down
4 changes: 4 additions & 0 deletions contracts/cosmwasm-vm/cw-cluster-connection/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ impl<'a> ClusterConnection<'a> {
Ok(validators_list)
}

pub fn is_validator(&self, store: &dyn Storage, pub_key: String) -> bool {
self.validators.has(store, pub_key)
}

pub fn store_signature_threshold(
&mut self,
store: &mut dyn Storage,
Expand Down
49 changes: 0 additions & 49 deletions contracts/cosmwasm-vm/cw-cluster-connection/src/utils.rs

This file was deleted.

Loading

0 comments on commit 4678082

Please sign in to comment.