diff --git a/Cargo.lock b/Cargo.lock index ad8d5e2..073a4fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -61,9 +61,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.19" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "611cc2ae7d2e242c457e4be7f97036b8ad9ca152b499f53faf99b1ed8fc2553f" +checksum = "45862d1c77f2228b9e10bc609d5bc203d86ebc9b87ad8d5d5167a6c9abf739d9" [[package]] name = "android-tzdata" @@ -554,9 +554,9 @@ dependencies = [ [[package]] name = "bstr" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40723b8fb387abc38f4f4a37c09073622e41dd12327033091ef8950659e6dc0c" +checksum = "1a68f1f47cdf0ec8ee4b941b2eee2a80cb796db73118c0dd09ac63fbe405be22" dependencies = [ "memchr", "serde", @@ -628,9 +628,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.37" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40545c26d092346d8a8dab71ee48e7685a7a9cba76e634790c215b41a4a7b4cf" +checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" dependencies = [ "jobserver", "libc", @@ -727,9 +727,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.20" +version = "4.5.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8" +checksum = "fb3b4b9e5a7c7514dfa52869339ee98b3156b0bfb4e8a77c4ff4babb64b1604f" dependencies = [ "clap_builder", "clap_derive", @@ -737,9 +737,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.20" +version = "4.5.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54" +checksum = "b17a95aa67cc7b5ebd32aa5370189aa0d79069ef1c64ce893bd30fb24bff20ec" dependencies = [ "anstream", "anstyle", @@ -761,9 +761,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" +checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" [[package]] name = "cmake" @@ -837,9 +837,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" +checksum = "0ca741a962e1b0bff6d724a1a0958b686406e853bb14061f218562e1896f95e6" dependencies = [ "libc", ] @@ -3429,9 +3429,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", @@ -3658,9 +3658,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.39" +version = "0.38.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375116bee2be9ed569afe2154ea6a99dfdffd257f533f187498c2a8f5feaf4ee" +checksum = "99e4ea3e1cdc4b559b8e5650f9c8e5998e3e5c1343b4eaf034565f32318d63c0" dependencies = [ "bitflags 2.6.0", "errno", @@ -3937,9 +3937,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.214" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" +checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" dependencies = [ "serde_derive", ] @@ -3965,9 +3965,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.214" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" +checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", @@ -4336,18 +4336,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.68" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02dd99dc800bbb97186339685293e1cc5d9df1f8fae2d0aecd9ff1c77efea892" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.68" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7c61ec9a6f64d2793d8a45faba21efbe3ced62a886d44c36a009b2b519b4c7e" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", @@ -5531,10 +5531,8 @@ dependencies = [ "whoami", "zaino-fetch", "zaino-proto", - "zcash_client_backend", "zebra-chain 1.0.0-beta.42 (git+https://github.com/ZcashFoundation/zebra.git?rev=4eb285de50848f1a4dcebd0fbe353e4f150fd371)", "zebra-rpc 1.0.0-beta.42 (git+https://github.com/ZcashFoundation/zebra.git?rev=4eb285de50848f1a4dcebd0fbe353e4f150fd371)", - "zingo-netutils 0.1.0 (git+https://github.com/zingolabs/zingolib.git?tag=zaino_dep_002_091024_95e5b0d8f9d5ee0485c6141533da2f727aeafae2)", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 84ff835..cea4feb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,8 +5,6 @@ members = [ "zaino-testutils", "zainod", "zaino-serve", - # "zaino-wallet", - # "zaino-nym", "zaino-state", "zaino-fetch", "zaino-proto", @@ -25,8 +23,6 @@ license = "Apache-2.0" [workspace.dependencies] # Zingolabs -# -# NOTE: This may have to move to Zaino-testutils once Nym code is reintroduced and Zaino-Wallet becomes a dependency of zingolib. zingolib = { git = "https://github.com/zingolabs/zingolib.git", tag = "zaino_dep_002_091024_95e5b0d8f9d5ee0485c6141533da2f727aeafae2", features = ["zaino-test"] } # Librustzcash @@ -38,14 +34,6 @@ zcash_protocol = { git = "https://github.com/zingolabs/librustzcash.git", tag = zebra-chain = { git = "https://github.com/ZcashFoundation/zebra.git", rev = "4eb285de50848f1a4dcebd0fbe353e4f150fd371" } zebra-rpc = { git = "https://github.com/ZcashFoundation/zebra.git", rev = "4eb285de50848f1a4dcebd0fbe353e4f150fd371" } - -# Temporarily removed until dependency conflict can be resolved. -# Nym -# nym-sdk = { git = "https://github.com/nymtech/nym", branch = "master" } -# nym-sphinx-addressing = { git = "https://github.com/nymtech/nym", branch = "master" } -# nym-bin-common = { git = "https://github.com/nymtech/nym", branch = "master" } -# nym-sphinx-anonymous-replies = { git = "https://github.com/nymtech/nym", branch = "master" } - # Miscellaneous tokio = { version = "1.38", features = ["full"] } tonic = "0.12" diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index a9813bc..d8f798a 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -9,9 +9,6 @@ repository = { workspace = true } [features] -# NOTE: Deprecated -nym_poc = [] - # Used by zcash-local-net: test_fixtures = [] diff --git a/integration-tests/tests/integrations.rs b/integration-tests/tests/integrations.rs index c7aa287..cb8271d 100644 --- a/integration-tests/tests/integrations.rs +++ b/integration-tests/tests/integrations.rs @@ -6,7 +6,7 @@ use std::sync::{atomic::AtomicBool, Arc}; use zaino_testutils::{drop_test_manager, zingo_lightclient::get_address, TestManager}; -mod wallet_basic { +mod zingo_wallet_basic { use zingolib::{lightclient::LightClient, testutils::lightclient::from_inputs}; use super::*; @@ -314,7 +314,3 @@ mod wallet_basic { .await; } } - -mod nym { - // TODO: Build nym enhanced zingolib version using zingo-rpc::walletrpc::service. -} diff --git a/zaino-nym/Cargo.toml b/zaino-nym/Cargo.toml deleted file mode 100644 index 5c1f93f..0000000 --- a/zaino-nym/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "zaino-nym" -version = "0.1.0" -description = "Crate containing the NymClient and related functionality." -edition = { workspace = true } -authors = { workspace = true } -license = { workspace = true } -repository = { workspace = true } - -[dependencies] -zaino-fetch = { path = "../zaino-fetch" } - -# NymSdk -nym-sdk = { workspace = true } -nym-sphinx-addressing = { workspace = true } - -# # Miscellaneous Workspace -tonic = { workspace = true } -thiserror = { workspace = true } diff --git a/zaino-nym/src/client.rs b/zaino-nym/src/client.rs deleted file mode 100644 index 281178c..0000000 --- a/zaino-nym/src/client.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Nym client functionality. - -use nym_sdk::mixnet::{ - MixnetClient, MixnetClientBuilder, MixnetMessageSender, Recipient, ReconstructedMessage, - StoragePaths, -}; -use std::path::PathBuf; - -use crate::error::NymError; - -/// Wrapper struct for a Nym client. -pub struct NymClient { - /// Nym SDK Client. - pub client: MixnetClient, - /// Nym client address. - pub addr: String, -} - -impl NymClient { - /// Spawns a nym client and connects to the mixnet. - pub async fn spawn(str_path: &str) -> Result { - //nym_bin_common::logging::setup_logging(); - let client = MixnetClientBuilder::new_with_default_storage(StoragePaths::new_from_dir( - PathBuf::from(str_path), - )?) - .await? - .build()? - .connect_to_mixnet() - .await?; - let addr = client.nym_address().to_string(); - Ok(Self { client, addr }) - } - - /// Forwards an encoded gRPC request over the nym mixnet to the nym address specified and waits for the response. - /// - /// TODO: Add timout for waiting for response. - pub async fn send( - &mut self, - recipient_address: &str, - message: Vec, - ) -> Result, NymError> { - // Box> { - let recipient: Recipient = - Recipient::try_from_base58_string(recipient_address.to_string())?; - self.client.send_plain_message(recipient, message).await?; - - let mut nym_response: Vec = Vec::new(); - while let Some(response_in) = self.client.wait_for_messages().await { - if response_in.is_empty() { - continue; - } - nym_response = response_in; - break; - } - let response_out = nym_response - .first() - .map(|r| r.message.clone()) - .ok_or_else(|| { - NymError::ConnectionError("No response received from the nym network".to_string()) - })?; - Ok(response_out) - } - - /// Closes the nym client. - pub async fn close(self) { - self.client.disconnect().await; - } -} diff --git a/zaino-nym/src/error.rs b/zaino-nym/src/error.rs deleted file mode 100644 index fb785d1..0000000 --- a/zaino-nym/src/error.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Hold error types for Nym related functionality. - -use zaino_fetch::chain::error::ParseError; - -/// Parser Error Type. -#[derive(Debug, thiserror::Error)] -pub enum NymError { - /// Serialization and deserialization error. - #[error("Parser Error: {0}")] - ParseError(#[from] ParseError), - /// Nym-SDK related error, look at specific types for detail. - /// - /// TODO: Handle certain Nym-SDK Errors specifically (network related errors, nym client startup..). - #[error("Nym-SDK Error: {0}")] - NymError(#[from] nym_sdk::Error), - /// Nym address formatting errors. - #[error("Nym Recipient Formatting Error: {0}")] - RecipientFormattingError(#[from] nym_sphinx_addressing::clients::RecipientFormattingError), - /// Mixnet connection error. - #[error("Connection Error: {0}")] - ConnectionError(String), - /// Custom error for empty messages received from the Nym network. - #[error("Empty message received from the mixnet")] - EmptyMessageError, - /// Custom error for receiveing not AnonSenderTag (surb) from the Nym network. - #[error("No AnonSenderTag received from the mixnet")] - EmptyRecipientTagError, -} - -impl From for tonic::Status { - fn from(error: NymError) -> Self { - match error { - NymError::ParseError(e) => tonic::Status::internal(format!("Parse error: {}", e)), - NymError::NymError(e) => tonic::Status::internal(format!("Nym-SDK error: {}", e)), - NymError::RecipientFormattingError(e) => { - tonic::Status::invalid_argument(format!("Recipient formatting error: {}", e)) - } - NymError::ConnectionError(e) => { - tonic::Status::internal(format!("Connection error: {}", e)) - } - NymError::EmptyMessageError => { - tonic::Status::internal("Empty message received from nym mixnet".to_string()) - } - NymError::EmptyRecipientTagError => { - tonic::Status::internal("No AnonSenderTag received from nym mixnet".to_string()) - } - } - } -} diff --git a/zaino-nym/src/lib.rs b/zaino-nym/src/lib.rs deleted file mode 100644 index 50a89e3..0000000 --- a/zaino-nym/src/lib.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! Crate containing the NymClient and related functionality. - -#![warn(missing_docs)] -#![forbid(unsafe_code)] - -pub mod client; -pub mod error; -pub mod utils; diff --git a/zaino-nym/src/utils.rs b/zaino-nym/src/utils.rs deleted file mode 100644 index 0631625..0000000 --- a/zaino-nym/src/utils.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Utility functions for Nym-Mixnet - -use crate::error::NymError; -use std::io::Cursor; -use zaino_fetch::chain::{ - error::ParseError, - utils::{read_bytes, CompactSize}, -}; - -/// Reads a RPC method name from a Vec and returns this as a string along with the remaining data in the input. -fn read_nym_method(data: &[u8]) -> Result<(String, &[u8]), NymError> { - let mut cursor = Cursor::new(data); - let method_len = CompactSize::read(&mut cursor).map_err(ParseError::Io)? as usize; - let method = String::from_utf8(read_bytes(&mut cursor, method_len, "failed to read")?) - .map_err(ParseError::FromUtf8Error)?; - Ok((method, &data[cursor.position() as usize..])) -} - -/// Check the body of the request is the correct length. -fn check_nym_body(data: &[u8]) -> Result<&[u8], NymError> { - let mut cursor = Cursor::new(data); - let body_len = CompactSize::read(&mut cursor).map_err(ParseError::Io)? as usize; - if body_len != data[cursor.position() as usize..].len() { - return Err(NymError::ParseError(ParseError::InvalidData( - "Incorrect request body size read.".to_string(), - ))); - }; - Ok(&data[cursor.position() as usize..]) -} - -/// Extracts metadata from a NymRequest. -/// -/// Returns [ID, Method, RequestData]. -pub fn read_nym_request_data(data: &[u8]) -> Result<(u64, String, &[u8]), NymError> { - let mut cursor = Cursor::new(data); - let id = CompactSize::read(&mut cursor).map_err(ParseError::Io)?; - let (method, data) = read_nym_method(&data[cursor.position() as usize..])?; - let body = check_nym_body(data)?; - Ok((id, method, body)) -} diff --git a/zaino-serve/Cargo.toml b/zaino-serve/Cargo.toml index 352f361..75d59ae 100644 --- a/zaino-serve/Cargo.toml +++ b/zaino-serve/Cargo.toml @@ -7,20 +7,7 @@ authors = { workspace = true } license = { workspace = true } repository = { workspace = true } -[features] -# NOTE: Deprecated -nym_poc = ["zingo-netutils", "zcash_client_backend"] - [dependencies] -# Zinglib and LibRustZcash: -# -# Only used in original nym_poc code, to be removed with creation of nym enhanced zingolib build. -# -# Not to be used in production code as zingo-rpc will become a dep of zingolib and zingo-indexer now builds its onw CompactTxStreamer. -zingo-netutils = { git = "https://github.com/zingolabs/zingolib.git", tag = "zaino_dep_002_091024_95e5b0d8f9d5ee0485c6141533da2f727aeafae2", optional = true } -# zingo-netutils = { git = "https://github.com/idky137/zingolib.git", branch = "zaino_temp_dep", optional = true } -zcash_client_backend = { git = "https://github.com/zingolabs/librustzcash.git", tag = "zcash_client_sqlite-0.11.2_plus_zingolabs_changes-1-g7ad60b5d5-2-g121371a08", features = ["lightwalletd-tonic"], optional = true } - zaino-proto = { path = "../zaino-proto" } zaino-fetch = { path = "../zaino-fetch" } @@ -28,13 +15,6 @@ zaino-fetch = { path = "../zaino-fetch" } zebra-chain = { workspace = true } zebra-rpc = { workspace = true } -# Temporarily removed until dependency conflic can be resolved. -# zaino-nym = { path = "../zaino-nym" } -# zaino-wallet = { path = "../zaino-wallet" } -# NymSdk -# nym-sdk = { workspace = true } -# nym-sphinx-anonymous-replies = { workspace = true } - # Miscellaneous Workspace tokio = { workspace = true, features = ["full"] } tonic = { workspace = true } diff --git a/zaino-serve/src/lib.rs b/zaino-serve/src/lib.rs index e68b1b1..fc4c59c 100644 --- a/zaino-serve/src/lib.rs +++ b/zaino-serve/src/lib.rs @@ -1,6 +1,8 @@ -//! Holds a gRPC server capable of servicing clients over both https and the nym mixnet. +//! Holds a gRPC server capable of servicing clients over TCP. //! -//! Also holds the rust implementations of the LightWallet Service (CompactTxStreamerServer) and (eventually) Darkside RPCs (DarksideTxStremerServer). +//! - server::ingestor has been built so that other ingestors may be added that use different transport protocols (Nym, TOR). +//! +//! Also holds rust implementations of the LightWallet gRPC Service (CompactTxStreamerServer). #![warn(missing_docs)] #![forbid(unsafe_code)] @@ -8,4 +10,3 @@ pub mod rpc; pub mod server; pub(crate) mod utils; - diff --git a/zaino-serve/src/rpc.rs b/zaino-serve/src/rpc.rs index f0dd68e..a9da92e 100644 --- a/zaino-serve/src/rpc.rs +++ b/zaino-serve/src/rpc.rs @@ -1,14 +1,9 @@ -//! Lightwallet service RPC implementations and Nym functionality. +//! Lightwallet service RPC implementations. use std::sync::{atomic::AtomicBool, Arc}; -// #[cfg(feature = "nym_poc")] -// pub mod nymwalletservice; -// #[cfg(not(feature = "nym_poc"))] pub mod service; -// pub mod nymservice; - #[derive(Debug, Clone)] /// Configuration data for gRPC server. pub struct GrpcClient { diff --git a/zaino-serve/src/rpc/nymservice.rs b/zaino-serve/src/rpc/nymservice.rs deleted file mode 100644 index 9f9d02a..0000000 --- a/zaino-serve/src/rpc/nymservice.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! Lightwallet service RPC Nym implementations. - -use prost::Message; - -use crate::{rpc::GrpcClient, server::request::NymServerRequest}; - -#[cfg(not(feature = "nym_poc"))] -use zaino_proto::proto::service::compact_tx_streamer_server::CompactTxStreamer; - -#[cfg(feature = "nym_poc")] -use zcash_client_backend::proto::service::compact_tx_streamer_server::CompactTxStreamer; - -impl GrpcClient { - /// Processes gRPC requests coming from the nym server. - pub async fn process_nym_request( - &self, - request: &NymServerRequest, - ) -> Result, tonic::Status> { - match request.get_request().method().as_str() { - "GetLightdInfo" => match prost::Message::decode(&request.get_request().body()[..]) { - Ok(input) => { - let tonic_request = tonic::Request::new(input); - let tonic_response = self.get_lightd_info(tonic_request) - .await?.into_inner(); - - let mut response_vec = Vec::new(); - tonic_response.encode(&mut response_vec).map_err(|e| { - tonic::Status::internal(format!( - "Failed to encode response: {}", - e - )) - })?; - Ok(response_vec) - } - Err(e) => Err(tonic::Status::internal(format!( - "Failed to decode request: {}", - e - ))), - }, - "SendTransaction" => match prost::Message::decode(&request.get_request().body()[..]) { - Ok(input) => { - let tonic_request = tonic::Request::new(input); - let tonic_response = self.send_transaction(tonic_request) - .await?.into_inner(); - let mut response_vec = Vec::new(); - tonic_response.encode(&mut response_vec).map_err(|e| { - tonic::Status::internal(format!( - "Failed to encode response: {}", - e - )) - })?; - Ok(response_vec) - } - Err(e) => Err(tonic::Status::internal(format!( - "Failed to decode request: {}", - e - ))), - }, - "get_latest_block" | - "get_block" | - "get_block_nullifiers" | - "get_block_range" | - "get_block_range_nullifiers" | - "get_transaction" | - "send_transaction" | - "get_taddress_txids" | - "get_taddress_balance" | - "get_taddress_balance_stream" | - "get_mempool_tx" | - "get_mempool_stream" | - "get_tree_state" | - "get_latest_tree_state" | - "get_subtree_roots" | - "get_address_utxos" | - "get_address_utxos_stream" | - "ping" => { - Err(tonic::Status::unimplemented("RPC not yet implemented over nym. If you require this RPC please open an issue or PR at the Zingo-Indexer github (https://github.com/zingolabs/zingo-indexer).")) - }, - _ => Err(tonic::Status::invalid_argument("Incorrect Method String")), - } - } -} diff --git a/zaino-serve/src/rpc/nymwalletservice.rs b/zaino-serve/src/rpc/nymwalletservice.rs deleted file mode 100644 index 93383db..0000000 --- a/zaino-serve/src/rpc/nymwalletservice.rs +++ /dev/null @@ -1,311 +0,0 @@ -//! Client-side service RPC nym wrapper implementations. -//! -//! NOTE: DEPRICATED. - -use crate::rpc::GrpcClient; -use std::env; -use tonic::{async_trait, Request, Response, Status}; -use zaino_nym::client::NymClient; -use zaino_wallet::utils::{deserialize_response, serialize_request, write_nym_request_data}; -use zcash_client_backend::proto::{ - compact_formats::{CompactBlock, CompactTx}, - service::{ - compact_tx_streamer_server::CompactTxStreamer, Address, AddressList, Balance, BlockId, - BlockRange, ChainSpec, Duration, Empty, Exclude, GetAddressUtxosArg, GetAddressUtxosReply, - GetAddressUtxosReplyList, GetSubtreeRootsArg, LightdInfo, PingResponse, RawTransaction, - SendResponse, SubtreeRoot, TransparentAddressBlockFilter, TreeState, TxFilter, - }, -}; - -macro_rules! define_grpc_passthrough { - (fn - $name:ident( - &$self:ident$(,$($arg:ident: $argty:ty,)*)? - ) -> $ret:ty - ) => { - #[must_use] - #[allow(clippy::type_complexity, clippy::type_repetition_in_bounds)] - fn $name<'life0, 'async_trait>(&'life0 $self$($(, $arg: $argty)*)?) -> - ::core::pin::Pin, - ::tonic::Status - > - > + ::core::marker::Send + 'async_trait - >> - where - 'life0: 'async_trait, - Self: 'async_trait, - { - println!("@zingoindexerd: Received call of {}.", stringify!($name)); - Box::pin(async { - ::zingo_netutils::GrpcConnector::new($self.lightwalletd_uri.clone()) - .get_client() - .await - .expect("Server failed to create client") - .$name($($($arg),*)?) - .await - }) - } - }; -} - -#[async_trait] -impl CompactTxStreamer for GrpcClient { - define_grpc_passthrough!( - fn get_latest_block( - &self, - request: tonic::Request, - ) -> BlockId - ); - - define_grpc_passthrough!( - fn get_block( - &self, - request: tonic::Request, - ) -> CompactBlock - ); - - #[doc = "Server streaming response type for the GetBlockRange method."] - type GetBlockRangeStream = tonic::Streaming; - - define_grpc_passthrough!( - fn get_block_range( - &self, - request: tonic::Request, - ) -> Self::GetBlockRangeStream - ); - - define_grpc_passthrough!( - fn get_transaction( - &self, - request: tonic::Request, - ) -> RawTransaction - ); - - async fn send_transaction( - &self, - request: Request, - ) -> Result, Status> { - println!("@zingoindexerd[nym_poc]: Received call of send_transaction."); - // -- serialize RawTransaction - let serialized_request = match serialize_request(&request.into_inner()).await { - Ok(data) => data, - Err(e) => { - return Err(Status::internal(format!( - "Failed to serialize request: {}", - e - ))) - } - }; - // -- create ZingoIndexerRequest - let nym_request = match write_nym_request_data( - 0, - "SendTransaction".to_string(), - serialized_request.as_ref(), - ) { - Ok(data) => data, - Err(e) => { - return Err(Status::internal(format!( - "Failed to write nym request data: {}", - e - ))) - } - }; - // -- forward request over nym and wait for response - let args: Vec = env::args().collect(); - let recipient_address: String = args[1].clone(); - let nym_conf_path = "/tmp/nym_client"; - let mut client = NymClient::spawn(nym_conf_path).await?; - let response_data = client.send(recipient_address.as_str(), nym_request).await?; - client.close().await; - // -- deserialize SendResponse - let response: SendResponse = match deserialize_response(response_data.as_slice()).await { - Ok(res) => res, - Err(e) => { - return Err(Status::internal(format!( - "Failed to decode response: {}", - e - ))) - } - }; - Ok(Response::new(response)) - } - - #[doc = "Server streaming response type for the GetTaddressTxids method."] - type GetTaddressTxidsStream = tonic::Streaming; - - define_grpc_passthrough!( - fn get_taddress_txids( - &self, - request: tonic::Request, - ) -> Self::GetTaddressTxidsStream - ); - - define_grpc_passthrough!( - fn get_taddress_balance( - &self, - request: tonic::Request, - ) -> Balance - ); - - /// This isn't easily definable with the macro, and I beleive it to be unused - #[must_use] - #[allow(clippy::type_complexity, clippy::type_repetition_in_bounds)] - fn get_taddress_balance_stream<'life0, 'async_trait>( - &'life0 self, - _request: tonic::Request>, - ) -> ::core::pin::Pin< - Box< - dyn ::core::future::Future, tonic::Status>> - + ::core::marker::Send - + 'async_trait, - >, - > - where - 'life0: 'async_trait, - Self: 'async_trait, - { - todo!("this isn't expected to be called. Please implement this if you need it") - } - - #[doc = "Server streaming response type for the GetMempoolTx method."] - type GetMempoolTxStream = tonic::Streaming; - - define_grpc_passthrough!( - fn get_mempool_tx( - &self, - request: tonic::Request, - ) -> Self::GetMempoolTxStream - ); - - #[doc = "Server streaming response type for the GetMempoolStream method."] - type GetMempoolStreamStream = tonic::Streaming; - - define_grpc_passthrough!( - fn get_mempool_stream( - &self, - request: tonic::Request, - ) -> Self::GetMempoolStreamStream - ); - - define_grpc_passthrough!( - fn get_tree_state( - &self, - request: tonic::Request, - ) -> TreeState - ); - - define_grpc_passthrough!( - fn get_address_utxos( - &self, - request: tonic::Request, - ) -> GetAddressUtxosReplyList - ); - - #[doc = "Server streaming response type for the GetAddressUtxosStream method."] - type GetAddressUtxosStreamStream = tonic::Streaming; - - define_grpc_passthrough!( - fn get_address_utxos_stream( - &self, - request: tonic::Request, - ) -> tonic::Streaming - ); - - define_grpc_passthrough!( - fn get_lightd_info( - &self, - request: tonic::Request, - ) -> LightdInfo - ); - // async fn get_lightd_info( - // &self, - // request: Request, - // ) -> Result, Status> { - // println!("@zingoindexerd[nym_poc]: Received call of get_lightd_info."); - // // -- serialize Empty - // let serialized_request = match serialize_request(&request.into_inner()).await { - // Ok(data) => data, - // Err(e) => { - // return Err(Status::internal(format!( - // "Failed to serialize request: {}", - // e - // ))) - // } - // }; - // // -- create ZingoIndexerRequest - // let nym_request = match write_nym_request_data( - // 0, - // "GetLightdInfo".to_string(), - // serialized_request.as_ref(), - // ) { - // Ok(data) => data, - // Err(e) => { - // return Err(Status::internal(format!( - // "Failed to write nym request data: {}", - // e - // ))) - // } - // }; - // // -- forward request over nym and wait for response - // let args: Vec = env::args().collect(); - // let recipient_address: String = args[1].clone(); - // let nym_conf_path = "/tmp/nym_client"; - // let mut client = NymClient::spawn(nym_conf_path).await?; - // let response_data = client.send(recipient_address.as_str(), nym_request).await?; - // client.close().await; - // // -- deserialize LightdInfo - // let response: LightdInfo = match deserialize_response(response_data.as_slice()).await { - // Ok(res) => res, - // Err(e) => { - // return Err(Status::internal(format!( - // "Failed to decode response: {}", - // e - // ))) - // } - // }; - // Ok(Response::new(response)) - // } - - define_grpc_passthrough!( - fn ping( - &self, - request: tonic::Request, - ) -> PingResponse - ); - - define_grpc_passthrough!( - fn get_block_nullifiers( - &self, - request: tonic::Request, - ) -> CompactBlock - ); - - define_grpc_passthrough!( - fn get_block_range_nullifiers( - &self, - request: tonic::Request, - ) -> Self::GetBlockRangeNullifiersStream - ); - #[doc = " Server streaming response type for the GetBlockRangeNullifiers method."] - type GetBlockRangeNullifiersStream = tonic::Streaming; - - define_grpc_passthrough!( - fn get_latest_tree_state( - &self, - request: tonic::Request, - ) -> TreeState - ); - - define_grpc_passthrough!( - fn get_subtree_roots( - &self, - request: tonic::Request, - ) -> Self::GetSubtreeRootsStream - ); - - #[doc = " Server streaming response type for the GetSubtreeRoots method."] - type GetSubtreeRootsStream = tonic::Streaming; -} diff --git a/zaino-serve/src/rpc/service.rs b/zaino-serve/src/rpc/service.rs index 16a40e6..9246bef 100644 --- a/zaino-serve/src/rpc/service.rs +++ b/zaino-serve/src/rpc/service.rs @@ -18,7 +18,11 @@ use zaino_fetch::{ use zaino_proto::proto::{ compact_formats::{CompactBlock, CompactTx}, service::{ - compact_tx_streamer_server::CompactTxStreamer, Address, AddressList, Balance, BlockId, BlockRange, ChainSpec, Duration, Empty, Exclude, GetAddressUtxosArg, GetAddressUtxosReply, GetAddressUtxosReplyList, GetSubtreeRootsArg, LightdInfo, PingResponse, RawTransaction, SendResponse, ShieldedProtocol, SubtreeRoot, TransparentAddressBlockFilter, TreeState, TxFilter + compact_tx_streamer_server::CompactTxStreamer, Address, AddressList, Balance, BlockId, + BlockRange, ChainSpec, Duration, Empty, Exclude, GetAddressUtxosArg, GetAddressUtxosReply, + GetAddressUtxosReplyList, GetSubtreeRootsArg, LightdInfo, PingResponse, RawTransaction, + SendResponse, ShieldedProtocol, SubtreeRoot, TransparentAddressBlockFilter, TreeState, + TxFilter }, }; @@ -1880,7 +1884,6 @@ impl CompactTxStreamer for GrpcClient { { println!("[TEST] Received call of get_lightd_info."); // TODO: Add user and password as fields of GrpcClient and use here. - // TODO: Return Nym_Address in get_lightd_info response, for use by wallets. Box::pin(async { let zebrad_client = JsonRpcConnector::new( self.zebrad_uri.clone(), diff --git a/zaino-serve/src/server/director.rs b/zaino-serve/src/server/director.rs index caa93ef..6f5ccc0 100644 --- a/zaino-serve/src/server/director.rs +++ b/zaino-serve/src/server/director.rs @@ -1,7 +1,6 @@ //! Zingo-Indexer gRPC server. use http::Uri; -// use nym_sphinx_anonymous_replies::requests::AnonymousSenderTag; use std::{ net::SocketAddr, sync::{ @@ -25,11 +24,8 @@ pub struct ServerStatus { /// Status of the Server. pub server_status: AtomicStatus, tcp_ingestor_status: AtomicStatus, - nym_ingestor_status: AtomicStatus, - nym_dispatcher_status: AtomicStatus, workerpool_status: WorkerPoolStatus, request_queue_status: Arc, - nym_response_queue_status: Arc, } impl ServerStatus { @@ -38,11 +34,8 @@ impl ServerStatus { ServerStatus { server_status: AtomicStatus::new(5), tcp_ingestor_status: AtomicStatus::new(5), - nym_ingestor_status: AtomicStatus::new(5), - nym_dispatcher_status: AtomicStatus::new(5), workerpool_status: WorkerPoolStatus::new(max_workers), request_queue_status: Arc::new(AtomicUsize::new(0)), - nym_response_queue_status: Arc::new(AtomicUsize::new(0)), } } @@ -50,27 +43,20 @@ impl ServerStatus { pub fn load(&self) -> ServerStatus { self.server_status.load(); self.tcp_ingestor_status.load(); - self.nym_ingestor_status.load(); - self.nym_dispatcher_status.load(); self.workerpool_status.load(); self.request_queue_status.load(Ordering::SeqCst); - self.nym_response_queue_status.load(Ordering::SeqCst); self.clone() } } -/// LightWallet server capable of servicing clients over both http and nym. +/// LightWallet server capable of servicing clients over TCP. pub struct Server { /// Listens for incoming gRPC requests over HTTP. tcp_ingestor: Option, - // /// Listens for incoming gRPC requests over Nym Mixnet, also sends responses back to clients. - // nym_ingestor: Option, /// Dynamically sized pool of workers. worker_pool: WorkerPool, /// Request queue. request_queue: Queue, - // /// Nym response queue. - // nym_response_queue: Queue<(Vec, AnonymousSenderTag)>, /// Servers current status. status: ServerStatus, /// Represents the Online status of the Server. @@ -83,8 +69,6 @@ impl Server { pub async fn spawn( tcp_active: bool, tcp_ingestor_listen_addr: Option, - nym_active: bool, - nym_conf_path: Option, lightwalletd_uri: Uri, zebrad_uri: Uri, max_queue_size: u16, @@ -93,9 +77,9 @@ impl Server { status: ServerStatus, online: Arc, ) -> Result { - if (!tcp_active) && (!nym_active) { + if !tcp_active { return Err(ServerError::ServerConfigError( - "Cannot start server with no ingestors selected, at least one of either nym or tcp must be set to active in conf.".to_string(), + "Cannot start server with no ingestors selected.".to_string(), )); } if tcp_active && tcp_ingestor_listen_addr.is_none() { @@ -103,21 +87,11 @@ impl Server { "TCP is active but no address provided.".to_string(), )); } - if nym_active && nym_conf_path.is_none() { - return Err(ServerError::ServerConfigError( - "NYM is active but no conf path provided.".to_string(), - )); - } println!("Launching Server!\n"); status.server_status.store(0); let request_queue: Queue = Queue::new(max_queue_size as usize, status.request_queue_status.clone()); status.request_queue_status.store(0, Ordering::SeqCst); - // let nym_response_queue: Queue<(Vec, AnonymousSenderTag)> = Queue::new( - // max_queue_size as usize, - // status.nym_response_queue_status.clone(), - // ); - status.nym_response_queue_status.store(0, Ordering::SeqCst); let tcp_ingestor = if tcp_active { println!("Launching TcpIngestor.."); Some( @@ -133,32 +107,12 @@ impl Server { } else { None }; - // let nym_ingestor = if nym_active { - // println!("Launching NymIngestor.."); - // let nym_conf_path_string = - // nym_conf_path.expect("nym_conf_path returned none when used."); - // Some( - // NymIngestor::spawn( - // nym_conf_path_string.clone().as_str(), - // request_queue.tx().clone(), - // nym_response_queue.rx().clone(), - // nym_response_queue.tx().clone(), - // status.nym_ingestor_status.clone(), - // online.clone(), - // ) - // .await?, - // ) - // } else { - // None - // }; - println!("Launching WorkerPool.."); let worker_pool = WorkerPool::spawn( max_worker_pool_size, idle_worker_pool_size, request_queue.rx().clone(), request_queue.tx().clone(), - // nym_response_queue.tx().clone(), lightwalletd_uri, zebrad_uri, status.workerpool_status.clone(), @@ -167,10 +121,8 @@ impl Server { .await; Ok(Server { tcp_ingestor, - // nym_ingestor, worker_pool, request_queue, - // nym_response_queue, status: status.clone(), online, }) @@ -186,12 +138,8 @@ impl Server { tokio::task::spawn(async move { // NOTE: This interval may need to be reduced or removed / moved once scale testing begins. let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(50)); - // let mut nym_ingestor_handle = None; let mut tcp_ingestor_handle = None; let mut worker_handles; - // if let Some(ingestor) = self.nym_ingestor.take() { - // nym_ingestor_handle = Some(ingestor.serve().await); - // } if let Some(ingestor) = self.tcp_ingestor.take() { tcp_ingestor_handle = Some(ingestor.serve().await); } @@ -229,12 +177,8 @@ impl Server { let worker_handle_options: Vec< Option>>, > = worker_handles.into_iter().map(Some).collect(); - self.shutdown_components( - tcp_ingestor_handle, - None, // nym_ingestor_handle, - worker_handle_options, - ) - .await; + self.shutdown_components(tcp_ingestor_handle, worker_handle_options) + .await; self.status.server_status.store(5); return Ok(()); } @@ -263,17 +207,12 @@ impl Server { async fn shutdown_components( &mut self, tcp_ingestor_handle: Option>>, - nym_ingestor_handle: Option>>, mut worker_handles: Vec>>>, ) { if let Some(handle) = tcp_ingestor_handle { self.status.tcp_ingestor_status.store(4); handle.await.ok(); } - if let Some(handle) = nym_ingestor_handle { - self.status.nym_ingestor_status.store(4); - handle.await.ok(); - } self.worker_pool.shutdown(&mut worker_handles).await; } @@ -291,14 +230,9 @@ impl Server { pub fn statuses(&mut self) -> ServerStatus { self.status.server_status.load(); self.status.tcp_ingestor_status.load(); - self.status.nym_ingestor_status.load(); - self.status.nym_dispatcher_status.load(); self.status .request_queue_status .store(self.request_queue.queue_length(), Ordering::SeqCst); - // self.status - // .nym_response_queue_status - // .store(self.nym_response_queue.queue_length(), Ordering::SeqCst); self.worker_pool.status(); self.status.clone() } diff --git a/zaino-serve/src/server/error.rs b/zaino-serve/src/server/error.rs index 84195cf..9ca6d99 100644 --- a/zaino-serve/src/server/error.rs +++ b/zaino-serve/src/server/error.rs @@ -4,7 +4,6 @@ use std::io; use tokio::sync::mpsc::error::TrySendError; use crate::server::request::ZingoIndexerRequest; -// use zaino_nym::error::NymError; /// Zingo-Indexer queue errors. #[derive(Debug, thiserror::Error)] @@ -29,9 +28,6 @@ pub enum RequestError { /// System time errors. #[error("System time error: {0}")] SystemTimeError(#[from] std::time::SystemTimeError), - // /// Nym Related Errors - // #[error("Nym error: {0}")] - // NymError(#[from] NymError), } /// Zingo-Indexer ingestor errors. @@ -40,9 +36,6 @@ pub enum IngestorError { /// Request based errors. #[error("Request error: {0}")] RequestError(#[from] RequestError), - // /// Nym based errors. - // #[error("Nym error: {0}")] - // NymError(#[from] NymError), /// Tcp listener based error. #[error("Failed to accept TcpStream: {0}")] ClientConnectionError(#[from] io::Error), @@ -74,9 +67,6 @@ pub enum ServerError { /// Request based errors. #[error("Request error: {0}")] RequestError(#[from] RequestError), - // /// Nym based errors. - // #[error("Nym error: {0}")] - // NymError(#[from] NymError), /// Ingestor based errors. #[error("Ingestor error: {0}")] IngestorError(#[from] IngestorError), diff --git a/zaino-serve/src/server/ingestor.rs b/zaino-serve/src/server/ingestor.rs index da3f379..cfec2cb 100644 --- a/zaino-serve/src/server/ingestor.rs +++ b/zaino-serve/src/server/ingestor.rs @@ -1,7 +1,5 @@ //! Holds the server ingestor (listener) implementations. -// use nym_sdk::mixnet::MixnetMessageSender; -// use nym_sphinx_anonymous_replies::requests::AnonymousSenderTag; use std::{ net::SocketAddr, sync::{ @@ -17,7 +15,6 @@ use crate::server::{ request::ZingoIndexerRequest, AtomicStatus, StatusType, }; -// use zaino_nym::{client::NymClient, error::NymError}; /// Listens for incoming gRPC requests over HTTP. pub(crate) struct TcpIngestor { @@ -128,174 +125,3 @@ impl TcpIngestor { self.online.load(Ordering::SeqCst) } } - -// /// Listens for incoming gRPC requests over Nym Mixnet. -// /// -// /// Temporarily removed until nym dependency conflic can be resolved. -// pub(crate) struct NymIngestor { -// /// Nym Client -// ingestor: NymClient, -// /// Used to send requests to the queue. -// queue: QueueSender, -// /// Used to send requests to the queue. -// response_queue: QueueReceiver<(Vec, AnonymousSenderTag)>, -// /// Used to send requests to the queue. -// response_requeue: QueueSender<(Vec, AnonymousSenderTag)>, -// /// Current status of the ingestor. -// status: AtomicStatus, -// /// Represents the Online status of the gRPC server. -// online: Arc, -// } - -// impl NymIngestor { -// /// Creates a Nym Ingestor -// pub(crate) async fn spawn( -// nym_conf_path: &str, -// queue: QueueSender, -// response_queue: QueueReceiver<(Vec, AnonymousSenderTag)>, -// response_requeue: QueueSender<(Vec, AnonymousSenderTag)>, -// status: AtomicStatus, -// online: Arc, -// ) -> Result { -// status.store(0); -// // TODO: HANDLE THESE ERRORS TO SMOOTH MIXNET CLIENT SPAWN PROCESS! -// let listener = NymClient::spawn(&format!("{}/ingestor", nym_conf_path)).await?; -// println!("NymIngestor listening at: {}.", listener.addr); -// Ok(NymIngestor { -// ingestor: listener, -// queue, -// response_queue, -// response_requeue, -// online, -// status, -// }) -// } - -// /// Starts Nym service. -// pub(crate) async fn serve(mut self) -> tokio::task::JoinHandle> { -// tokio::task::spawn(async move { -// // NOTE: This interval may need to be reduced or removed / moved once scale testing begins. -// let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(50)); -// // TODO Check blockcache sync status and wait on server / node if on hold. -// self.status.store(1); -// loop { -// tokio::select! { -// _ = interval.tick() => { -// if self.check_for_shutdown().await { -// self.status.store(5); -// return Ok(()) -// } -// } -// incoming = self.ingestor.client.wait_for_messages() => { -// // NOTE: This may need to be removed /moved for scale use. -// if self.check_for_shutdown().await { -// self.status.store(5); -// return Ok(()) -// } -// match incoming { -// Some(request) => { -// // NOTE / TODO: POC server checked for empty messages here (if request.is_empty()). Could be required here... -// let request_vu8 = request -// .first() -// .map(|r| r.message.clone()) -// .ok_or_else(|| IngestorError::NymError(NymError::EmptyMessageError))?; -// // TODO: Handle EmptyRecipientTagError here. -// let return_recipient = request[0] -// .sender_tag -// .ok_or_else(|| IngestorError::NymError(NymError::EmptyRecipientTagError))?; -// // TODO: Handle RequestError here. -// let zingo_proxy_request = -// ZingoIndexerRequest::new_from_nym(return_recipient, request_vu8.as_ref())?; -// match self.queue.try_send(zingo_proxy_request) { -// Ok(_) => {} -// Err(QueueError::QueueFull(_request)) => { -// eprintln!("Queue Full."); -// // TODO: Return queue full tonic status over mixnet. -// } -// Err(e) => { -// eprintln!("Queue Closed. Failed to send request to queue: {}", e); -// // TODO: Handle queue closed error here. -// } -// } -// } -// None => { -// eprintln!("Failed to receive message from Nym network."); -// // TODO: Error in nym client, handle error here (restart ingestor?). -// } -// } -// } -// outgoing = self.response_queue.listen() => { -// match outgoing { -// Ok(response) => { -// println!("[TEST] Dispatcher received response: {:?}", response); -// // NOTE: This may need to be removed / moved for scale use. -// if self.check_for_shutdown().await { -// self.status.store(5); -// return Ok(()); -// } -// if let Err(nym_e) = self.ingestor -// .client -// .send_reply(response.1, response.0.clone()) -// .await.map_err(NymError::from) { -// eprintln!("Failed to send response over Nym Mixnet: {}", nym_e); -// match self.response_requeue.try_send(response) { -// Ok(_) => { -// eprintln!("Failed to send response over nym: {}\nResponse requeued, restarting nym dispatcher.", nym_e); -// // TODO: Handle error. Restart nym dispatcher. -// } -// Err(QueueError::QueueFull(_request)) => { -// eprintln!("Failed to send response over nym: {}\nAnd failed to requeue response due to full response queue.\nFatal error! Restarting nym dispatcher.", nym_e); -// // TODO: Handle queue full error here (start up second dispatcher?). Restart nym dispatcher -// } -// Err(_e) => { -// eprintln!("Failed to send response over nym: {}\nAnd failed to requeue response due to the queue being closed.\nFatal error! Nym dispatcher shutting down..", nym_e); -// // TODO: Handle queue closed error here. (return correct error type?) -// self.status.store(6); -// return Ok(()); //Return Err! -// } -// } -// } -// } -// Err(_e) => { -// eprintln!("Response queue closed, nym dispatcher shutting down."); -// //TODO: Handle this error here (return correct error type?) -// self.status.store(6); -// return Ok(()); // Return Err! -// } -// } -// } -// } -// } -// }) -// } - -// /// Checks indexers online status and ingestors internal status for closure signal. -// pub(crate) async fn check_for_shutdown(&self) -> bool { -// if self.status() >= 4 { -// return true; -// } -// if !self.check_online() { -// return true; -// } -// false -// } - -// /// Sets the ingestor to close gracefully. -// pub(crate) async fn _shutdown(&mut self) { -// self.status.store(4) -// } - -// /// Returns the ingestor current status usize. -// pub(crate) fn status(&self) -> usize { -// self.status.load() -// } - -// /// Returns the ingestor current statustype. -// pub(crate) fn _statustype(&self) -> StatusType { -// StatusType::from(self.status()) -// } - -// fn check_online(&self) -> bool { -// self.online.load(Ordering::SeqCst) -// } -// } diff --git a/zaino-serve/src/server/request.rs b/zaino-serve/src/server/request.rs index d085cac..cf5c449 100644 --- a/zaino-serve/src/server/request.rs +++ b/zaino-serve/src/server/request.rs @@ -1,10 +1,8 @@ //! Request types. use crate::server::error::RequestError; -// use nym_sphinx_anonymous_replies::requests::AnonymousSenderTag; use std::time::SystemTime; use tokio::net::TcpStream; -// use zaino_nym::utils::read_nym_request_data; /// Requests queuing metadata. #[derive(Debug, Clone)] @@ -42,37 +40,6 @@ impl QueueData { } } -// /// Nym request data. -// #[derive(Debug, Clone)] -// pub struct NymRequest { -// id: u64, -// method: String, -// metadata: AnonymousSenderTag, -// body: Vec, -// } - -// impl NymRequest { -// /// Returns the client assigned id for this request, only used to construct response. -// pub fn client_id(&self) -> u64 { -// self.id -// } - -// /// Returns the RPC being called by the request. -// pub fn method(&self) -> String { -// self.method.clone() -// } - -// /// Returns request metadata including sender data. -// pub fn metadata(&self) -> AnonymousSenderTag { -// self.metadata -// } - -// /// Returns the request body. -// pub fn body(&self) -> Vec { -// self.body.clone() -// } -// } - /// TcpStream holing an incoming gRPC request. #[derive(Debug)] pub struct TcpRequest(TcpStream); @@ -84,20 +51,6 @@ impl TcpRequest { } } -// /// Requests originating from the Nym server. -// #[derive(Debug, Clone)] -// pub struct NymServerRequest { -// queuedata: QueueData, -// request: NymRequest, -// } - -// impl NymServerRequest { -// /// Returns the underlying request. -// pub fn get_request(&self) -> NymRequest { -// self.request.clone() -// } -// } - /// Requests originating from the Tcp server. #[derive(Debug)] pub struct TcpServerRequest { @@ -113,31 +66,13 @@ impl TcpServerRequest { } /// Zingo-Indexer request, used by request queue. -/// -/// Temporarily removed until nym dependency conflic can be resolved. #[derive(Debug)] pub enum ZingoIndexerRequest { - // /// Requests originating from the Nym server. - // NymServerRequest(NymServerRequest), /// Requests originating from the gRPC server. TcpServerRequest(TcpServerRequest), } impl ZingoIndexerRequest { - // /// Creates a ZingoIndexerRequest from an encoded gRPC service call, recieved by the Nym server. - // pub fn new_from_nym(metadata: AnonymousSenderTag, bytes: &[u8]) -> Result { - // let (id, method, body) = read_nym_request_data(bytes)?; - // Ok(ZingoIndexerRequest::NymServerRequest(NymServerRequest { - // queuedata: QueueData::new(), - // request: NymRequest { - // id, - // method, - // metadata, - // body: body.to_vec(), - // }, - // })) - // } - /// Creates a ZingoIndexerRequest from a gRPC service call, recieved by the gRPC server. /// /// TODO: implement proper functionality along with queue. @@ -151,7 +86,6 @@ impl ZingoIndexerRequest { /// Increases the requeue attempts for the request. pub fn increase_requeues(&mut self) { match self { - // ZingoIndexerRequest::NymServerRequest(ref mut req) => req.queuedata.increase_requeues(), ZingoIndexerRequest::TcpServerRequest(ref mut req) => req.queuedata.increase_requeues(), } } @@ -159,7 +93,6 @@ impl ZingoIndexerRequest { /// Returns the duration sunce the request was received. pub fn duration(&self) -> Result { match self { - // ZingoIndexerRequest::NymServerRequest(ref req) => req.queuedata.duration(), ZingoIndexerRequest::TcpServerRequest(ref req) => req.queuedata.duration(), } } @@ -167,7 +100,6 @@ impl ZingoIndexerRequest { /// Returns the number of times the request has been requeued. pub fn requeues(&self) -> u32 { match self { - // ZingoIndexerRequest::NymServerRequest(ref req) => req.queuedata.requeues(), ZingoIndexerRequest::TcpServerRequest(ref req) => req.queuedata.requeues(), } } diff --git a/zaino-serve/src/server/worker.rs b/zaino-serve/src/server/worker.rs index 02219ba..4c6db84 100644 --- a/zaino-serve/src/server/worker.rs +++ b/zaino-serve/src/server/worker.rs @@ -6,7 +6,6 @@ use std::sync::{ }; use http::Uri; -// use nym_sphinx_anonymous_replies::requests::AnonymousSenderTag; use tonic::transport::Server; use crate::{ @@ -19,12 +18,8 @@ use crate::{ }, }; -#[cfg(not(feature = "nym_poc"))] use zaino_proto::proto::service::compact_tx_streamer_server::CompactTxStreamerServer; -#[cfg(feature = "nym_poc")] -use zcash_client_backend::proto::service::compact_tx_streamer_server::CompactTxStreamerServer; - /// A queue working is the entity that takes requests from the queue and processes them. /// /// TODO: - Add JsonRpcConnector to worker and pass to underlying RPC services. @@ -37,8 +32,6 @@ pub(crate) struct Worker { queue: QueueReceiver, /// Used to requeue requests. requeue: QueueSender, - // /// Used to send responses to the nym_dispatcher. - // nym_response_queue: QueueSender<(Vec, AnonymousSenderTag)>, /// gRPC client used for processing requests received over http. grpc_client: GrpcClient, /// Thread safe worker status. @@ -54,7 +47,6 @@ impl Worker { _worker_id: usize, queue: QueueReceiver, requeue: QueueSender, - // nym_response_queue: QueueSender<(Vec, AnonymousSenderTag)>, lightwalletd_uri: Uri, zebrad_uri: Uri, atomic_status: AtomicStatus, @@ -69,7 +61,6 @@ impl Worker { _worker_id, queue, requeue, - // nym_response_queue, grpc_client, atomic_status, online, @@ -108,33 +99,6 @@ impl Worker { ) .await?; } - // ZingoIndexerRequest::NymServerRequest(request) => { - // match self.grpc_client - // .process_nym_request(&request) - // .await { - // Ok(response) => { - // match self.nym_response_queue.try_send((response, request.get_request().metadata())) { - // Ok(_) => {} - // Err(QueueError::QueueFull(_request)) => { - // eprintln!("Response Queue Full."); - // // TODO: Handle this error! (open second nym responder?). - // } - // Err(e) => { - // self.atomic_status.store(5); - // eprintln!("Response Queue Closed. Failed to send response to queue: {}\nWorker shutting down.", e); - // // TODO: Handle queue closed error here. (return correct error?) - // return Ok(()); - // } - // } - // } - // Err(e) => { - // eprintln!("Failed to process nym received request: {}", e); - // // TODO:: Handle this error! - - // } - - // } - // } } // NOTE: This may need to be removed for scale use. if self.check_for_shutdown().await { @@ -241,7 +205,6 @@ impl WorkerPool { idle_size: u16, queue: QueueReceiver, _requeue: QueueSender, - // nym_response_queue: QueueSender<(Vec, AnonymousSenderTag)>, lightwalletd_uri: Uri, zebrad_uri: Uri, status: WorkerPoolStatus, @@ -254,7 +217,6 @@ impl WorkerPool { workers.len(), queue.clone(), _requeue.clone(), - // nym_response_queue.clone(), lightwalletd_uri.clone(), zebrad_uri.clone(), status.statuses[workers.len()].clone(), @@ -295,7 +257,6 @@ impl WorkerPool { worker_index, self.workers[0].queue.clone(), self.workers[0].requeue.clone(), - // self.workers[0].nym_response_queue.clone(), self.workers[0].grpc_client.lightwalletd_uri.clone(), self.workers[0].grpc_client.zebrad_uri.clone(), self.status.statuses[worker_index].clone(), diff --git a/zaino-testutils/Cargo.toml b/zaino-testutils/Cargo.toml index 042ea21..95322e9 100644 --- a/zaino-testutils/Cargo.toml +++ b/zaino-testutils/Cargo.toml @@ -8,9 +8,6 @@ license = { workspace = true } repository = { workspace = true } [features] -# NOTE: Deprecated -nym_poc = [] - # Used by zcash-local-net: test_fixtures = [] @@ -20,9 +17,6 @@ zainod = { path = "../zainod" } # ZingoLib zingolib = { workspace = true } -# zingolib = { git = "https://github.com/idky137/zingolib.git", branch = "zaino_temp_dep", features = ["zaino-test"] } -# zingolib = { path = "../../zingolib/zingolib", features = ["zaino-test"] } - # Miscellaneous Workspace tokio = { workspace = true } diff --git a/zaino-testutils/src/lib.rs b/zaino-testutils/src/lib.rs index a2a7763..4e9f166 100644 --- a/zaino-testutils/src/lib.rs +++ b/zaino-testutils/src/lib.rs @@ -9,17 +9,14 @@ static CTRL_C_ONCE: std::sync::Once = std::sync::Once::new(); /// Configuration data for Zingo-Indexer Tests. pub struct TestManager { - /// Temporary Directory for nym, zcashd and lightwalletd configuration and regtest data. + /// Temporary Directory for zcashd and lightwalletd configuration and regtest data. pub temp_conf_dir: tempfile::TempDir, - // std::path::PathBuf, /// Zingolib regtest manager. pub regtest_manager: zingolib::testutils::regtest::RegtestManager, /// Zingolib regtest network. pub regtest_network: zingolib::config::RegtestNetwork, /// Zingo-Indexer gRPC listen port. pub indexer_port: u16, - /// Zingo-Indexer Nym listen address. - pub nym_addr: Option, /// Zebrad/Zcashd JsonRpc listen port. pub zebrad_port: u16, /// Online status of Zingo-Indexer. @@ -41,7 +38,6 @@ impl TestManager { let temp_conf_dir = create_temp_conf_files(lwd_port, zebrad_port).unwrap(); let temp_conf_path = temp_conf_dir.path().to_path_buf(); - let _nym_conf_path = temp_conf_path.join("nym"); set_custom_drops(online.clone(), Some(temp_conf_path.clone())); @@ -53,13 +49,10 @@ impl TestManager { .launch(true) .expect("Failed to start regtest services"); - // TODO: This turns nym functionality off. for nym tests we will need to add option to include nym in test manager. - // - queue and workerpool sizes may need to be changed here. + // NOTE: queue and workerpool sizes may need to be changed here. let indexer_config = zainodlib::config::IndexerConfig { tcp_active: true, listen_port: Some(indexer_port), - nym_active: false, - nym_conf_path: None, lightwalletd_port: lwd_port, zebrad_port, node_user: Some("xxxxxx".to_string()), @@ -80,7 +73,6 @@ impl TestManager { regtest_manager, regtest_network, indexer_port, - nym_addr: None, zebrad_port, online, }, diff --git a/zaino-wallet/Cargo.toml b/zaino-wallet/Cargo.toml deleted file mode 100644 index b99ed2f..0000000 --- a/zaino-wallet/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "zaino-wallet" -version = "0.1.0" -description = "Crate containing Zingo's client-side, nym-enhanced, LightWallet RPC Implementations." -edition = { workspace = true } -authors = { workspace = true } -license = { workspace = true } -repository = { workspace = true } - -[dependencies] -zaino-proto = { path = "../zaino-proto" } -zaino-fetch = { path = "../zaino-fetch" } -zaino-nym = { path = "../zaino-nym" } - -# NymSdk -nym-sdk = { workspace = true } -nym-sphinx-addressing = { workspace = true } -nym-sphinx-anonymous-replies = { workspace = true } - -# Miscellaneous Workspace -tonic = { workspace = true } -http = { workspace = true } - -# Miscellaneous Crate -prost = "0.13" -bytes = "1.6" -http-body = "0.4" # update to "v1.0" diff --git a/zaino-wallet/src/lib.rs b/zaino-wallet/src/lib.rs deleted file mode 100644 index 80d702a..0000000 --- a/zaino-wallet/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Crate containing Zingo's client-side, nym-enhanced, LightWallet RPC Implementations. - -#![warn(missing_docs)] -#![forbid(unsafe_code)] - -pub mod service; -pub mod utils; diff --git a/zaino-wallet/src/service.rs b/zaino-wallet/src/service.rs deleted file mode 100644 index 46fe52a..0000000 --- a/zaino-wallet/src/service.rs +++ /dev/null @@ -1,467 +0,0 @@ -//! Wrapper implementation of LibRustZCash's CompactTXStreamerClient that also holds nym-enabled implementations. -//! -//! NOTE: Currently only send_transaction has been implemented over nym. - -use bytes::Bytes; -use http::Uri; -use http_body::Body; -use std::error::Error as StdError; -use tonic::{self, codec::CompressionEncoding, Status}; -use tonic::{service::interceptor::InterceptedService, transport::Endpoint}; - -use crate::utils::{deserialize_response, serialize_request, write_nym_request_data}; -use zaino_nym::client::NymClient; -use zaino_proto::proto::{ - compact_formats::{CompactBlock, CompactTx}, - service::{ - compact_tx_streamer_client::CompactTxStreamerClient, Address, AddressList, Balance, - BlockId, BlockRange, ChainSpec, Duration, Empty, Exclude, GetAddressUtxosArg, - GetAddressUtxosReply, GetAddressUtxosReplyList, GetSubtreeRootsArg, LightdInfo, - PingResponse, RawTransaction, SendResponse, SubtreeRoot, TransparentAddressBlockFilter, - TreeState, TxFilter, - }, -}; - -/// Wrapper struct for the Nym enabled CompactTxStreamerClient. -#[derive(Debug, Clone)] -pub struct NymTxStreamerClient { - /// LibRustZcash's CompactTxStreamerClient. - pub compact_tx_streamer_client: CompactTxStreamerClient, -} - -impl NymTxStreamerClient { - /// Attempt to create a new client by connecting to a given endpoint. - pub async fn connect(dst: D) -> Result - where - D: TryInto, - D::Error: Into> + Send + Sync + 'static, - >::Error: std::error::Error, - { - let client = CompactTxStreamerClient::connect(dst).await?; - Ok(Self { - compact_tx_streamer_client: client, - }) - } -} - -impl NymTxStreamerClient -where - T: tonic::client::GrpcService + Send + 'static, - T::Error: - std::error::Error + Into> + Send + Sync, - T::ResponseBody: Body + Send + 'static, - ::Error: - std::error::Error + Into> + Send + Sync, -{ - /// Creates a new gRPC clientwith the provided [`GrpcService`]. - pub fn new(inner: T) -> Self { - Self { - compact_tx_streamer_client: CompactTxStreamerClient::new(inner), - } - } - - /// Creates a new gRPC client with the provided [`GrpcService`] and `Uri`. - /// - /// The provided Uri will use only the scheme and authority parts as the path_and_query portion will be set for each method. - pub fn with_origin(inner: T, origin: Uri) -> Self { - Self { - compact_tx_streamer_client: CompactTxStreamerClient::with_origin(inner, origin), - } - } - - /// Creates a new service with interceptor middleware. - pub fn with_interceptor( - inner: T, - interceptor: F, - ) -> CompactTxStreamerClient> - where - F: tonic::service::Interceptor, - T::ResponseBody: Default, - T: tonic::codegen::Service< - http::Request, - Response = http::Response< - >::ResponseBody, - >, - >, - >>::Error: - Into> + Send + Sync + 'static, - >, - >>::Error: std::error::Error, - { - CompactTxStreamerClient::new(InterceptedService::new(inner, interceptor)) - } - - /// Compress requests with the given encoding. - /// - /// This requires the server to support it otherwise it might respond with an error. - #[must_use] - pub fn send_compressed(self, encoding: CompressionEncoding) -> Self { - Self { - compact_tx_streamer_client: CompactTxStreamerClient::send_compressed( - self.compact_tx_streamer_client, - encoding, - ), - } - } - - /// Enable decompressing responses. - #[must_use] - pub fn accept_compressed(self, encoding: CompressionEncoding) -> Self { - Self { - compact_tx_streamer_client: CompactTxStreamerClient::accept_compressed( - self.compact_tx_streamer_client, - encoding, - ), - } - } - - /// Limits the maximum size of a decoded message. - /// - /// Default: `4MB` - #[must_use] - pub fn max_decoding_message_size(self, limit: usize) -> Self { - Self { - compact_tx_streamer_client: CompactTxStreamerClient::max_decoding_message_size( - self.compact_tx_streamer_client, - limit, - ), - } - } - - /// Limits the maximum size of an encoded message. - /// - /// Default: `usize::MAX` - #[must_use] - pub fn max_encoding_message_size(self, limit: usize) -> Self { - Self { - compact_tx_streamer_client: CompactTxStreamerClient::max_encoding_message_size( - self.compact_tx_streamer_client, - limit, - ), - } - } - - /// Return the height of the tip of the best chain. - pub async fn get_latest_block( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_latest_block(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Return the compact block corresponding to the given block identifier. - pub async fn get_block( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_block(&mut self.compact_tx_streamer_client, request).await - } - - /// Same as GetBlock except actions contain only nullifiers. - pub async fn get_block_nullifiers( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_block_nullifiers(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Return a list of consecutive compact blocks - pub async fn get_block_range( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result>, tonic::Status> - { - CompactTxStreamerClient::get_block_range(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Same as GetBlockRange except actions contain only nullifiers. - pub async fn get_block_range_nullifiers( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result>, tonic::Status> - { - CompactTxStreamerClient::get_block_range_nullifiers( - &mut self.compact_tx_streamer_client, - request, - ) - .await - } - - /// Return the requested full (not compact) transaction (as from zcashd). - pub async fn get_transaction( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_transaction(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Submit the given transaction to the Zcash network. - /// - /// If nym_addr is provided, the transaction is encoded and sent over the Nym mixnet. - pub async fn send_transaction( - &mut self, - request: impl tonic::IntoRequest, - nym_addr: Option<&str>, - ) -> std::result::Result, Status> { - match nym_addr { - Some(addr) => { - match nym_sphinx_addressing::clients::Recipient::try_from_base58_string(addr) { - Ok(_recipient) => { - let serialized_request = - match serialize_request(&request.into_request().into_inner()).await { - Ok(data) => data, - Err(e) => { - return Err(Status::internal(format!( - "Failed to serialize request: {}", - e - ))) - } - }; - let nym_request = match write_nym_request_data( - 0, - "SendTransaction".to_string(), - serialized_request.as_ref(), - ) { - Ok(data) => data, - Err(e) => { - return Err(Status::internal(format!( - "Failed to write nym request data: {}", - e - ))) - } - }; - let nym_conf_path = "/tmp/nym_client"; - let mut client = NymClient::spawn(nym_conf_path).await?; - let response_data = client.send(addr, nym_request).await?; - client.close().await; - let response: SendResponse = - match deserialize_response(response_data.as_slice()).await { - Ok(res) => res, - Err(e) => { - return Err(Status::internal(format!( - "Failed to decode response: {}", - e - ))) - } - }; - Ok(tonic::Response::new(response)) - } - Err(e) => { - Err(Status::invalid_argument(format!( - "Failed to parse nym address: {}", - e - ))) - } - } - } - None => { - CompactTxStreamerClient::send_transaction( - &mut self.compact_tx_streamer_client, - request, - ) - .await - } - } - } - - /// Return the txids corresponding to the given t-address within the given block range. - pub async fn get_taddress_txids( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result>, tonic::Status> - { - CompactTxStreamerClient::get_taddress_txids(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Return the balance corresponding to the given t-address. - pub async fn get_taddress_balance( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_taddress_balance(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Return the balance corresponding to the given t-address. - /// - /// TODO: Doc comment is ambiguous, add correct information. - pub async fn get_taddress_balance_stream( - &mut self, - request: impl tonic::IntoStreamingRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_taddress_balance_stream( - &mut self.compact_tx_streamer_client, - request, - ) - .await - } - - /// Return the compact transactions currently in the mempool; the results - /// can be a few seconds out of date. If the Exclude list is empty, return - /// all transactions; otherwise return all *except* those in the Exclude list - /// (if any); this allows the client to avoid receiving transactions that it - /// already has (from an earlier call to this rpc). The transaction IDs in the - /// Exclude list can be shortened to any number of bytes to make the request - /// more bandwidth-efficient; if two or more transactions in the mempool - /// match a shortened txid, they are all sent (none is excluded). Transactions - /// in the exclude list that don't exist in the mempool are ignored. - pub async fn get_mempool_tx( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result>, tonic::Status> - { - CompactTxStreamerClient::get_mempool_tx(&mut self.compact_tx_streamer_client, request).await - } - - /// Return a stream of current Mempool transactions. This will keep the output stream open while - /// there are mempool transactions. It will close the returned stream when a new block is mined. - pub async fn get_mempool_stream( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result>, tonic::Status> - { - CompactTxStreamerClient::get_mempool_stream(&mut self.compact_tx_streamer_client, request) - .await - } - - /// GetTreeState returns the note commitment tree state corresponding to the given block. - /// See section 3.7 of the Zcash protocol specification. It returns several other useful - /// values also (even though they can be obtained using GetBlock). - /// The block can be specified by either height or hash. - pub async fn get_tree_state( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_tree_state(&mut self.compact_tx_streamer_client, request).await - } - - /// Returns the note commitment tree state. - /// - /// TODO: Doc comment is ambiguous, add correct information. - pub async fn get_latest_tree_state( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_latest_tree_state( - &mut self.compact_tx_streamer_client, - request, - ) - .await - } - - /// Returns a stream of information about roots of subtrees of the Sapling and Orchard - /// note commitment trees. - pub async fn get_subtree_roots( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result>, tonic::Status> - { - CompactTxStreamerClient::get_subtree_roots(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Returns utxos belonging to the given address. - pub async fn get_address_utxos( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::get_address_utxos(&mut self.compact_tx_streamer_client, request) - .await - } - - /// Returns stream of utxos belonging to the given address. - pub async fn get_address_utxos_stream( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result< - tonic::Response>, - tonic::Status, - > { - CompactTxStreamerClient::get_address_utxos_stream( - &mut self.compact_tx_streamer_client, - request, - ) - .await - } - - /// Return information about this lightwalletd instance and the blockchain. - pub async fn get_lightd_info( - &mut self, - request: impl tonic::IntoRequest, - nym_addr: Option<&str>, - ) -> std::result::Result, tonic::Status> { - match nym_addr { - Some(addr) => { - match nym_sphinx_addressing::clients::Recipient::try_from_base58_string(addr) { - Ok(_recipient) => { - let serialized_request = - match serialize_request(&request.into_request().into_inner()).await { - Ok(data) => data, - Err(e) => { - return Err(Status::internal(format!( - "Failed to serialize request: {}", - e - ))) - } - }; - let nym_request = match write_nym_request_data( - 0, - "GetLightdInfo".to_string(), - serialized_request.as_ref(), - ) { - Ok(data) => data, - Err(e) => { - return Err(Status::internal(format!( - "Failed to write nym request data: {}", - e - ))) - } - }; - let nym_conf_path = "/tmp/nym_client"; - let mut client = NymClient::spawn(nym_conf_path).await?; - let response_data = client.send(addr, nym_request).await?; - client.close().await; - let response: LightdInfo = - match deserialize_response(response_data.as_slice()).await { - Ok(res) => res, - Err(e) => { - return Err(Status::internal(format!( - "Failed to decode response: {}", - e - ))) - } - }; - Ok(tonic::Response::new(response)) - } - Err(e) => { - Err(Status::invalid_argument(format!( - "Failed to parse nym address: {}", - e - ))) - } - } - } - None => { - CompactTxStreamerClient::get_lightd_info( - &mut self.compact_tx_streamer_client, - request, - ) - .await - } - } - } - - /// Testing-only, requires lightwalletd --ping-very-insecure (do not enable in production). - pub async fn ping( - &mut self, - request: impl tonic::IntoRequest, - ) -> std::result::Result, tonic::Status> { - CompactTxStreamerClient::ping(&mut self.compact_tx_streamer_client, request).await - } -} diff --git a/zaino-wallet/src/utils.rs b/zaino-wallet/src/utils.rs deleted file mode 100644 index 8697d5d..0000000 --- a/zaino-wallet/src/utils.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! Utility functions for wallet side nym code. - -use zaino_nym::error::NymError; -use zaino_fetch::chain::{error::ParseError, utils::CompactSize}; - -/// Serialises gRPC request to a buffer. -pub async fn serialize_request( - request: &T, -) -> std::io::Result> { - let mut buf = Vec::new(); - request.encode(&mut buf)?; - Ok(buf) -} - -/// Decodes gRPC request from a buffer -pub async fn deserialize_response(data: &[u8]) -> Result { - T::decode(data).map_err(|e| NymError::from(ParseError::from(e))) -} - -/// Prepends an encoded tonic request with metadata required by the Nym server. -/// -/// Encodes the request ID as a Zcash CompactSize [u64]. -/// Encodes the RPC method String into a Vec prepended by a Zcash CompactSize indicating its length in bytes. -pub fn write_nym_request_data(id: u64, method: String, body: &[u8]) -> Result, NymError> { - let method_bytes = method.into_bytes(); - let mut buffer = Vec::new(); - CompactSize::write(&mut buffer, id as usize).map_err(ParseError::Io)?; - CompactSize::write(&mut buffer, method_bytes.len()).map_err(ParseError::Io)?; - buffer.extend(method_bytes); - CompactSize::write(&mut buffer, body.len()).map_err(ParseError::Io)?; - buffer.extend(body); - Ok(buffer) -} diff --git a/zainod/Cargo.toml b/zainod/Cargo.toml index f03381e..359f4bc 100644 --- a/zainod/Cargo.toml +++ b/zainod/Cargo.toml @@ -15,18 +15,10 @@ path = "src/main.rs" name = "zainodlib" path = "src/lib.rs" -[features] -# NOTE: Deprecated -nym_poc = [] - [dependencies] zaino-fetch = { path = "../zaino-fetch" } zaino-serve = { path = "../zaino-serve" } -# Temporarily removed until dependency conflic can be resolved. -# NymSdk -# nym-bin-common = { workspace = true } - # Miscellaneous Workspace tokio = { workspace = true, features = ["full"] } http = { workspace = true } diff --git a/zainod/src/config.rs b/zainod/src/config.rs index d065059..2628419 100644 --- a/zainod/src/config.rs +++ b/zainod/src/config.rs @@ -1,7 +1,6 @@ //! Zaino config. use crate::error::IndexerError; -use std::path::Path; /// Config information required for Zaino. #[derive(Debug, Clone, serde::Deserialize)] @@ -10,12 +9,8 @@ pub struct IndexerConfig { pub tcp_active: bool, /// TcpIngestors listen port pub listen_port: Option, - /// Sets the NymIngestor's and NymDispatchers status. - pub nym_active: bool, - /// Nym conf path used for micnet client conf. - pub nym_conf_path: Option, /// LightWalletD listen port [DEPRECATED]. - /// Used by nym_poc and zingo-testutils. + /// Used by zingo-testutils. pub lightwalletd_port: u16, /// Full node / validator listen port. pub zebrad_port: u16, @@ -34,13 +29,12 @@ pub struct IndexerConfig { impl IndexerConfig { /// Performs checks on config data. /// - /// - Checks that at least 1 of nym or tpc is active. + /// - Checks that at least 1 ingestor is active. /// - Checks listen port is given is tcp is active. - /// - Checks nym_conf_path is given if nym is active and holds a valid utf8 string. pub fn check_config(&self) -> Result<(), IndexerError> { - if (!self.tcp_active) && (!self.nym_active) { + if !self.tcp_active { return Err(IndexerError::ConfigError( - "Cannot start server with no ingestors selected, at least one of either nym or tcp must be set to active in conf.".to_string(), + "Cannot start server with no ingestors selected.".to_string(), )); } if self.tcp_active && self.listen_port.is_none() { @@ -48,29 +42,15 @@ impl IndexerConfig { "TCP is active but no address provided.".to_string(), )); } - if let Some(path_str) = self.nym_conf_path.clone() { - if Path::new(&path_str).to_str().is_none() { - return Err(IndexerError::ConfigError( - "Invalid nym conf path syntax or non-UTF-8 characters in path.".to_string(), - )); - } - } else if self.nym_active { - return Err(IndexerError::ConfigError( - "NYM is active but no conf path provided.".to_string(), - )); - } Ok(()) } } -#[cfg(not(feature = "nym_poc"))] impl Default for IndexerConfig { fn default() -> Self { Self { tcp_active: true, listen_port: Some(8080), - nym_active: true, - nym_conf_path: Some("/tmp/indexer/nym".to_string()), lightwalletd_port: 9067, zebrad_port: 18232, node_user: Some("xxxxxx".to_string()), @@ -82,25 +62,6 @@ impl Default for IndexerConfig { } } -#[cfg(feature = "nym_poc")] -impl Default for IndexerConfig { - fn default() -> Self { - Self { - tcp_active: true, - listen_port: Some(8088), - nym_active: false, - nym_conf_path: None, - lightwalletd_port: 8080, - zebrad_port: 18232, - node_user: Some("xxxxxx".to_string()), - node_password: Some("xxxxxx".to_string()), - max_queue_size: 1024, - max_worker_pool_size: 32, - idle_worker_pool_size: 4, - } - } -} - /// Attempts to load config data from a toml file at the specified path. pub fn load_config(file_path: &std::path::PathBuf) -> IndexerConfig { let mut config = IndexerConfig::default(); @@ -110,8 +71,6 @@ pub fn load_config(file_path: &std::path::PathBuf) -> IndexerConfig { config = IndexerConfig { tcp_active: parsed_config.tcp_active, listen_port: parsed_config.listen_port.or(config.listen_port), - nym_active: parsed_config.nym_active, - nym_conf_path: parsed_config.nym_conf_path.or(config.nym_conf_path), lightwalletd_port: parsed_config.lightwalletd_port, zebrad_port: parsed_config.zebrad_port, node_user: parsed_config.node_user.or(config.node_user), diff --git a/zainod/src/indexer.rs b/zainod/src/indexer.rs index c20df38..71169fc 100644 --- a/zainod/src/indexer.rs +++ b/zainod/src/indexer.rs @@ -80,9 +80,6 @@ impl Indexer { ) -> Result>, IndexerError> { // NOTE: This interval may need to be reduced or removed / moved once scale testing begins. let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(50)); - // if config.nym_active { - // nym_bin_common::logging::setup_logging(); - // } println!("Launching Zingdexer!"); let mut indexer: Indexer = Indexer::new(config, online.clone()).await?; Ok(tokio::task::spawn(async move { @@ -135,8 +132,6 @@ impl Indexer { Server::spawn( config.tcp_active, tcp_ingestor_listen_addr, - config.nym_active, - config.nym_conf_path.clone(), lightwalletd_uri, zebrad_uri, config.max_queue_size, @@ -241,7 +236,7 @@ fn startup_message() { - Donate to us at https://free2z.cash/zingolabs. - Submit any security conserns to us at zingodisclosure@proton.me. -****** Please note Zingdexer is currently in development and should not be used to run mainnet nodes. ****** +****** Please note Zaino is currently in development and should not be used to run mainnet nodes. ****** "#; println!("{}", welcome_message); } diff --git a/zainod/zindexer.toml b/zainod/zindexer.toml index e3fe3ab..ba7b650 100644 --- a/zainod/zindexer.toml +++ b/zainod/zindexer.toml @@ -6,12 +6,6 @@ tcp_active = true # Optional TcpIngestors listen port (use None or specify a port number) listen_port = 8137 -# Sets the NymIngestor's and NymDispatchers status (true or false) -nym_active = true - -# Optional Nym conf path used for micnet client conf -nym_conf_path = "/tmp/indexer/nym" - # LightWalletD listen port [DEPRECATED] lightwalletd_port = 9067