From eea78d0040e5703e857e41c464025962d93f646b Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 28 Dec 2023 00:26:55 +0800 Subject: [PATCH] Refacotor create vp client (#473) * add todo note * fix cargo check * refactor error handler * should build_* function return Option value * Add refactor create client add only-init-vp optional * remove relate create vp client code * revert should build_* function return Option value modify * Update --------- Co-authored-by: Yuanchao Sun --- Cargo.lock | 3 + crates/relayer-cli/Cargo.toml | 4 + crates/relayer-cli/src/commands/keys/add.rs | 8 +- .../relayer-cli/src/commands/keys/delete.rs | 4 +- crates/relayer-cli/src/commands/tx/client.rs | 395 ++++++++++- crates/relayer/src/chain.rs | 3 - crates/relayer/src/chain/client.rs | 2 - crates/relayer/src/chain/near/contract.rs | 28 +- crates/relayer/src/chain/near/error.rs | 95 ++- crates/relayer/src/chain/near/mod.rs | 65 +- crates/relayer/src/chain/near/rpc/client.rs | 55 +- crates/relayer/src/chain/near/rpc/result.rs | 2 +- crates/relayer/src/chain/near/rpc/tool.rs | 624 +++++++++++++++--- crates/relayer/src/chain/vp_client.rs | 611 ----------------- crates/relayer/src/keyring.rs | 2 +- crates/relayer/src/link/relay_path.rs | 22 +- crates/relayer/src/spawn.rs | 2 - tools/test-framework/src/bootstrap/init.rs | 24 + tools/test-framework/src/types/config.rs | 14 + tools/test-framework/src/types/single/node.rs | 7 + 20 files changed, 1122 insertions(+), 848 deletions(-) delete mode 100644 crates/relayer/src/chain/vp_client.rs diff --git a/Cargo.lock b/Cargo.lock index 8b6a5576be..8be54818c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2619,13 +2619,16 @@ dependencies = [ "http", "humantime", "ibc-chain-registry", + "ibc-proto", "ibc-relayer", "ibc-relayer-rest", "ibc-relayer-types", "ibc-telemetry", + "ic-agent", "itertools", "once_cell", "oneline-eyre", + "prost 0.12.1", "regex", "serde", "serde_json", diff --git a/crates/relayer-cli/Cargo.toml b/crates/relayer-cli/Cargo.toml index 98c3272e84..dcfce4713d 100644 --- a/crates/relayer-cli/Cargo.toml +++ b/crates/relayer-cli/Cargo.toml @@ -25,6 +25,7 @@ telemetry = ["ibc-relayer/telemetry", "ibc-telemetry"] rest-server = ["ibc-relayer-rest"] [dependencies] +ibc-proto = { version = "0.38.0", features = ["serde"] } ibc-relayer-types = { version = "0.26.3", path = "../relayer-types" } ibc-relayer = { version = "0.26.3", path = "../relayer" } ibc-telemetry = { version = "0.26.3", path = "../telemetry", optional = true } @@ -55,6 +56,9 @@ tokio = { version = "1.0", features = ["full"] } tracing = "0.1.36" tracing-subscriber = { version = "0.3.14", features = ["fmt", "env-filter", "json"]} time = "0.3" +prost = { version = "0.12" } +ic-agent = { version = "0.29.0", features = ["pem"] } + [dependencies.tendermint] version = "0.34.0" features = ["secp256k1"] diff --git a/crates/relayer-cli/src/commands/keys/add.rs b/crates/relayer-cli/src/commands/keys/add.rs index 304422aae6..b94579e95c 100644 --- a/crates/relayer-cli/src/commands/keys/add.rs +++ b/crates/relayer-cli/src/commands/keys/add.rs @@ -43,10 +43,10 @@ use crate::conclude::Output; #[derive(Clone, Command, Debug, Parser, PartialEq, Eq)] #[clap(override_usage = "Add a key from a Comet keyring file: hermes keys add [OPTIONS] --chain --key-file - + Add a key from a file containing its mnemonic: hermes keys add [OPTIONS] --chain --mnemonic-file - + On *nix platforms, both flags also accept `/dev/stdin` as a value, which will read the key or the mnemonic from stdin.")] pub struct KeysAddCmd { #[clap( @@ -205,7 +205,7 @@ pub fn add_key( overwrite: bool, ) -> eyre::Result { let key_pair = match config.r#type { - ChainType::CosmosSdk | ChainType::Vp => { + ChainType::CosmosSdk => { let mut keyring = KeyRing::new_secp256k1( Store::Test, &config.account_prefix, @@ -256,7 +256,7 @@ pub fn restore_key( fs::read_to_string(mnemonic).map_err(|_| eyre!("error reading the mnemonic file"))?; let key_pair = match config.r#type { - ChainType::CosmosSdk | ChainType::Vp => { + ChainType::CosmosSdk => { let mut keyring = KeyRing::new_secp256k1( Store::Test, &config.account_prefix, diff --git a/crates/relayer-cli/src/commands/keys/delete.rs b/crates/relayer-cli/src/commands/keys/delete.rs index fa73c3e671..8e9fa43ee8 100644 --- a/crates/relayer-cli/src/commands/keys/delete.rs +++ b/crates/relayer-cli/src/commands/keys/delete.rs @@ -114,7 +114,7 @@ impl Runnable for KeysDeleteCmd { pub fn delete_key(config: &ChainConfig, key_name: &str) -> eyre::Result<()> { match config.r#type { - ChainType::CosmosSdk | ChainType::Vp => { + ChainType::CosmosSdk => { let mut keyring = KeyRing::new_secp256k1( Store::Test, &config.account_prefix, @@ -138,7 +138,7 @@ pub fn delete_key(config: &ChainConfig, key_name: &str) -> eyre::Result<()> { pub fn delete_all_keys(config: &ChainConfig) -> eyre::Result<()> { match config.r#type { - ChainType::CosmosSdk | ChainType::Vp => { + ChainType::CosmosSdk => { let mut keyring = KeyRing::new_secp256k1( Store::Test, &config.account_prefix, diff --git a/crates/relayer-cli/src/commands/tx/client.rs b/crates/relayer-cli/src/commands/tx/client.rs index 8014baacee..b3829edefa 100644 --- a/crates/relayer-cli/src/commands/tx/client.rs +++ b/crates/relayer-cli/src/commands/tx/client.rs @@ -2,24 +2,47 @@ use core::{ fmt::{Display, Error as FmtError, Formatter}, time::Duration, }; +use ibc_proto::google::protobuf::Any; +use ibc_relayer_types::core::ics02_client::msgs::create_client::MsgCreateClient; +use ibc_relayer_types::tx_msg::Msg; +use std::sync::Arc; use std::thread; use abscissa_core::clap::Parser; use abscissa_core::{Command, Runnable}; - +use core::future::Future; +use ibc_proto::Protobuf; +use ibc_relayer::chain::client::ClientSettings; +use ibc_relayer::chain::ic::VpClient; use ibc_relayer::chain::requests::{ IncludeProof, PageRequest, QueryClientStateRequest, QueryClientStatesRequest, QueryHeight, }; +use ibc_relayer::chain::tracking::TrackedMsgs; +use ibc_relayer::client_state::AnyClientState; +use ibc_relayer::config::ChainConfig; use ibc_relayer::config::Config; +use ibc_relayer::error::Error as RelayerError; use ibc_relayer::event::IbcEventWithHeight; +use ibc_relayer::foreign_client::ForeignClientError; use ibc_relayer::foreign_client::{CreateOptions, ForeignClient}; use ibc_relayer::{chain::handle::ChainHandle, config::GenesisRestart}; +use ibc_relayer_types::core::ics02_client::client_type::ClientType; +use ibc_relayer_types::core::ics02_client::events::Attributes; +use ibc_relayer_types::core::ics02_client::events::CreateClient; use ibc_relayer_types::core::ics24_host::identifier::{ChainId, ClientId}; use ibc_relayer_types::events::IbcEvent; +use ibc_relayer_types::events::IbcEvent as IbcRelayerTypeEvent; +use ibc_relayer_types::signer::Signer; use ibc_relayer_types::Height; +use ibc_relayer_types::Height as ICSHeight; +use ic_agent::identity::Secp256k1Identity; +use ic_agent::Identity; +use prost::Message; +use std::str::FromStr; use tendermint::block::Height as BlockHeight; use tendermint_light_client_verifier::types::TrustThreshold; use tendermint_rpc::Url; +use tokio::runtime::Runtime as TokioRuntime; use tracing::debug; use crate::application::app_config; @@ -72,6 +95,10 @@ pub struct TxCreateClientCmd { /// and trusted validator set is sufficient for a commit to be accepted going forward. #[clap(long = "trust-threshold", value_name = "TRUST_THRESHOLD", parse(try_from_str = parse_trust_threshold))] trust_threshold: Option, + + /// Only initialize the verification package for the client, do not create the client. + #[clap(long = "only-init-vp", value_name = "ONLY_INIT_VP")] + only_init_vp: Option, } /// Sample to run this tx: @@ -84,28 +111,341 @@ impl Runnable for TxCreateClientCmd { Output::error("source and destination chains must be different".to_string()).exit() } - let chains = match ChainHandlePair::spawn(&config, &self.src_chain_id, &self.dst_chain_id) { - Ok(chains) => chains, - Err(e) => Output::error(e).exit(), - }; + if self.only_init_vp.unwrap_or(false) { + run_only_init_vp( + &config, + &self.src_chain_id, + &self.dst_chain_id, + self.clock_drift, + self.trusting_period, + self.trust_threshold, + ); + } else { + run_create_client( + &config, + &self.src_chain_id, + &self.dst_chain_id, + self.clock_drift, + self.trusting_period, + self.trust_threshold, + ); + } + } +} - let client = ForeignClient::restore(ClientId::default(), chains.dst, chains.src); +fn run_create_client( + config: &Config, + src_chain_id: &ChainId, + dst_chain_id: &ChainId, + clock_drift: Option, + trusting_period: Option, + trust_threshold: Option, +) { + let chains = match ChainHandlePair::spawn(&config, &src_chain_id, dst_chain_id) { + Ok(chains) => chains, + Err(e) => Output::error(e).exit(), + }; - let options = CreateOptions { - max_clock_drift: self.clock_drift.map(Into::into), - trusting_period: self.trusting_period.map(Into::into), - trust_threshold: self.trust_threshold.map(Into::into), - }; + let client = ForeignClient::restore(ClientId::default(), chains.dst, chains.src); + + let options = CreateOptions { + max_clock_drift: clock_drift.map(Into::into), + trusting_period: trusting_period.map(Into::into), + trust_threshold: trust_threshold.map(Into::into), + }; + + // Trigger client creation via the "build" interface, so that we obtain the resulting event + let res: Result = client + .build_create_client_and_send(options) + .map_err(Error::foreign_client); + + match res { + Ok(receipt) => Output::success(receipt.event).exit(), + Err(e) => Output::error(e).exit(), + } +} - // Trigger client creation via the "build" interface, so that we obtain the resulting event - let res: Result = client - .build_create_client_and_send(options) +fn run_only_init_vp( + config: &Config, + src_chain_id: &ChainId, + _dst_chain_id: &ChainId, + clock_drift: Option, + trusting_period: Option, + trust_threshold: Option, +) { + let chain_config = config + .find_chain(src_chain_id) + .expect("not found src chain Config"); + let src_chain = match spawn_chain_runtime(&config, src_chain_id) { + Ok(handle) => handle, + Err(e) => Output::error(e).exit(), + }; + + let options = CreateOptions { + max_clock_drift: clock_drift.map(Into::into), + trusting_period: trusting_period.map(Into::into), + trust_threshold: trust_threshold.map(Into::into), + }; + + let rt = Arc::new(TokioRuntime::new().unwrap()); + + let vp_client = match VpChain::new(src_chain_id.clone(), chain_config.clone(), rt) { + Ok(client) => client, + Err(e) => Output::error(e).exit(), + }; + + // Trigger client creation via the "build" interface, so that we obtain the resulting event + let res: Result = + build_and_create_client_and_send(src_chain, vp_client, options) .map_err(Error::foreign_client); - match res { - Ok(receipt) => Output::success(receipt.event).exit(), - Err(e) => Output::error(e).exit(), + match res { + Ok(receipt) => Output::success(receipt.event).exit(), + Err(e) => Output::error(e).exit(), + } +} + +/// Lower-level interface for preparing a message to create a client. +pub fn build_create_client( + src_chain: impl ChainHandle, + vp_client: VpChain, + options: CreateOptions, +) -> Result { + // Get signer + let signer = vp_client.get_signer().map_err(|e| { + ForeignClientError::client_create( + src_chain.id(), + format!( + "failed while fetching the dst chain ({}) signer", + vp_client.chain_id(), + ), + e, + ) + })?; + + // Build client create message with the data from source chain at latest height. + let latest_height = src_chain.query_latest_height().map_err(|e| { + ForeignClientError::client_create( + src_chain.id(), + "failed while querying src chain for latest height".to_string(), + e, + ) + })?; + + // Calculate client state settings from the chain configurations and + // optional user overrides. + let src_config = src_chain.config().map_err(|e| { + ForeignClientError::client_create( + src_chain.id(), + "failed while querying the source chain for configuration".to_string(), + e, + ) + })?; + + //NOTE:(davirain) this use a src_chain config, but this conif not use in this create vp client + let dst_config = src_chain.config().map_err(|e| { + ForeignClientError::client_create( + src_chain.id(), + "failed while querying the source chain for configuration".to_string(), + e, + ) + })?; + let settings = ClientSettings::for_create_command(options, &src_config, &dst_config); + + let client_state: AnyClientState = src_chain + .build_client_state(latest_height, settings) + .map_err(|e| { + ForeignClientError::client_create( + src_chain.id(), + "failed when building client state".to_string(), + e, + ) + })?; + + let consensus_state = src_chain + .build_consensus_state( + client_state.latest_height(), + latest_height, + client_state.clone(), + ) + .map_err(|e| { + ForeignClientError::client_create( + src_chain.id(), + "failed while building client consensus state from src chain".to_string(), + e, + ) + })?; + + //TODO Get acct_prefix + let msg = MsgCreateClient::new(client_state.into(), consensus_state.into(), signer) + .map_err(|e| ForeignClientError::client(e))?; + + Ok(msg) +} + +/// Returns the identifier of the newly created client. +fn build_and_create_client_and_send( + src_chain: impl ChainHandle, + vp_client: VpChain, + options: CreateOptions, +) -> Result { + let new_msg = build_create_client(src_chain, vp_client.clone(), options)?; + + let res = vp_client + .send_messages_and_wait_commit(TrackedMsgs::new_single(new_msg.to_any(), "create client")) + .map_err(|e| { + ForeignClientError::client_create( + vp_client.chain_id().clone(), + "failed sending message to dst chain ".to_string(), + e, + ) + })?; + + assert!(!res.is_empty()); + Ok(res[0].clone()) +} + +#[derive(Debug, Clone)] +pub struct VpChain { + chain_id: ChainId, + config: ChainConfig, + rt: Arc, + vp_client: VpClient, + signer: String, +} + +impl VpChain { + pub fn new( + chain_id: ChainId, + chain_config: ChainConfig, + rt: Arc, + ) -> Result { + let canister_pem_path = if chain_config.canister_pem.is_absolute() { + chain_config.canister_pem.clone() + } else { + let current_dir = + std::env::current_dir().map_err(|e| RelayerError::report_error(e.to_string()))?; + current_dir.join(chain_config.canister_pem.clone()) + }; + + let signer = Secp256k1Identity::from_pem_file(canister_pem_path.clone()).map_err(|e| { + let position = std::panic::Location::caller(); + RelayerError::report_error(format!( + "build vp client failed Error({:?}) \n{}", + e, position + )) + })?; + + let sender = signer + .sender() + .map_err(|e| { + let position = std::panic::Location::caller(); + RelayerError::report_error(format!( + "build vp client failed Error({:?}) \n{}", + e, position + )) + })? + .to_text(); + + let vp_client = rt + .block_on(VpClient::new(&chain_config.ic_endpoint, &canister_pem_path)) + .map_err(|e| { + let position = std::panic::Location::caller(); + RelayerError::report_error(format!( + "build vp client failed Error({:?}) \n{}", + e, position + )) + })?; + // Retrieve the version specification of this chain + + Ok(Self { + chain_id, + config: chain_config.clone(), + vp_client, + rt, + signer: sender, + }) + } + + /// Run a future to completion on the Tokio runtime. + fn block_on(&self, f: F) -> F::Output { + self.rt.block_on(f) + } + + /// Get the account for the signer + fn get_signer(&self) -> Result { + Signer::from_str(self.signer.as_str()) + .map_err(|e| RelayerError::report_error(e.to_string())) + } + + fn chain_id(&self) -> &ChainId { + &self.chain_id + } + + fn send_messages_and_wait_commit( + &self, + tracked_msgs: TrackedMsgs, + ) -> Result, RelayerError> { + // let mut tracked_msgs = tracked_msgs.clone(); + // if tracked_msgs.tracking_id().to_string() != "ft-transfer" { + let canister_id = self.config.canister_id.id.as_str(); + let mut msgs: Vec = Vec::new(); + for msg in tracked_msgs.messages() { + let res = self + .block_on(self.vp_client.deliver(canister_id, msg.encode_to_vec())) + .map_err(|e| { + let position = std::panic::Location::caller(); + RelayerError::report_error(format!( + "call vp deliver failed Error({}) \n{}", + e, position + )) + })?; + assert!(!res.is_empty()); + if !res.is_empty() { + msgs.push(Any::decode(&res[..]).map_err(|e| { + let position = std::panic::Location::caller(); + RelayerError::report_error(format!( + "decode call vp deliver result failed Error({}) \n{}", + e, position + )) + })?); + } } + assert_eq!(msgs.len(), 1); + let create_client_msg = msgs.remove(0); + let domain_msg: MsgCreateClient = MsgCreateClient::decode_vec(&create_client_msg.value) + .map_err(|e| { + let position = std::panic::Location::caller(); + RelayerError::report_error(format!( + "decode call vp deliver result failed Error({}) \n{}", + e, position + )) + })?; + + let client_state = + ibc_relayer_types::clients::ics06_solomachine::client_state::ClientState::try_from( + domain_msg.client_state, + ) + .unwrap(); + println!("new solomachine client state created: {:?}", client_state); + let serialized_pub_key = + serde_json::to_string(&client_state.consensus_state.public_key.0).unwrap(); + println!("pubkey: {:?}", serialized_pub_key); + println!( + "timestamp: {:?}", + client_state.consensus_state.timestamp.nanoseconds() + ); + // todo: maybe need to check the response from ic + let create_client_event = CreateClient::from(Attributes { + client_id: ClientId::new(ClientType::Solomachine, 0).unwrap(), + client_type: ClientType::Solomachine, + consensus_height: ICSHeight::new(0, 1).unwrap(), + }); + let create_event_with_height = IbcEventWithHeight { + event: IbcRelayerTypeEvent::CreateClient(create_client_event), + height: ICSHeight::new(0, 1).unwrap(), + }; + Ok(vec![create_event_with_height]) } } @@ -629,7 +969,8 @@ mod tests { src_chain_id: ChainId::from_string("reference_chain"), clock_drift: None, trusting_period: None, - trust_threshold: None + trust_threshold: None, + only_init_vp: None, }, TxCreateClientCmd::parse_from([ "test", @@ -649,7 +990,8 @@ mod tests { src_chain_id: ChainId::from_string("reference_chain"), clock_drift: Some("5s".parse::().unwrap()), trusting_period: None, - trust_threshold: None + trust_threshold: None, + only_init_vp: None, }, TxCreateClientCmd::parse_from([ "test", @@ -667,7 +1009,8 @@ mod tests { src_chain_id: ChainId::from_string("reference_chain"), clock_drift: Some("3s".parse::().unwrap()), trusting_period: None, - trust_threshold: None + trust_threshold: None, + only_init_vp: None }, TxCreateClientCmd::parse_from([ "test", @@ -689,7 +1032,8 @@ mod tests { src_chain_id: ChainId::from_string("reference_chain"), clock_drift: None, trusting_period: Some("5s".parse::().unwrap()), - trust_threshold: None + trust_threshold: None, + only_init_vp: None, }, TxCreateClientCmd::parse_from([ "test", @@ -707,7 +1051,8 @@ mod tests { src_chain_id: ChainId::from_string("reference_chain"), clock_drift: None, trusting_period: Some("3s".parse::().unwrap()), - trust_threshold: None + trust_threshold: None, + only_init_vp: None }, TxCreateClientCmd::parse_from([ "test", @@ -729,7 +1074,8 @@ mod tests { src_chain_id: ChainId::from_string("reference_chain"), clock_drift: None, trusting_period: None, - trust_threshold: Some(TrustThreshold::new(1, 2).unwrap()) + trust_threshold: Some(TrustThreshold::new(1, 2).unwrap()), + only_init_vp: None, }, TxCreateClientCmd::parse_from([ "test", @@ -751,7 +1097,8 @@ mod tests { src_chain_id: ChainId::from_string("reference_chain"), clock_drift: Some("5s".parse::().unwrap()), trusting_period: Some("3s".parse::().unwrap()), - trust_threshold: Some(TrustThreshold::new(1, 2).unwrap()) + trust_threshold: Some(TrustThreshold::new(1, 2).unwrap()), + only_init_vp: None, }, TxCreateClientCmd::parse_from([ "test", diff --git a/crates/relayer/src/chain.rs b/crates/relayer/src/chain.rs index ce3cdab31c..46e635d992 100644 --- a/crates/relayer/src/chain.rs +++ b/crates/relayer/src/chain.rs @@ -8,7 +8,6 @@ pub mod near; pub mod requests; pub mod runtime; pub mod tracking; -pub mod vp_client; use serde::{de::Error, Deserialize, Serialize}; @@ -22,7 +21,6 @@ pub enum ChainType { /// Chains based on the Cosmos SDK CosmosSdk, Near, - Vp, } impl<'de> Deserialize<'de> for ChainType { @@ -36,7 +34,6 @@ impl<'de> Deserialize<'de> for ChainType { match s.as_str() { "cosmossdk" => Ok(Self::CosmosSdk), "near" => Ok(Self::Near), - "vp" => Ok(Self::Vp), // NOTE(new): Add a case here _ => Err(D::Error::unknown_variant(&original, &["cosmos-sdk"])), // NOTE(new): mention the new variant here diff --git a/crates/relayer/src/chain/client.rs b/crates/relayer/src/chain/client.rs index b0cb6c3dc4..301c36ec78 100644 --- a/crates/relayer/src/chain/client.rs +++ b/crates/relayer/src/chain/client.rs @@ -13,7 +13,6 @@ use crate::foreign_client::CreateOptions; pub enum ClientSettings { Tendermint(cosmos::client::Settings), Near(near::client::Settings), - Vp, } impl ClientSettings { @@ -41,7 +40,6 @@ impl ClientSettings { src_chain_config, dst_chain_config, )), - ChainType::Vp => ClientSettings::Vp, } } diff --git a/crates/relayer/src/chain/near/contract.rs b/crates/relayer/src/chain/near/contract.rs index a8b5c4e72b..27b1208d06 100644 --- a/crates/relayer/src/chain/near/contract.rs +++ b/crates/relayer/src/chain/near/contract.rs @@ -62,7 +62,9 @@ pub trait NearIbcContract { // As we use solomachine client, we set the revision number to 0 // TODO: ibc height reversion number is chainid version Height::new(0, height.revision_height()) - .map_err(NearError::build_ibc_height_error) + .map_err(|e| { + NearError::build_ibc_height_error(std::panic::Location::caller().to_string(), e) + }) .map_err(Into::into) } @@ -185,7 +187,9 @@ pub trait NearIbcContract { client_id, std::panic::Location::caller() ); - let client_id = serde_json::to_string(client_id).map_err(NearError::serde_json_error)?; + let client_id = serde_json::to_string(client_id).map_err(|e| { + NearError::serde_json_error(std::panic::Location::caller().to_string(), e) + })?; self.view( self.get_contract_id(), @@ -235,7 +239,9 @@ pub trait NearIbcContract { std::panic::Location::caller() ); - let request = serde_json::to_string(&request).map_err(NearError::serde_json_error)?; + let request = serde_json::to_string(&request).map_err(|e| { + NearError::serde_json_error(std::panic::Location::caller().to_string(), e) + })?; self.view( self.get_contract_id(), @@ -256,7 +262,9 @@ pub trait NearIbcContract { std::panic::Location::caller() ); - let request = serde_json::to_string(&request).map_err(NearError::serde_json_error)?; + let request = serde_json::to_string(&request).map_err(|e| { + NearError::serde_json_error(std::panic::Location::caller().to_string(), e) + })?; self.view( self.get_contract_id(), @@ -277,7 +285,9 @@ pub trait NearIbcContract { std::panic::Location::caller() ); - let request = serde_json::to_string(&request).map_err(NearError::serde_json_error)?; + let request = serde_json::to_string(&request).map_err(|e| { + NearError::serde_json_error(std::panic::Location::caller().to_string(), e) + })?; self.view( self.get_contract_id(), @@ -557,12 +567,14 @@ pub async fn test123() -> anyhow::Result<()> { .into_bytes(), ) .await - .map_err(|e| NearError::custom_error(e.to_string()))?; + .map_err(|e| { + NearError::custom_error(e.to_string(), std::panic::Location::caller().to_string()) + })?; let result_raw: serde_json::value::Value = result.json().unwrap(); dbg!(&result_raw); - let connection_end: ConnectionEnd = - serde_json::from_value(result_raw).map_err(NearError::serde_json_error)?; + let connection_end: ConnectionEnd = serde_json::from_value(result_raw) + .map_err(|e| NearError::serde_json_error(std::panic::Location::caller().to_string(), e))?; dbg!(&connection_end); Ok(()) } diff --git a/crates/relayer/src/chain/near/error.rs b/crates/relayer/src/chain/near/error.rs index ffe35903c3..1178966893 100644 --- a/crates/relayer/src/chain/near/error.rs +++ b/crates/relayer/src/chain/near/error.rs @@ -12,112 +12,111 @@ use std::string::FromUtf8Error; define_error! { NearError { SerdeJsonError + { line: String } [ TraceError] - |_| { - let caller = std::panic::Location::caller(); - format!("serde json failure \n{}", caller) + |e| { + format!("serde json failure \n{}", e.line) }, CustomError - { reason: String } + { reason: String, line: String } |e| { - let caller = std::panic::Location::caller(); - format!("Custom error: {} \n{}", e.reason, caller) + format!("Custom error: {} \n{}", e.reason, e.line) }, RpcQueryError + { line: String } [ TraceError> ] - | _ | { - let caller = std::panic::Location::caller(); - format!("near rpc query error \n{}", caller) + | e | { + format!("near rpc query error \n{}", e.line) }, RpcTransactionError + { line: String } [ TraceError>] - | _ | { - let caller = std::panic::Location::caller(); - format!("near rpc transaction error \n{}", caller) + | e | { + format!("near rpc transaction error \n{}", e.line) }, RpcBlockError + { line: String } [ TraceError>] - | _ | { - let caller = std::panic::Location::caller(); - format!("near rpc block error \n{}", caller) + | e | { + format!("near rpc block error \n{}", e.line) }, RpcStateChangesError + { line: String } [ TraceError>] - | _ | { - let caller = std::panic::Location::caller(); - format!("near rpc state changes error \n{}", caller) + | e | { + format!("near rpc state changes error \n{}", e.line) }, DeliverError - |_| { - let caller = std::panic::Location::caller(); - format!("near chain Deliver failed \n{}", caller) + { line: String } + | e | { + format!("near chain Deliver failed \n{}", e.line) }, VpDeliverError + { line: String } [ TraceError] - | _ | { - let caller = std::panic::Location::caller(); - format!("call vp deliver error, \n{}", caller) + | e | { + format!("call vp deliver error, \n{}", e.line) }, DecodeVpDeliverResultFailed + { line: String } [ TraceError] - | _ | { - let caller = std::panic::Location::caller(); - format!("decode vp deliver result failed, \n{}", caller) + | e | { + format!("decode vp deliver result failed, \n{}", e.line) }, BuildVpClientError - | _ | { - let caller = std::panic::Location::caller(); - format!("near chain bootstrap build VpClientFailed \n{}", caller) + { line: String } + | e | { + format!("near chain bootstrap build VpClientFailed \n{}", e.line) }, BuildIbcHeightError + { line: String } [ TraceError] - | _ | { - let caller = std::panic::Location::caller(); - format!("build ibc height failed \n{}", caller) + | e | { + format!("build ibc height failed \n{}", e.line) }, VpError + { line: String } [ TraceError ] - | _ | { - let caller = std::panic::Location::caller(); - format!("vp error \n{}", caller) + | e | { + format!("vp error \n{}", e.line) }, NextBpsEmpty - | _ | { - let caller = std::panic::Location::caller(); - format!("next bps empty \n{}", caller) + { line: String } + | e | { + format!("next bps empty \n{}",e.line) }, ParseIntError + { line: String } [ TraceError ] - |_ | { - let caller = std::panic::Location::caller(); - format!("parse int error \n{}", caller) + | e | { + format!("parse int error \n{}", e.line) }, DecodeStringError + { line: String } [ TraceError ] - | _ | { - let caller = std::panic::Location::caller(); - format!("decode string error \n{}", caller) + | e | { + format!("decode string error \n{}", e.line) }, BuildNearProofsFailed + { line: String } [ TraceError] - | _ | { - let caller = std::panic::Location::caller(); - format!("build near proofs failed \n{}", caller) + | e | { + format!("build near proofs failed \n{}", e.line) } } } diff --git a/crates/relayer/src/chain/near/mod.rs b/crates/relayer/src/chain/near/mod.rs index e21673111a..21c330bd7b 100644 --- a/crates/relayer/src/chain/near/mod.rs +++ b/crates/relayer/src/chain/near/mod.rs @@ -216,7 +216,11 @@ impl NearChain { } } }) - .map_err(|_| Error::near_chain_error(NearError::deliver_error())) + .map_err(|_| { + Error::near_chain_error(NearError::deliver_error( + std::panic::Location::caller().to_string(), + )) + }) } fn init_signing_key_pair(&mut self) { @@ -412,8 +416,12 @@ impl NearChain { }?; let proofs: Vec> = state.proof.iter().map(|proof| proof.to_vec()).collect(); - to_vec(&NearProofs(proofs)) - .map_err(|e| Error::near_chain_error(NearError::build_near_proofs_failed(e))) + to_vec(&NearProofs(proofs)).map_err(|e| { + Error::near_chain_error(NearError::build_near_proofs_failed( + std::panic::Location::caller().to_string(), + e, + )) + }) } } @@ -508,8 +516,12 @@ impl ChainEndpoint for NearChain { .get_contract_version() .map_err(Error::near_chain_error)?; - let str_version = String::from_utf8(version) - .map_err(|e| Error::near_chain_error(NearError::decode_string_error(e)))?; + let str_version = String::from_utf8(version).map_err(|e| { + Error::near_chain_error(NearError::decode_string_error( + std::panic::Location::caller().to_string(), + e, + )) + })?; let version = Version::parse(&str_version) .map_err(|e| Error::report_error(e.to_string())) @@ -1154,7 +1166,10 @@ impl ChainEndpoint for NearChain { consensus_height: request.consensus_height, })), height: Height::new(0, 9).map_err(|e| { - Error::near_chain_error(NearError::build_ibc_height_error(e)) + Error::near_chain_error(NearError::build_ibc_height_error( + std::panic::Location::caller().to_string(), + e, + )) })?, }]) } @@ -1179,6 +1194,7 @@ impl ChainEndpoint for NearChain { request.height = request.height.map(|height| match height { QueryHeight::Latest => QueryHeight::Latest, QueryHeight::Specific(value) => QueryHeight::Specific( + // TODO(davirina): why +10? Height::new(value.revision_number(), value.revision_height() + 10) .expect("failed construct ibc height"), ), @@ -1694,17 +1710,33 @@ pub fn collect_ibc_event_by_outcome( for log in receipt_outcome.outcome.logs { if log.starts_with("EVENT_JSON:") { let event = log.replace("EVENT_JSON:", ""); - let event_value = serde_json::value::Value::from_str(event.as_str()) - .map_err(|e| Error::near_chain_error(NearError::serde_json_error(e)))?; + let event_value = + serde_json::value::Value::from_str(event.as_str()).map_err(|e| { + Error::near_chain_error(NearError::serde_json_error( + std::panic::Location::caller().to_string(), + e, + )) + })?; if "near-ibc" == event_value["standard"] { - let ibc_event: IbcEvent = - serde_json::from_value(event_value["raw-ibc-event"].clone()) - .map_err(|e| Error::near_chain_error(NearError::serde_json_error(e)))?; + let ibc_event: IbcEvent = serde_json::from_value( + event_value["raw-ibc-event"].clone(), + ) + .map_err(|e| { + Error::near_chain_error(NearError::serde_json_error( + std::panic::Location::caller().to_string(), + e, + )) + })?; debug!("collect_ibc_event_by_outcome ibc event: {:?} ", ibc_event); let block_height = u64::from_str(event_value["block_height"].as_str().ok_or( Error::report_error("Failed to get block_height field".to_string()), )?) - .map_err(|e| Error::near_chain_error(NearError::parse_int_error(e)))?; + .map_err(|e| { + Error::near_chain_error(NearError::parse_int_error( + std::panic::Location::caller().to_string(), + e, + )) + })?; match ibc_event { IbcEvent::Message(_) => continue, @@ -1712,7 +1744,10 @@ pub fn collect_ibc_event_by_outcome( event: convert_ibc_event_to_hermes_ibc_event(&ibc_event) .map_err(Error::near_chain_error)?, height: Height::new(0, block_height).map_err(|e| { - Error::near_chain_error(NearError::build_ibc_height_error(e)) + Error::near_chain_error(NearError::build_ibc_height_error( + std::panic::Location::caller().to_string(), + e, + )) })?, }), } @@ -1759,7 +1794,9 @@ pub fn produce_light_client_block( next_bps: Some( view.next_bps .as_ref() - .ok_or(Error::near_chain_error(NearError::next_bps_empty()))? + .ok_or(Error::near_chain_error(NearError::next_bps_empty( + std::panic::Location::caller().to_string(), + )))? .iter() .map(|f| match f { NearValidatorStakeView::V1(v) => { diff --git a/crates/relayer/src/chain/near/rpc/client.rs b/crates/relayer/src/chain/near/rpc/client.rs index 736e4a6338..4f0364225a 100644 --- a/crates/relayer/src/chain/near/rpc/client.rs +++ b/crates/relayer/src/chain/near/rpc/client.rs @@ -176,11 +176,16 @@ impl NearRpcClient { }, }) .await - .map_err(NearError::rpc_query_error)?; + .map_err(|e| { + NearError::rpc_query_error(std::panic::Location::caller().to_string(), e) + })?; match query_resp.kind { QueryResponseKind::CallResult(result) => Ok(result.into()), - _ => Err(NearError::custom_error(ERR_INVALID_VARIANT.to_string())), + _ => Err(NearError::custom_error( + ERR_INVALID_VARIANT.to_string(), + std::panic::Location::caller().to_string(), + )), } } @@ -204,11 +209,16 @@ impl NearRpcClient { }, }) .await - .map_err(NearError::rpc_query_error)?; + .map_err(|e| { + NearError::rpc_query_error(std::panic::Location::caller().to_string(), e) + })?; match query_resp.kind { QueryResponseKind::ViewState(state) => Ok(state), - _ => Err(NearError::custom_error(ERR_INVALID_VARIANT.to_string())), + _ => Err(NearError::custom_error( + ERR_INVALID_VARIANT.to_string(), + std::panic::Location::caller().to_string(), + )), } } @@ -229,7 +239,9 @@ impl NearRpcClient { }, }) .await - .map_err(NearError::rpc_state_changes_error)?; + .map_err(|e| { + NearError::rpc_state_changes_error(std::panic::Location::caller().to_string(), e) + })?; Ok(query_resp.changes) } @@ -249,11 +261,16 @@ impl NearRpcClient { request: QueryRequest::ViewAccount { account_id }, }) .await - .map_err(NearError::rpc_query_error)?; + .map_err(|e| { + NearError::rpc_query_error(std::panic::Location::caller().to_string(), e) + })?; match query_resp.kind { QueryResponseKind::ViewAccount(account) => Ok(account), - _ => Err(NearError::custom_error(ERR_INVALID_VARIANT.to_string())), + _ => Err(NearError::custom_error( + ERR_INVALID_VARIANT.to_string(), + std::panic::Location::caller().to_string(), + )), } } @@ -272,11 +289,16 @@ impl NearRpcClient { request: QueryRequest::ViewCode { account_id }, }) .await - .map_err(NearError::rpc_query_error)?; + .map_err(|e| { + NearError::rpc_query_error(std::panic::Location::caller().to_string(), e) + })?; match query_resp.kind { QueryResponseKind::ViewCode(code) => Ok(code), - _ => Err(NearError::custom_error(ERR_INVALID_VARIANT.to_string())), + _ => Err(NearError::custom_error( + ERR_INVALID_VARIANT.to_string(), + std::panic::Location::caller().to_string(), + )), } } @@ -288,7 +310,9 @@ impl NearRpcClient { let block_view = self .query(&methods::block::RpcBlockRequest { block_reference }) .await - .map_err(NearError::rpc_block_error)?; + .map_err(|e| { + NearError::rpc_block_error(std::panic::Location::caller().to_string(), e) + })?; Ok(block_view) } @@ -299,7 +323,9 @@ impl NearRpcClient { ) -> Result { self.query(&methods::tx::RpcTransactionStatusRequest { transaction_info }) .await - .map_err(NearError::rpc_transaction_error) + .map_err(|e| { + NearError::rpc_transaction_error(std::panic::Location::caller().to_string(), e) + }) } pub async fn deploy( @@ -480,12 +506,13 @@ pub async fn access_key( }, }) .await - .map_err(NearError::rpc_query_error)?; + .map_err(|e| NearError::rpc_query_error(std::panic::Location::caller().to_string(), e))?; match query_resp.kind { QueryResponseKind::AccessKey(access_key) => Ok((access_key, query_resp.block_hash)), _ => Err(NearError::custom_error( "Could not retrieve access key".to_string(), + std::panic::Location::caller().to_string(), )), } } @@ -511,7 +538,9 @@ pub async fn send_tx( signed_transaction: tx, }) .await - .map_err(NearError::rpc_transaction_error) + .map_err(|e| { + NearError::rpc_transaction_error(std::panic::Location::caller().to_string(), e) + }) } pub async fn send_tx_and_retry( diff --git a/crates/relayer/src/chain/near/rpc/result.rs b/crates/relayer/src/chain/near/rpc/result.rs index 4dedfe8124..5543d54e96 100644 --- a/crates/relayer/src/chain/near/rpc/result.rs +++ b/crates/relayer/src/chain/near/rpc/result.rs @@ -216,7 +216,7 @@ impl ViewResultDetails { warn!("serde deserilize error: {:?}", self.result); } - res.map_err(NearError::serde_json_error) + res.map_err(|e| NearError::serde_json_error(std::panic::Location::caller().to_string(), e)) } /// Deserialize an instance of type `T` from bytes sourced from this view call's diff --git a/crates/relayer/src/chain/near/rpc/tool.rs b/crates/relayer/src/chain/near/rpc/tool.rs index c3f95bb313..99bc033641 100644 --- a/crates/relayer/src/chain/near/rpc/tool.rs +++ b/crates/relayer/src/chain/near/rpc/tool.rs @@ -32,15 +32,31 @@ pub fn convert_ibc_event_to_hermes_ibc_event( HermesIbcEvent::CreateClient( ibc_relayer_types::core::ics02_client::events::CreateClient::from(Attributes { - client_id: ClientId::from_str(create_client.client_id().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + client_id: ClientId::from_str(create_client.client_id().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, client_type: ClientType::from_str(create_client.client_type().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, consensus_height: Height::new( create_client.consensus_height().revision_number(), create_client.consensus_height().revision_height(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }), ) } @@ -49,15 +65,31 @@ pub fn convert_ibc_event_to_hermes_ibc_event( HermesIbcEvent::UpdateClient( ibc_relayer_types::core::ics02_client::events::UpdateClient::from(Attributes { - client_id: ClientId::from_str(update_client.client_id().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + client_id: ClientId::from_str(update_client.client_id().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, client_type: ClientType::from_str(update_client.client_type().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, consensus_height: Height::new( update_client.consensus_height().revision_number(), update_client.consensus_height().revision_height(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }), ) } @@ -66,15 +98,31 @@ pub fn convert_ibc_event_to_hermes_ibc_event( HermesIbcEvent::UpgradeClient( ibc_relayer_types::core::ics02_client::events::UpgradeClient::from(Attributes { - client_id: ClientId::from_str(upgrade_client.client_id().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + client_id: ClientId::from_str(upgrade_client.client_id().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, client_type: ClientType::from_str(upgrade_client.client_type().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, consensus_height: Height::new( upgrade_client.consensus_height().revision_number(), upgrade_client.consensus_height().revision_height(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }), ) } @@ -85,11 +133,21 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics02_client::events::ClientMisbehaviour::from( Attributes { client_id: ClientId::from_str(client_misbehaviour.client_id().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, client_type: ClientType::from_str( client_misbehaviour.client_type().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, consensus_height: todo!(), //todo in ibc-rs(latest) have not this variant }, ), @@ -101,17 +159,32 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics03_connection::events::OpenInit::from(Attributes { connection_id: Some( ConnectionId::from_str(open_init_connection.conn_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), client_id: ClientId::from_str(open_init_connection.client_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_connection_id: open_init_connection .conn_id_on_b() .and_then(|id| ConnectionId::from_str(id.as_str()).ok()), counterparty_client_id: ClientId::from_str( open_init_connection.client_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }), ) } @@ -121,22 +194,43 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics03_connection::events::OpenTry::from(Attributes { connection_id: Some( ConnectionId::from_str(open_try_connection.conn_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), client_id: ClientId::from_str(open_try_connection.client_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_connection_id: open_try_connection .conn_id_on_a() .ok_or(NearError::custom_error( "counterparty_connection_id is None".to_string(), + std::panic::Location::caller().to_string(), )) .map(|e| ConnectionId::from_str(e.as_str())) - .map_err(|e| NearError::custom_error(e.to_string()))? + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })? .ok(), counterparty_client_id: ClientId::from_str( open_try_connection.client_id_on_a().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }), ) } @@ -146,22 +240,43 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics03_connection::events::OpenAck::from(Attributes { connection_id: Some( ConnectionId::from_str(open_ack_connection.conn_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), client_id: ClientId::from_str(open_ack_connection.client_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_connection_id: open_ack_connection .conn_id_on_b() .ok_or(NearError::custom_error( "counterparty_connection_id is None".to_string(), + std::panic::Location::caller().to_string(), )) .map(|e| ConnectionId::from_str(e.as_str())) - .map_err(|e| NearError::custom_error(e.to_string()))? + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })? .ok(), counterparty_client_id: ClientId::from_str( open_ack_connection.client_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }), ) } @@ -171,111 +286,257 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics03_connection::events::OpenConfirm::from(Attributes { connection_id: Some( ConnectionId::from_str(open_confirm_connection.conn_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), client_id: ClientId::from_str( open_confirm_connection.client_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_connection_id: open_confirm_connection .conn_id_on_a() .ok_or(NearError::custom_error( "counterparty_connection_id is None".to_string(), + std::panic::Location::caller().to_string(), )) .map(|e| ConnectionId::from_str(e.as_str())) - .map_err(|e| NearError::custom_error(e.to_string()))? + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })? .ok(), counterparty_client_id: ClientId::from_str( open_confirm_connection.client_id_on_a().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }), ) } IbcEvent::OpenInitChannel(open_init_channel) => HermesIbcEvent::OpenInitChannel( ibc_relayer_types::core::ics04_channel::events::OpenInit { - port_id: PortId::from_str(open_init_channel.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + port_id: PortId::from_str(open_init_channel.port_id_on_a().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, channel_id: Some( - ChannelId::from_str(open_init_channel.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(open_init_channel.chan_id_on_a().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, ), connection_id: ConnectionId::from_str(open_init_channel.conn_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_port_id: PortId::from_str(open_init_channel.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_channel_id: None, }, ), IbcEvent::OpenTryChannel(open_try_channel) => HermesIbcEvent::OpenTryChannel( ibc_relayer_types::core::ics04_channel::events::OpenTry { - port_id: PortId::from_str(open_try_channel.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + port_id: PortId::from_str(open_try_channel.port_id_on_b().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, channel_id: Some( - ChannelId::from_str(open_try_channel.chan_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(open_try_channel.chan_id_on_b().as_str()).map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), connection_id: ConnectionId::from_str(open_try_channel.conn_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_port_id: PortId::from_str(open_try_channel.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_channel_id: Some( - ChannelId::from_str(open_try_channel.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(open_try_channel.chan_id_on_a().as_str()).map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), }, ), IbcEvent::OpenAckChannel(open_ack_channel) => HermesIbcEvent::OpenAckChannel( ibc_relayer_types::core::ics04_channel::events::OpenAck { - port_id: PortId::from_str(open_ack_channel.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + port_id: PortId::from_str(open_ack_channel.port_id_on_a().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, channel_id: Some( - ChannelId::from_str(open_ack_channel.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(open_ack_channel.chan_id_on_a().as_str()).map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), connection_id: ConnectionId::from_str(open_ack_channel.conn_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_port_id: PortId::from_str(open_ack_channel.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_channel_id: Some( - ChannelId::from_str(open_ack_channel.chan_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(open_ack_channel.chan_id_on_b().as_str()).map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), }, ), IbcEvent::OpenConfirmChannel(open_confirm_channel) => HermesIbcEvent::OpenConfirmChannel( ibc_relayer_types::core::ics04_channel::events::OpenConfirm { - port_id: PortId::from_str(open_confirm_channel.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + port_id: PortId::from_str(open_confirm_channel.port_id_on_b().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, channel_id: Some( - ChannelId::from_str(open_confirm_channel.chan_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(open_confirm_channel.chan_id_on_b().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, ), connection_id: ConnectionId::from_str(open_confirm_channel.conn_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_port_id: PortId::from_str( open_confirm_channel.port_id_on_a().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_channel_id: Some( - ChannelId::from_str(open_confirm_channel.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(open_confirm_channel.chan_id_on_a().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, ), }, ), IbcEvent::CloseInitChannel(close_init_channel) => HermesIbcEvent::CloseInitChannel( ibc_relayer_types::core::ics04_channel::events::CloseInit { - port_id: PortId::from_str(close_init_channel.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + port_id: PortId::from_str(close_init_channel.port_id_on_a().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, channel_id: ChannelId::from_str(close_init_channel.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, connection_id: ConnectionId::from_str(close_init_channel.conn_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_port_id: PortId::from_str(close_init_channel.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_channel_id: Some( - ChannelId::from_str(close_init_channel.chan_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + ChannelId::from_str(close_init_channel.chan_id_on_b().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, ), }, ), @@ -284,21 +545,46 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics04_channel::events::CloseConfirm { channel_id: Some( ChannelId::from_str(close_confirm_channel.chan_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), port_id: PortId::from_str(close_confirm_channel.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, connection_id: ConnectionId::from_str( close_confirm_channel.conn_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_port_id: PortId::from_str( close_confirm_channel.port_id_on_a().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, counterparty_channel_id: Some( ChannelId::from_str(close_confirm_channel.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, ), }, ) @@ -307,20 +593,46 @@ pub fn convert_ibc_event_to_hermes_ibc_event( HermesIbcEvent::SendPacket(ibc_relayer_types::core::ics04_channel::events::SendPacket { packet: Packet { sequence: u64::from(*send_packet.seq_on_a()).into(), - source_port: PortId::from_str(send_packet.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + source_port: PortId::from_str(send_packet.port_id_on_a().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, source_channel: ChannelId::from_str(send_packet.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_port: PortId::from_str(send_packet.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_channel: ChannelId::from_str(send_packet.chan_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, data: send_packet.packet_data().to_vec(), timeout_height: convert_timeout_height(*send_packet.timeout_height_on_b())?, timeout_timestamp: Timestamp::from_nanoseconds( send_packet.timeout_timestamp_on_b().nanoseconds(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }, }) } @@ -328,22 +640,48 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics04_channel::events::ReceivePacket { packet: Packet { sequence: u64::from(*receive_packet.seq_on_b()).into(), - source_port: PortId::from_str(receive_packet.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + source_port: PortId::from_str(receive_packet.port_id_on_b().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, source_channel: ChannelId::from_str(receive_packet.chan_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_port: PortId::from_str(receive_packet.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_channel: ChannelId::from_str( receive_packet.chan_id_on_a().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, data: receive_packet.packet_data().to_vec(), timeout_height: convert_timeout_height(*receive_packet.timeout_height_on_b())?, timeout_timestamp: Timestamp::from_nanoseconds( receive_packet.timeout_timestamp_on_b().nanoseconds(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }, }, ), @@ -355,19 +693,39 @@ pub fn convert_ibc_event_to_hermes_ibc_event( source_port: PortId::from_str( write_acknowledgement.port_id_on_a().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, source_channel: ChannelId::from_str( write_acknowledgement.chan_id_on_a().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_port: PortId::from_str( write_acknowledgement.port_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_channel: ChannelId::from_str( write_acknowledgement.chan_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, data: write_acknowledgement.packet_data().to_vec(), timeout_height: convert_timeout_height( *write_acknowledgement.timeout_height_on_b(), @@ -375,7 +733,12 @@ pub fn convert_ibc_event_to_hermes_ibc_event( timeout_timestamp: Timestamp::from_nanoseconds( write_acknowledgement.timeout_timestamp_on_b().nanoseconds(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }, ack: write_acknowledgement.acknowledgement().as_bytes().to_vec(), }, @@ -386,15 +749,35 @@ pub fn convert_ibc_event_to_hermes_ibc_event( packet: Packet { sequence: u64::from(*acknowledge_packet.seq_on_a()).into(), source_port: PortId::from_str(acknowledge_packet.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, source_channel: ChannelId::from_str(acknowledge_packet.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_port: PortId::from_str(acknowledge_packet.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_channel: ChannelId::from_str( acknowledge_packet.chan_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, data: vec![], timeout_height: convert_timeout_height( *acknowledge_packet.timeout_height_on_b(), @@ -402,7 +785,12 @@ pub fn convert_ibc_event_to_hermes_ibc_event( timeout_timestamp: Timestamp::from_nanoseconds( acknowledge_packet.timeout_timestamp_on_b().nanoseconds(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }, }, ), @@ -410,22 +798,48 @@ pub fn convert_ibc_event_to_hermes_ibc_event( ibc_relayer_types::core::ics04_channel::events::TimeoutPacket { packet: Packet { sequence: u64::from(*timeout_packet.seq_on_a()).into(), - source_port: PortId::from_str(timeout_packet.port_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + source_port: PortId::from_str(timeout_packet.port_id_on_a().as_str()).map_err( + |e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + }, + )?, source_channel: ChannelId::from_str(timeout_packet.chan_id_on_a().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_port: PortId::from_str(timeout_packet.port_id_on_b().as_str()) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, destination_channel: ChannelId::from_str( timeout_packet.chan_id_on_b().as_str(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, data: vec![], timeout_height: convert_timeout_height(*timeout_packet.timeout_height_on_b())?, timeout_timestamp: Timestamp::from_nanoseconds( timeout_packet.timeout_timestamp_on_b().nanoseconds(), ) - .map_err(|e| NearError::custom_error(e.to_string()))?, + .map_err(|e| { + NearError::custom_error( + e.to_string(), + std::panic::Location::caller().to_string(), + ) + })?, }, }, ), @@ -438,7 +852,12 @@ pub fn convert_ibc_event_to_hermes_ibc_event( module_name: ModuleId::from_str( get_name_from_module_event_attributes(&app_module.attributes).as_str(), ) - .map_err(|e| NearError::custom_error(format!("{:?}", e)))?, + .map_err(|e| { + NearError::custom_error( + format!("{:?}", e), + std::panic::Location::caller().to_string(), + ) + })?, attributes: app_module .attributes .iter() @@ -476,8 +895,9 @@ fn convert_timeout_height( match timeout_height { ibc::core::channel::types::timeout::TimeoutHeight::Never => Ok(TimeoutHeight::Never), ibc::core::channel::types::timeout::TimeoutHeight::At(height) => Ok(TimeoutHeight::At( - Height::new(height.revision_number(), height.revision_height()) - .map_err(NearError::build_ibc_height_error)?, + Height::new(height.revision_number(), height.revision_height()).map_err(|e| { + NearError::build_ibc_height_error(std::panic::Location::caller().to_string(), e) + })?, )), } } diff --git a/crates/relayer/src/chain/vp_client.rs b/crates/relayer/src/chain/vp_client.rs deleted file mode 100644 index 9c1490dddb..0000000000 --- a/crates/relayer/src/chain/vp_client.rs +++ /dev/null @@ -1,611 +0,0 @@ -use super::client::ClientSettings; -use super::ic::VpClient; -use crate::keyring::{KeyRing, Secp256k1KeyPair}; -use crate::{ - account::Balance, - chain::endpoint::{ChainEndpoint, ChainStatus, HealthCheck}, - chain::handle::Subscription, - chain::requests::{ - CrossChainQueryRequest, QueryChannelClientStateRequest, QueryChannelRequest, - QueryChannelsRequest, QueryClientConnectionsRequest, QueryClientStatesRequest, - QueryConnectionChannelsRequest, QueryConnectionRequest, QueryConnectionsRequest, - QueryConsensusStateHeightsRequest, QueryConsensusStateRequest, - QueryNextSequenceReceiveRequest, QueryPacketAcknowledgementsRequest, - QueryPacketCommitmentsRequest, QueryPacketEventDataRequest, QueryTxRequest, - QueryUnreceivedAcksRequest, QueryUnreceivedPacketsRequest, - }, - chain::requests::{ - IncludeProof, QueryClientStateRequest, QueryHostConsensusStateRequest, - QueryPacketAcknowledgementRequest, QueryPacketCommitmentRequest, QueryPacketReceiptRequest, - QueryUpgradedClientStateRequest, QueryUpgradedConsensusStateRequest, - }, - chain::tracking::TrackedMsgs, - client_state::{AnyClientState, IdentifiedAnyClientState}, - config::ChainConfig, - consensus_state::AnyConsensusState, - denom::DenomTrace, - error::Error, - event::IbcEventWithHeight, - misbehaviour::MisbehaviourEvidence, -}; -use ic_agent::identity::Secp256k1Identity; -use ic_agent::Identity; - -use alloc::{string::String, sync::Arc}; -use core::future::Future; -use ibc_proto::Protobuf; -use ibc_relayer_types::clients::ics06_solomachine::consensus_state::PublicKey; -use ibc_relayer_types::clients::ics06_solomachine::{ - client_state::ClientState as SoloClientState, - consensus_state::ConsensusState as SoloConsensusState, header::Header as SoloHeader, -}; -use ibc_relayer_types::core::ics02_client::msgs::create_client::MsgCreateClient; -use ibc_relayer_types::{ - applications::ics31_icq::response::CrossChainQueryResponse, - core::ics02_client::events::{Attributes, CreateClient, UpdateClient}, - core::ics23_commitment::commitment::CommitmentRoot, - core::ics23_commitment::merkle::MerkleProof, - core::{ - ics02_client::client_type::ClientType, - ics03_connection::connection::{ConnectionEnd, IdentifiedConnectionEnd}, - ics04_channel::{ - channel::{ChannelEnd, IdentifiedChannelEnd}, - packet::Sequence, - }, - ics23_commitment::commitment::CommitmentPrefix, - ics24_host::identifier::{ChainId, ChannelId, ClientId, ConnectionId, PortId}, - }, - events::IbcEvent as IbcRelayerTypeEvent, - signer::Signer, - timestamp::Timestamp, - Height, Height as ICSHeight, -}; -use std::str::FromStr; - -use prost::Message; -use semver::Version; -use tendermint_rpc::endpoint::broadcast::tx_sync::Response as TxResponse; -use tokio::runtime::Runtime as TokioRuntime; -use tracing::info; - -/// Defines an upper limit on how large any transaction can be. -/// This upper limit is defined as a fraction relative to the block's -/// maximum bytes. For example, if the fraction is `0.9`, then -/// `max_tx_size` will not be allowed to exceed 0.9 of the -/// maximum block size of any Cosmos SDK network. -/// -/// The default fraction we use is `0.9`; anything larger than that -/// would be risky, as transactions might be rejected; a smaller value -/// might be un-necessarily restrictive on the relayer side. -/// The [default max. block size in Tendermint 0.37 is 21MB](tm-37-max). -/// With a fraction of `0.9`, then Hermes will never permit the configuration -/// of `max_tx_size` to exceed ~18.9MB. -/// -/// [tm-37-max]: https://github.com/tendermint/tendermint/blob/v0.37.0-rc1/types/params.go#L79 -pub const BLOCK_MAX_BYTES_MAX_FRACTION: f64 = 0.9; -pub struct VpChain { - config: ChainConfig, - rt: Arc, - vp_client: VpClient, - signer: String, -} - -impl VpChain { - /// Run a future to completion on the Tokio runtime. - fn block_on(&self, f: F) -> F::Output { - self.rt.block_on(f) - } -} - -impl ChainEndpoint for VpChain { - type LightBlock = (); - type Header = SoloHeader; - type ConsensusState = SoloConsensusState; - type ClientState = SoloClientState; - type Time = Timestamp; - type SigningKeyPair = Secp256k1KeyPair; - - fn bootstrap(config: ChainConfig, rt: Arc) -> Result { - let canister_pem_path = if config.canister_pem.is_absolute() { - config.canister_pem.clone() - } else { - let current_dir = - std::env::current_dir().map_err(|e| Error::report_error(e.to_string()))?; - current_dir.join(config.canister_pem.clone()) - }; - - let signer = Secp256k1Identity::from_pem_file(canister_pem_path.clone()).map_err(|e| { - let position = std::panic::Location::caller(); - Error::report_error(format!( - "build vp client failed Error({:?}) \n{}", - e, position - )) - })?; - - let sender = signer - .sender() - .map_err(|e| { - let position = std::panic::Location::caller(); - Error::report_error(format!( - "build vp client failed Error({:?}) \n{}", - e, position - )) - })? - .to_text(); - - let vp_client = rt - .block_on(VpClient::new(&config.ic_endpoint, &canister_pem_path)) - .map_err(|e| { - let position = std::panic::Location::caller(); - Error::report_error(format!( - "build vp client failed Error({:?}) \n{}", - e, position - )) - })?; - // Retrieve the version specification of this chain - - let chain = Self { - config: config.clone(), - vp_client, - rt, - signer: sender, - }; - - Ok(chain) - } - - fn shutdown(self) -> Result<(), Error> { - todo!() - } - - fn keybase(&self) -> &KeyRing { - todo!() - } - - fn keybase_mut(&mut self) -> &mut KeyRing { - todo!() - } - - fn subscribe(&mut self) -> Result { - todo!() - } - - /// Does multiple RPC calls to the full node, to check for - /// reachability and some basic APIs are available. - /// - /// Currently this checks that: - /// - the node responds OK to `/health` RPC call; - /// - the node has transaction indexing enabled; - /// - the SDK & IBC versions are supported; - /// - /// Emits a log warning in case anything is amiss. - /// Exits early if any health check fails, without doing any - /// further checks. - fn health_check(&mut self) -> Result { - todo!() - } - - /// Fetch a header from the chain at the given height and verify it. - fn verify_header( - &mut self, - _trusted: ICSHeight, - _target: ICSHeight, - _client_state: &AnyClientState, - ) -> Result { - Ok(()) - } - - /// Perform misbehavior detection for the given client state and update event. - fn check_misbehaviour( - &mut self, - _update: &UpdateClient, - _client_state: &AnyClientState, - ) -> Result, Error> { - todo!() - } - - // Queries - - /// Send one or more transactions that include all the specified messages. - /// The `proto_msgs` are split in transactions such they don't exceed the configured maximum - /// number of messages per transaction and the maximum transaction size. - /// Then `send_tx()` is called with each Tx. `send_tx()` determines the fee based on the - /// on-chain simulation and if this exceeds the maximum gas specified in the configuration file - /// then it returns error. - /// TODO - more work is required here for a smarter split maybe iteratively accumulating/ evaluating - /// msgs in a Tx until any of the max size, max num msgs, max fee are exceeded. - fn send_messages_and_wait_commit( - &mut self, - tracked_msgs: TrackedMsgs, - ) -> Result, Error> { - info!( - "tracked_msgs: {:?}, tracking_id: {:?}, \n{}", - tracked_msgs - .msgs - .iter() - .map(|msg| msg.type_url.clone()) - .collect::>(), - tracked_msgs.tracking_id, - std::panic::Location::caller() - ); - use ibc_proto::google::protobuf::Any; - - // let mut tracked_msgs = tracked_msgs.clone(); - // if tracked_msgs.tracking_id().to_string() != "ft-transfer" { - let canister_id = self.config.canister_id.id.as_str(); - let mut msgs: Vec = Vec::new(); - for msg in tracked_msgs.messages() { - let res = self - .block_on(self.vp_client.deliver(canister_id, msg.encode_to_vec())) - .map_err(|e| { - let position = std::panic::Location::caller(); - Error::report_error(format!( - "call vp deliver failed Error({}) \n{}", - e, position - )) - })?; - assert!(!res.is_empty()); - if !res.is_empty() { - msgs.push(Any::decode(&res[..]).map_err(|e| { - let position = std::panic::Location::caller(); - Error::report_error(format!( - "decode call vp deliver result failed Error({}) \n{}", - e, position - )) - })?); - } - } - assert_eq!(msgs.len(), 1); - let create_client_msg = msgs.remove(0); - let domain_msg: MsgCreateClient = MsgCreateClient::decode_vec(&create_client_msg.value) - .map_err(|e| { - let position = std::panic::Location::caller(); - Error::report_error(format!( - "decode call vp deliver result failed Error({}) \n{}", - e, position - )) - })?; - - let client_state = - ibc_relayer_types::clients::ics06_solomachine::client_state::ClientState::try_from( - domain_msg.client_state, - ) - .unwrap(); - println!("new solomachine client state created: {:?}", client_state); - let serialized_pub_key = - serde_json::to_string(&client_state.consensus_state.public_key.0).unwrap(); - println!("pubkey: {:?}", serialized_pub_key); - println!( - "timestamp: {:?}", - client_state.consensus_state.timestamp.nanoseconds() - ); - // todo: maybe need to check the response from ic - let create_client_event = CreateClient::from(Attributes { - client_id: ClientId::new(ClientType::Solomachine, 0).unwrap(), - client_type: ClientType::Solomachine, - consensus_height: ICSHeight::new(0, 1).unwrap(), - }); - let create_event_with_height = IbcEventWithHeight { - event: IbcRelayerTypeEvent::CreateClient(create_client_event), - height: ICSHeight::new(0, 1).unwrap(), - }; - Ok(vec![create_event_with_height]) - } - - fn send_messages_and_wait_check_tx( - &mut self, - _tracked_msgs: TrackedMsgs, - ) -> Result, Error> { - todo!() - } - - /// Get the account for the signer - fn get_signer(&self) -> Result { - Signer::from_str(self.signer.as_str()).map_err(|e| Error::report_error(e.to_string())) - } - - /// Get the chain configuration - fn config(&self) -> &ChainConfig { - &self.config - } - - fn ibc_version(&self) -> Result, Error> { - todo!() - } - - fn query_balance( - &self, - _key_name: Option<&str>, - _denom: Option<&str>, - ) -> Result { - todo!() - } - - fn query_all_balances(&self, _key_name: Option<&str>) -> Result, Error> { - todo!() - } - - fn query_denom_trace(&self, _hash: String) -> Result { - todo!() - } - - fn query_commitment_prefix(&self) -> Result { - todo!() - } - - /// Query the application status - fn query_application_status(&self) -> Result { - // Add template code here - Ok(ChainStatus { - height: ICSHeight::new(0, 1).unwrap(), - timestamp: Timestamp::none(), - }) - } - - fn query_clients( - &self, - _request: QueryClientStatesRequest, - ) -> Result, Error> { - todo!() - } - - fn query_client_state( - &self, - _request: QueryClientStateRequest, - _include_proof: IncludeProof, - ) -> Result<(AnyClientState, Option), Error> { - todo!() - } - - fn query_upgraded_client_state( - &self, - _request: QueryUpgradedClientStateRequest, - ) -> Result<(AnyClientState, MerkleProof), Error> { - todo!() - } - - fn query_upgraded_consensus_state( - &self, - _request: QueryUpgradedConsensusStateRequest, - ) -> Result<(AnyConsensusState, MerkleProof), Error> { - todo!() - } - - fn query_consensus_state_heights( - &self, - _request: QueryConsensusStateHeightsRequest, - ) -> Result, Error> { - todo!() - } - - fn query_consensus_state( - &self, - _request: QueryConsensusStateRequest, - _include_proof: IncludeProof, - ) -> Result<(AnyConsensusState, Option), Error> { - todo!() - } - - fn query_client_connections( - &self, - _request: QueryClientConnectionsRequest, - ) -> Result, Error> { - todo!() - } - - fn query_connections( - &self, - _request: QueryConnectionsRequest, - ) -> Result, Error> { - todo!() - } - - fn query_connection( - &self, - _request: QueryConnectionRequest, - _include_proof: IncludeProof, - ) -> Result<(ConnectionEnd, Option), Error> { - todo!() - } - - fn query_connection_channels( - &self, - _request: QueryConnectionChannelsRequest, - ) -> Result, Error> { - todo!() - } - - fn query_channels( - &self, - _request: QueryChannelsRequest, - ) -> Result, Error> { - todo!() - } - - fn query_channel( - &self, - _request: QueryChannelRequest, - _include_proof: IncludeProof, - ) -> Result<(ChannelEnd, Option), Error> { - todo!() - } - - fn query_channel_client_state( - &self, - _request: QueryChannelClientStateRequest, - ) -> Result, Error> { - todo!() - } - - fn query_packet_commitment( - &self, - _request: QueryPacketCommitmentRequest, - _include_proof: IncludeProof, - ) -> Result<(Vec, Option), Error> { - todo!() - } - - /// Queries the packet commitment hashes associated with a channel. - fn query_packet_commitments( - &self, - _request: QueryPacketCommitmentsRequest, - ) -> Result<(Vec, ICSHeight), Error> { - todo!() - } - - fn query_packet_receipt( - &self, - _request: QueryPacketReceiptRequest, - _include_proof: IncludeProof, - ) -> Result<(Vec, Option), Error> { - todo!() - } - - /// Queries the unreceived packet sequences associated with a channel. - fn query_unreceived_packets( - &self, - _request: QueryUnreceivedPacketsRequest, - ) -> Result, Error> { - todo!() - } - - fn query_packet_acknowledgement( - &self, - _request: QueryPacketAcknowledgementRequest, - _include_proof: IncludeProof, - ) -> Result<(Vec, Option), Error> { - todo!() - } - - /// Queries the packet acknowledgment hashes associated with a channel. - fn query_packet_acknowledgements( - &self, - _request: QueryPacketAcknowledgementsRequest, - ) -> Result<(Vec, ICSHeight), Error> { - todo!() - } - - /// Queries the unreceived acknowledgements sequences associated with a channel. - fn query_unreceived_acknowledgements( - &self, - _request: QueryUnreceivedAcksRequest, - ) -> Result, Error> { - todo!() - } - - fn query_next_sequence_receive( - &self, - _request: QueryNextSequenceReceiveRequest, - _include_proof: IncludeProof, - ) -> Result<(Sequence, Option), Error> { - todo!() - } - - /// This function queries transactions for events matching certain criteria. - /// 1. Client Update request - returns a vector with at most one update client event - /// 2. Transaction event request - returns all IBC events resulted from a Tx execution - fn query_txs(&self, _request: QueryTxRequest) -> Result, Error> { - todo!() - } - - /// This function queries transactions for packet events matching certain criteria. - /// It returns at most one packet event for each sequence specified in the request. - /// Note - there is no way to format the packet query such that it asks for Tx-es with either - /// sequence (the query conditions can only be AND-ed). - /// There is a possibility to include "<=" and ">=" conditions but it doesn't work with - /// string attributes (sequence is emmitted as a string). - /// Therefore, for packets we perform one tx_search for each sequence. - /// Alternatively, a single query for all packets could be performed but it would return all - /// packets ever sent. - fn query_packet_events( - &self, - mut _request: QueryPacketEventDataRequest, - ) -> Result, Error> { - todo!() - } - - fn query_host_consensus_state( - &self, - _request: QueryHostConsensusStateRequest, - ) -> Result { - todo!() - } - - fn build_client_state( - &self, - _height: ICSHeight, - _settings: ClientSettings, - ) -> Result { - // todo: maybet this is not correct! - let json_string = "{\"type\":\"tendermint/PubKeyEd25519\",\"value\":\"RblzMO4is5L1hZz6wo4kPbptzOyue6LTk4+lPhD1FRk=\"}"; - let pubkey: tendermint::PublicKey = serde_json::from_str(json_string).unwrap(); - - let public_key = PublicKey::from(pubkey); - let consensus_state = SoloConsensusState { - public_key, - diversifier: "oct".to_string(), - timestamp: Timestamp::none(), - root: CommitmentRoot::from(vec![1, 0, 1, 0]), - }; - Ok(SoloClientState { - sequence: Height::new(0, 1).unwrap(), - is_frozen: false, - consensus_state, - }) - } - - fn build_consensus_state( - &self, - _light_block: Self::LightBlock, - ) -> Result { - // todo: maybet this is not correct! - let json_string = "{\"type\":\"tendermint/PubKeyEd25519\",\"value\":\"RblzMO4is5L1hZz6wo4kPbptzOyue6LTk4+lPhD1FRk=\"}"; - let pubkey: tendermint::PublicKey = serde_json::from_str(json_string).unwrap(); - - let public_key = PublicKey::from(pubkey); - let consensus_state = SoloConsensusState { - public_key, - diversifier: "oct".to_string(), - timestamp: Timestamp::none(), - root: CommitmentRoot::from(vec![1, 0, 1, 0]), - }; - - Ok(consensus_state) - } - - fn build_header( - &mut self, - _trusted_height: ICSHeight, - _target_height: ICSHeight, - _client_state: &AnyClientState, - ) -> Result<(Self::Header, Vec), Error> { - todo!() - } - - fn maybe_register_counterparty_payee( - &mut self, - _channel_id: &ChannelId, - _port_id: &PortId, - _counterparty_payee: &Signer, - ) -> Result<(), Error> { - todo!() - } - - fn cross_chain_query( - &self, - _requests: Vec, - ) -> Result, Error> { - todo!() - } - - fn query_incentivized_packet( - &self, - _request: ibc_proto::ibc::apps::fee::v1::QueryIncentivizedPacketRequest, - ) -> Result { - todo!() - } - - fn query_consumer_chains(&self) -> Result, Error> { - todo!() - } -} diff --git a/crates/relayer/src/keyring.rs b/crates/relayer/src/keyring.rs index 719501e7e5..3647c74ed0 100644 --- a/crates/relayer/src/keyring.rs +++ b/crates/relayer/src/keyring.rs @@ -302,7 +302,7 @@ impl KeyRing { pub fn list_keys(config: &ChainConfig) -> Result, Error> { let keys = match config.r#type { - ChainType::CosmosSdk | ChainType::Vp => { + ChainType::CosmosSdk => { let keyring = KeyRing::new_secp256k1( Store::Test, &config.account_prefix, diff --git a/crates/relayer/src/link/relay_path.rs b/crates/relayer/src/link/relay_path.rs index 69986aa0fa..c9ab8140ad 100644 --- a/crates/relayer/src/link/relay_path.rs +++ b/crates/relayer/src/link/relay_path.rs @@ -617,7 +617,7 @@ impl RelayPath { event_with_height: event_with_height.clone(), msg: msg.clone(), }); - }) + }); } // Collect timeout messages, to be sent to the source chain @@ -1211,8 +1211,6 @@ impl RelayPath { packet: &Packet, height: Height, ) -> Result>, LinkError> { - let mut msgs: Vec = Vec::new(); - if self .src_chain() .config() @@ -1222,7 +1220,7 @@ impl RelayPath { .r#type == ChainType::Near { - msgs = self.build_update_client_on_dst(height)?; + let mut msgs = self.build_update_client_on_dst(height)?; assert!(!msgs.is_empty()); let msg_update_client = msgs.last().ok_or(LinkError::custom_error( "[in connection: build_recv_packet msgs.last() is none]".into(), @@ -1256,7 +1254,9 @@ impl RelayPath { .map_err(|e| LinkError::packet_proofs_constructor(self.src_chain().id(), e))?; let msg = MsgRecvPacket::new(packet.clone(), proofs.clone(), self.dst_signer()?); + trace!(packet = %packet, height = %proofs.height(), "built recv_packet msg"); msgs.push(msg.to_any()); + Ok(Some(msgs)) } else { let proofs = self .src_chain() @@ -1270,11 +1270,9 @@ impl RelayPath { .map_err(|e| LinkError::packet_proofs_constructor(self.src_chain().id(), e))?; let msg = MsgRecvPacket::new(packet.clone(), proofs.clone(), self.dst_signer()?); - msgs.push(msg.to_any()); trace!(packet = %packet, height = %proofs.height(), "built recv_packet msg"); + Ok(Some(vec![msg.to_any()])) } - - Ok(Some(msgs)) } fn build_ack_from_recv_event( @@ -1284,8 +1282,6 @@ impl RelayPath { ) -> Result>, LinkError> { let packet = event.packet.clone(); - let mut msgs: Vec = Vec::new(); - if self .src_chain() .config() @@ -1295,7 +1291,7 @@ impl RelayPath { .r#type == ChainType::Near { - msgs = self.build_update_client_on_dst(height)?; + let mut msgs = self.build_update_client_on_dst(height)?; assert!(!msgs.is_empty()); let msg_update_client = msgs.last().ok_or(LinkError::custom_error( "[in connection: build_recv_packet msgs.last() is none]".into(), @@ -1334,7 +1330,9 @@ impl RelayPath { proofs.clone(), self.dst_signer()?, ); + trace!(packet = %msg.packet, height = %proofs.height(), "built acknowledgment msg"); msgs.push(msg.to_any()); + Ok(Some(msgs)) } else { let proofs = self .src_chain() @@ -1354,10 +1352,8 @@ impl RelayPath { self.dst_signer()?, ); trace!(packet = %msg.packet, height = %proofs.height(), "built acknowledgment msg"); - msgs.push(msg.to_any()); + Ok(Some(vec![msg.to_any()])) } - - Ok(Some(msgs)) } fn build_timeout_packet( diff --git a/crates/relayer/src/spawn.rs b/crates/relayer/src/spawn.rs index 54cec6e9ed..6e4a5157f3 100644 --- a/crates/relayer/src/spawn.rs +++ b/crates/relayer/src/spawn.rs @@ -12,7 +12,6 @@ use crate::{ }; use crate::chain::near::NearChain; -use crate::chain::vp_client::VpChain; define_error! { SpawnError { @@ -86,7 +85,6 @@ pub fn spawn_chain_runtime_with_config( let handle = match config.r#type { ChainType::CosmosSdk => ChainRuntime::::spawn::(config, rt), ChainType::Near => ChainRuntime::::spawn::(config, rt), - ChainType::Vp => ChainRuntime::::spawn::(config, rt), } .map_err(SpawnError::relayer)?; diff --git a/tools/test-framework/src/bootstrap/init.rs b/tools/test-framework/src/bootstrap/init.rs index 795f19787c..ae4d6073cc 100644 --- a/tools/test-framework/src/bootstrap/init.rs +++ b/tools/test-framework/src/bootstrap/init.rs @@ -7,6 +7,8 @@ use eyre::Report as Error; use ibc_relayer_cli::components::enable_ansi; use std::env; use std::fs; +use std::path::PathBuf; +use std::str::FromStr; use std::sync::Once; use tracing_subscriber::{ self as ts, @@ -65,6 +67,23 @@ pub fn init_test() -> Result { .map(|val| val == "1") .unwrap_or(false); + let ic_endpoint = + env::var("IC_ENDPOINT").unwrap_or_else(|_| "http://localhost:4943".to_string()); + + let home_dir = std::env::var("HOME").unwrap(); + + let canister_pem = PathBuf::from_str(&format!( + "{}/.config/dfx/identity/default/identity.pem", + home_dir + )) + .unwrap(); + + //TODO: need update(davirain) + let near_ibc_address = "v5.nearibc.testnet".to_string(); + let canister_id = "bkyz2-fmaaa-aaaaa-qaaaq-cai".to_string(); + let near_rpc_endpoint = + "https://near-testnet.infura.io/v3/272532ecf0b64d7782a03db0cbcf3c30".to_string(); + Ok(TestConfig { chain_command_paths, chain_store_dir, @@ -73,6 +92,11 @@ pub fn init_test() -> Result { bootstrap_with_random_ids: false, native_tokens, compat_modes, + ic_endpoint, + canister_pem, + near_ibc_address, + canister_id, + near_rpc_endpoint, }) } diff --git a/tools/test-framework/src/types/config.rs b/tools/test-framework/src/types/config.rs index ea3944b3f5..4da10bc8c7 100644 --- a/tools/test-framework/src/types/config.rs +++ b/tools/test-framework/src/types/config.rs @@ -62,4 +62,18 @@ pub struct TestConfig { pub hang_on_fail: bool, pub bootstrap_with_random_ids: bool, + + // config for icp rpc endpoint url + pub ic_endpoint: String, + + // config for icp canister pem file path + pub canister_pem: PathBuf, + + // near ibc smart contract address + pub near_ibc_address: String, + + // canister id for near ibc smart contract + pub canister_id: String, + + pub near_rpc_endpoint: String, } diff --git a/tools/test-framework/src/types/single/node.rs b/tools/test-framework/src/types/single/node.rs index 4265faadac..55197217cc 100644 --- a/tools/test-framework/src/types/single/node.rs +++ b/tools/test-framework/src/types/single/node.rs @@ -10,6 +10,8 @@ use ibc_relayer::chain::ChainType; use ibc_relayer::config; use ibc_relayer::config::compat_mode::CompatMode; use ibc_relayer::config::gas_multiplier::GasMultiplier; +use ibc_relayer::config::CanisterIdConfig; +use ibc_relayer::config::NearIbcContractAddress; use ibc_relayer::keyring::Store; use ibc_relayer_types::core::ics24_host::identifier::ChainId; use std::sync::{Arc, RwLock}; @@ -145,6 +147,11 @@ impl FullNode { Ok(config::ChainConfig { id: self.chain_driver.chain_id.clone(), r#type: ChainType::CosmosSdk, + ic_endpoint: test_config.ic_endpoint.clone(), + canister_pem: test_config.canister_pem.clone(), + near_ibc_address: NearIbcContractAddress::from_str(&test_config.near_ibc_address) + .unwrap(), + canister_id: CanisterIdConfig::from_str(&test_config.canister_id).unwrap(), rpc_addr: Url::from_str(&self.chain_driver.rpc_address())?, grpc_addr: Url::from_str(&self.chain_driver.grpc_address())?, event_source: config::EventSourceMode::Push {