From 489a65fac67ceb75a5d7d69088ce757fb49f0253 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Florkiewicz?= Date: Tue, 5 Nov 2024 10:03:21 +0100 Subject: [PATCH] tonic crate --- Cargo.lock | 19 ++- Cargo.toml | 2 +- rpc/Cargo.toml | 2 - rpc/src/lib.rs | 2 - rpc/src/tonic/mod.rs | 270 -------------------------------- rpc/src/tonic/tendermint.rs | 19 --- rpc/src/tonic/types.rs | 182 --------------------- rpc/src/tonic/types/tx.rs | 116 -------------- rpc/tests/tonic.rs | 40 ----- rpc/tests/utils/mod.rs | 2 - rpc/tests/utils/tonic_client.rs | 46 ------ 11 files changed, 19 insertions(+), 681 deletions(-) delete mode 100644 rpc/src/tonic/mod.rs delete mode 100644 rpc/src/tonic/tendermint.rs delete mode 100644 rpc/src/tonic/types.rs delete mode 100644 rpc/src/tonic/types/tx.rs delete mode 100644 rpc/tests/tonic.rs delete mode 100644 rpc/tests/utils/tonic_client.rs diff --git a/Cargo.lock b/Cargo.lock index 70cdae91..51e8cc80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -805,7 +805,6 @@ dependencies = [ "serde", "thiserror", "tokio", - "tonic", "tracing", "wasm-bindgen-test", ] @@ -858,6 +857,24 @@ dependencies = [ "time", ] +[[package]] +name = "celestia-tonic" +version = "0.1.0" +dependencies = [ + "anyhow", + "celestia-proto", + "celestia-tendermint", + "celestia-tendermint-proto", + "celestia-types", + "cosmrs", + "dotenvy", + "pbjson-types", + "prost", + "thiserror", + "tokio", + "tonic", +] + [[package]] name = "celestia-types" version = "0.6.1" diff --git a/Cargo.toml b/Cargo.toml index 6329d591..35870b9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["cli", "node", "node-wasm", "proto", "rpc", "types"] +members = ["cli", "node", "node-wasm", "proto", "rpc", "tonic", "types"] [workspace.dependencies] blockstore = "0.7.0" diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index c3b82c38..c96e048a 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -37,7 +37,6 @@ tracing = "0.1.40" http = "1.1.0" jsonrpsee = { version = "0.24.2", features = ["http-client", "ws-client"] } pbjson-types = "0.7.0" -tonic = { version = "0.12.3", optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] libp2p = { workspace = true, features = [ @@ -60,7 +59,6 @@ wasm-bindgen-test = "0.3.42" [features] default = ["p2p", "secp256k1"] -tonic = ["celestia-proto/tonic", "dep:tonic"] p2p = ["celestia-types/p2p"] wasm-bindgen = ["celestia-types/wasm-bindgen", "jsonrpsee/wasm-client"] secp256k1 = ["celestia-tendermint/secp256k1"] diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index 620f32a6..bf02329a 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -9,8 +9,6 @@ mod header; mod p2p; pub mod share; mod state; -#[cfg(all(feature = "tonic", not(target_arch = "wasm32")))] -pub mod tonic; pub use crate::blob::BlobClient; #[cfg(any( diff --git a/rpc/src/tonic/mod.rs b/rpc/src/tonic/mod.rs deleted file mode 100644 index a9efd41e..00000000 --- a/rpc/src/tonic/mod.rs +++ /dev/null @@ -1,270 +0,0 @@ -use std::convert::Infallible; - -use celestia_types::auth::{AuthParams, BaseAccount}; -use celestia_types::blob::BlobParams; - -use celestia_proto::celestia::blob::v1 as blob; -use celestia_proto::cosmos::auth::v1beta1 as auth; -use celestia_proto::cosmos::base::node::v1beta1 as config; -use celestia_proto::cosmos::base::tendermint::v1beta1 as tendermint; -use celestia_proto::cosmos::tx::v1beta1 as tx; - -use cosmrs::ErrorReport; - -use tonic::service::Interceptor; -use tonic::transport::Channel; -use tonic::Status; - -pub mod types; - -use types::tx::{GetTxResponse, TxResponse}; -use types::Block; -use types::{FromGrpcResponse, IntoGrpcParam}; - -use celestia_tendermint_proto::v0_34::types::BlobTx; - -/* -use celestia_proto::celestia::blob::v1::query_client::QueryClient; -use celestia_tendermint_proto::v0_34::types::{ - Blob as PbBlob, - BlobTx, -}; - -use celestia_proto::{ - celestia::blob::v1::{ - query_client::QueryClient as BlobQueryClient, - MsgPayForBlobs, - QueryParamsRequest as QueryBlobParamsRequest, - Params as BlobParams, - }, - cosmos::{ - auth::v1beta1::{ - query_client::QueryClient as AuthQueryClient, - BaseAccount, - Params as AuthParams, - QueryAccountRequest, - QueryAccountResponse, - QueryParamsRequest as QueryAuthParamsRequest, - }, - base::{ - node::v1beta1::{ - service_client::ServiceClient as MinGasPriceClient, - ConfigRequest as MinGasPriceRequest, - ConfigResponse as MinGasPriceResponse, - }, - tendermint::v1beta1::{ - service_client::ServiceClient as TendermintServiceClient, - GetNodeInfoRequest, - }, - v1beta1::Coin, - }, - crypto::secp256k1, - tx::v1beta1::{ - mode_info::{ - Single, - Sum, - }, - service_client::ServiceClient as TxClient, - AuthInfo, - BroadcastMode, - BroadcastTxRequest, - BroadcastTxResponse, - Fee, - GetTxRequest, - GetTxResponse, - ModeInfo, - SignDoc, - SignerInfo, - Tx, - TxBody, - }, - }, -}; -*/ - -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error(transparent)] - TonicError(#[from] Status), - - #[error(transparent)] - TendermintError(#[from] celestia_tendermint::Error), - - #[error(transparent)] - CosmrsError(#[from] ErrorReport), - - #[error(transparent)] - TendermintProtoError(#[from] celestia_tendermint_proto::Error), - - #[error("Failed to parse response")] - FailedToParseResponse, - - #[error("Unexpected response type")] - UnexpectedResponseType(String), - - /// Unreachable. Added to appease try_into conversion for GrpcClient method macro - #[error(transparent)] - Infallible(#[from] Infallible), -} - -pub struct GrpcClient -where - I: Interceptor, -{ - grpc_channel: Channel, - auth_interceptor: I, -} - -/* -macro_rules! make_method { - ($name:ident, $service_client:ident, $method:ident, $param:ty, $ret:ty) => { - pub async fn $name(&mut self, param: $param) -> Result<$ret, Error> { - let mut service_client = - $service_client::service_client::ServiceClient::with_interceptor( - self.grpc_channel.clone(), - self.auth_interceptor.clone(), - ); - let response = service_client.$method(param).await; - - Ok(response?.into_inner().try_into()?) - } - }; - ($name:ident, $service_client:ident, $method:ident, $ret:ty) => { - pub async fn $name(&mut self) -> Result<$ret, Error> { - let mut service_client = - $service_client::service_client::ServiceClient::with_interceptor( - self.grpc_channel.clone(), - self.auth_interceptor.clone(), - ); - let response = service_client - .$method(::tonic::Request::new(Default::default())) - .await; - - Ok(response?.into_inner().try_into()?) - } - }; -} - -macro_rules! make_query { - ($name:ident, $service_client:ident, $method:ident, $param:ty, $ret:ty) => { - pub async fn $name(&mut self, param: $param) -> Result<$ret, Error> { - let mut client = $service_client::query_client::QueryClient::with_interceptor( - self.grpc_channel.clone(), - self.auth_interceptor.clone(), - ); - let response = client.$method(param).await; - - Ok(response?.into_inner().try_into()?) - } - }; - ($name:ident, $service_client:ident, $method:ident, $ret:ty) => { - pub async fn $name(&mut self) -> Result<$ret, Error> { - let mut client = $service_client::query_client::QueryClient::with_interceptor( - self.grpc_channel.clone(), - self.auth_interceptor.clone(), - ); - let response = client - .$method(::tonic::Request::new(Default::default())) - .await; - - Ok(response?.into_inner().try_into()?) - } - }; -} -*/ - -/* -macro_rules! make_method { - ($path:ident :: $client_module:ident :: $client_struct:ident :: $method:ident; $name:ident ( $param:ty ) -> $ret:ty) => { - pub async fn $name(&mut self, param: $param) -> Result<$ret, Error> { - let mut client = $path::$client_module::$client_struct::with_interceptor( - self.grpc_channel.clone(), - self.auth_interceptor.clone(), - ); - let response = client.$method(param.into_parameter()).await; - - Ok(response?.into_inner().try_from_response()?) - } - }; - ($path:ident :: $client_module:ident :: $client_struct:ident :: $method:ident; $name:ident () -> $ret:ty) => { - pub async fn $name(&mut self) -> Result<$ret, Error> { - let mut client = $path::$client_module::$client_struct::with_interceptor( - self.grpc_channel.clone(), - self.auth_interceptor.clone(), - ); - let response = client - .$method(::tonic::Request::new(Default::default())) - .await; - - Ok(response?.into_inner().try_from_response()?) - } - }; -} -*/ - -// macro takes a path to an appropriate generated gRPC method and a desired function signature. -// If parameters need to be converted, they should implement [`types::IntoGrpcParam`] into -// appropriate type and return type is converted using TryFrom -// -// One limitation is that it expects gRPC method to be provided in exactly 4 `::` delimited -// segments, requiring importing the proto module with `as`. This might be possible to overcome -// by rewriting the macro as tt-muncher, but it'd increase its complexity significantly -macro_rules! make_method2 { - ($path:ident :: $client_module:ident :: $client_struct:ident :: $method:ident; $name:ident ( $( $param:ident : $param_type:ty ),* ) -> $ret:ty) => { - pub async fn $name(&mut self, $($param: $param_type),*) -> Result<$ret, Error> { - let mut client = $path::$client_module::$client_struct::with_interceptor( - self.grpc_channel.clone(), - self.auth_interceptor.clone(), - ); - let request = ::tonic::Request::new(( $($param),* ).into_parameter()); - let response = client.$method(request).await; - - Ok(response?.into_inner().try_from_response()?) - } - }; -} - -/* -macro_rules! mm { - ($prefix:ident $(:: $tail:path)+; $name:ident ( $param:ty ) -> $ret:ty ) => { - mm!($prefix :: ; $($tail),* | $name($param) -> $ret); - }; - - ($($module:ident ::)+ ; $head:ident, $($tail:ident),+ | $name:ident ($param:ty) -> $ret:ty ) => { - - }; - - //(@resolved $module:path, $client_module:ident, $client_struct:ident, $method:ident; ) -} - -mm!(tendermint::service_client::ServiceClient::get_block_by_height; get_block_by_height(i64) -> Block); -*/ - -impl GrpcClient -where - I: Interceptor + Clone, -{ - pub fn new(grpc_channel: Channel, auth_interceptor: I) -> Self { - Self { - grpc_channel, - auth_interceptor, - } - } - - make_method2!(config::service_client::ServiceClient::config; get_min_gas_price() -> f64); - - make_method2!(tendermint::service_client::ServiceClient::get_latest_block; get_latest_block() -> Block); - make_method2!(tendermint::service_client::ServiceClient::get_block_by_height; get_block_by_height(height:i64) -> Block); - // TODO get_node_info - // make_method!(tendermint::service_client::ServiceClient::get_node_info; get_node_info() -> NodeInfo); - - make_method2!(blob::query_client::QueryClient::params; get_blob_params() -> BlobParams); - - make_method2!(auth::query_client::QueryClient::params; get_auth_params() -> AuthParams); - make_method2!(auth::query_client::QueryClient::account; get_account(account: String) -> BaseAccount); - // TODO: pagination? - make_method2!(auth::query_client::QueryClient::accounts; get_accounts() -> Vec); - - make_method2!(tx::service_client::ServiceClient::broadcast_tx; broadcast_tx(blob_tx: BlobTx, mode: tx::BroadcastMode) -> TxResponse); - make_method2!(tx::service_client::ServiceClient::get_tx; get_tx(hash: String) -> GetTxResponse); -} diff --git a/rpc/src/tonic/tendermint.rs b/rpc/src/tonic/tendermint.rs deleted file mode 100644 index 8f14a7d7..00000000 --- a/rpc/src/tonic/tendermint.rs +++ /dev/null @@ -1,19 +0,0 @@ -use crate::Error; -use crate::tonic::GrpcClient; - -use celestia_proto::cosmos::base::tendermint::v1beta1::{ - service_client::ServiceClient as TendermintServiceClient, - GetNodeInfoRequest, -}; - - -impl GrpcClient { - async fn get_node_info(&self) -> Result<(), Error> { - let service_client = TendermintServiceClient::with_interceptor(self.grpc_channel, self.auth_interceptor); - let request = GetNodeInfoRequest {}; - - let node_info = service_client.get_node_info(request).await?; - - node_info - } -} diff --git a/rpc/src/tonic/types.rs b/rpc/src/tonic/types.rs deleted file mode 100644 index ec4ecd7a..00000000 --- a/rpc/src/tonic/types.rs +++ /dev/null @@ -1,182 +0,0 @@ -use prost::{Message, Name}; - -use celestia_types::auth::{AuthParams, BaseAccount}; -use celestia_types::blob::BlobParams; - -use celestia_proto::celestia::blob::v1::{ - QueryParamsRequest as QueryBlobParamsRequest, QueryParamsResponse as QueryBlobParamsResponse, -}; -use celestia_proto::cosmos::auth::v1beta1::{ - BaseAccount as RawBaseAccount, QueryAccountRequest, QueryAccountResponse, QueryAccountsRequest, - QueryAccountsResponse, -}; -use celestia_proto::cosmos::auth::v1beta1::{ - QueryParamsRequest as QueryAuthParamsRequest, QueryParamsResponse as QueryAuthParamsResponse, -}; -use celestia_proto::cosmos::base::node::v1beta1::{ConfigRequest, ConfigResponse}; -use celestia_proto::cosmos::base::tendermint::v1beta1::{ - GetBlockByHeightRequest, GetBlockByHeightResponse, GetLatestBlockRequest, - GetLatestBlockResponse, -}; -use celestia_proto::cosmos::tx::v1beta1::{BroadcastMode, BroadcastTxRequest, GetTxRequest}; - -use celestia_tendermint::block::Block as TendermintBlock; - -use celestia_tendermint_proto::v0_34::types::BlobTx; - -use cosmrs::crypto::PublicKey; -use cosmrs::Any; - -use crate::tonic::Error; - -pub mod tx; - -pub struct Block(pub TendermintBlock); - -pub(crate) trait FromGrpcResponse { - fn try_from_response(self) -> Result; -} - -pub(crate) trait IntoGrpcParam { - fn into_parameter(self) -> T; -} - -impl FromGrpcResponse for QueryBlobParamsResponse { - fn try_from_response(self) -> Result { - let params = self.params.ok_or(Error::FailedToParseResponse)?; - Ok(BlobParams { - gas_per_blob_byte: params.gas_per_blob_byte, - gov_max_square_size: params.gov_max_square_size, - }) - } -} - -impl FromGrpcResponse for GetBlockByHeightResponse { - fn try_from_response(self) -> Result { - Ok(Block( - self.block.ok_or(Error::FailedToParseResponse)?.try_into()?, - )) - } -} - -impl FromGrpcResponse for GetLatestBlockResponse { - fn try_from_response(self) -> Result { - Ok(Block( - self.block.ok_or(Error::FailedToParseResponse)?.try_into()?, - )) - } -} - -impl FromGrpcResponse for QueryAuthParamsResponse { - fn try_from_response(self) -> Result { - let params = self.params.ok_or(Error::FailedToParseResponse)?; - Ok(AuthParams { - max_memo_characters: params.max_memo_characters, - tx_sig_limit: params.tx_sig_limit, - tx_size_cost_per_byte: params.tx_size_cost_per_byte, - sig_verify_cost_ed25519: params.sig_verify_cost_ed25519, - sig_verify_cost_secp256k1: params.sig_verify_cost_secp256k1, - }) - } -} -fn account_from_any(any: pbjson_types::Any) -> Result { - if any.type_url != RawBaseAccount::type_url() { - return Err(Error::UnexpectedResponseType(any.type_url)); - } - let base_account = - RawBaseAccount::decode(&*any.value).map_err(|_| Error::FailedToParseResponse)?; - - let any_pub_key = base_account.pub_key.ok_or(Error::FailedToParseResponse)?; - // cosmrs has different Any type than pbjson_types Any - let pub_key = PublicKey::try_from(Any { - type_url: any_pub_key.type_url, - value: any_pub_key.value.to_vec(), - })?; - - Ok(BaseAccount { - address: base_account.address, - pub_key, - account_number: base_account.account_number, - sequence: base_account.sequence, - }) -} - -impl FromGrpcResponse for QueryAccountResponse { - fn try_from_response(self) -> Result { - account_from_any(self.account.ok_or(Error::FailedToParseResponse)?) - } -} - -impl FromGrpcResponse> for QueryAccountsResponse { - fn try_from_response(self) -> Result, Error> { - self.accounts - .into_iter() - .map(|acct| account_from_any(acct)) - .collect() - } -} - -impl FromGrpcResponse for ConfigResponse { - fn try_from_response(self) -> Result { - const UNITS_SUFFIX: &str = "utia"; - - let min_gas_price_with_suffix = self.minimum_gas_price; - let min_gas_price_str = min_gas_price_with_suffix - .strip_suffix(UNITS_SUFFIX) - .ok_or(Error::FailedToParseResponse)?; - let min_gas_price = min_gas_price_str - .parse::() - .map_err(|_| Error::FailedToParseResponse)?; - - Ok(min_gas_price) - } -} - -impl IntoGrpcParam for i64 { - fn into_parameter(self) -> GetBlockByHeightRequest { - GetBlockByHeightRequest { height: self } - } -} - -impl IntoGrpcParam for String { - fn into_parameter(self) -> QueryAccountRequest { - QueryAccountRequest { address: self } - } -} - -impl IntoGrpcParam for (BlobTx, BroadcastMode) { - fn into_parameter(self) -> BroadcastTxRequest { - let (blob_tx, mode) = self; - BroadcastTxRequest { - tx_bytes: blob_tx.encode_to_vec(), - mode: mode.into(), - } - } -} - -impl IntoGrpcParam for String { - fn into_parameter(self) -> GetTxRequest { - GetTxRequest { hash: self } - } -} - -impl IntoGrpcParam for () { - fn into_parameter(self) -> QueryAccountsRequest { - QueryAccountsRequest { pagination: None } - } -} - -macro_rules! make_empty_params { - ($request_type:ident) => { - impl IntoGrpcParam<$request_type> for () { - fn into_parameter(self) -> $request_type { - $request_type {} - } - } - }; -} - -make_empty_params!(GetLatestBlockRequest); -make_empty_params!(ConfigRequest); -make_empty_params!(QueryAuthParamsRequest); -make_empty_params!(QueryBlobParamsRequest); diff --git a/rpc/src/tonic/types/tx.rs b/rpc/src/tonic/types/tx.rs deleted file mode 100644 index 07b90cac..00000000 --- a/rpc/src/tonic/types/tx.rs +++ /dev/null @@ -1,116 +0,0 @@ -use cosmrs::Tx; - -use celestia_proto::cosmos::base::abci::v1beta1::TxResponse as RawTxResponse; -use celestia_proto::cosmos::tx::v1beta1::{BroadcastTxResponse, GetTxResponse as RawGetTxResponse}; - -use crate::tonic::types::FromGrpcResponse; -use crate::tonic::Error; - -pub struct TxResponse { - /// The block height - pub height: i64, - - /// The transaction hash. - pub txhash: String, - - /// Namespace for the Code - pub codespace: String, - - /// Response code. - pub code: u32, - - /// Result bytes, if any. - pub data: String, - - /// The output of the application's logger (raw string). May be - /// non-deterministic. - pub raw_log: String, - - // The output of the application's logger (typed). May be non-deterministic. - //#[serde(with = "crate::serializers::null_default")] - //pub logs: ::prost::alloc::vec::Vec, - /// Additional information. May be non-deterministic. - pub info: String, - - /// Amount of gas requested for transaction. - pub gas_wanted: i64, - - /// Amount of gas consumed by transaction. - pub gas_used: i64, - - // The request transaction bytes. - //#[serde(with = "crate::serializers::option_any")] - //pub tx: ::core::option::Option<::pbjson_types::Any>, - /// Time of the previous block. For heights > 1, it's the weighted median of - /// the timestamps of the valid votes in the block.LastCommit. For height == 1, - /// it's genesis time. - pub timestamp: String, - // Events defines all the events emitted by processing a transaction. Note, - // these events include those emitted by processing all the messages and those - // emitted from the ante. Whereas Logs contains the events, with - // additional metadata, emitted only by processing the messages. - // - // Since: cosmos-sdk 0.42.11, 0.44.5, 0.45 - //#[serde(with = "crate::serializers::null_default")] - //pub events: ::prost::alloc::vec::Vec< ::celestia_tendermint_proto::v0_34::abci::Event, >, -} - -pub struct GetTxResponse { - pub tx: Tx, - - pub tx_response: TxResponse, -} - -impl TryFrom for TxResponse { - type Error = Error; - - fn try_from(response: RawTxResponse) -> Result { - // TODO: add missing fields with conversion - Ok(TxResponse { - height: response.height, - txhash: response.txhash, - codespace: response.codespace, - code: response.code, - data: response.data, - raw_log: response.raw_log, - //logs: response.logs - info: response.info, - gas_wanted: response.gas_wanted, - gas_used: response.gas_used, - //tx: response.tx - timestamp: response.timestamp, - //events: response.events - }) - } -} - -impl FromGrpcResponse for BroadcastTxResponse { - fn try_from_response(self) -> Result { - self.tx_response - .ok_or(Error::FailedToParseResponse)? - .try_into() - } -} - -impl FromGrpcResponse for RawGetTxResponse { - fn try_from_response(self) -> Result { - let tx_response = self - .tx_response - .ok_or(Error::FailedToParseResponse)? - .try_into()?; - let tx = self.tx.ok_or(Error::FailedToParseResponse)?; - let cosmos_tx = Tx { - body: tx.body.ok_or(Error::FailedToParseResponse)?.try_into()?, - auth_info: tx - .auth_info - .ok_or(Error::FailedToParseResponse)? - .try_into()?, - signatures: tx.signatures, - }; - - Ok(GetTxResponse { - tx: cosmos_tx, - tx_response, - }) - } -} diff --git a/rpc/tests/tonic.rs b/rpc/tests/tonic.rs deleted file mode 100644 index 290558e3..00000000 --- a/rpc/tests/tonic.rs +++ /dev/null @@ -1,40 +0,0 @@ -#![cfg(feature = "tonic")] - -pub mod utils; - -use crate::utils::client::AuthLevel; -use crate::utils::tonic_client::new_test_client; - -#[tokio::test] -async fn get_min_gas_price() { - let mut client = new_test_client(AuthLevel::Write).await.unwrap(); - let gas_price = client.get_min_gas_price().await.unwrap(); - assert!(gas_price > 0.0); -} - -#[tokio::test] -async fn get_block() { - let mut client = new_test_client(AuthLevel::Write).await.unwrap(); - - let latest_block = client.get_latest_block().await.unwrap(); - let height = latest_block.0.header.height.value() as i64; - - let block = client.get_block_by_height(height).await.unwrap(); - assert_eq!(block.0.header, latest_block.0.header); -} - -#[tokio::test] -async fn get_account() { - let mut client = new_test_client(AuthLevel::Write).await.unwrap(); - - let accounts = client.get_accounts().await.unwrap(); - - println!("first account : {:?}", accounts.first()); - - let acct = client - .get_account("celestia1p3ucd3ptpw902fluyjzhq3ffgq4ntddaf0pdta".to_string()) - .await - .unwrap(); - - println!("{acct:?}"); -} diff --git a/rpc/tests/utils/mod.rs b/rpc/tests/utils/mod.rs index a4f0fb8c..8755e6ed 100644 --- a/rpc/tests/utils/mod.rs +++ b/rpc/tests/utils/mod.rs @@ -6,8 +6,6 @@ use rand::{Rng, RngCore}; pub mod client; #[cfg(feature = "p2p")] pub mod tiny_node; -#[cfg(feature = "tonic")] -pub mod tonic_client; fn ns_to_u128(ns: Namespace) -> u128 { let mut bytes = [0u8; 16]; diff --git a/rpc/tests/utils/tonic_client.rs b/rpc/tests/utils/tonic_client.rs deleted file mode 100644 index 7a3e51d9..00000000 --- a/rpc/tests/utils/tonic_client.rs +++ /dev/null @@ -1,46 +0,0 @@ -use crate::utils::client::{env_or, token_from_env}; -use crate::AuthLevel; - -use anyhow::Result; -use tonic::metadata::{Ascii, MetadataValue}; -use tonic::service::Interceptor; -use tonic::transport::Channel; -use tonic::{Request, Status}; - -use celestia_rpc::tonic::GrpcClient; - -const CELESTIA_GRPC_URL: &str = "http://localhost:19090"; -//const CELESTIA_GRPC_URL: &str = "https://rpc.celestia.pops.one:9090"; - -#[derive(Clone)] -pub struct TestAuthInterceptor { - token: Option>, -} - -impl Interceptor for TestAuthInterceptor { - fn call(&mut self, mut request: Request<()>) -> Result, Status> { - if let Some(token) = &self.token { - request - .metadata_mut() - .insert("authorization", token.clone()); - } - Ok(request) - } -} - -impl TestAuthInterceptor { - pub fn new(bearer_token: Option) -> Result { - let token = bearer_token.map(|token| token.parse()).transpose()?; - Ok(Self { token }) - } -} - -pub async fn new_test_client(auth_level: AuthLevel) -> Result> { - let _ = dotenvy::dotenv(); - let url = env_or("CELESTIA_GRPC_URL", CELESTIA_GRPC_URL); - let grpc_channel = Channel::from_shared(url)?.connect().await?; - - let token = token_from_env(auth_level)?; - let auth_interceptor = TestAuthInterceptor::new(token)?; - Ok(GrpcClient::new(grpc_channel, auth_interceptor)) -}