Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ampd): skip events from unknown contracts #259

Merged
merged 7 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 4 additions & 7 deletions ampd/src/handlers/evm_verify_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@
#[derive(Deserialize, Debug)]
#[try_from("wasm-messages_poll_started")]
struct PollStartedEvent {
#[serde(rename = "_contract_address")]
contract_address: TMAddress,
poll_id: PollId,
source_chain: connection_router::state::ChainName,
source_gateway_address: EVMAddress,
Expand Down Expand Up @@ -150,8 +148,11 @@
type Err = Error;

async fn handle(&self, event: &events::Event) -> Result<()> {
if !event.is_from_contract(self.voting_verifier.as_ref()) {
return Ok(());

Check warning on line 152 in ampd/src/handlers/evm_verify_msg.rs

View check run for this annotation

Codecov / codecov/patch

ampd/src/handlers/evm_verify_msg.rs#L152

Added line #L152 was not covered by tests
}

let PollStartedEvent {
contract_address,
poll_id,
source_chain,
source_gateway_address,
Expand All @@ -166,10 +167,6 @@
event => event.change_context(DeserializeEvent)?,
};

if self.voting_verifier != contract_address {
return Ok(());
}

if self.chain != source_chain {
return Ok(());
}
Expand Down
11 changes: 4 additions & 7 deletions ampd/src/handlers/evm_verify_worker_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@
#[derive(Deserialize, Debug)]
#[try_from("wasm-worker_set_poll_started")]
struct PollStartedEvent {
#[serde(rename = "_contract_address")]
contract_address: TMAddress,
worker_set: WorkerSetConfirmation,
poll_id: PollId,
source_chain: connection_router::state::ChainName,
Expand Down Expand Up @@ -146,8 +144,11 @@
type Err = Error;

async fn handle(&self, event: &events::Event) -> Result<()> {
if !event.is_from_contract(self.voting_verifier.as_ref()) {
return Ok(());

Check warning on line 148 in ampd/src/handlers/evm_verify_worker_set.rs

View check run for this annotation

Codecov / codecov/patch

ampd/src/handlers/evm_verify_worker_set.rs#L148

Added line #L148 was not covered by tests
}

let PollStartedEvent {
contract_address,
poll_id,
source_chain,
source_gateway_address,
Expand All @@ -162,10 +163,6 @@
event => event.change_context(Error::DeserializeEvent)?,
};

if self.voting_verifier != contract_address {
return Ok(());
}

if self.chain != source_chain {
return Ok(());
}
Expand Down
86 changes: 74 additions & 12 deletions ampd/src/handlers/multisig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
#[derive(Debug, Deserialize)]
#[try_from("wasm-signing_started")]
struct SigningStartedEvent {
#[serde(rename = "_contract_address")]
contract_address: TMAddress,
session_id: u64,
#[serde(deserialize_with = "deserialize_public_keys")]
pub_keys: HashMap<TMAddress, PublicKey>,
Expand Down Expand Up @@ -132,8 +130,11 @@
type Err = Error;

async fn handle(&self, event: &events::Event) -> error_stack::Result<(), Error> {
if !event.is_from_contract(self.multisig.as_ref()) {
return Ok(());
}

let SigningStartedEvent {
contract_address,
session_id,
pub_keys,
msg,
Expand All @@ -145,10 +146,6 @@
result => result.change_context(DeserializeEvent)?,
};

if self.multisig != contract_address {
return Ok(());
}

info!(
session_id = session_id,
msg = encode(&msg),
Expand Down Expand Up @@ -278,6 +275,38 @@
.unwrap()
}

// this returns an event that is named SigningStarted, but some expected fields are missing
fn signing_started_event_with_missing_fields(contract_address: &str) -> events::Event {
let pub_keys = (0..10)
.map(|_| (rand_account().to_string(), rand_public_key()))
.collect::<HashMap<String, PublicKey>>();

let poll_started = SigningStarted {
session_id: Uint64::one(),
worker_set_id: "worker_set_id".to_string(),
pub_keys,
msg: MsgToSign::unchecked(rand_message()),
chain_name: rand_chain_name(),
expires_at: 100u64,
};

let mut event: cosmwasm_std::Event = poll_started.into();
event.ty = format!("wasm-{}", event.ty);
cjcobb23 marked this conversation as resolved.
Show resolved Hide resolved
event = event.add_attribute("_contract_address", contract_address);
event.attributes.retain(|attr| attr.key != "expires_at");

events::Event::try_from(abci::Event::new(
event.ty,
event
.attributes
.into_iter()
.map(|cosmwasm_std::Attribute { key, value }| {
(STANDARD.encode(key), STANDARD.encode(value))
}),
))
.unwrap()
}

fn get_handler(
worker: TMAddress,
multisig: TMAddress,
Expand All @@ -292,7 +321,7 @@
let (broadcaster, _) =
QueuedBroadcaster::new(broadcaster, Gas::default(), 100, Duration::from_secs(5));

let (tx, rx) = watch::channel(latest_block_height);
let (_, rx) = watch::channel(latest_block_height);

Handler::new(worker, multisig, broadcaster.client(), signer, rx)
}
Expand Down Expand Up @@ -352,12 +381,45 @@
assert!(event.is_ok());
}

#[tokio::test]
async fn should_not_handle_event_with_missing_fields_if_multisig_address_does_not_match() {
let client = MockEcdsaClient::new();

let handler = get_handler(
rand_account(),
TMAddress::from(MULTISIG_ADDRESS.parse::<AccountId>().unwrap()),
SharableEcdsaClient::new(client),
100u64,
);

assert!(handler
.handle(&signing_started_event_with_missing_fields(
&rand_account().to_string()
))
.await

Check warning on line 399 in ampd/src/handlers/multisig.rs

View check run for this annotation

Codecov / codecov/patch

ampd/src/handlers/multisig.rs#L399

Added line #L399 was not covered by tests
.is_ok());
}

#[tokio::test]
async fn should_error_on_event_with_missing_fields_if_multisig_address_does_match() {
let client = MockEcdsaClient::new();

let handler = get_handler(
rand_account(),
TMAddress::from(MULTISIG_ADDRESS.parse::<AccountId>().unwrap()),
SharableEcdsaClient::new(client),
100u64,
);

assert!(handler
.handle(&signing_started_event_with_missing_fields(MULTISIG_ADDRESS))
.await

Check warning on line 416 in ampd/src/handlers/multisig.rs

View check run for this annotation

Codecov / codecov/patch

ampd/src/handlers/multisig.rs#L416

Added line #L416 was not covered by tests
.is_err());
}

#[tokio::test]
async fn should_not_handle_event_if_multisig_address_does_not_match() {
let mut client = MockEcdsaClient::new();
client
.expect_sign()
.returning(move |_, _, _| Err(Report::from(tofnd::error::Error::SignFailed)));
let client = MockEcdsaClient::new();

let handler = get_handler(
rand_account(),
Expand Down
11 changes: 4 additions & 7 deletions ampd/src/handlers/sui_verify_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ pub struct Message {
#[derive(Deserialize, Debug)]
#[try_from("wasm-messages_poll_started")]
struct PollStartedEvent {
#[serde(rename = "_contract_address")]
contract_address: TMAddress,
poll_id: PollId,
source_gateway_address: SuiAddress,
messages: Vec<Message>,
Expand Down Expand Up @@ -102,8 +100,11 @@ where
type Err = Error;

async fn handle(&self, event: &Event) -> Result<()> {
if !event.is_from_contract(self.voting_verifier.as_ref()) {
return Ok(());
}

let PollStartedEvent {
contract_address,
poll_id,
source_gateway_address,
messages,
Expand All @@ -117,10 +118,6 @@ where
event => event.change_context(Error::DeserializeEvent)?,
};

if self.voting_verifier != contract_address {
return Ok(());
}

if !participants.contains(&self.worker) {
return Ok(());
}
Expand Down
11 changes: 4 additions & 7 deletions ampd/src/handlers/sui_verify_worker_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@
#[derive(Deserialize, Debug)]
#[try_from("wasm-worker_set_poll_started")]
struct PollStartedEvent {
#[serde(rename = "_contract_address")]
contract_address: TMAddress,
poll_id: PollId,
source_gateway_address: SuiAddress,
worker_set: WorkerSetConfirmation,
Expand Down Expand Up @@ -110,8 +108,11 @@
type Err = Error;

async fn handle(&self, event: &Event) -> error_stack::Result<(), Error> {
if !event.is_from_contract(self.voting_verifier.as_ref()) {
return Ok(());

Check warning on line 112 in ampd/src/handlers/sui_verify_worker_set.rs

View check run for this annotation

Codecov / codecov/patch

ampd/src/handlers/sui_verify_worker_set.rs#L112

Added line #L112 was not covered by tests
}

let PollStartedEvent {
contract_address,
poll_id,
source_gateway_address,
worker_set,
Expand All @@ -125,10 +126,6 @@
event => event.change_context(Error::DeserializeEvent)?,
};

if self.voting_verifier != contract_address {
return Ok(());
}

if !participants.contains(&self.worker) {
return Ok(());
}
Expand Down
1 change: 1 addition & 0 deletions packages/events/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ edition = "2021"
[dependencies]
axelar-wasm-std = { workspace = true }
base64 = "0.21.2"
cosmrs = { version = "0.14.0", features = ["cosmwasm"] }
error-stack = { workspace = true }
serde_json = "1.0.105"
# Need to switch to our own fork of tendermint and tendermint-rpc due to event attribute value being nullable.
Expand Down
88 changes: 88 additions & 0 deletions packages/events/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use crate::errors::DecodingError;
use crate::Error;

use cosmrs::AccountId;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
BlockBegin(block::Height),
Expand All @@ -27,6 +29,25 @@
pub fn block_end(height: impl Into<block::Height>) -> Self {
Event::BlockEnd(height.into())
}

pub fn is_from_contract(&self, from_address: &AccountId) -> bool {
match self.contract_address() {
Some(emitting_address) => &emitting_address == from_address,
_ => false,
}
}

fn contract_address(&self) -> Option<AccountId> {
match self {
Event::Abci {
event_type: _,
attributes,
} => attributes
.get("_contract_address")
.and_then(|address| serde_json::from_value::<AccountId>(address.clone()).ok()),
_ => None,

Check warning on line 48 in packages/events/src/event.rs

View check run for this annotation

Codecov / codecov/patch

packages/events/src/event.rs#L48

Added line #L48 was not covered by tests
}
}
}

impl TryFrom<abci::Event> for Event {
Expand Down Expand Up @@ -71,3 +92,70 @@
fn base64_to_utf8(base64_str: &str) -> std::result::Result<String, DecodingError> {
Ok(STANDARD.decode(base64_str)?.then(String::from_utf8)?)
}

#[cfg(test)]
mod test {
use std::str::FromStr;

use cosmrs::AccountId;

use crate::Event;

fn make_event_with_contract_address(contract_address: &AccountId) -> Event {
let mut attributes = serde_json::Map::new();
attributes.insert(
"_contract_address".to_string(),
contract_address.to_string().into(),
);
Event::Abci {
event_type: "some_event".to_string(),
attributes,
}
}

#[test]
fn should_get_contract_address_if_exists() {
let expected_contract_address =
AccountId::from_str("axelarvaloper1zh9wrak6ke4n6fclj5e8yk397czv430ygs5jz7").unwrap();

let event = make_event_with_contract_address(&expected_contract_address);

let contract_address = event.contract_address();
assert_eq!(contract_address, Some(expected_contract_address));
}

#[test]
fn should_not_get_contract_address_if_not_exists() {
let event = Event::Abci {
event_type: "some_event".to_string(),
attributes: serde_json::Map::new(),
};
let contract_address = event.contract_address();
assert!(contract_address.is_none());
}

#[test]
fn event_is_from_contract_should_return_true_iff_contract_address_matches() {
let contract_address =
AccountId::from_str("axelarvaloper1zh9wrak6ke4n6fclj5e8yk397czv430ygs5jz7").unwrap();
let event = make_event_with_contract_address(&contract_address);
assert!(event.is_from_contract(&contract_address));

let diff_contract_address =
AccountId::from_str("axelarvaloper1tee73c83k2vqky9gt59jd3ztwxhqjm27l588q6").unwrap();
assert!(!event.is_from_contract(&diff_contract_address));
}

#[test]
fn event_is_from_contract_should_return_false_if_contract_address_does_not_exist() {
let contract_address =
AccountId::from_str("axelarvaloper1zh9wrak6ke4n6fclj5e8yk397czv430ygs5jz7").unwrap();

let event_without_contract_address = Event::Abci {
event_type: "some_event".to_string(),
attributes: serde_json::Map::new(),
};

assert!(!event_without_contract_address.is_from_contract(&contract_address));
}
}
Loading