diff --git a/Cargo.lock b/Cargo.lock index b315759900..7d61a368d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4860,13 +4860,11 @@ dependencies = [ "anyhow", "async-trait", "axum 0.7.9", - "axum-extra", "axum-test 16.4.1", "bincode", "bip39", "bs58", "cfg-if", - "chrono", "clap", "console-subscriber", "cosmwasm-std", @@ -4875,13 +4873,9 @@ dependencies = [ "cw3", "cw4", "dashmap", - "dirs", "dotenv", "futures", - "getset", "humantime-serde", - "itertools 0.14.0", - "k256", "moka", "nym-api-requests 0.1.0", "nym-bandwidth-controller", @@ -4896,12 +4890,11 @@ dependencies = [ "nym-crypto 0.4.0", "nym-dkg", "nym-ecash-contract-common 0.1.0", + "nym-ecash-signer-check", "nym-ecash-time 0.1.0", "nym-gateway-client", "nym-http-api-common 0.1.0", - "nym-inclusion-probability", "nym-mixnet-contract-common 0.6.0", - "nym-multisig-contract-common 0.1.0", "nym-node-requests 0.1.0", "nym-node-tester-utils", "nym-pemstore 0.3.0", @@ -4913,7 +4906,6 @@ dependencies = [ "nym-topology 0.1.0", "nym-types", "nym-validator-client 0.1.0", - "nym-vesting-contract-common 0.7.0", "pin-project", "rand 0.8.5", "rand_chacha 0.3.1", @@ -4949,14 +4941,15 @@ dependencies = [ "cosmrs", "cosmwasm-std", "ecdsa", - "getset", "hex", "humantime-serde", + "nym-coconut-dkg-common 0.1.0", "nym-compact-ecash 0.1.0", "nym-config 0.1.0", "nym-contracts-common 0.5.0", "nym-credentials-interface 0.1.0", "nym-crypto 0.4.0", + "nym-ecash-signer-check-types", "nym-ecash-time 0.1.0", "nym-mixnet-contract-common 0.6.0", "nym-network-defaults 0.1.0", @@ -5060,6 +5053,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.12", + "time", "tokio", "tokio-stream", "tokio-util", @@ -5674,9 +5668,11 @@ dependencies = [ name = "nym-credential-verification" version = "0.1.0" dependencies = [ + "async-trait", "bs58", "cosmwasm-std", "cw-utils", + "dyn-clone", "futures", "nym-api-requests 0.1.0", "nym-credentials", @@ -5859,6 +5855,36 @@ dependencies = [ "thiserror 2.0.12", ] +[[package]] +name = "nym-ecash-signer-check" +version = "0.1.0" +dependencies = [ + "futures", + "nym-ecash-signer-check-types", + "nym-network-defaults 0.1.0", + "nym-validator-client 0.1.0", + "semver 1.0.26", + "thiserror 2.0.12", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "nym-ecash-signer-check-types" +version = "0.1.0" +dependencies = [ + "nym-coconut-dkg-common 0.1.0", + "nym-crypto 0.4.0", + "semver 1.0.26", + "serde", + "thiserror 2.0.12", + "time", + "tracing", + "url", + "utoipa", +] + [[package]] name = "nym-ecash-time" version = "0.1.0" @@ -6060,8 +6086,10 @@ dependencies = [ name = "nym-gateway-storage" version = "0.1.0" dependencies = [ + "async-trait", "bincode", "defguard_wireguard_rs", + "dyn-clone", "nym-credentials-interface 0.1.0", "nym-gateway-requests", "nym-sphinx 0.1.0", @@ -7989,11 +8017,13 @@ dependencies = [ name = "nym-wireguard" version = "0.1.0" dependencies = [ + "async-trait", "base64 0.22.1", "bincode", "chrono", "dashmap", "defguard_wireguard_rs", + "dyn-clone", "futures", "ip_network", "log", @@ -13144,3 +13174,20 @@ dependencies = [ "cc", "pkg-config", ] + +[[package]] +name = "zulip-client" +version = "0.1.0" +dependencies = [ + "itertools 0.14.0", + "nym-bin-common 0.6.0", + "nym-http-api-client 0.1.0", + "reqwest 0.12.22", + "serde", + "serde_json", + "thiserror 2.0.12", + "tokio", + "tracing", + "url", + "zeroize", +] diff --git a/Cargo.toml b/Cargo.toml index 672a690c05..1bee069b76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,8 @@ members = [ "common/cosmwasm-smart-contracts/ecash-contract", "common/cosmwasm-smart-contracts/group-contract", "common/cosmwasm-smart-contracts/mixnet-contract", - "common/cosmwasm-smart-contracts/multisig-contract", "common/cosmwasm-smart-contracts/nym-performance-contract", + "common/cosmwasm-smart-contracts/multisig-contract", + "common/cosmwasm-smart-contracts/nym-performance-contract", "common/cosmwasm-smart-contracts/nym-pool-contract", "common/cosmwasm-smart-contracts/vesting-contract", "common/credential-storage", @@ -49,6 +50,8 @@ members = [ "common/credentials-interface", "common/crypto", "common/dkg", + "common/ecash-signer-check", + "common/ecash-signer-check-types", "common/ecash-time", "common/execute", "common/exit-policy", @@ -99,7 +102,7 @@ members = [ "common/wasm/storage", "common/wasm/utils", "common/wireguard", - "common/wireguard-types", + "common/wireguard-types", "common/zulip-client", "documentation/autodoc", "gateway", "nym-api", @@ -234,6 +237,7 @@ digest = "0.10.7" dirs = "5.0" doc-comment = "0.3" dotenvy = "0.15.6" +dyn-clone = "1.0.19" ecdsa = "0.16" ed25519-dalek = "2.1" encoding_rs = "0.8.35" diff --git a/common/authenticator-requests/src/v5/registration.rs b/common/authenticator-requests/src/v5/registration.rs index 28aadf9c6d..3c51776ca0 100644 --- a/common/authenticator-requests/src/v5/registration.rs +++ b/common/authenticator-requests/src/v5/registration.rs @@ -28,8 +28,6 @@ pub type HmacSha256 = Hmac; pub type Nonce = u64; pub type Taken = Option; -pub const BANDWIDTH_CAP_PER_DAY: u64 = 250 * 1024 * 1024 * 1024; // 250 GB - #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct IpPair { pub ipv4: Ipv4Addr, diff --git a/common/client-libs/validator-client/src/nym_api/mod.rs b/common/client-libs/validator-client/src/nym_api/mod.rs index 1136952e62..31b7014f64 100644 --- a/common/client-libs/validator-client/src/nym_api/mod.rs +++ b/common/client-libs/validator-client/src/nym_api/mod.rs @@ -6,16 +6,18 @@ use crate::nym_api::routes::{ecash, CORE_STATUS_COUNT, SINCE_ARG}; use async_trait::async_trait; use nym_api_requests::ecash::models::{ AggregatedCoinIndicesSignatureResponse, AggregatedExpirationDateSignatureResponse, - BatchRedeemTicketsBody, EcashBatchTicketRedemptionResponse, EcashTicketVerificationResponse, - IssuedTicketbooksChallengeCommitmentRequest, IssuedTicketbooksChallengeCommitmentResponse, - IssuedTicketbooksDataRequest, IssuedTicketbooksDataResponse, IssuedTicketbooksForCountResponse, - IssuedTicketbooksForResponse, VerifyEcashTicketBody, + BatchRedeemTicketsBody, EcashBatchTicketRedemptionResponse, EcashSignerStatusResponse, + EcashTicketVerificationResponse, IssuedTicketbooksChallengeCommitmentRequest, + IssuedTicketbooksChallengeCommitmentResponse, IssuedTicketbooksDataRequest, + IssuedTicketbooksDataResponse, IssuedTicketbooksForCountResponse, IssuedTicketbooksForResponse, + VerifyEcashTicketBody, }; use nym_api_requests::ecash::VerificationKeyResponse; use nym_api_requests::models::{ - AnnotationResponse, ApiHealthResponse, BinaryBuildInformationOwned, ChainStatusResponse, - KeyRotationInfoResponse, LegacyDescribedMixNode, NodePerformanceResponse, NodeRefreshBody, - NymNodeDescription, PerformanceHistoryResponse, RewardedSetResponse, + AnnotationResponse, ApiHealthResponse, BinaryBuildInformationOwned, ChainBlocksStatusResponse, + ChainStatusResponse, KeyRotationInfoResponse, LegacyDescribedMixNode, NodePerformanceResponse, + NodeRefreshBody, NymNodeDescription, PerformanceHistoryResponse, RewardedSetResponse, + SignerInformationResponse, }; use nym_api_requests::nym_nodes::{ NodesByAddressesRequestBody, NodesByAddressesResponse, PaginatedCachedNodesResponseV1, @@ -1331,6 +1333,22 @@ pub trait NymApiClientExt: ApiClient { .await } + async fn get_chain_blocks_status(&self) -> Result { + self.get_json("/v1/network/chain-blocks-status", NO_PARAMS) + .await + } + + #[instrument(level = "debug", skip(self))] + async fn get_signer_status(&self) -> Result { + self.get_json("/v1/ecash/signer-status", NO_PARAMS).await + } + + #[instrument(level = "debug", skip(self))] + async fn get_signer_information(&self) -> Result { + self.get_json("/v1/api-status/signer-information", NO_PARAMS) + .await + } + #[instrument(level = "debug", skip(self))] async fn get_key_rotation_info(&self) -> Result { self.get_json( diff --git a/common/client-libs/validator-client/src/nyxd/contract_traits/dkg_query_client.rs b/common/client-libs/validator-client/src/nyxd/contract_traits/dkg_query_client.rs index a77d15eda9..49b5e56cbe 100644 --- a/common/client-libs/validator-client/src/nyxd/contract_traits/dkg_query_client.rs +++ b/common/client-libs/validator-client/src/nyxd/contract_traits/dkg_query_client.rs @@ -8,11 +8,11 @@ use crate::nyxd::CosmWasmClient; use async_trait::async_trait; use cosmrs::AccountId; use cosmwasm_std::Addr; +use nym_coconut_dkg_common::dealer::RegisteredDealerDetails; use nym_coconut_dkg_common::types::{ChunkIndex, NodeIndex, StateAdvanceResponse}; use serde::Deserialize; use tracing::trace; -use nym_coconut_dkg_common::dealer::RegisteredDealerDetails; pub use nym_coconut_dkg_common::{ dealer::{DealerDetailsResponse, PagedDealerIndexResponse, PagedDealerResponse}, dealing::{ @@ -21,7 +21,9 @@ pub use nym_coconut_dkg_common::{ }, msg::QueryMsg as DkgQueryMsg, types::{DealerDetails, DealingIndex, Epoch, EpochId, EpochState, State}, - verification_key::{ContractVKShare, PagedVKSharesResponse, VkShareResponse}, + verification_key::{ + ContractVKShare, PagedVKSharesResponse, VerificationKeyShare, VkShareResponse, + }, }; #[cfg_attr(target_arch = "wasm32", async_trait(?Send))] diff --git a/common/client-libs/validator-client/src/nyxd/mod.rs b/common/client-libs/validator-client/src/nyxd/mod.rs index 80dcf01fb0..85b08ab12a 100644 --- a/common/client-libs/validator-client/src/nyxd/mod.rs +++ b/common/client-libs/validator-client/src/nyxd/mod.rs @@ -139,12 +139,22 @@ impl NyxdClient { }) } + pub fn connect_with_network_details( + endpoint: U, + network_details: NymNetworkDetails, + ) -> Result + where + U: TryInto, + { + let config = Config::try_from_nym_network_details(&network_details)?; + Self::connect(config, endpoint) + } + pub fn connect_to_default_env(endpoint: U) -> Result where U: TryInto, { - let config = Config::try_from_nym_network_details(&NymNetworkDetails::new_from_env())?; - Self::connect(config, endpoint) + Self::connect_with_network_details(endpoint, NymNetworkDetails::new_from_env()) } } diff --git a/common/credential-verification/Cargo.toml b/common/credential-verification/Cargo.toml index a86b7da382..e85589eaae 100644 --- a/common/credential-verification/Cargo.toml +++ b/common/credential-verification/Cargo.toml @@ -11,9 +11,11 @@ rust-version.workspace = true readme.workspace = true [dependencies] +async-trait = { workspace = true } bs58 = { workspace = true } cosmwasm-std = { workspace = true } cw-utils = { workspace = true } +dyn-clone = { workspace = true } futures = { workspace = true } rand = { workspace = true } si-scale = { workspace = true } diff --git a/common/credential-verification/src/bandwidth_storage_manager.rs b/common/credential-verification/src/bandwidth_storage_manager.rs index 5d51091346..17f89a59fb 100644 --- a/common/credential-verification/src/bandwidth_storage_manager.rs +++ b/common/credential-verification/src/bandwidth_storage_manager.rs @@ -7,25 +7,36 @@ use crate::ClientBandwidth; use nym_credentials::ecash::utils::ecash_today; use nym_credentials_interface::Bandwidth; use nym_gateway_requests::ServerResponse; -use nym_gateway_storage::GatewayStorage; +use nym_gateway_storage::traits::BandwidthGatewayStorage; use si_scale::helpers::bibytes2; use time::OffsetDateTime; use tracing::*; const FREE_TESTNET_BANDWIDTH_VALUE: Bandwidth = Bandwidth::new_unchecked(64 * 1024 * 1024 * 1024); // 64GB -#[derive(Clone)] pub struct BandwidthStorageManager { - pub(crate) storage: GatewayStorage, + pub(crate) storage: Box, pub(crate) client_bandwidth: ClientBandwidth, pub(crate) client_id: i64, pub(crate) bandwidth_cfg: BandwidthFlushingBehaviourConfig, pub(crate) only_coconut_credentials: bool, } +impl Clone for BandwidthStorageManager { + fn clone(&self) -> Self { + Self { + storage: dyn_clone::clone_box(&*self.storage), + client_bandwidth: self.client_bandwidth.clone(), + client_id: self.client_id, + bandwidth_cfg: self.bandwidth_cfg, + only_coconut_credentials: self.only_coconut_credentials, + } + } +} + impl BandwidthStorageManager { pub fn new( - storage: GatewayStorage, + storage: Box, client_bandwidth: ClientBandwidth, client_id: i64, bandwidth_cfg: BandwidthFlushingBehaviourConfig, diff --git a/common/credential-verification/src/ecash/mod.rs b/common/credential-verification/src/ecash/mod.rs index 71d0d993ff..107ac45299 100644 --- a/common/credential-verification/src/ecash/mod.rs +++ b/common/credential-verification/src/ecash/mod.rs @@ -2,12 +2,14 @@ // SPDX-License-Identifier: GPL-3.0-only use crate::Error; +use async_trait::async_trait; use credential_sender::CredentialHandler; use credential_sender::CredentialHandlerConfig; use error::EcashTicketError; use futures::channel::mpsc::{self, UnboundedSender}; use nym_credentials::CredentialSpendingData; use nym_credentials_interface::{ClientTicket, CompactEcashError, NymPayInfo, VerificationKeyAuth}; +use nym_gateway_storage::traits::BandwidthGatewayStorage; use nym_gateway_storage::GatewayStorage; use nym_validator_client::nym_api::EpochId; use nym_validator_client::DirectSigningHttpRpcNyxdClient; @@ -20,6 +22,7 @@ pub mod credential_sender; pub mod error; mod helpers; mod state; +pub mod traits; pub const TIME_RANGE_SEC: i64 = 30; @@ -31,44 +34,21 @@ pub struct EcashManager { cred_sender: UnboundedSender, } -impl EcashManager { - pub async fn new( - credential_handler_cfg: CredentialHandlerConfig, - nyxd_client: DirectSigningHttpRpcNyxdClient, - pk_bytes: [u8; 32], - shutdown: nym_task::TaskClient, - storage: GatewayStorage, - ) -> Result { - let shared_state = SharedState::new(nyxd_client, storage).await?; - - let (cred_sender, cred_receiver) = mpsc::unbounded(); - - let cs = - CredentialHandler::new(credential_handler_cfg, cred_receiver, shared_state.clone()) - .await?; - cs.start(shutdown); - - Ok(EcashManager { - shared_state, - pk_bytes, - pay_infos: Default::default(), - cred_sender, - }) - } - - pub async fn verification_key( +#[async_trait] +impl traits::EcashManager for EcashManager { + async fn verification_key( &self, epoch_id: EpochId, ) -> Result, EcashTicketError> { self.shared_state.verification_key(epoch_id).await } - pub fn storage(&self) -> &GatewayStorage { - &self.shared_state.storage + fn storage(&self) -> Box { + dyn_clone::clone_box(&*self.shared_state.storage) } //Check for duplicate pay_info, then check the payment, then insert pay_info if everything succeeded - pub async fn check_payment( + async fn check_payment( &self, credential: &CredentialSpendingData, aggregated_verification_key: &VerificationKeyAuth, @@ -88,6 +68,40 @@ impl EcashManager { .await } + fn async_verify(&self, ticket: ClientTicket) { + // TODO: I guess do something for shutdowns + let _ = self + .cred_sender + .unbounded_send(ticket) + .inspect_err(|_| error!("failed to send the client ticket for verification task")); + } +} + +impl EcashManager { + pub async fn new( + credential_handler_cfg: CredentialHandlerConfig, + nyxd_client: DirectSigningHttpRpcNyxdClient, + pk_bytes: [u8; 32], + shutdown: nym_task::TaskClient, + storage: GatewayStorage, + ) -> Result { + let shared_state = SharedState::new(nyxd_client, Box::new(storage)).await?; + + let (cred_sender, cred_receiver) = mpsc::unbounded(); + + let cs = + CredentialHandler::new(credential_handler_cfg, cred_receiver, shared_state.clone()) + .await?; + cs.start(shutdown); + + Ok(EcashManager { + shared_state, + pk_bytes, + pay_infos: Default::default(), + cred_sender, + }) + } + pub async fn verify_pay_info(&self, pay_info: NymPayInfo) -> Result { //Public key check if pay_info.pk() != self.pk_bytes { @@ -152,12 +166,86 @@ impl EcashManager { inner.insert(index, pay_info); Ok(()) } +} - pub fn async_verify(&self, ticket: ClientTicket) { - // TODO: I guess do something for shutdowns - let _ = self - .cred_sender - .unbounded_send(ticket) - .inspect_err(|_| error!("failed to send the client ticket for verification task")); +pub struct MockEcashManager { + verfication_key: tokio::sync::RwLock, + storage: Box, +} + +impl MockEcashManager { + pub fn new(storage: Box) -> Self { + Self { + verfication_key: tokio::sync::RwLock::new( + VerificationKeyAuth::from_bytes(&[ + 129, 187, 76, 12, 1, 51, 46, 26, 132, 205, 148, 109, 140, 131, 50, 119, 45, + 128, 51, 218, 106, 70, 181, 74, 244, 38, 162, 62, 42, 12, 5, 100, 7, 136, 32, + 155, 18, 219, 195, 182, 3, 56, 168, 16, 93, 154, 249, 230, 16, 202, 90, 134, + 246, 25, 98, 6, 175, 215, 188, 239, 71, 84, 66, 1, 43, 66, 197, 180, 216, 80, + 55, 185, 140, 216, 14, 48, 244, 214, 20, 68, 106, 41, 48, 252, 188, 181, 231, + 170, 23, 211, 215, 12, 91, 147, 47, 7, 4, 0, 0, 0, 0, 0, 0, 0, 174, 31, 237, + 215, 159, 183, 71, 125, 90, 147, 84, 78, 49, 216, 66, 232, 92, 206, 41, 230, + 239, 209, 211, 166, 131, 190, 148, 36, 225, 194, 146, 6, 120, 34, 194, 5, 154, + 155, 234, 41, 191, 119, 227, 51, 91, 128, 151, 240, 129, 208, 253, 171, 234, + 170, 71, 139, 251, 78, 49, 35, 218, 16, 77, 150, 177, 204, 83, 210, 67, 147, + 66, 162, 58, 25, 96, 168, 61, 180, 92, 21, 18, 78, 194, 98, 176, 123, 122, 176, + 81, 150, 187, 20, 64, 69, 0, 134, 142, 3, 84, 108, 3, 55, 107, 111, 73, 31, 46, + 51, 225, 248, 202, 173, 194, 24, 104, 96, 31, 61, 24, 140, 220, 31, 176, 200, + 30, 217, 66, 58, 11, 181, 158, 196, 179, 199, 177, 7, 210, 4, 119, 142, 149, + 59, 3, 186, 145, 27, 230, 125, 230, 246, 197, 196, 119, 70, 239, 115, 99, 215, + 63, 205, 63, 74, 108, 201, 42, 226, 150, 137, 3, 157, 45, 25, 163, 54, 107, + 153, 61, 141, 64, 207, 139, 41, 203, 39, 36, 97, 181, 72, 206, 235, 221, 178, + 171, 60, 4, 6, 170, 181, 213, 10, 216, 53, 28, 32, 33, 41, 224, 60, 247, 206, + 137, 108, 251, 229, 234, 112, 65, 145, 124, 212, 125, 116, 154, 114, 2, 125, + 202, 24, 25, 196, 219, 104, 200, 131, 133, 180, 39, 21, 144, 204, 8, 151, 218, + 99, 64, 209, 47, 5, 42, 13, 214, 139, 54, 112, 224, 53, 238, 250, 56, 42, 105, + 15, 21, 238, 99, 225, 79, 121, 104, 155, 230, 243, 133, 47, 39, 147, 98, 45, + 113, 137, 200, 102, 151, 122, 174, 9, 250, 17, 138, 191, 129, 202, 244, 107, + 75, 48, 141, 136, 89, 168, 124, 88, 174, 251, 17, 35, 146, 88, 76, 134, 102, + 105, 204, 16, 176, 214, 63, 13, 170, 225, 250, 112, 7, 237, 161, 160, 15, 71, + 10, 130, 137, 69, 186, 64, 223, 188, 5, 5, 228, 57, 214, 134, 247, 20, 171, + 140, 43, 230, 57, 29, 127, 136, 169, 80, 14, 137, 130, 200, 205, 222, 81, 143, + 40, 77, 68, 197, 91, 142, 91, 84, 164, 15, 133, 242, 149, 255, 173, 201, 108, + 208, 23, 188, 230, 158, 146, 54, 198, 52, 148, 123, 202, 52, 222, 50, 4, 62, + 211, 208, 176, 61, 104, 151, 227, 192, 224, 200, 132, 53, 187, 240, 254, 150, + 60, 30, 140, 11, 63, 71, 12, 30, 233, 255, 144, 250, 16, 81, 38, 33, 9, 185, + 195, 214, 0, 119, 117, 94, 100, 103, 144, 10, 189, 65, 113, 114, 192, 11, 177, + 214, 223, 218, 36, 139, 183, 2, 206, 247, 245, 88, 62, 231, 183, 50, 46, 95, + 202, 152, 82, 244, 80, 173, 192, 147, 51, 248, 46, 181, 194, 205, 233, 67, 144, + 155, 250, 142, 124, 71, 9, 136, 142, 88, 29, 99, 222, 43, 181, 172, 120, 187, + 179, 172, 240, 231, 57, 236, 195, 158, 182, 203, 19, 49, 220, 180, 212, 101, + 105, 239, 58, 215, 0, 50, 100, 172, 29, 236, 170, 108, 129, 150, 5, 64, 238, + 59, 50, 4, 21, 131, 197, 142, 191, 76, 101, 140, 133, 112, 38, 235, 113, 203, + 22, 161, 204, 84, 73, 125, 219, 70, 62, 67, 119, 52, 130, 208, 180, 231, 78, + 141, 181, 13, 207, 196, 126, 159, 70, 34, 195, 70, + ]) + .unwrap(), + ), + storage: dyn_clone::clone_box(&*storage), + } } } + +#[async_trait] +impl traits::EcashManager for MockEcashManager { + async fn verification_key( + &self, + _epoch_id: EpochId, + ) -> Result, EcashTicketError> { + Ok(self.verfication_key.read().await) + } + + fn storage(&self) -> Box { + dyn_clone::clone_box(&*self.storage) + } + + async fn check_payment( + &self, + _credential: &CredentialSpendingData, + _aggregated_verification_key: &VerificationKeyAuth, + ) -> Result<(), EcashTicketError> { + Ok(()) + } + + fn async_verify(&self, _ticket: ClientTicket) {} +} diff --git a/common/credential-verification/src/ecash/state.rs b/common/credential-verification/src/ecash/state.rs index 2c937fd692..c16db2111f 100644 --- a/common/credential-verification/src/ecash/state.rs +++ b/common/credential-verification/src/ecash/state.rs @@ -6,7 +6,7 @@ use crate::Error; use cosmwasm_std::{from_json, CosmosMsg, WasmMsg}; use nym_credentials_interface::VerificationKeyAuth; use nym_ecash_contract_common::msg::ExecuteMsg; -use nym_gateway_storage::GatewayStorage; +use nym_gateway_storage::traits::BandwidthGatewayStorage; use nym_validator_client::coconut::all_ecash_api_clients; use nym_validator_client::nym_api::EpochId; use nym_validator_client::nyxd::contract_traits::{ @@ -22,18 +22,28 @@ use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tracing::{error, trace, warn}; // state shared by different subtasks dealing with credentials -#[derive(Clone)] pub(crate) struct SharedState { pub(crate) nyxd_client: Arc>, pub(crate) address: AccountId, pub(crate) epoch_data: Arc>>, - pub(crate) storage: GatewayStorage, + pub(crate) storage: Box, +} + +impl Clone for SharedState { + fn clone(&self) -> Self { + Self { + nyxd_client: self.nyxd_client.clone(), + address: self.address.clone(), + epoch_data: self.epoch_data.clone(), + storage: dyn_clone::clone_box(&*self.storage), + } + } } impl SharedState { pub(crate) async fn new( nyxd_client: DirectSigningHttpRpcNyxdClient, - storage: GatewayStorage, + storage: Box, ) -> Result { let address = nyxd_client.address(); diff --git a/common/credential-verification/src/ecash/traits.rs b/common/credential-verification/src/ecash/traits.rs new file mode 100644 index 0000000000..a7e8197681 --- /dev/null +++ b/common/credential-verification/src/ecash/traits.rs @@ -0,0 +1,23 @@ +use async_trait::async_trait; +use nym_credentials::CredentialSpendingData; +use nym_credentials_interface::{ClientTicket, VerificationKeyAuth}; +use nym_gateway_storage::traits::BandwidthGatewayStorage; +use nym_validator_client::nym_api::EpochId; +use tokio::sync::RwLockReadGuard; + +use crate::ecash::error::EcashTicketError; + +#[async_trait] +pub trait EcashManager { + async fn verification_key( + &self, + epoch_id: EpochId, + ) -> Result, EcashTicketError>; + fn storage(&self) -> Box; + async fn check_payment( + &self, + credential: &CredentialSpendingData, + aggregated_verification_key: &VerificationKeyAuth, + ) -> Result<(), EcashTicketError>; + fn async_verify(&self, ticket: ClientTicket); +} diff --git a/common/credential-verification/src/lib.rs b/common/credential-verification/src/lib.rs index 50d6db1e05..2164c25514 100644 --- a/common/credential-verification/src/lib.rs +++ b/common/credential-verification/src/lib.rs @@ -1,8 +1,8 @@ // Copyright 2024 - Nym Technologies SA // SPDX-License-Identifier: Apache-2.0 +use crate::ecash::traits::EcashManager; use bandwidth_storage_manager::BandwidthStorageManager; -use ecash::EcashManager; use nym_credentials::ecash::utils::{cred_exp_date, ecash_today, EcashTime}; use nym_credentials_interface::{Bandwidth, ClientTicket, TicketType}; use nym_gateway_requests::models::CredentialSpendingRequest; @@ -20,14 +20,14 @@ pub mod error; pub struct CredentialVerifier { credential: CredentialSpendingRequest, - ecash_verifier: Arc, + ecash_verifier: Arc, bandwidth_storage_manager: BandwidthStorageManager, } impl CredentialVerifier { pub fn new( credential: CredentialSpendingRequest, - ecash_verifier: Arc, + ecash_verifier: Arc, bandwidth_storage_manager: BandwidthStorageManager, ) -> Self { CredentialVerifier { diff --git a/common/ecash-signer-check-types/Cargo.toml b/common/ecash-signer-check-types/Cargo.toml new file mode 100644 index 0000000000..0f07437c71 --- /dev/null +++ b/common/ecash-signer-check-types/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "nym-ecash-signer-check-types" +version = "0.1.0" +authors.workspace = true +repository.workspace = true +homepage.workspace = true +documentation.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +readme.workspace = true + +[dependencies] +semver = { workspace = true } +serde = { workspace = true, features = ["derive"] } +url = { workspace = true } +thiserror = { workspace = true } +time = { workspace = true } +tracing = { workspace = true } +utoipa = { workspace = true } + +nym-coconut-dkg-common = { path = "../cosmwasm-smart-contracts/coconut-dkg" } +nym-crypto = { path = "../crypto", features = ["asymmetric"] } + + +[lints] +workspace = true diff --git a/common/ecash-signer-check-types/src/dealer_information.rs b/common/ecash-signer-check-types/src/dealer_information.rs new file mode 100644 index 0000000000..b589fecb10 --- /dev/null +++ b/common/ecash-signer-check-types/src/dealer_information.rs @@ -0,0 +1,97 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use nym_coconut_dkg_common::dealer::DealerDetails; +use nym_coconut_dkg_common::verification_key::{ContractVKShare, VerificationKeyShare}; +use nym_crypto::asymmetric::ed25519; +use nym_crypto::asymmetric::ed25519::Ed25519RecoveryError; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use url::Url; +use utoipa::ToSchema; + +#[derive(Debug, Error)] +pub enum MalformedDealer { + #[error("dealer at {dealer_url} has provided invalid ed25519 pubkey: {source}")] + InvalidDealerPubkey { + dealer_url: String, + source: Ed25519RecoveryError, + }, + + #[error("dealer at {dealer_url} has provided invalid announce url: {source}")] + InvalidDealerAddress { + dealer_url: String, + source: url::ParseError, + }, +} + +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +pub struct RawDealerInformation { + pub announce_address: String, + pub owner_address: String, + pub node_index: u64, + pub public_key: String, + pub verification_key_share: Option, + pub share_verified: bool, +} + +impl RawDealerInformation { + pub fn new( + dealer_details: &DealerDetails, + contract_share: Option<&ContractVKShare>, + ) -> RawDealerInformation { + RawDealerInformation { + announce_address: dealer_details.announce_address.clone(), + owner_address: dealer_details.address.to_string(), + node_index: dealer_details.assigned_index, + public_key: dealer_details.ed25519_identity.clone(), + verification_key_share: contract_share.map(|s| s.share.clone()), + share_verified: contract_share.map(|s| s.verified).unwrap_or(false), + } + } + + pub fn parse(&self) -> Result { + Ok(DealerInformation { + announce_address: self.announce_address.parse().map_err(|source| { + MalformedDealer::InvalidDealerAddress { + dealer_url: self.announce_address.clone(), + source, + } + })?, + owner_address: self.owner_address.clone(), + node_index: self.node_index, + public_key: self.public_key.parse().map_err(|source| { + MalformedDealer::InvalidDealerPubkey { + dealer_url: self.announce_address.clone(), + source, + } + })?, + verification_key_share: self.verification_key_share.clone(), + share_verified: self.share_verified, + }) + } +} + +#[derive(Debug)] +pub struct DealerInformation { + pub announce_address: Url, + pub owner_address: String, + pub node_index: u64, + pub public_key: ed25519::PublicKey, + // no need to parse it into the full type as it doesn't get us anything + pub verification_key_share: Option, + pub share_verified: bool, +} + +impl From for RawDealerInformation { + fn from(d: DealerInformation) -> Self { + RawDealerInformation { + announce_address: d.announce_address.to_string(), + owner_address: d.owner_address, + node_index: d.node_index, + public_key: d.public_key.to_base58_string(), + verification_key_share: d.verification_key_share, + share_verified: d.share_verified, + } + } +} diff --git a/common/ecash-signer-check-types/src/helper_traits.rs b/common/ecash-signer-check-types/src/helper_traits.rs new file mode 100644 index 0000000000..c6d6becd33 --- /dev/null +++ b/common/ecash-signer-check-types/src/helper_traits.rs @@ -0,0 +1,127 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use nym_coconut_dkg_common::types::EpochId; +use nym_coconut_dkg_common::verification_key::VerificationKeyShare; +use nym_crypto::asymmetric::ed25519; +use std::time::Duration; +use time::OffsetDateTime; +use tracing::{debug, warn}; + +pub trait Verifiable { + fn verify_signature(&self, pub_key: &ed25519::PublicKey) -> bool; +} + +pub trait TimestampedResponse { + fn timestamp(&self) -> OffsetDateTime; +} + +pub trait LegacyChainResponse { + fn chain_synced(&self, now: OffsetDateTime, stall_threshold: Duration) -> bool; +} + +pub trait ChainResponse: Verifiable + TimestampedResponse { + fn chain_synced(&self) -> bool; + + fn chain_available( + &self, + pub_key: &ed25519::PublicKey, + now: OffsetDateTime, + stale_response_threshold: Duration, + ) -> bool { + if !self.verify_signature(pub_key) { + warn!("failed signature verification on chain status response"); + return false; + } + + // we rely on information provided from the api itself AS LONG AS it's not too outdated + if self.timestamp() + stale_response_threshold < now { + return false; + } + self.chain_synced() + } +} + +pub trait LegacySignerResponse { + fn signer_identity(&self) -> &str; + + fn signer_verification_key(&self) -> &Option; + + fn unprovable_signing_available( + &self, + pub_key: &ed25519::PublicKey, + expected_verification_key: Option, + share_verified: bool, + ) -> bool { + if self.signer_identity() != pub_key.to_base58_string() { + warn!("mismatched identity key on the legacy response"); + return false; + } + + // the contract share hasn't been verified yet, so we're probably in the middle of DKG + // thus if there's a bit of desync in the state, it's fine + if !share_verified { + return true; + } + + if self.signer_verification_key() != &expected_verification_key { + warn!("mismatched [ecash] verification key on the legacy response"); + return false; + } + + true + } +} + +pub trait SignerResponse: Verifiable + TimestampedResponse { + fn has_signing_keys(&self) -> bool; + + fn signer_disabled(&self) -> bool; + + fn is_ecash_signer(&self) -> bool; + + fn dkg_ecash_epoch_id(&self) -> EpochId; + + fn provable_signing_available( + &self, + pub_key: &ed25519::PublicKey, + dkg_epoch_id: EpochId, + now: OffsetDateTime, + stale_response_threshold: Duration, + ) -> bool { + if !self.verify_signature(pub_key) { + warn!("failed signature verification on chain status response"); + return false; + } + + // we rely on information provided from the api itself AS LONG AS it's not too outdated + if self.timestamp() + stale_response_threshold < now { + return false; + } + + if !self.has_signing_keys() { + debug!("missing signing keys"); + return false; + } + + if self.signer_disabled() { + debug!("signer functionalities explicitly disabled"); + return false; + } + + if !self.is_ecash_signer() { + debug!("signer doesn't recognise it's a signer for this epoch"); + return false; + } + + if dkg_epoch_id != self.dkg_ecash_epoch_id() { + debug!( + "mismatched dkg epoch id. current: {dkg_epoch_id}, signer's: {}", + self.dkg_ecash_epoch_id() + ); + return false; + } + + true + } +} diff --git a/common/ecash-signer-check-types/src/lib.rs b/common/ecash-signer-check-types/src/lib.rs new file mode 100644 index 0000000000..60e5ccd667 --- /dev/null +++ b/common/ecash-signer-check-types/src/lib.rs @@ -0,0 +1,6 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +pub mod dealer_information; +pub mod helper_traits; +pub mod status; diff --git a/common/ecash-signer-check-types/src/status.rs b/common/ecash-signer-check-types/src/status.rs new file mode 100644 index 0000000000..2a506d6c96 --- /dev/null +++ b/common/ecash-signer-check-types/src/status.rs @@ -0,0 +1,303 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::dealer_information::RawDealerInformation; +use crate::helper_traits::{ + ChainResponse, LegacyChainResponse, LegacySignerResponse, SignerResponse, +}; +use nym_coconut_dkg_common::types::EpochId; +use nym_coconut_dkg_common::verification_key::VerificationKeyShare; +use nym_crypto::asymmetric::ed25519; +use serde::{Deserialize, Serialize}; +use std::time::Duration; +use time::OffsetDateTime; +use utoipa::ToSchema; + +pub(crate) const CHAIN_STALL_THRESHOLD: Duration = Duration::from_secs(5 * 60); +pub(crate) const STALE_RESPONSE_THRESHOLD: Duration = Duration::from_secs(5 * 60); + +// the reason for generics is not to remove duplication of code, +// but because without them, we'd be having problems with circular dependencies, +// i.e. nym-api-requests depending on ecash-signer-check-types and +// ecash-signer-check-types needing nym-api-requests +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +pub enum Status { + /// The API, even though it reports correct version, did not response to the status query + Unreachable, + + /// The API is running an outdated version that does not expose the required endpoint + Outdated, + + /// Response to the legacy (unsigned) status query + ReachableLegacy { response: Box }, + + /// Response to the current (signed) status query + Reachable { response: Box }, +} + +impl Status +where + L: LegacyChainResponse, + T: ChainResponse, +{ + pub fn chain_available(&self, pub_key: ed25519::PublicKey) -> bool { + let now = OffsetDateTime::now_utc(); + + match self { + Status::Unreachable | Status::Outdated => false, + Status::ReachableLegacy { response } => { + response.chain_synced(now, CHAIN_STALL_THRESHOLD) + } + Status::Reachable { response } => { + response.chain_available(&pub_key, now, STALE_RESPONSE_THRESHOLD) + } + } + } + + pub fn chain_provably_stalled(&self, pub_key: ed25519::PublicKey) -> bool { + let now = OffsetDateTime::now_utc(); + + match self { + Status::Unreachable | Status::Outdated | Status::ReachableLegacy { .. } => false, + Status::Reachable { response } => { + !response.chain_available(&pub_key, now, STALE_RESPONSE_THRESHOLD) + } + } + } + + pub fn chain_unprovably_stalled(&self) -> bool { + let now = OffsetDateTime::now_utc(); + + match self { + Status::Unreachable | Status::Outdated | Status::Reachable { .. } => false, + Status::ReachableLegacy { response } => { + !response.chain_synced(now, CHAIN_STALL_THRESHOLD) + } + } + } +} + +impl Status +where + L: LegacySignerResponse, + T: SignerResponse, +{ + pub fn signing_available( + &self, + pub_key: ed25519::PublicKey, + dkg_epoch_id: u64, + expected_verification_key: Option, + share_verified: bool, + ) -> bool { + let now = OffsetDateTime::now_utc(); + + match self { + Status::Unreachable | Status::Outdated => false, + Status::ReachableLegacy { response } => response.unprovable_signing_available( + &pub_key, + expected_verification_key, + share_verified, + ), + Status::Reachable { response } => response.provable_signing_available( + &pub_key, + dkg_epoch_id, + now, + STALE_RESPONSE_THRESHOLD, + ), + } + } + + pub fn signing_provably_unavailable( + &self, + pub_key: ed25519::PublicKey, + dkg_epoch_id: EpochId, + ) -> bool { + let now = OffsetDateTime::now_utc(); + + match self { + Status::Unreachable | Status::Outdated | Status::ReachableLegacy { .. } => false, + Status::Reachable { response } => !response.provable_signing_available( + &pub_key, + dkg_epoch_id, + now, + STALE_RESPONSE_THRESHOLD, + ), + } + } + + pub fn signing_unprovably_unavailable( + &self, + pub_key: ed25519::PublicKey, + expected_verification_key: Option, + share_verified: bool, + ) -> bool { + match self { + Status::Unreachable | Status::Outdated | Status::Reachable { .. } => false, + Status::ReachableLegacy { response } => !response.unprovable_signing_available( + &pub_key, + expected_verification_key, + share_verified, + ), + } + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +pub struct SignerResult { + pub dkg_epoch_id: u64, + pub information: RawDealerInformation, + pub status: SignerStatus, +} + +impl SignerResult { + pub fn signer_unreachable(&self) -> bool { + matches!(self.status, SignerStatus::Unreachable) + } + + pub fn malformed_details(&self) -> bool { + self.information.parse().is_err() + } +} + +impl SignerResult +where + LC: LegacyChainResponse, + TC: ChainResponse, +{ + pub fn unknown_chain_status(&self) -> bool { + let Ok(_) = self.information.parse() else { + return true; + }; + if let SignerStatus::Tested { .. } = &self.status { + return false; + } + true + } + + pub fn chain_available(&self) -> bool { + let Ok(parsed_info) = self.information.parse() else { + return false; + }; + + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + result + .local_chain_status + .chain_available(parsed_info.public_key) + } + + pub fn chain_provably_stalled(&self) -> bool { + let Ok(parsed_info) = self.information.parse() else { + return false; + }; + + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + + result + .local_chain_status + .chain_provably_stalled(parsed_info.public_key) + } + + pub fn chain_unprovably_stalled(&self) -> bool { + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + + result.local_chain_status.chain_unprovably_stalled() + } +} + +impl SignerResult +where + LS: LegacySignerResponse, + TS: SignerResponse, +{ + pub fn unknown_signing_status(&self) -> bool { + let Ok(_) = self.information.parse() else { + return true; + }; + if let SignerStatus::Tested { .. } = &self.status { + return false; + } + true + } + + pub fn signing_available(&self) -> bool { + let Ok(parsed_info) = self.information.parse() else { + return false; + }; + + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + result.signing_status.signing_available( + parsed_info.public_key, + self.dkg_epoch_id, + parsed_info.verification_key_share, + parsed_info.share_verified, + ) + } + + pub fn signing_provably_unavailable(&self) -> bool { + let Ok(parsed_info) = self.information.parse() else { + return false; + }; + + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + + result + .signing_status + .signing_provably_unavailable(parsed_info.public_key, self.dkg_epoch_id) + } + + pub fn signing_unprovably_unavailable(&self) -> bool { + let Ok(parsed_info) = self.information.parse() else { + return false; + }; + + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + + result.signing_status.signing_unprovably_unavailable( + parsed_info.public_key, + parsed_info.verification_key_share, + parsed_info.share_verified, + ) + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +pub enum SignerStatus { + Unreachable, + ProvidedInvalidDetails, + Tested { + result: SignerTestResult, + }, +} + +impl SignerStatus { + pub fn with_details( + self, + information: impl Into, + dkg_epoch_id: u64, + ) -> SignerResult { + SignerResult { + dkg_epoch_id, + status: self, + information: information.into(), + } + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +pub struct SignerTestResult { + pub reported_version: String, + pub signing_status: Status, + pub local_chain_status: Status, +} diff --git a/common/ecash-signer-check/Cargo.toml b/common/ecash-signer-check/Cargo.toml new file mode 100644 index 0000000000..be22872ad8 --- /dev/null +++ b/common/ecash-signer-check/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "nym-ecash-signer-check" +version = "0.1.0" +authors.workspace = true +repository.workspace = true +homepage.workspace = true +documentation.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +readme.workspace = true + +[dependencies] +futures = { workspace = true } +thiserror = { workspace = true } +semver = { workspace = true } +tokio = { workspace = true, features = ["time"] } +tracing = { workspace = true } +url = { workspace = true } + + +nym-validator-client = { path = "../client-libs/validator-client" } +nym-network-defaults = { path = "../network-defaults" } +nym-ecash-signer-check-types = { path = "../ecash-signer-check-types" } + +[lints] +workspace = true diff --git a/common/ecash-signer-check/src/client_check.rs b/common/ecash-signer-check/src/client_check.rs new file mode 100644 index 0000000000..b5c367794d --- /dev/null +++ b/common/ecash-signer-check/src/client_check.rs @@ -0,0 +1,225 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::{LocalChainStatus, SigningStatus, TypedSignerResult}; +use nym_ecash_signer_check_types::dealer_information::RawDealerInformation; +use nym_ecash_signer_check_types::status::{SignerStatus, SignerTestResult}; +use nym_validator_client::client::NymApiClientExt; +use nym_validator_client::models::BinaryBuildInformationOwned; +use nym_validator_client::nyxd::contract_traits::dkg_query_client::{ + ContractVKShare, DealerDetails, +}; +use nym_validator_client::NymApiClient; +use std::time::Duration; +use tracing::{error, warn}; +use url::Url; + +pub(crate) mod chain_status { + + // Dorina + pub(crate) const MINIMUM_VERSION_LEGACY: semver::Version = semver::Version::new(1, 1, 51); + + // Gruyere + pub(crate) const MINIMUM_VERSION: semver::Version = semver::Version::new(1, 1, 64); +} + +pub(crate) mod signing_status { + // Magura (possibly earlier) + pub(crate) const MINIMUM_LEGACY_VERSION: semver::Version = semver::Version::new(1, 1, 46); + + // Gruyere + pub(crate) const MINIMUM_VERSION: semver::Version = semver::Version::new(1, 1, 64); +} + +struct ClientUnderTest { + api_client: NymApiClient, + build_info: Option, +} + +impl ClientUnderTest { + pub(crate) fn new(api_url: &Url) -> Self { + ClientUnderTest { + api_client: NymApiClient::new(api_url.clone()), + build_info: None, + } + } + + pub(crate) async fn try_retrieve_build_information(&mut self) -> bool { + match tokio::time::timeout( + Duration::from_secs(5), + self.api_client.nym_api.build_information(), + ) + .await + { + Ok(Ok(build_information)) => { + self.build_info = Some(build_information); + true + } + Ok(Err(err)) => { + warn!("{}: failed to retrieve build information: {err}. the signer is most likely down", self.api_client.api_url()); + false + } + Err(_timeout) => { + warn!( + "{}: timed out while attempting to retrieve build information", + self.api_client.api_url() + ); + false + } + } + } + + pub(crate) fn version(&self) -> Option { + self.build_info.as_ref().and_then(|build_info| { + build_info + .build_version + .parse() + .inspect_err(|err| { + error!( + "ecash signer '{}' reports invalid version {}: {err}", + self.api_client.api_url(), + build_info.build_version + ) + }) + .ok() + }) + } + + pub(crate) fn supports_legacy_signing_status_query(&self) -> bool { + let Some(version) = self.version() else { + return false; + }; + version >= signing_status::MINIMUM_LEGACY_VERSION + } + + pub(crate) fn supports_signing_status_query(&self) -> bool { + let Some(version) = self.version() else { + return false; + }; + version >= signing_status::MINIMUM_VERSION + } + + pub(crate) fn supports_chain_status_query(&self) -> bool { + let Some(version) = self.version() else { + return false; + }; + version >= chain_status::MINIMUM_VERSION + } + + pub(crate) fn supports_legacy_chain_status_query(&self) -> bool { + let Some(version) = self.version() else { + return false; + }; + version >= chain_status::MINIMUM_VERSION_LEGACY + } + + pub(crate) async fn check_local_chain(&self) -> LocalChainStatus { + // check if it at least supports legacy query + if !self.supports_legacy_chain_status_query() { + return LocalChainStatus::Outdated; + } + + // check if it supports the current query + if self.supports_chain_status_query() { + return match self.api_client.nym_api.get_chain_blocks_status().await { + Ok(status) => LocalChainStatus::Reachable { + response: Box::new(status), + }, + Err(err) => { + warn!( + "{}: failed to retrieve local chain status: {err}", + self.api_client.api_url() + ); + LocalChainStatus::Unreachable + } + }; + } + + // fallback to the legacy query + match self.api_client.nym_api.get_chain_status().await { + Ok(status) => LocalChainStatus::ReachableLegacy { + response: Box::new(status), + }, + Err(err) => { + warn!( + "{}: failed to retrieve [legacy] local chain status: {err}", + self.api_client.api_url() + ); + LocalChainStatus::Unreachable + } + } + } + + pub(crate) async fn check_signing_status(&self) -> SigningStatus { + // check if it at least supports legacy query + if !self.supports_legacy_signing_status_query() { + return SigningStatus::Outdated; + } + + // check if it supports the current query + if self.supports_signing_status_query() { + return match self.api_client.nym_api.get_signer_status().await { + Ok(response) => SigningStatus::Reachable { + response: Box::new(response), + }, + Err(err) => { + warn!( + "{}: failed to retrieve signer chain status: {err}", + self.api_client.api_url() + ); + SigningStatus::Unreachable + } + }; + } + + // fallback to the legacy query + match self.api_client.nym_api.get_signer_information().await { + Ok(status) => SigningStatus::ReachableLegacy { + response: Box::new(status), + }, + Err(err) => { + warn!( + "{}: failed to retrieve [legacy] signer chain status: {err}", + self.api_client.api_url() + ); + // NOTE: this might equally mean the signing is disabled + SigningStatus::Unreachable + } + } + } +} + +pub(crate) async fn check_client( + dealer_details: DealerDetails, + dkg_epoch: u64, + contract_share: Option<&ContractVKShare>, +) -> TypedSignerResult { + let dealer_information = RawDealerInformation::new(&dealer_details, contract_share); + + // 7. attempt to construct client instances out of them + let Ok(parsed_information) = dealer_information.parse() else { + return SignerStatus::ProvidedInvalidDetails.with_details(dealer_information, dkg_epoch); + }; + + let mut client = ClientUnderTest::new(&parsed_information.announce_address); + + // 8. check basic connection status - can you retrieve build information? + if !client.try_retrieve_build_information().await { + return SignerStatus::Unreachable.with_details(dealer_information, dkg_epoch); + } + + // 9. check perceived chain status + let local_chain_status = client.check_local_chain().await; + + // 10. check signer status + let signing_status = client.check_signing_status().await; + + SignerStatus::Tested { + result: SignerTestResult { + reported_version: client.version().map(|v| v.to_string()).unwrap_or_default(), + signing_status, + local_chain_status, + }, + } + .with_details(dealer_information, dkg_epoch) +} diff --git a/common/ecash-signer-check/src/dealer_information.rs b/common/ecash-signer-check/src/dealer_information.rs new file mode 100644 index 0000000000..73f13cc489 --- /dev/null +++ b/common/ecash-signer-check/src/dealer_information.rs @@ -0,0 +1,80 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::SignerCheckError; +use nym_crypto::asymmetric::ed25519; +use nym_validator_client::nyxd::contract_traits::dkg_query_client::{ + ContractVKShare, DealerDetails, VerificationKeyShare, +}; +use url::Url; + +#[derive(Debug)] +pub struct RawDealerInformation { + pub announce_address: String, + pub owner_address: String, + pub node_index: u64, + pub public_key: String, + pub verification_key_share: Option, + pub share_verified: bool, +} + +impl RawDealerInformation { + pub fn new( + dealer_details: &DealerDetails, + contract_share: Option<&ContractVKShare>, + ) -> RawDealerInformation { + RawDealerInformation { + announce_address: dealer_details.announce_address.clone(), + owner_address: dealer_details.address.to_string(), + node_index: dealer_details.assigned_index, + public_key: dealer_details.ed25519_identity.clone(), + verification_key_share: contract_share.map(|s| s.share.clone()), + share_verified: contract_share.map(|s| s.verified).unwrap_or(false), + } + } + + pub fn parse(&self) -> Result { + Ok(DealerInformation { + announce_address: self.announce_address.parse().map_err(|source| { + SignerCheckError::InvalidDealerAddress { + dealer_url: self.announce_address.clone(), + source, + } + })?, + owner_address: self.owner_address.clone(), + node_index: self.node_index, + public_key: self.announce_address.parse().map_err(|source| { + SignerCheckError::InvalidDealerPubkey { + dealer_url: self.announce_address.clone(), + source, + } + })?, + verification_key_share: self.verification_key_share.clone(), + share_verified: self.share_verified, + }) + } +} + +#[derive(Debug)] +pub struct DealerInformation { + pub announce_address: Url, + pub owner_address: String, + pub node_index: u64, + pub public_key: ed25519::PublicKey, + // no need to parse it into the full type as it doesn't get us anything + pub verification_key_share: Option, + pub share_verified: bool, +} + +impl From for RawDealerInformation { + fn from(d: DealerInformation) -> Self { + RawDealerInformation { + announce_address: d.announce_address.to_string(), + owner_address: d.owner_address, + node_index: d.node_index, + public_key: d.public_key.to_base58_string(), + verification_key_share: d.verification_key_share, + share_verified: d.share_verified, + } + } +} diff --git a/common/ecash-signer-check/src/error.rs b/common/ecash-signer-check/src/error.rs new file mode 100644 index 0000000000..bb7c3c719b --- /dev/null +++ b/common/ecash-signer-check/src/error.rs @@ -0,0 +1,24 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use nym_validator_client::nyxd::error::NyxdError; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum SignerCheckError { + #[error("failed to connect to nyxd chain due to invalid connection details: {source}")] + InvalidNyxdConnectionDetails { source: NyxdError }, + + #[error("failed to query the DKG contract: {source}")] + DKGContractQueryFailure { source: NyxdError }, +} + +impl SignerCheckError { + pub fn invalid_nyxd_connection_details(source: NyxdError) -> Self { + Self::InvalidNyxdConnectionDetails { source } + } + + pub fn dkg_contract_query_failure(source: NyxdError) -> Self { + Self::DKGContractQueryFailure { source } + } +} diff --git a/common/ecash-signer-check/src/lib.rs b/common/ecash-signer-check/src/lib.rs new file mode 100644 index 0000000000..2915119a27 --- /dev/null +++ b/common/ecash-signer-check/src/lib.rs @@ -0,0 +1,94 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::client_check::check_client; +use futures::stream::{FuturesUnordered, StreamExt}; +use nym_network_defaults::NymNetworkDetails; +use nym_validator_client::nyxd::contract_traits::{DkgQueryClient, PagedDkgQueryClient}; +use nym_validator_client::QueryHttpRpcNyxdClient; +use std::collections::HashMap; +use url::Url; + +pub use error::SignerCheckError; +use nym_ecash_signer_check_types::status::{SignerResult, Status}; +use nym_validator_client::ecash::models::EcashSignerStatusResponse; +use nym_validator_client::models::{ + ChainBlocksStatusResponse, ChainStatusResponse, SignerInformationResponse, +}; + +mod client_check; +pub mod error; + +pub type TypedSignerResult = SignerResult< + SignerInformationResponse, + EcashSignerStatusResponse, + ChainStatusResponse, + ChainBlocksStatusResponse, +>; +pub type LocalChainStatus = Status; +pub type SigningStatus = Status; + +pub struct SignersTestResult { + pub threshold: Option, + pub results: Vec, +} + +pub async fn check_signers( + rpc_endpoint: Url, + // details such as denoms, prefixes, etc. + network_details: NymNetworkDetails, +) -> Result { + // 1. create nyx client instance + let client = QueryHttpRpcNyxdClient::connect_with_network_details( + rpc_endpoint.as_str(), + network_details, + ) + .map_err(SignerCheckError::invalid_nyxd_connection_details)?; + + check_signers_with_client(&client).await +} + +pub async fn check_signers_with_client(client: &C) -> Result +where + C: DkgQueryClient + Sync, +{ + // 2. retrieve current dkg epoch + let dkg_epoch = client + .get_current_epoch() + .await + .map_err(SignerCheckError::dkg_contract_query_failure)?; + + // 3. retrieve the dkg threshold as reference point + let threshold = client + .get_epoch_threshold(dkg_epoch.epoch_id) + .await + .map_err(SignerCheckError::dkg_contract_query_failure)?; + + // 4. retrieve information on current DKG dealers (i.e. eligible signers) + let dealers = client + .get_all_current_dealers() + .await + .map_err(SignerCheckError::dkg_contract_query_failure)?; + + // 5. retrieve their published keys (if available) + let shares: HashMap<_, _> = client + .get_all_verification_key_shares(dkg_epoch.epoch_id) + .await + .map_err(SignerCheckError::dkg_contract_query_failure)? + .into_iter() + .map(|share| (share.node_index, share)) + .collect(); + + // 6. for each dealer attempt to perform the checks + let results = dealers + .into_iter() + .map(|d| { + let share = shares.get(&d.assigned_index); + check_client(d, dkg_epoch.epoch_id, share) + }) + .collect::>() + .collect::>() + .await; + + Ok(SignersTestResult { threshold, results }) +} diff --git a/common/ecash-signer-check/src/status.rs b/common/ecash-signer-check/src/status.rs new file mode 100644 index 0000000000..a75a86448c --- /dev/null +++ b/common/ecash-signer-check/src/status.rs @@ -0,0 +1,73 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::chain_status::LocalChainStatus; +use crate::dealer_information::RawDealerInformation; +use crate::signing_status::SigningStatus; +use std::time::Duration; + +pub(crate) const STALE_RESPONSE_THRESHOLD: Duration = Duration::from_secs(5 * 60); + +#[derive(Debug)] +pub struct SignerResult { + pub dkg_epoch_id: u64, + pub information: RawDealerInformation, + pub status: SignerStatus, +} + +impl SignerResult { + pub fn chain_available(&self) -> bool { + let Ok(parsed_info) = self.information.parse() else { + return false; + }; + + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + result.local_chain_status.available(parsed_info.public_key) + } + + pub fn signer_available(&self) -> bool { + let Ok(parsed_info) = self.information.parse() else { + return false; + }; + let SignerStatus::Tested { result } = &self.status else { + return false; + }; + + result.signing_status.available( + parsed_info.public_key, + self.dkg_epoch_id, + parsed_info.verification_key_share, + parsed_info.share_verified, + ) + } +} + +#[derive(Debug)] +pub enum SignerStatus { + Unreachable, + ProvidedInvalidDetails, + Tested { result: SignerTestResult }, +} + +impl SignerStatus { + pub fn with_details( + self, + information: impl Into, + dkg_epoch_id: u64, + ) -> SignerResult { + SignerResult { + dkg_epoch_id, + status: self, + information: information.into(), + } + } +} + +#[derive(Debug)] +pub struct SignerTestResult { + pub reported_version: String, + pub signing_status: SigningStatus, + pub local_chain_status: LocalChainStatus, +} diff --git a/common/gateway-storage/Cargo.toml b/common/gateway-storage/Cargo.toml index 810697f258..4ead02b939 100644 --- a/common/gateway-storage/Cargo.toml +++ b/common/gateway-storage/Cargo.toml @@ -9,8 +9,10 @@ edition.workspace = true license.workspace = true [dependencies] +async-trait = { workspace = true } bincode = { workspace = true } defguard_wireguard_rs = { workspace = true } +dyn-clone = { workspace = true } sqlx = { workspace = true, features = [ "runtime-tokio-rustls", "sqlite", @@ -21,6 +23,7 @@ sqlx = { workspace = true, features = [ ] } time = { workspace = true } thiserror = { workspace = true } +tokio = { workspace = true, features = ["sync"], optional = true } tracing = { workspace = true } nym-credentials-interface = { path = "../credentials-interface" } @@ -35,3 +38,7 @@ sqlx = { workspace = true, features = [ "macros", "migrate", ] } + +[features] +default = [] +mock = ["tokio"] \ No newline at end of file diff --git a/common/gateway-storage/migrations/20250605120000_trim_wireguard_peer_data.sql b/common/gateway-storage/migrations/20250605120000_trim_wireguard_peer_data.sql new file mode 100644 index 0000000000..cd627850bf --- /dev/null +++ b/common/gateway-storage/migrations/20250605120000_trim_wireguard_peer_data.sql @@ -0,0 +1,19 @@ +/* + * Copyright 2025 - Nym Technologies SA + * SPDX-License-Identifier: Apache-2.0 + */ + +DELETE FROM wireguard_peer WHERE client_id IS NULL; + +CREATE TABLE wireguard_peer_new +( + public_key TEXT NOT NULL PRIMARY KEY UNIQUE, + allowed_ips BLOB NOT NULL, + client_id INTEGER REFERENCES clients(id) NOT NULL +); + +INSERT INTO wireguard_peer_new (public_key, allowed_ips, client_id) +SELECT public_key, allowed_ips, client_id FROM wireguard_peer; + +DROP TABLE wireguard_peer; +ALTER TABLE wireguard_peer_new RENAME TO wireguard_peer; \ No newline at end of file diff --git a/common/gateway-storage/src/clients.rs b/common/gateway-storage/src/clients.rs index 8bee61e04b..83365f8cfd 100644 --- a/common/gateway-storage/src/clients.rs +++ b/common/gateway-storage/src/clients.rs @@ -3,6 +3,8 @@ use std::str::FromStr; +use nym_credentials_interface::TicketType; + use crate::models::Client; #[derive(Debug, PartialEq, sqlx::Type)] @@ -15,6 +17,17 @@ pub enum ClientType { ExitWireguard, } +impl From for ClientType { + fn from(value: TicketType) -> Self { + match value { + TicketType::V1MixnetEntry => ClientType::EntryMixnet, + TicketType::V1MixnetExit => ClientType::ExitMixnet, + TicketType::V1WireguardEntry => ClientType::EntryWireguard, + TicketType::V1WireguardExit => ClientType::ExitWireguard, + } + } +} + impl FromStr for ClientType { type Err = &'static str; diff --git a/common/gateway-storage/src/error.rs b/common/gateway-storage/src/error.rs index 272d86b557..2600451751 100644 --- a/common/gateway-storage/src/error.rs +++ b/common/gateway-storage/src/error.rs @@ -20,6 +20,18 @@ pub enum GatewayStorageError { #[error("the stored data associated with ticket {ticket_id} is malformed!")] MalformedStoredTicketData { ticket_id: i64 }, - #[error("Failed to convert from type of database: {0}")] - TypeConversion(String), + #[error("Failed to convert from type of database: {field_key}")] + TypeConversion { field_key: &'static str }, + + #[error("Serialization failure for {field_key}")] + Serialize { + field_key: &'static str, + source: bincode::Error, + }, + + #[error("Deserialization failure for {field_key}")] + Deserialize { + field_key: &'static str, + source: bincode::Error, + }, } diff --git a/common/gateway-storage/src/lib.rs b/common/gateway-storage/src/lib.rs index ea534b8c1b..e10fdc3c1e 100644 --- a/common/gateway-storage/src/lib.rs +++ b/common/gateway-storage/src/lib.rs @@ -1,6 +1,7 @@ // Copyright 2020 - Nym Technologies SA // SPDX-License-Identifier: GPL-3.0-only +use async_trait::async_trait; use bandwidth::BandwidthManager; use clients::{ClientManager, ClientType}; use models::{ @@ -15,10 +16,10 @@ use sqlx::{ sqlite::{SqliteAutoVacuum, SqliteSynchronous}, ConnectOptions, }; -use std::path::Path; +use std::{path::Path, time::Duration}; use tickets::TicketStorageManager; use time::OffsetDateTime; -use tracing::{debug, error}; +use tracing::{debug, error, log::LevelFilter}; pub mod bandwidth; mod clients; @@ -27,11 +28,21 @@ mod inboxes; pub mod models; mod shared_keys; mod tickets; +pub mod traits; mod wireguard_peers; pub use error::GatewayStorageError; pub use inboxes::InboxManager; +use crate::traits::{BandwidthGatewayStorage, InboxGatewayStorage, SharedKeyGatewayStorage}; + +fn make_bincode_serializer() -> impl bincode::Options { + use bincode::Options; + bincode::DefaultOptions::new() + .with_big_endian() + .with_varint_encoding() +} + // note that clone here is fine as upon cloning the same underlying pool will be used #[derive(Clone)] pub struct GatewayStorage { @@ -71,6 +82,21 @@ impl GatewayStorage { &self.wireguard_peer_manager } + pub async fn handle_forget_me( + &self, + client_address: DestinationAddressBytes, + ) -> Result<(), GatewayStorageError> { + let client_id = self.get_mixnet_client_id(client_address).await?; + self.inbox_manager() + .remove_messages_for_client(&client_address.as_base58_string()) + .await?; + self.bandwidth_manager().remove_client(client_id).await?; + self.shared_key_manager() + .remove_shared_keys(&client_address.as_base58_string()) + .await?; + Ok(()) + } + /// Initialises `PersistentStorage` using the provided path. /// /// # Arguments @@ -92,6 +118,7 @@ impl GatewayStorage { .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) .synchronous(SqliteSynchronous::Normal) .auto_vacuum(SqliteAutoVacuum::Incremental) + .log_slow_statements(LevelFilter::Warn, Duration::from_millis(250)) .filename(database_path) .create_if_missing(true) .disable_statement_logging(); @@ -123,8 +150,9 @@ impl GatewayStorage { } } -impl GatewayStorage { - pub async fn get_mixnet_client_id( +#[async_trait] +impl SharedKeyGatewayStorage for GatewayStorage { + async fn get_mixnet_client_id( &self, client_address: DestinationAddressBytes, ) -> Result { @@ -134,22 +162,7 @@ impl GatewayStorage { .await?) } - pub async fn handle_forget_me( - &self, - client_address: DestinationAddressBytes, - ) -> Result<(), GatewayStorageError> { - let client_id = self.get_mixnet_client_id(client_address).await?; - self.inbox_manager() - .remove_messages_for_client(&client_address.as_base58_string()) - .await?; - self.bandwidth_manager().remove_client(client_id).await?; - self.shared_key_manager() - .remove_shared_keys(&client_address.as_base58_string()) - .await?; - Ok(()) - } - - pub async fn insert_shared_keys( + async fn insert_shared_keys( &self, client_address: DestinationAddressBytes, shared_keys: &SharedGatewayKey, @@ -178,7 +191,7 @@ impl GatewayStorage { Ok(client_id) } - pub async fn get_shared_keys( + async fn get_shared_keys( &self, client_address: DestinationAddressBytes, ) -> Result, GatewayStorageError> { @@ -190,7 +203,7 @@ impl GatewayStorage { } #[allow(dead_code)] - pub async fn remove_shared_keys( + async fn remove_shared_keys( &self, client_address: DestinationAddressBytes, ) -> Result<(), GatewayStorageError> { @@ -200,7 +213,7 @@ impl GatewayStorage { Ok(()) } - pub async fn update_last_used_authentication_timestamp( + async fn update_last_used_authentication_timestamp( &self, client_id: i64, last_used_authentication_timestamp: OffsetDateTime, @@ -214,12 +227,15 @@ impl GatewayStorage { Ok(()) } - pub async fn get_client(&self, client_id: i64) -> Result, GatewayStorageError> { + async fn get_client(&self, client_id: i64) -> Result, GatewayStorageError> { let client = self.client_manager.get_client(client_id).await?; Ok(client) } +} - pub async fn store_message( +#[async_trait] +impl InboxGatewayStorage for GatewayStorage { + async fn store_message( &self, client_address: DestinationAddressBytes, message: Vec, @@ -230,7 +246,7 @@ impl GatewayStorage { Ok(()) } - pub async fn retrieve_messages( + async fn retrieve_messages( &self, client_address: DestinationAddressBytes, start_after: Option, @@ -242,19 +258,22 @@ impl GatewayStorage { Ok(messages) } - pub async fn remove_messages(&self, ids: Vec) -> Result<(), GatewayStorageError> { + async fn remove_messages(&self, ids: Vec) -> Result<(), GatewayStorageError> { for id in ids { self.inbox_manager.remove_message(id).await?; } Ok(()) } +} - pub async fn create_bandwidth_entry(&self, client_id: i64) -> Result<(), GatewayStorageError> { +#[async_trait] +impl BandwidthGatewayStorage for GatewayStorage { + async fn create_bandwidth_entry(&self, client_id: i64) -> Result<(), GatewayStorageError> { self.bandwidth_manager.insert_new_client(client_id).await?; Ok(()) } - pub async fn set_expiration( + async fn set_expiration( &self, client_id: i64, expiration: OffsetDateTime, @@ -265,12 +284,12 @@ impl GatewayStorage { Ok(()) } - pub async fn reset_bandwidth(&self, client_id: i64) -> Result<(), GatewayStorageError> { + async fn reset_bandwidth(&self, client_id: i64) -> Result<(), GatewayStorageError> { self.bandwidth_manager.reset_bandwidth(client_id).await?; Ok(()) } - pub async fn get_available_bandwidth( + async fn get_available_bandwidth( &self, client_id: i64, ) -> Result, GatewayStorageError> { @@ -280,7 +299,7 @@ impl GatewayStorage { .await?) } - pub async fn increase_bandwidth( + async fn increase_bandwidth( &self, client_id: i64, amount: i64, @@ -291,7 +310,7 @@ impl GatewayStorage { .await?) } - pub async fn revoke_ticket_bandwidth( + async fn revoke_ticket_bandwidth( &self, ticket_id: i64, amount: i64, @@ -302,7 +321,7 @@ impl GatewayStorage { .await?) } - pub async fn decrease_bandwidth( + async fn decrease_bandwidth( &self, client_id: i64, amount: i64, @@ -313,7 +332,7 @@ impl GatewayStorage { .await?) } - pub async fn insert_epoch_signers( + async fn insert_epoch_signers( &self, epoch_id: i64, signer_ids: Vec, @@ -324,7 +343,7 @@ impl GatewayStorage { Ok(()) } - pub async fn insert_received_ticket( + async fn insert_received_ticket( &self, client_id: i64, received_at: OffsetDateTime, @@ -344,11 +363,11 @@ impl GatewayStorage { Ok(ticket_id) } - pub async fn contains_ticket(&self, serial_number: &[u8]) -> Result { + async fn contains_ticket(&self, serial_number: &[u8]) -> Result { Ok(self.ticket_manager.has_ticket_data(serial_number).await?) } - pub async fn insert_ticket_verification( + async fn insert_ticket_verification( &self, ticket_id: i64, signer_id: i64, @@ -361,7 +380,7 @@ impl GatewayStorage { Ok(()) } - pub async fn update_rejected_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError> { + async fn update_rejected_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError> { // set the ticket as rejected self.ticket_manager.set_rejected_ticket(ticket_id).await?; @@ -372,7 +391,7 @@ impl GatewayStorage { Ok(()) } - pub async fn update_verified_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError> { + async fn update_verified_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError> { // 1. insert into verified table self.ticket_manager .insert_verified_ticket(ticket_id) @@ -386,7 +405,7 @@ impl GatewayStorage { Ok(()) } - pub async fn remove_verified_ticket_binary_data( + async fn remove_verified_ticket_binary_data( &self, ticket_id: i64, ) -> Result<(), GatewayStorageError> { @@ -396,7 +415,7 @@ impl GatewayStorage { Ok(()) } - pub async fn get_all_verified_tickets_with_sn( + async fn get_all_verified_tickets_with_sn( &self, ) -> Result, GatewayStorageError> { Ok(self @@ -405,7 +424,7 @@ impl GatewayStorage { .await?) } - pub async fn get_all_proposed_tickets_with_sn( + async fn get_all_proposed_tickets_with_sn( &self, proposal_id: u32, ) -> Result, GatewayStorageError> { @@ -415,7 +434,7 @@ impl GatewayStorage { .await?) } - pub async fn insert_redemption_proposal( + async fn insert_redemption_proposal( &self, tickets: &[VerifiedTicket], proposal_id: u32, @@ -438,7 +457,7 @@ impl GatewayStorage { Ok(()) } - pub async fn clear_post_proposal_data( + async fn clear_post_proposal_data( &self, proposal_id: u32, resolved_at: OffsetDateTime, @@ -462,13 +481,11 @@ impl GatewayStorage { Ok(()) } - pub async fn latest_proposal(&self) -> Result, GatewayStorageError> { + async fn latest_proposal(&self) -> Result, GatewayStorageError> { Ok(self.ticket_manager.get_latest_redemption_proposal().await?) } - pub async fn get_all_unverified_tickets( - &self, - ) -> Result, GatewayStorageError> { + async fn get_all_unverified_tickets(&self) -> Result, GatewayStorageError> { self.ticket_manager .get_unverified_tickets() .await? @@ -477,21 +494,21 @@ impl GatewayStorage { .collect() } - pub async fn get_all_unresolved_proposals(&self) -> Result, GatewayStorageError> { + async fn get_all_unresolved_proposals(&self) -> Result, GatewayStorageError> { Ok(self .ticket_manager .get_all_unresolved_redemption_proposal_ids() .await?) } - pub async fn get_votes(&self, ticket_id: i64) -> Result, GatewayStorageError> { + async fn get_votes(&self, ticket_id: i64) -> Result, GatewayStorageError> { Ok(self .ticket_manager .get_verification_votes(ticket_id) .await?) } - pub async fn get_signers(&self, epoch_id: i64) -> Result, GatewayStorageError> { + async fn get_signers(&self, epoch_id: i64) -> Result, GatewayStorageError> { Ok(self.ticket_manager.get_epoch_signers(epoch_id).await?) } @@ -500,34 +517,20 @@ impl GatewayStorage { /// # Arguments /// /// * `peer`: wireguard peer data to be stored - /// * `with_client_id`: if the peer should have a corresponding client_id - /// (created with entry wireguard ticket) or live without one (or with an - /// exiting one), for temporary backwards compatibility. - pub async fn insert_wireguard_peer( + async fn insert_wireguard_peer( &self, peer: &defguard_wireguard_rs::host::Peer, - with_client_id: bool, - ) -> Result, GatewayStorageError> { + client_type: ClientType, + ) -> Result { let client_id = match self .wireguard_peer_manager .retrieve_peer(&peer.public_key.to_string()) .await? { Some(peer) => peer.client_id, - _ => { - if with_client_id { - Some( - self.client_manager - .insert_client(ClientType::EntryWireguard) - .await?, - ) - } else { - None - } - } + None => self.client_manager.insert_client(client_type).await?, }; - let mut peer = WireguardPeer::from(peer.clone()); - peer.client_id = client_id; + let peer = WireguardPeer::from_defguard_peer(peer.clone(), client_id)?; self.wireguard_peer_manager.insert_peer(&peer).await?; Ok(client_id) } @@ -537,7 +540,7 @@ impl GatewayStorage { /// # Arguments /// /// * `peer_public_key`: wireguard public key of the peer to be retrieved. - pub async fn get_wireguard_peer( + async fn get_wireguard_peer( &self, peer_public_key: &str, ) -> Result, GatewayStorageError> { @@ -549,7 +552,7 @@ impl GatewayStorage { } /// Retrieves all wireguard peers. - pub async fn get_all_wireguard_peers(&self) -> Result, GatewayStorageError> { + async fn get_all_wireguard_peers(&self) -> Result, GatewayStorageError> { let ret = self.wireguard_peer_manager.retrieve_all_peers().await?; Ok(ret) } @@ -559,7 +562,7 @@ impl GatewayStorage { /// # Arguments /// /// * `peer_public_key`: wireguard public key of the peer to be removed. - pub async fn remove_wireguard_peer( + async fn remove_wireguard_peer( &self, peer_public_key: &str, ) -> Result<(), GatewayStorageError> { diff --git a/common/gateway-storage/src/models.rs b/common/gateway-storage/src/models.rs index 531ed355de..32b12b80a5 100644 --- a/common/gateway-storage/src/models.rs +++ b/common/gateway-storage/src/models.rs @@ -1,9 +1,7 @@ // Copyright 2021-2024 - Nym Technologies SA // SPDX-License-Identifier: GPL-3.0-only -use std::time::SystemTime; - -use crate::error::GatewayStorageError; +use crate::{error::GatewayStorageError, make_bincode_serializer}; use nym_credentials_interface::{AvailableBandwidth, ClientTicket, CredentialSpendingData}; use nym_gateway_requests::shared_key::{LegacySharedKeys, SharedGatewayKey, SharedSymmetricKey}; use sqlx::FromRow; @@ -112,35 +110,24 @@ impl TryFrom for ClientTicket { #[derive(Debug, Clone, FromRow)] pub struct WireguardPeer { pub public_key: String, - pub preshared_key: Option, - pub protocol_version: Option, - pub endpoint: Option, - pub last_handshake: Option, - pub tx_bytes: i64, - pub rx_bytes: i64, - pub persistent_keepalive_interval: Option, pub allowed_ips: Vec, - pub client_id: Option, + pub client_id: i64, } -impl From for WireguardPeer { - fn from(value: defguard_wireguard_rs::host::Peer) -> Self { - WireguardPeer { +impl WireguardPeer { + pub fn from_defguard_peer( + value: defguard_wireguard_rs::host::Peer, + client_id: i64, + ) -> Result { + Ok(WireguardPeer { public_key: value.public_key.to_string(), - preshared_key: value.preshared_key.as_ref().map(|k| k.to_string()), - protocol_version: value.protocol_version.map(|v| v as i64), - endpoint: value.endpoint.map(|e| e.to_string()), - last_handshake: value.last_handshake.map(OffsetDateTime::from), - tx_bytes: value.tx_bytes as i64, - rx_bytes: value.rx_bytes as i64, - persistent_keepalive_interval: value.persistent_keepalive_interval.map(|v| v as i64), - allowed_ips: bincode::Options::serialize( - bincode::DefaultOptions::new(), - &value.allowed_ips, - ) - .unwrap_or_default(), - client_id: None, - } + allowed_ips: bincode::Options::serialize(make_bincode_serializer(), &value.allowed_ips) + .map_err(|source| crate::error::GatewayStorageError::Serialize { + field_key: "allowed_ips", + source, + })?, + client_id, + }) } } @@ -149,49 +136,20 @@ impl TryFrom for defguard_wireguard_rs::host::Peer { fn try_from(value: WireguardPeer) -> Result { Ok(Self { - public_key: value - .public_key - .as_str() - .try_into() - .map_err(|e| Self::Error::TypeConversion(format!("public key {e}")))?, - preshared_key: value - .preshared_key - .as_deref() - .map(TryFrom::try_from) - .transpose() - .map_err(|e| Self::Error::TypeConversion(format!("preshared key {e}")))?, - protocol_version: value - .protocol_version - .map(TryFrom::try_from) - .transpose() - .map_err(|e| Self::Error::TypeConversion(format!("protocol version {e}")))?, - endpoint: value - .endpoint - .as_deref() - .map(|e| e.parse()) - .transpose() - .map_err(|e| Self::Error::TypeConversion(format!("endpoint {e}")))?, - last_handshake: value.last_handshake.map(SystemTime::from), - tx_bytes: value - .tx_bytes - .try_into() - .map_err(|e| Self::Error::TypeConversion(format!("tx bytes {e}")))?, - rx_bytes: value - .rx_bytes - .try_into() - .map_err(|e| Self::Error::TypeConversion(format!("rx bytes {e}")))?, - persistent_keepalive_interval: value - .persistent_keepalive_interval - .map(TryFrom::try_from) - .transpose() - .map_err(|e| { - Self::Error::TypeConversion(format!("persistent keepalive interval {e}")) - })?, + public_key: value.public_key.as_str().try_into().map_err(|_| { + Self::Error::TypeConversion { + field_key: "public_key", + } + })?, allowed_ips: bincode::Options::deserialize( bincode::DefaultOptions::new(), &value.allowed_ips, ) - .map_err(|e| Self::Error::TypeConversion(format!("allowed ips {e}")))?, + .map_err(|source| Self::Error::Deserialize { + field_key: "allowed_ips", + source, + })?, + ..Default::default() }) } } diff --git a/common/gateway-storage/src/traits.rs b/common/gateway-storage/src/traits.rs new file mode 100644 index 0000000000..aa7e01e434 --- /dev/null +++ b/common/gateway-storage/src/traits.rs @@ -0,0 +1,511 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use async_trait::async_trait; +use nym_credentials_interface::ClientTicket; +use nym_gateway_requests::SharedGatewayKey; +use nym_sphinx::DestinationAddressBytes; +use time::OffsetDateTime; + +use crate::{ + clients::ClientType, + models::{ + Client, PersistedBandwidth, PersistedSharedKeys, RedemptionProposal, StoredMessage, + VerifiedTicket, WireguardPeer, + }, + GatewayStorageError, +}; + +#[async_trait] +pub trait SharedKeyGatewayStorage { + async fn get_mixnet_client_id( + &self, + client_address: DestinationAddressBytes, + ) -> Result; + async fn insert_shared_keys( + &self, + client_address: DestinationAddressBytes, + shared_keys: &SharedGatewayKey, + ) -> Result; + async fn get_shared_keys( + &self, + client_address: DestinationAddressBytes, + ) -> Result, GatewayStorageError>; + #[allow(dead_code)] + async fn remove_shared_keys( + &self, + client_address: DestinationAddressBytes, + ) -> Result<(), GatewayStorageError>; + async fn update_last_used_authentication_timestamp( + &self, + client_id: i64, + last_used_authentication_timestamp: OffsetDateTime, + ) -> Result<(), GatewayStorageError>; + async fn get_client(&self, client_id: i64) -> Result, GatewayStorageError>; +} + +#[async_trait] +pub trait InboxGatewayStorage { + async fn store_message( + &self, + client_address: DestinationAddressBytes, + message: Vec, + ) -> Result<(), GatewayStorageError>; + async fn retrieve_messages( + &self, + client_address: DestinationAddressBytes, + start_after: Option, + ) -> Result<(Vec, Option), GatewayStorageError>; + async fn remove_messages(&self, ids: Vec) -> Result<(), GatewayStorageError>; +} + +#[async_trait] +pub trait BandwidthGatewayStorage: dyn_clone::DynClone { + async fn create_bandwidth_entry(&self, client_id: i64) -> Result<(), GatewayStorageError>; + async fn set_expiration( + &self, + client_id: i64, + expiration: OffsetDateTime, + ) -> Result<(), GatewayStorageError>; + async fn reset_bandwidth(&self, client_id: i64) -> Result<(), GatewayStorageError>; + async fn get_available_bandwidth( + &self, + client_id: i64, + ) -> Result, GatewayStorageError>; + async fn increase_bandwidth( + &self, + client_id: i64, + amount: i64, + ) -> Result; + async fn revoke_ticket_bandwidth( + &self, + ticket_id: i64, + amount: i64, + ) -> Result<(), GatewayStorageError>; + async fn decrease_bandwidth( + &self, + client_id: i64, + amount: i64, + ) -> Result; + + async fn insert_epoch_signers( + &self, + epoch_id: i64, + signer_ids: Vec, + ) -> Result<(), GatewayStorageError>; + async fn insert_received_ticket( + &self, + client_id: i64, + received_at: OffsetDateTime, + serial_number: Vec, + data: Vec, + ) -> Result; + async fn contains_ticket(&self, serial_number: &[u8]) -> Result; + async fn insert_ticket_verification( + &self, + ticket_id: i64, + signer_id: i64, + verified_at: OffsetDateTime, + accepted: bool, + ) -> Result<(), GatewayStorageError>; + async fn update_rejected_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError>; + async fn update_verified_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError>; + async fn remove_verified_ticket_binary_data( + &self, + ticket_id: i64, + ) -> Result<(), GatewayStorageError>; + async fn get_all_verified_tickets_with_sn( + &self, + ) -> Result, GatewayStorageError>; + async fn get_all_proposed_tickets_with_sn( + &self, + proposal_id: u32, + ) -> Result, GatewayStorageError>; + async fn insert_redemption_proposal( + &self, + tickets: &[VerifiedTicket], + proposal_id: u32, + created_at: OffsetDateTime, + ) -> Result<(), GatewayStorageError>; + async fn clear_post_proposal_data( + &self, + proposal_id: u32, + resolved_at: OffsetDateTime, + rejected: bool, + ) -> Result<(), GatewayStorageError>; + async fn latest_proposal(&self) -> Result, GatewayStorageError>; + async fn get_all_unverified_tickets(&self) -> Result, GatewayStorageError>; + async fn get_all_unresolved_proposals(&self) -> Result, GatewayStorageError>; + async fn get_votes(&self, ticket_id: i64) -> Result, GatewayStorageError>; + async fn get_signers(&self, epoch_id: i64) -> Result, GatewayStorageError>; + + /// Insert a wireguard peer in the storage. + /// + /// # Arguments + /// + /// * `peer`: wireguard peer data to be stored + async fn insert_wireguard_peer( + &self, + peer: &defguard_wireguard_rs::host::Peer, + client_type: ClientType, + ) -> Result; + + /// Tries to retrieve a particular peer with the given public key. + /// + /// # Arguments + /// + /// * `peer_public_key`: wireguard public key of the peer to be retrieved. + async fn get_wireguard_peer( + &self, + peer_public_key: &str, + ) -> Result, GatewayStorageError>; + + /// Retrieves all wireguard peers. + async fn get_all_wireguard_peers(&self) -> Result, GatewayStorageError>; + + /// Remove a wireguard peer from the storage. + /// + /// # Arguments + /// + /// * `peer_public_key`: wireguard public key of the peer to be removed. + async fn remove_wireguard_peer(&self, peer_public_key: &str) + -> Result<(), GatewayStorageError>; +} + +#[cfg(feature = "mock")] +pub mod mock { + use std::{collections::HashMap, sync::Arc}; + + use tokio::sync::RwLock; + + use super::*; + + struct EcashSigner { + _epoch_id: i64, + _signer_id: i64, + } + + struct ReceivedTicket { + client_id: i64, + _received_at: OffsetDateTime, + rejected: Option, + } + + struct TicketData { + serial_number: Vec, + data: Option>, + } + + struct TicketVerification { + _ticket_id: i64, + _signer_id: i64, + _verified_at: OffsetDateTime, + _accepted: bool, + } + + #[derive(Default)] + pub struct MockGatewayStorage { + available_bandwidth: HashMap, + ecash_signers: Vec, + received_ticket: HashMap, + ticket_data: HashMap, + ticket_verification: HashMap, + verified_tickets: Vec, + wireguard_peers: HashMap, + clients: HashMap, + } + + #[async_trait] + impl BandwidthGatewayStorage for Arc> { + async fn create_bandwidth_entry(&self, client_id: i64) -> Result<(), GatewayStorageError> { + self.write().await.available_bandwidth.insert( + client_id, + PersistedBandwidth { + client_id, + available: 0, + expiration: Some(OffsetDateTime::UNIX_EPOCH), + }, + ); + Ok(()) + } + + async fn set_expiration( + &self, + client_id: i64, + expiration: OffsetDateTime, + ) -> Result<(), GatewayStorageError> { + if let Some(bw) = self.write().await.available_bandwidth.get_mut(&client_id) { + bw.expiration = Some(expiration); + } + Ok(()) + } + + async fn reset_bandwidth(&self, client_id: i64) -> Result<(), GatewayStorageError> { + if let Some(bw) = self.write().await.available_bandwidth.get_mut(&client_id) { + bw.available = 0; + bw.expiration = Some(OffsetDateTime::UNIX_EPOCH); + } + Ok(()) + } + + async fn get_available_bandwidth( + &self, + client_id: i64, + ) -> Result, GatewayStorageError> { + Ok(self + .read() + .await + .available_bandwidth + .get(&client_id) + .cloned()) + } + + async fn increase_bandwidth( + &self, + client_id: i64, + amount: i64, + ) -> Result { + self.write() + .await + .available_bandwidth + .get_mut(&client_id) + .map(|bw| { + bw.available += amount; + bw.available + }) + .ok_or(GatewayStorageError::InternalDatabaseError( + sqlx::Error::RowNotFound, + )) + } + + async fn revoke_ticket_bandwidth( + &self, + ticket_id: i64, + amount: i64, + ) -> Result<(), GatewayStorageError> { + let mut guard = self.write().await; + if let Some(client_id) = guard + .received_ticket + .get(&ticket_id) + .map(|ticket| ticket.client_id) + { + if let Some(bw) = guard.available_bandwidth.get_mut(&client_id) { + bw.available -= amount; + } + } + Ok(()) + } + + async fn decrease_bandwidth( + &self, + client_id: i64, + amount: i64, + ) -> Result { + self.write() + .await + .available_bandwidth + .get_mut(&client_id) + .map(|bw| { + bw.available -= amount; + bw.available + }) + .ok_or(GatewayStorageError::InternalDatabaseError( + sqlx::Error::RowNotFound, + )) + } + + async fn insert_epoch_signers( + &self, + _epoch_id: i64, + signer_ids: Vec, + ) -> Result<(), GatewayStorageError> { + self.write() + .await + .ecash_signers + .extend(signer_ids.iter().map(|signer_id| EcashSigner { + _epoch_id, + _signer_id: *signer_id, + })); + Ok(()) + } + + async fn insert_received_ticket( + &self, + client_id: i64, + _received_at: OffsetDateTime, + serial_number: Vec, + data: Vec, + ) -> Result { + let mut guard = self.write().await; + let ticket_id = guard.received_ticket.len() as i64; + guard.received_ticket.insert( + ticket_id, + ReceivedTicket { + client_id, + _received_at, + rejected: None, + }, + ); + guard.ticket_data.insert( + ticket_id, + TicketData { + serial_number, + data: Some(data), + }, + ); + Ok(ticket_id) + } + + async fn contains_ticket(&self, serial_number: &[u8]) -> Result { + Ok(self + .read() + .await + .ticket_data + .values() + .any(|ticket_data| ticket_data.serial_number == serial_number)) + } + + async fn insert_ticket_verification( + &self, + _ticket_id: i64, + _signer_id: i64, + _verified_at: OffsetDateTime, + _accepted: bool, + ) -> Result<(), GatewayStorageError> { + self.write().await.ticket_verification.insert( + _ticket_id, + TicketVerification { + _ticket_id, + _signer_id, + _verified_at, + _accepted, + }, + ); + Ok(()) + } + + async fn update_rejected_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError> { + let mut guard = self.write().await; + if let Some(ticket) = guard.received_ticket.get_mut(&ticket_id) { + ticket.rejected = Some(true); + } + guard.ticket_data.remove(&ticket_id); + Ok(()) + } + + async fn update_verified_ticket(&self, ticket_id: i64) -> Result<(), GatewayStorageError> { + let mut guard = self.write().await; + guard.verified_tickets.push(ticket_id); + guard.ticket_verification.remove(&ticket_id); + Ok(()) + } + + async fn remove_verified_ticket_binary_data( + &self, + ticket_id: i64, + ) -> Result<(), GatewayStorageError> { + if let Some(ticket) = self.write().await.ticket_data.get_mut(&ticket_id) { + ticket.data = None; + } + Ok(()) + } + + async fn get_all_verified_tickets_with_sn( + &self, + ) -> Result, GatewayStorageError> { + todo!() + } + + async fn get_all_proposed_tickets_with_sn( + &self, + _proposal_id: u32, + ) -> Result, GatewayStorageError> { + todo!() + } + + async fn insert_redemption_proposal( + &self, + _tickets: &[VerifiedTicket], + _proposal_id: u32, + _created_at: OffsetDateTime, + ) -> Result<(), GatewayStorageError> { + todo!() + } + + async fn clear_post_proposal_data( + &self, + _proposal_id: u32, + _resolved_at: OffsetDateTime, + _rejected: bool, + ) -> Result<(), GatewayStorageError> { + todo!() + } + + async fn latest_proposal(&self) -> Result, GatewayStorageError> { + todo!() + } + + async fn get_all_unverified_tickets( + &self, + ) -> Result, GatewayStorageError> { + todo!() + } + + async fn get_all_unresolved_proposals(&self) -> Result, GatewayStorageError> { + todo!() + } + + async fn get_votes(&self, _ticket_id: i64) -> Result, GatewayStorageError> { + todo!() + } + + async fn get_signers(&self, _epoch_id: i64) -> Result, GatewayStorageError> { + todo!() + } + + async fn insert_wireguard_peer( + &self, + peer: &defguard_wireguard_rs::host::Peer, + client_type: ClientType, + ) -> Result { + let mut guard = self.write().await; + let client_id = + if let Some(peer) = guard.wireguard_peers.get(&peer.public_key.to_string()) { + peer.client_id + } else { + let client_id = guard.clients.len() as i64; + guard.clients.insert(client_id, client_type.to_string()); + client_id + }; + guard.wireguard_peers.insert( + peer.public_key.to_string(), + WireguardPeer::from_defguard_peer(peer.clone(), client_id)?, + ); + Ok(client_id) + } + + async fn get_wireguard_peer( + &self, + peer_public_key: &str, + ) -> Result, GatewayStorageError> { + Ok(self + .read() + .await + .wireguard_peers + .get(peer_public_key) + .cloned()) + } + + async fn get_all_wireguard_peers(&self) -> Result, GatewayStorageError> { + todo!() + } + + async fn remove_wireguard_peer( + &self, + peer_public_key: &str, + ) -> Result<(), GatewayStorageError> { + self.write().await.wireguard_peers.remove(peer_public_key); + Ok(()) + } + } +} diff --git a/common/gateway-storage/src/wireguard_peers.rs b/common/gateway-storage/src/wireguard_peers.rs index 00c41483be..22bf178d99 100644 --- a/common/gateway-storage/src/wireguard_peers.rs +++ b/common/gateway-storage/src/wireguard_peers.rs @@ -27,15 +27,18 @@ impl WgPeerManager { pub(crate) async fn insert_peer(&self, peer: &WireguardPeer) -> Result<(), sqlx::Error> { sqlx::query!( r#" - INSERT OR IGNORE INTO wireguard_peer(public_key, preshared_key, protocol_version, endpoint, last_handshake, tx_bytes, rx_bytes, persistent_keepalive_interval, allowed_ips, client_id) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + INSERT OR IGNORE INTO wireguard_peer(public_key, allowed_ips, client_id) + VALUES (?, ?, ?); UPDATE wireguard_peer - SET preshared_key = ?, protocol_version = ?, endpoint = ?, last_handshake = ?, tx_bytes = ?, rx_bytes = ?, persistent_keepalive_interval = ?, allowed_ips = ?, client_id = ? + SET allowed_ips = ?, client_id = ? WHERE public_key = ? "#, - peer.public_key, peer.preshared_key, peer.protocol_version, peer.endpoint, peer.last_handshake, peer.tx_bytes, peer.rx_bytes, peer.persistent_keepalive_interval, peer.allowed_ips, peer.client_id, - peer.preshared_key, peer.protocol_version, peer.endpoint, peer.last_handshake, peer.tx_bytes, peer.rx_bytes, peer.persistent_keepalive_interval, peer.allowed_ips, peer.client_id, + peer.public_key, + peer.allowed_ips, + peer.client_id, + peer.allowed_ips, + peer.client_id, peer.public_key, ) .execute(&self.connection_pool) diff --git a/common/http-api-client/src/dns.rs b/common/http-api-client/src/dns.rs index eb93f71407..3c68afee1e 100644 --- a/common/http-api-client/src/dns.rs +++ b/common/http-api-client/src/dns.rs @@ -6,9 +6,9 @@ //! The resolver itself is the set combination of the google, cloudflare, and quad9 endpoints //! supporting DoH and DoT. //! -//! This resolver implements a fallback mechanism where, should the DNS-over-TLS resolution fail, a +//! This resolver supports a fallback mechanism where, should the DNS-over-TLS resolution fail, a //! followup resolution will be done using the hosts configured default (e.g. `/etc/resolve.conf` on -//! linux). +//! linux). This is disabled by default and can be enabled using [`enable_system_fallback`]. //! //! Requires the `dns-over-https-rustls`, `webpki-roots` feature for the //! `hickory-resolver` crate @@ -93,14 +93,14 @@ pub struct HickoryDnsResolver { // Tokio Runtime in initialization, so we must delay the actual // construction of the resolver. state: Arc>, - fallback: Arc>, + fallback: Option>>, dont_use_shared: bool, } impl Resolve for HickoryDnsResolver { fn resolve(&self, name: Name) -> Resolving { let resolver = self.state.clone(); - let fallback = self.fallback.clone(); + let maybe_fallback = self.fallback.clone(); let independent = self.dont_use_shared; Box::pin(async move { let resolver = resolver.get_or_try_init(|| { @@ -117,23 +117,30 @@ impl Resolve for HickoryDnsResolver { let lookup = match resolver.lookup_ip(name.as_str()).await { Ok(res) => res, Err(e) => { - // on failure use the fall back system configured DNS resolver - if !e.is_no_records_found() { - warn!("primary DNS failed w/ error {e}: using system fallback"); - } - let resolver = fallback.get_or_try_init(|| { - // using a closure here is slightly gross, but this makes sure that if the - // lazy-init returns an error it can be handled by the client - if independent { - new_resolver_system() - } else { - Ok(SHARED_RESOLVER - .fallback - .get_or_try_init(new_resolver_system)? - .clone()) + if let Some(ref fallback) = maybe_fallback { + // on failure use the fall back system configured DNS resolver + if !e.is_no_records_found() { + warn!("primary DNS failed w/ error {e}: using system fallback"); } - })?; - resolver.lookup_ip(name.as_str()).await? + let resolver = fallback.get_or_try_init(|| { + // using a closure here is slightly gross, but this makes sure that if the + // lazy-init returns an error it can be handled by the client + if independent { + new_resolver_system() + } else { + Ok(SHARED_RESOLVER + .fallback + .as_ref() + .ok_or(e)? // if the shared resolver has no fallback return the original error + .get_or_try_init(new_resolver_system)? + .clone()) + } + })?; + + resolver.lookup_ip(name.as_str()).await? + } else { + return Err(e.into()); + } } }; @@ -162,14 +169,17 @@ impl HickoryDnsResolver { let lookup = match resolver.lookup_ip(name).await { Ok(res) => res, Err(e) => { - // on failure use the fall back system configured DNS resolver - if !e.is_no_records_found() { - warn!("primary DNS failed w/ error {e}: using system fallback"); + if let Some(ref fallback) = self.fallback { + // on failure use the fall back system configured DNS resolver + if !e.is_no_records_found() { + warn!("primary DNS failed w/ error {e}: using system fallback"); + } + + let resolver = fallback.get_or_try_init(|| self.new_resolver_system())?; + resolver.lookup_ip(name).await? + } else { + return Err(e.into()); } - let resolver = self - .fallback - .get_or_try_init(|| self.new_resolver_system())?; - resolver.lookup_ip(name).await? } }; @@ -193,15 +203,34 @@ impl HickoryDnsResolver { } fn new_resolver_system(&self) -> Result { - if self.dont_use_shared { + if self.dont_use_shared || SHARED_RESOLVER.fallback.is_none() { new_resolver_system() } else { Ok(SHARED_RESOLVER .fallback + .as_ref() + .unwrap() .get_or_try_init(new_resolver_system)? .clone()) } } + + /// Enable fallback to the system default resolver if the primary (DoX) resolver fails + pub fn enable_system_fallback(&mut self) -> Result<(), HickoryDnsError> { + self.fallback = Some(Default::default()); + let _ = self + .fallback + .as_ref() + .unwrap() + .get_or_try_init(new_resolver_system)?; + Ok(()) + } + + /// Disable fallback resolution. If the primary resolver fails the error is + /// returned immediately + pub fn disable_system_fallback(&mut self) { + self.fallback = None; + } } /// Create a new resolver with a custom DoT based configuration. The options are overridden to look diff --git a/common/http-api-client/src/user_agent.rs b/common/http-api-client/src/user_agent.rs index 54fe6ac24e..1543798a6a 100644 --- a/common/http-api-client/src/user_agent.rs +++ b/common/http-api-client/src/user_agent.rs @@ -16,7 +16,7 @@ pub struct UserAgent { pub version: String, /// client platform pub platform: String, - /// source commit version for the calling calling crate / subsystem + /// source commit version for the calling crate / subsystem pub git_commit: String, } diff --git a/common/http-api-common/src/response/mod.rs b/common/http-api-common/src/response/mod.rs index ee1a84a785..2753aaf8f0 100644 --- a/common/http-api-common/src/response/mod.rs +++ b/common/http-api-common/src/response/mod.rs @@ -146,6 +146,12 @@ pub struct OutputParams { pub output: Option, } +impl OutputParams { + pub fn get_output(&self) -> Output { + self.output.unwrap_or_default() + } +} + impl Output { pub fn to_response(self, data: T) -> FormattedResponse { match self { diff --git a/common/wireguard/Cargo.toml b/common/wireguard/Cargo.toml index c999861cd6..cfa82a8bda 100644 --- a/common/wireguard/Cargo.toml +++ b/common/wireguard/Cargo.toml @@ -11,11 +11,13 @@ license.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +async-trait = { workspace = true } base64 = { workspace = true } bincode = { workspace = true } chrono = { workspace = true } dashmap = { workspace = true } defguard_wireguard_rs = { workspace = true } +dyn-clone = { workspace = true } futures = { workspace = true } # The latest version on crates.io at the time of writing this (6.0.0) has a # version mismatch with x25519-dalek/curve25519-dalek that is resolved in the @@ -37,3 +39,11 @@ nym-network-defaults = { path = "../network-defaults" } nym-task = { path = "../task" } nym-wireguard-types = { path = "../wireguard-types" } nym-node-metrics = { path = "../../nym-node/nym-node-metrics" } + +[dev-dependencies] +nym-gateway-storage = { path = "../gateway-storage", features = ["mock"] } + +[features] +default = [] +mock = ["nym-gateway-storage/mock"] + diff --git a/common/wireguard/src/error.rs b/common/wireguard/src/error.rs index d2fd0e7956..1353fba023 100644 --- a/common/wireguard/src/error.rs +++ b/common/wireguard/src/error.rs @@ -3,18 +3,18 @@ #[derive(Debug, thiserror::Error)] pub enum Error { - #[error("traffic byte data needs to be increasing")] - InconsistentConsumedBytes, - #[error("{0}")] Defguard(#[from] defguard_wireguard_rs::error::WireguardInterfaceError), #[error("internal {0}")] Internal(String), - #[error("storage should have the requested bandwidht entry")] + #[error("storage should have the requested bandwidth entry")] MissingClientBandwidthEntry, + #[error("kernel should have the requested client entry: {0}")] + MissingClientKernelEntry(String), + #[error("{0}")] GatewayStorage(#[from] nym_gateway_storage::error::GatewayStorageError), diff --git a/common/wireguard/src/lib.rs b/common/wireguard/src/lib.rs index 6b83c648d2..2706e17982 100644 --- a/common/wireguard/src/lib.rs +++ b/common/wireguard/src/lib.rs @@ -6,16 +6,15 @@ // #![warn(clippy::expect_used)] // #![warn(clippy::unwrap_used)] -use defguard_wireguard_rs::WGApi; +use defguard_wireguard_rs::{host::Peer, key::Key, net::IpAddrMask, WGApi, WireguardInterfaceApi}; use nym_crypto::asymmetric::x25519::KeyPair; +#[cfg(target_os = "linux")] +use nym_gateway_storage::GatewayStorage; use nym_wireguard_types::Config; use peer_controller::PeerControlRequest; use std::sync::Arc; use tokio::sync::mpsc::{self, Receiver, Sender}; -#[cfg(target_os = "linux")] -use defguard_wireguard_rs::{host::Peer, key::Key, net::IpAddrMask}; - #[cfg(target_os = "linux")] use nym_network_defaults::constants::WG_TUN_BASE_NAME; @@ -28,6 +27,81 @@ pub struct WgApiWrapper { inner: WGApi, } +impl WireguardInterfaceApi for WgApiWrapper { + fn create_interface( + &self, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.create_interface() + } + + fn assign_address( + &self, + address: &IpAddrMask, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.assign_address(address) + } + + fn configure_peer_routing( + &self, + peers: &[Peer], + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.configure_peer_routing(peers) + } + + #[cfg(not(target_os = "windows"))] + fn configure_interface( + &self, + config: &defguard_wireguard_rs::InterfaceConfiguration, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.configure_interface(config) + } + + #[cfg(target_os = "windows")] + fn configure_interface( + &self, + config: &defguard_wireguard_rs::InterfaceConfiguration, + dns: &[std::net::IpAddr], + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.configure_interface(config, dns) + } + + fn remove_interface( + &self, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.remove_interface() + } + + fn configure_peer( + &self, + peer: &Peer, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.configure_peer(peer) + } + + fn remove_peer( + &self, + peer_pubkey: &Key, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.remove_peer(peer_pubkey) + } + + fn read_interface_data( + &self, + ) -> Result< + defguard_wireguard_rs::host::Host, + defguard_wireguard_rs::error::WireguardInterfaceError, + > { + self.inner.read_interface_data() + } + + fn configure_dns( + &self, + dns: &[std::net::IpAddr], + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.inner.configure_dns(dns) + } +} + impl WgApiWrapper { pub fn new(wg_api: WGApi) -> Self { WgApiWrapper { inner: wg_api } @@ -84,9 +158,9 @@ pub struct WireguardData { /// Start wireguard device #[cfg(target_os = "linux")] pub async fn start_wireguard( - storage: nym_gateway_storage::GatewayStorage, + storage: GatewayStorage, metrics: nym_node_metrics::NymNodeMetrics, - all_peers: Vec, + peers: Vec, task_client: nym_task::TaskClient, wireguard_data: WireguardData, ) -> Result, Box> { @@ -100,29 +174,13 @@ pub async fn start_wireguard( let ifname = String::from(WG_TUN_BASE_NAME); let wg_api = defguard_wireguard_rs::WGApi::new(ifname.clone(), false)?; - let mut peer_bandwidth_managers = HashMap::with_capacity(all_peers.len()); - let peers = all_peers - .into_iter() - .map(Peer::try_from) - .collect::, _>>()? - .into_iter() - .map(|mut peer| { - // since WGApi doesn't set those values on init, let's set them to 0 - peer.rx_bytes = 0; - peer.tx_bytes = 0; - peer - }) - .collect::>(); + let mut peer_bandwidth_managers = HashMap::with_capacity(peers.len()); + for peer in peers.iter() { - let bandwidth_manager = - PeerController::generate_bandwidth_manager(storage.clone(), &peer.public_key) - .await? - .map(|bw_m| Arc::new(RwLock::new(bw_m))); - // Update storage with *x_bytes set to 0, as in kernel peers we can't set those values - // so we need to restart counting. Hopefully the bandwidth was counted in available_bandwidth - storage - .insert_wireguard_peer(peer, bandwidth_manager.is_some()) - .await?; + let bandwidth_manager = Arc::new(RwLock::new( + PeerController::generate_bandwidth_manager(Box::new(storage.clone()), &peer.public_key) + .await?, + )); peer_bandwidth_managers.insert(peer.public_key.clone(), (bandwidth_manager, peer.clone())); } @@ -175,7 +233,7 @@ pub async fn start_wireguard( let host = wg_api.read_interface_data()?; let wg_api = std::sync::Arc::new(WgApiWrapper::new(wg_api)); let mut controller = PeerController::new( - storage, + Box::new(storage), metrics, wg_api.clone(), host, diff --git a/common/wireguard/src/peer_controller.rs b/common/wireguard/src/peer_controller.rs index 0718d233ab..c7b8d5e32b 100644 --- a/common/wireguard/src/peer_controller.rs +++ b/common/wireguard/src/peer_controller.rs @@ -8,14 +8,11 @@ use defguard_wireguard_rs::{ }; use futures::channel::oneshot; use log::info; -use nym_authenticator_requests::latest::registration::{ - RemainingBandwidthData, BANDWIDTH_CAP_PER_DAY, -}; use nym_credential_verification::{ bandwidth_storage_manager::BandwidthStorageManager, BandwidthFlushingBehaviourConfig, ClientBandwidth, }; -use nym_gateway_storage::GatewayStorage; +use nym_gateway_storage::traits::BandwidthGatewayStorage; use nym_node_metrics::NymNodeMetrics; use nym_wireguard_types::DEFAULT_PEER_TIMEOUT_CHECK; use std::time::{Duration, SystemTime}; @@ -23,14 +20,12 @@ use std::{collections::HashMap, sync::Arc}; use tokio::sync::{mpsc, RwLock}; use tokio_stream::{wrappers::IntervalStream, StreamExt}; -use crate::WgApiWrapper; use crate::{error::Error, peer_handle::SharedBandwidthStorageManager}; -use crate::{peer_handle::PeerHandle, peer_storage_manager::PeerStorageManager}; +use crate::{peer_handle::PeerHandle, peer_storage_manager::CachedPeerManager}; pub enum PeerControlRequest { AddPeer { peer: Peer, - client_id: Option, response_tx: oneshot::Sender, }, RemovePeer { @@ -41,10 +36,6 @@ pub enum PeerControlRequest { key: Key, response_tx: oneshot::Sender, }, - QueryBandwidth { - key: Key, - response_tx: oneshot::Sender, - }, GetClientBandwidth { key: Key, response_tx: oneshot::Sender, @@ -64,17 +55,12 @@ pub struct QueryPeerControlResponse { pub peer: Option, } -pub struct QueryBandwidthControlResponse { - pub success: bool, - pub bandwidth_data: Option, -} - pub struct GetClientBandwidthControlResponse { pub client_bandwidth: Option, } pub struct PeerController { - storage: GatewayStorage, + storage: Box, // we have "all" metrics of a node, but they're behind a single Arc pointer, // so the overhead is minimal @@ -83,9 +69,9 @@ pub struct PeerController { // used to receive commands from individual handles too request_tx: mpsc::Sender, request_rx: mpsc::Receiver, - wg_api: Arc, + wg_api: Arc, host_information: Arc>, - bw_storage_managers: HashMap>, + bw_storage_managers: HashMap, timeout_check_interval: IntervalStream, task_client: nym_task::TaskClient, } @@ -93,11 +79,11 @@ pub struct PeerController { impl PeerController { #[allow(clippy::too_many_arguments)] pub fn new( - storage: GatewayStorage, + storage: Box, metrics: NymNodeMetrics, - wg_api: Arc, + wg_api: Arc, initial_host_information: Host, - bw_storage_managers: HashMap, Peer)>, + bw_storage_managers: HashMap, request_tx: mpsc::Sender, request_rx: mpsc::Receiver, task_client: nym_task::TaskClient, @@ -107,15 +93,11 @@ impl PeerController { ); let host_information = Arc::new(RwLock::new(initial_host_information)); for (public_key, (bandwidth_storage_manager, peer)) in bw_storage_managers.iter() { - let peer_storage_manager = PeerStorageManager::new( - storage.clone(), - peer.clone(), - bandwidth_storage_manager.is_some(), - ); + let cached_peer_manager = CachedPeerManager::new(peer); let mut handle = PeerHandle::new( public_key.clone(), host_information.clone(), - peer_storage_manager, + cached_peer_manager, bandwidth_storage_manager.clone(), request_tx.clone(), &task_client, @@ -144,32 +126,11 @@ impl PeerController { } } - // Function that should be used for peer insertion, to handle both storage and kernel interaction - pub async fn add_peer(&self, peer: &Peer, client_id: Option) -> Result<(), Error> { - if client_id.is_none() { - self.storage.insert_wireguard_peer(peer, false).await?; - } - let ret: Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> = - self.wg_api.inner.configure_peer(peer); - if client_id.is_none() && ret.is_err() { - // Try to revert the insertion in storage - if self - .storage - .remove_wireguard_peer(&peer.public_key.to_string()) - .await - .is_err() - { - log::error!("The storage has been corrupted. Wireguard peer {} will persist in storage indefinitely.", peer.public_key); - } - } - Ok(ret?) - } - // Function that should be used for peer removal, to handle both storage and kernel interaction pub async fn remove_peer(&mut self, key: &Key) -> Result<(), Error> { self.storage.remove_wireguard_peer(&key.to_string()).await?; self.bw_storage_managers.remove(key); - let ret = self.wg_api.inner.remove_peer(key); + let ret = self.wg_api.remove_peer(key); if ret.is_err() { log::error!("Wireguard peer could not be removed from wireguard kernel module. Process should be restarted so that the interface is reset."); } @@ -177,50 +138,43 @@ impl PeerController { } pub async fn generate_bandwidth_manager( - storage: GatewayStorage, + storage: Box, public_key: &Key, - ) -> Result, Error> { - if let Some(client_id) = storage + ) -> Result { + let client_id = storage .get_wireguard_peer(&public_key.to_string()) .await? .ok_or(Error::MissingClientBandwidthEntry)? - .client_id - { - let bandwidth = storage - .get_available_bandwidth(client_id) - .await? - .ok_or(Error::MissingClientBandwidthEntry)?; - Ok(Some(BandwidthStorageManager::new( - storage, - ClientBandwidth::new(bandwidth.into()), - client_id, - BandwidthFlushingBehaviourConfig::default(), - true, - ))) - } else { - Ok(None) - } + .client_id; + + let bandwidth = storage + .get_available_bandwidth(client_id) + .await? + .ok_or(Error::MissingClientBandwidthEntry)?; + + Ok(BandwidthStorageManager::new( + storage, + ClientBandwidth::new(bandwidth.into()), + client_id, + BandwidthFlushingBehaviourConfig::default(), + true, + )) } - async fn handle_add_request( - &mut self, - peer: &Peer, - client_id: Option, - ) -> Result<(), Error> { - self.add_peer(peer, client_id).await?; - let bandwidth_storage_manager = - Self::generate_bandwidth_manager(self.storage.clone(), &peer.public_key) - .await? - .map(|bw_m| Arc::new(RwLock::new(bw_m))); - let peer_storage_manager = PeerStorageManager::new( - self.storage.clone(), - peer.clone(), - bandwidth_storage_manager.is_some(), - ); + async fn handle_add_request(&mut self, peer: &Peer) -> Result<(), Error> { + self.wg_api.configure_peer(peer)?; + let bandwidth_storage_manager = Arc::new(RwLock::new( + Self::generate_bandwidth_manager( + dyn_clone::clone_box(&*self.storage), + &peer.public_key, + ) + .await?, + )); + let cached_peer_manager = CachedPeerManager::new(peer); let mut handle = PeerHandle::new( peer.public_key.clone(), self.host_information.clone(), - peer_storage_manager, + cached_peer_manager, bandwidth_storage_manager.clone(), self.request_tx.clone(), &self.task_client, @@ -228,7 +182,7 @@ impl PeerController { self.bw_storage_managers .insert(peer.public_key.clone(), bandwidth_storage_manager); // try to immediately update the host information, to eliminate races - if let Ok(host_information) = self.wg_api.inner.read_interface_data() { + if let Ok(host_information) = self.wg_api.read_interface_data() { *self.host_information.write().await = host_information; } let public_key = peer.public_key.clone(); @@ -248,35 +202,8 @@ impl PeerController { .transpose()?) } - async fn handle_query_bandwidth( - &self, - key: &Key, - ) -> Result, Error> { - let Some(bandwidth_storage_manager) = self.bw_storage_managers.get(key) else { - return Ok(None); - }; - let available_bandwidth = if let Some(bandwidth_storage_manager) = bandwidth_storage_manager - { - bandwidth_storage_manager - .read() - .await - .available_bandwidth() - .await - } else { - let Some(peer) = self.host_information.read().await.peers.get(key).cloned() else { - // host information not updated yet - return Ok(None); - }; - BANDWIDTH_CAP_PER_DAY.saturating_sub(peer.rx_bytes + peer.tx_bytes) as i64 - }; - - Ok(Some(RemainingBandwidthData { - available_bandwidth, - })) - } - async fn handle_get_client_bandwidth(&self, key: &Key) -> Option { - if let Some(Some(bandwidth_storage_manager)) = self.bw_storage_managers.get(key) { + if let Some(bandwidth_storage_manager) = self.bw_storage_managers.get(key) { Some(bandwidth_storage_manager.read().await.client_bandwidth()) } else { None @@ -362,7 +289,7 @@ impl PeerController { loop { tokio::select! { _ = self.timeout_check_interval.next() => { - let Ok(host) = self.wg_api.inner.read_interface_data() else { + let Ok(host) = self.wg_api.read_interface_data() else { log::error!("Can't read wireguard kernel data"); continue; }; @@ -376,8 +303,8 @@ impl PeerController { } msg = self.request_rx.recv() => { match msg { - Some(PeerControlRequest::AddPeer { peer, client_id, response_tx }) => { - let ret = self.handle_add_request(&peer, client_id).await; + Some(PeerControlRequest::AddPeer { peer, response_tx }) => { + let ret = self.handle_add_request(&peer).await; if ret.is_ok() { response_tx.send(AddPeerControlResponse { success: true }).ok(); } else { @@ -396,14 +323,6 @@ impl PeerController { response_tx.send(QueryPeerControlResponse { success: false, peer: None }).ok(); } } - Some(PeerControlRequest::QueryBandwidth { key, response_tx }) => { - let ret = self.handle_query_bandwidth(&key).await; - if let Ok(bandwidth_data) = ret { - response_tx.send(QueryBandwidthControlResponse { success: true, bandwidth_data }).ok(); - } else { - response_tx.send(QueryBandwidthControlResponse { success: false, bandwidth_data: None }).ok(); - } - } Some(PeerControlRequest::GetClientBandwidth { key, response_tx }) => { let client_bandwidth = self.handle_get_client_bandwidth(&key).await; response_tx.send(GetClientBandwidthControlResponse { client_bandwidth }).ok(); @@ -419,3 +338,135 @@ impl PeerController { } } } + +#[cfg(feature = "mock")] +#[derive(Default)] +struct MockWgApi { + peers: std::sync::RwLock>, +} + +#[cfg(feature = "mock")] +impl WireguardInterfaceApi for MockWgApi { + fn create_interface( + &self, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + todo!() + } + + fn assign_address( + &self, + _address: &defguard_wireguard_rs::net::IpAddrMask, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + todo!() + } + + fn configure_peer_routing( + &self, + _peers: &[Peer], + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + todo!() + } + + #[cfg(not(target_os = "windows"))] + fn configure_interface( + &self, + _config: &defguard_wireguard_rs::InterfaceConfiguration, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + todo!() + } + + #[cfg(target_os = "windows")] + fn configure_interface( + &self, + _config: &defguard_wireguard_rs::InterfaceConfiguration, + _dns: &[std::net::IpAddr], + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + todo!() + } + + fn remove_interface( + &self, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + todo!() + } + + fn configure_peer( + &self, + peer: &Peer, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.peers + .write() + .unwrap() + .insert(peer.public_key.clone(), peer.clone()); + Ok(()) + } + + fn remove_peer( + &self, + peer_pubkey: &Key, + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + self.peers.write().unwrap().remove(peer_pubkey); + Ok(()) + } + + fn read_interface_data( + &self, + ) -> Result { + let mut host = Host::default(); + host.peers = self.peers.read().unwrap().clone(); + Ok(host) + } + + fn configure_dns( + &self, + _dns: &[std::net::IpAddr], + ) -> Result<(), defguard_wireguard_rs::error::WireguardInterfaceError> { + todo!() + } +} + +#[cfg(feature = "mock")] +pub fn start_controller( + request_tx: mpsc::Sender, + request_rx: mpsc::Receiver, +) -> ( + Arc>, + nym_task::TaskManager, +) { + let storage = Arc::new(RwLock::new( + nym_gateway_storage::traits::mock::MockGatewayStorage::default(), + )); + let wg_api = Arc::new(MockWgApi::default()); + let task_manager = nym_task::TaskManager::default(); + let mut peer_controller = PeerController::new( + Box::new(storage.clone()), + Default::default(), + wg_api, + Default::default(), + Default::default(), + request_tx, + request_rx, + task_manager.subscribe(), + ); + tokio::spawn(async move { peer_controller.run().await }); + + (storage, task_manager) +} + +#[cfg(feature = "mock")] +pub async fn stop_controller(mut task_manager: nym_task::TaskManager) { + task_manager.signal_shutdown().unwrap(); + task_manager.wait_for_shutdown().await; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn start_and_stop() { + let (request_tx, request_rx) = mpsc::channel(1); + let (_, task_manager) = start_controller(request_tx.clone(), request_rx); + stop_controller(task_manager).await; + } +} diff --git a/common/wireguard/src/peer_handle.rs b/common/wireguard/src/peer_handle.rs index e4de154ee6..f6c4673e21 100644 --- a/common/wireguard/src/peer_handle.rs +++ b/common/wireguard/src/peer_handle.rs @@ -3,13 +3,10 @@ use crate::error::Error; use crate::peer_controller::PeerControlRequest; -use crate::peer_storage_manager::PeerStorageManager; -use defguard_wireguard_rs::host::Peer; +use crate::peer_storage_manager::{CachedPeerManager, PeerInformation}; use defguard_wireguard_rs::{host::Host, key::Key}; use futures::channel::oneshot; -use nym_authenticator_requests::latest::registration::BANDWIDTH_CAP_PER_DAY; use nym_credential_verification::bandwidth_storage_manager::BandwidthStorageManager; -use nym_gateway_storage::models::WireguardPeer; use nym_task::TaskClient; use nym_wireguard_types::DEFAULT_PEER_TIMEOUT_CHECK; use std::sync::Arc; @@ -21,8 +18,8 @@ pub(crate) type SharedBandwidthStorageManager = Arc>, - peer_storage_manager: PeerStorageManager, - bandwidth_storage_manager: Option, + cached_peer: CachedPeerManager, + bandwidth_storage_manager: SharedBandwidthStorageManager, request_tx: mpsc::Sender, timeout_check_interval: IntervalStream, task_client: TaskClient, @@ -32,8 +29,8 @@ impl PeerHandle { pub fn new( public_key: Key, host_information: Arc>, - peer_storage_manager: PeerStorageManager, - bandwidth_storage_manager: Option, + cached_peer: CachedPeerManager, + bandwidth_storage_manager: SharedBandwidthStorageManager, request_tx: mpsc::Sender, task_client: &TaskClient, ) -> Self { @@ -45,7 +42,7 @@ impl PeerHandle { PeerHandle { public_key, host_information, - peer_storage_manager, + cached_peer, bandwidth_storage_manager, request_tx, timeout_check_interval, @@ -69,14 +66,10 @@ impl PeerHandle { Ok(success) } - fn compute_spent_bandwidth(kernel_peer: &Peer, storage_peer: &WireguardPeer) -> Option { - let storage_peer_rx_bytes = u64::try_from(storage_peer.rx_bytes) - .inspect_err(|e| tracing::error!("Storage rx bytes could not be converted: {e}")) - .ok()?; - let storage_peer_tx_bytes = u64::try_from(storage_peer.tx_bytes) - .inspect_err(|e| tracing::error!("Storage tx bytes could not be converted: {e}")) - .ok()?; - + fn compute_spent_bandwidth( + kernel_peer: PeerInformation, + cached_peer: PeerInformation, + ) -> Option { let kernel_total = kernel_peer .rx_bytes .checked_add(kernel_peer.tx_bytes) @@ -88,21 +81,26 @@ impl PeerHandle { ); None })?; - let storage_total = storage_peer_rx_bytes - .checked_add(storage_peer_tx_bytes) + let cached_total = cached_peer + .rx_bytes + .checked_add(cached_peer.tx_bytes) .or_else(|| { - tracing::error!("Overflow on storage adding bytes: {storage_peer_rx_bytes} + {storage_peer_tx_bytes}"); + tracing::error!( + "Overflow on cached adding bytes: {} + {}", + cached_peer.rx_bytes, + cached_peer.tx_bytes + ); None })?; - kernel_total.checked_sub(storage_total).or_else(|| { - tracing::error!("Overflow on spent bandwidth subtraction: kernel - storage = {kernel_total} - {storage_total}"); + kernel_total.checked_sub(cached_total).or_else(|| { + tracing::error!("Overflow on spent bandwidth subtraction: kernel - cached = {kernel_total} - {cached_total}"); None }) } - async fn active_peer(&mut self, kernel_peer: &Peer) -> Result { - let Some(storage_peer) = self.peer_storage_manager.get_peer() else { + async fn active_peer(&mut self, kernel_peer: PeerInformation) -> Result { + let Some(cached_peer) = self.cached_peer.get_peer() else { log::debug!( "Peer {:?} not in storage anymore, shutting down handle", self.public_key @@ -110,76 +108,51 @@ impl PeerHandle { return Ok(false); }; - if let Some(bandwidth_manager) = &self.bandwidth_storage_manager { - let spent_bandwidth = Self::compute_spent_bandwidth(kernel_peer, &storage_peer) - .unwrap_or_else(|| { - // if gateway restarted, the kernel values restart from 0 - // and we should restart from 0 in storage as well - if let Some(peer_information) = - self.peer_storage_manager.peer_information.as_mut() - { - peer_information.force_sync = true; - peer_information.peer.rx_bytes = kernel_peer.rx_bytes; - peer_information.peer.tx_bytes = kernel_peer.tx_bytes; - } - 0 - }) - .try_into() - .map_err(|_| Error::InconsistentConsumedBytes)?; - if spent_bandwidth > 0 { - self.peer_storage_manager.update_trx(kernel_peer); - if bandwidth_manager - .write() - .await - .try_use_bandwidth(spent_bandwidth) - .await - .is_err() - { - tracing::debug!( - "Peer {} is out of bandwidth, removing it", - kernel_peer.public_key.to_string() - ); - let success = self.remove_peer().await?; - self.peer_storage_manager.remove_peer(); - return Ok(!success); - } - } - } else { - let spent_bandwidth = kernel_peer.rx_bytes + kernel_peer.tx_bytes; - if spent_bandwidth >= BANDWIDTH_CAP_PER_DAY { - log::debug!( - "Peer {} doesn't have bandwidth anymore, removing it", - self.public_key - ); - let success = self.remove_peer().await?; - return Ok(!success); - } + let spent_bandwidth = Self::compute_spent_bandwidth(kernel_peer, cached_peer) + .unwrap_or_default() + .try_into() + .inspect_err(|err| tracing::error!("Could not convert from u64 to i64: {err:?}")) + .unwrap_or_default(); + + self.cached_peer.update(kernel_peer); + + if spent_bandwidth > 0 + && self + .bandwidth_storage_manager + .write() + .await + .try_use_bandwidth(spent_bandwidth) + .await + .is_err() + { + tracing::debug!( + "Peer {} is out of bandwidth, removing it", + self.public_key.to_string() + ); + let success = self.remove_peer().await?; + self.cached_peer.remove_peer(); + return Ok(!success); } Ok(true) } async fn continue_checking(&mut self) -> Result { - let Some(kernel_peer) = self + let kernel_peer = self .host_information .read() .await .peers .get(&self.public_key) - .cloned() - else { - // the host information hasn't beed updated yet - return Ok(true); - }; - if !self.active_peer(&kernel_peer).await? { + .ok_or(Error::MissingClientKernelEntry(self.public_key.to_string()))? + .into(); + if !self.active_peer(kernel_peer).await? { log::debug!( "Peer {:?} is not active anymore, shutting down handle", self.public_key ); Ok(false) } else { - // Update storage values - self.peer_storage_manager.sync_storage_peer().await?; Ok(true) } } @@ -208,11 +181,10 @@ impl PeerHandle { _ = self.task_client.recv() => { log::trace!("PeerHandle: Received shutdown"); - if let Some(bandwidth_manager) = &self.bandwidth_storage_manager { - if let Err(e) = bandwidth_manager.write().await.sync_storage_bandwidth().await { - log::error!("Storage sync failed - {e}, unaccounted bandwidth might have been consumed"); - } + if let Err(e) = self.bandwidth_storage_manager.write().await.sync_storage_bandwidth().await { + log::error!("Storage sync failed - {e}, unaccounted bandwidth might have been consumed"); } + log::trace!("PeerHandle: Finished shutdown"); } } diff --git a/common/wireguard/src/peer_storage_manager.rs b/common/wireguard/src/peer_storage_manager.rs index 97a7463533..1675cf6b2f 100644 --- a/common/wireguard/src/peer_storage_manager.rs +++ b/common/wireguard/src/peer_storage_manager.rs @@ -1,12 +1,8 @@ // Copyright 2024 - Nym Technologies SA // SPDX-License-Identifier: Apache-2.0 -use crate::error::Error; use defguard_wireguard_rs::host::Peer; -use nym_gateway_storage::models::WireguardPeer; -use nym_gateway_storage::GatewayStorage; use std::time::Duration; -use time::OffsetDateTime; const DEFAULT_PEER_MAX_FLUSHING_RATE: Duration = Duration::from_secs(60 * 60 * 24); // 24h const DEFAULT_PEER_MAX_DELTA_FLUSHING_AMOUNT: u64 = 512 * 1024 * 1024; // 512MB @@ -29,116 +25,50 @@ impl Default for PeerFlushingBehaviourConfig { } } -pub struct PeerStorageManager { - pub(crate) storage: GatewayStorage, +pub struct CachedPeerManager { pub(crate) peer_information: Option, - pub(crate) cfg: PeerFlushingBehaviourConfig, - pub(crate) with_client_id: bool, } -impl PeerStorageManager { - pub(crate) fn new(storage: GatewayStorage, peer: Peer, with_client_id: bool) -> Self { - let peer_information = Some(PeerInformation::new(peer)); +impl CachedPeerManager { + pub(crate) fn new(peer: &Peer) -> Self { Self { - storage, - peer_information, - cfg: PeerFlushingBehaviourConfig::default(), - with_client_id, + peer_information: Some(peer.into()), } } - pub(crate) fn get_peer(&self) -> Option { + pub(crate) fn get_peer(&self) -> Option { self.peer_information - .as_ref() - .map(|p| p.peer.clone().into()) } pub(crate) fn remove_peer(&mut self) { self.peer_information = None; } - pub(crate) fn update_trx(&mut self, kernel_peer: &Peer) { + pub(crate) fn update(&mut self, kernel_peer: PeerInformation) { if let Some(peer_information) = self.peer_information.as_mut() { - peer_information.update_trx_bytes(kernel_peer.tx_bytes, kernel_peer.rx_bytes); + peer_information.update_trx_bytes(kernel_peer); } } - - pub(crate) async fn sync_storage_peer(&mut self) -> Result<(), Error> { - let Some(peer_information) = self.peer_information.as_mut() else { - return Ok(()); - }; - if !peer_information.should_sync(self.cfg) { - return Ok(()); - } - if self - .storage - .get_wireguard_peer(&peer_information.peer().public_key.to_string()) - .await? - .is_none() - { - self.peer_information = None; - return Ok(()); - } - self.storage - .insert_wireguard_peer(peer_information.peer(), self.with_client_id) - .await?; - - peer_information.resync_peer_with_storage(); - - Ok(()) - } } -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] pub(crate) struct PeerInformation { - pub(crate) peer: Peer, - pub(crate) last_synced: OffsetDateTime, + pub(crate) tx_bytes: u64, + pub(crate) rx_bytes: u64, +} - pub(crate) bytes_delta_since_sync: u64, - pub(crate) force_sync: bool, +impl From<&Peer> for PeerInformation { + fn from(value: &Peer) -> Self { + Self { + tx_bytes: value.tx_bytes, + rx_bytes: value.rx_bytes, + } + } } impl PeerInformation { - pub fn new(peer: Peer) -> PeerInformation { - PeerInformation { - peer, - last_synced: OffsetDateTime::now_utc(), - bytes_delta_since_sync: 0, - force_sync: false, - } - } - - pub(crate) fn should_sync(&self, cfg: PeerFlushingBehaviourConfig) -> bool { - if self.force_sync { - return true; - } - if self.bytes_delta_since_sync >= cfg.peer_max_delta_flushing_amount { - return true; - } - - if self.last_synced + cfg.peer_max_flushing_rate < OffsetDateTime::now_utc() - && self.bytes_delta_since_sync != 0 - { - return true; - } - - false - } - - pub(crate) fn peer(&self) -> &Peer { - &self.peer - } - - pub(crate) fn update_trx_bytes(&mut self, tx_bytes: u64, rx_bytes: u64) { - self.bytes_delta_since_sync += tx_bytes.saturating_sub(self.peer.tx_bytes) - + rx_bytes.saturating_sub(self.peer.rx_bytes); - self.peer.tx_bytes = tx_bytes; - self.peer.rx_bytes = rx_bytes; - } - - pub(crate) fn resync_peer_with_storage(&mut self) { - self.bytes_delta_since_sync = 0; - self.last_synced = OffsetDateTime::now_utc(); - self.force_sync = false; + pub(crate) fn update_trx_bytes(&mut self, peer: PeerInformation) { + self.tx_bytes = peer.tx_bytes; + self.rx_bytes = peer.rx_bytes; } } diff --git a/common/zulip-client/Cargo.toml b/common/zulip-client/Cargo.toml new file mode 100644 index 0000000000..acfc84a540 --- /dev/null +++ b/common/zulip-client/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "zulip-client" +version = "0.1.0" +authors.workspace = true +repository.workspace = true +homepage.workspace = true +documentation.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +readme.workspace = true + +[dependencies] +thiserror = { workspace = true } + +itertools = { workspace = true } +url = { workspace = true, features = ["serde"] } +serde = { workspace = true, features = ["derive"] } +zeroize = { workspace = true } + +nym-bin-common = { path = "../bin-common" } +nym-http-api-client = { path = "../http-api-client" } +reqwest = { workspace = true } +tracing = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true, features = ["full"] } +serde_json = { workspace = true } + +[lints] +workspace = true diff --git a/common/zulip-client/src/client.rs b/common/zulip-client/src/client.rs new file mode 100644 index 0000000000..5de0a18b5c --- /dev/null +++ b/common/zulip-client/src/client.rs @@ -0,0 +1,151 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +//! An incomplete Zulip API Client +//! +//! Currently, it serves a single purpose: to send a message to a server, +//! however, it could very easily be extended with additional functionalities. +//! +//! ## Sending Direct Message +//! +//! ```rust +//! # use zulip_client::{Client, ZulipClientError}; +//! # use zulip_client::message::DirectMessage; +//! # async fn try_send() -> Result<(), ZulipClientError> { +//! let api_key = "your-api-key"; +//! let email = "associated-email-address"; +//! let server = "https://server-address.com"; +//! let client = Client::builder(email, api_key, server)?.build()?; +//! // send to userid 12 +//! client.send_message((12u32, "hello world")).await?; +//! // more concrete typing +//! client.send_message(DirectMessage::new(12, "hello world2")).await?; +//! # Ok(()) +//! # } +//! ``` + +use crate::error::ZulipClientError; +use crate::message::{SendMessageResponse, SendableMessage}; +use nym_bin_common::bin_info; +use nym_http_api_client::UserAgent; +use reqwest::{header, Method, RequestBuilder}; +use serde::{Deserialize, Serialize}; +use std::str::FromStr; +use tracing::trace; +use url::Url; +use zeroize::Zeroizing; + +#[derive(Serialize, Deserialize)] +pub struct ClientConfig { + pub user_email: String, + pub api_key: String, + // TODO: introduce validation + pub user_agent: Option, + pub server_url: Url, +} + +pub struct Client { + server_url: Url, + + api_key: Zeroizing, + user_email: String, + + inner_client: reqwest::Client, +} + +fn default_user_agent() -> String { + UserAgent::from(bin_info!()).to_string() +} + +impl Client { + const MESSAGES_ENDPOINT: &'static str = "/api/v1/messages"; + + pub fn builder( + user_email: impl Into, + api_key: impl Into, + server_url: impl Into, + ) -> Result { + ClientBuilder::new(user_email, api_key, server_url) + } + + pub fn new(config: ClientConfig) -> Result { + let builder = ClientBuilder::new(config.user_email, config.api_key, config.server_url)?; + match config.user_agent { + Some(user_agent) => builder.user_agent(user_agent).build(), + None => builder.build(), + } + } + + pub async fn send_message( + &self, + msg: impl Into, + ) -> Result { + let url = format!("{}{}", self.server_url, Self::MESSAGES_ENDPOINT); + + self.build_request(Method::POST, Self::MESSAGES_ENDPOINT) + .form(&msg.into()) + .send() + .await + .map_err(|source| ZulipClientError::RequestSendingFailure { source, url })? + .json() + .await + .map_err(|source| ZulipClientError::RequestDecodeFailure { source }) + } + + fn build_request(&self, method: Method, endpoint: &'static str) -> RequestBuilder { + let url = format!("{}{endpoint}", self.server_url); + trace!("posting to {url}"); + + self.inner_client + .request(method, url) + .basic_auth(&self.user_email, Some(self.api_key.to_string())) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + } +} + +pub struct ClientBuilder { + api_key: Zeroizing, + user_email: String, + server_url: Url, + user_agent: Option, +} + +impl ClientBuilder { + pub fn new( + user_email: impl Into, + api_key: impl Into, + server_url: impl Into, + ) -> Result { + let server_url = server_url.into(); + let parsed_url = + Url::from_str(&server_url).map_err(|source| ZulipClientError::MalformedServerUrl { + raw: server_url, + source, + })?; + Ok(ClientBuilder { + api_key: Zeroizing::new(api_key.into()), + user_email: user_email.into(), + server_url: parsed_url, + user_agent: None, + }) + } + + #[must_use] + pub fn user_agent(mut self, user_agent: impl Into) -> Self { + self.user_agent = Some(user_agent.into()); + self + } + + pub fn build(self) -> Result { + let user_agent = self.user_agent.unwrap_or_else(default_user_agent); + Ok(Client { + api_key: self.api_key, + server_url: self.server_url, + user_email: self.user_email, + inner_client: reqwest::ClientBuilder::new() + .user_agent(user_agent) + .build() + .map_err(|source| ZulipClientError::ClientBuildFailure { source })?, + }) + } +} diff --git a/common/zulip-client/src/error.rs b/common/zulip-client/src/error.rs new file mode 100644 index 0000000000..8556833855 --- /dev/null +++ b/common/zulip-client/src/error.rs @@ -0,0 +1,22 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum ZulipClientError { + #[error("failed to send request to {url}: {source}")] + RequestSendingFailure { url: String, source: reqwest::Error }, + + #[error("failed to decode received response: {source}")] + RequestDecodeFailure { source: reqwest::Error }, + + #[error("failed to build internal client: {source}")] + ClientBuildFailure { source: reqwest::Error }, + + #[error("provided url ({raw}) is malformed: {source}")] + MalformedServerUrl { + raw: String, + source: url::ParseError, + }, +} diff --git a/common/zulip-client/src/lib.rs b/common/zulip-client/src/lib.rs new file mode 100644 index 0000000000..a7c25f7c52 --- /dev/null +++ b/common/zulip-client/src/lib.rs @@ -0,0 +1,11 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +pub mod client; +pub mod error; +pub mod message; + +pub type Id = u32; + +pub use client::{Client, ClientBuilder}; +pub use error::ZulipClientError; diff --git a/common/zulip-client/src/message/mod.rs b/common/zulip-client/src/message/mod.rs new file mode 100644 index 0000000000..307ef0222c --- /dev/null +++ b/common/zulip-client/src/message/mod.rs @@ -0,0 +1,215 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use crate::message::to::{ToChannel, ToDirect}; +use serde::{Deserialize, Serialize}; + +pub mod to; + +#[derive(Serialize, Deserialize, Debug)] +#[serde(tag = "result")] +#[serde(rename_all = "snake_case")] +pub enum SendMessageResponse { + Success { + id: i64, + automatic_new_visibility_policy: Option, + msg: String, + }, + Error { + code: String, + msg: String, + stream: Option, + }, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[serde(tag = "type")] +pub enum SendableMessageContent { + // old name: 'private' + Direct { + // internally this is a list + to: String, + content: String, + }, + // alternative name: 'channel' + Stream { + to: String, + topic: Option, + content: String, + }, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct SendableMessage { + #[serde(flatten)] + content: SendableMessageContent, + + /// For clients supporting local echo, the event queue ID for the client. + /// If passed, `local_id` is required. If the message is successfully sent, + /// the server will include `local_id` in the message event that the client with this `queue_id` + /// will receive notifying it of the new message via `GET /events`. + /// This lets the client know unambiguously that it should replace the locally echoed message, + /// rather than adding this new message + /// (which would be correct if the user had sent the new message from another device). + /// example: "fb67bf8a-c031-47cc-84cf-ed80accacda8" + queue_id: Option, + + /// For clients supporting local echo, a unique string-format identifier chosen freely by the client; + /// the server will pass it back to the client without inspecting it, as described in the `queue_id` description. + /// example: "100.01" + local_id: Option, + + /// Whether the message should be initially marked read by its sender. + /// If unspecified, the server uses a heuristic based on the client name. + read_by_sender: bool, +} + +impl SendableMessage { + pub fn new(content: impl Into) -> Self { + SendableMessage { + content: content.into(), + queue_id: None, + local_id: None, + read_by_sender: false, + } + } + + #[must_use] + pub fn with_queue(mut self, queue_id: impl Into, local_id: impl Into) -> Self { + self.queue_id = Some(queue_id.into()); + self.local_id = Some(local_id.into()); + self + } + + #[must_use] + pub fn read_by_sender(mut self, read_by_sender: bool) -> Self { + self.read_by_sender = read_by_sender; + self + } +} + +pub type PrivateMessage = DirectMessage; + +pub struct DirectMessage { + to: String, + content: String, +} + +impl DirectMessage { + pub fn new(to: impl Into, content: impl Into) -> Self { + DirectMessage { + to: to.into().to_string(), + content: content.into(), + } + } +} + +pub type ChannelMessage = StreamMessage; +pub struct StreamMessage { + to: String, + topic: Option, + content: String, +} + +impl StreamMessage { + pub fn new( + to: impl Into, + content: impl Into, + topic: Option, + ) -> Self { + StreamMessage { + to: to.into().to_string(), + topic, + content: content.into(), + } + } + + pub fn no_topic(to: impl Into, content: impl Into) -> Self { + Self::new(to, content, None) + } + + #[must_use] + pub fn with_topic(mut self, topic: impl Into) -> Self { + self.topic = Some(topic.into()); + self + } +} + +impl From for SendableMessage { + fn from(content: SendableMessageContent) -> Self { + SendableMessage::new(content) + } +} + +impl From for SendableMessage { + fn from(msg: DirectMessage) -> Self { + SendableMessageContent::from(msg).into() + } +} + +impl From for SendableMessageContent { + fn from(msg: DirectMessage) -> Self { + SendableMessageContent::Direct { + to: msg.to, + content: msg.content, + } + } +} + +impl From<(T, S)> for DirectMessage +where + T: Into, + S: Into, +{ + fn from((to, content): (T, S)) -> Self { + DirectMessage::new(to, content) + } +} + +impl From<(T, S)> for SendableMessage +where + T: Into, + S: Into, +{ + fn from((to, content): (T, S)) -> Self { + DirectMessage::new(to, content).into() + } +} + +impl From for SendableMessage { + fn from(msg: StreamMessage) -> Self { + SendableMessageContent::from(msg).into() + } +} + +impl From for SendableMessageContent { + fn from(msg: StreamMessage) -> Self { + SendableMessageContent::Stream { + to: msg.to, + topic: msg.topic, + content: msg.content, + } + } +} + +impl From<(T, S, Option)> for StreamMessage +where + T: Into, + S: Into, +{ + fn from((to, content, topic): (T, S, Option)) -> Self { + StreamMessage::new(to, content, topic.map(Into::into)) + } +} + +impl From<(T, S, Option)> for SendableMessage +where + T: Into, + S: Into, +{ + fn from(inner: (T, S, Option)) -> Self { + StreamMessage::from(inner).into() + } +} diff --git a/common/zulip-client/src/message/to.rs b/common/zulip-client/src/message/to.rs new file mode 100644 index 0000000000..0bafc3fe11 --- /dev/null +++ b/common/zulip-client/src/message/to.rs @@ -0,0 +1,128 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use crate::Id; +use itertools::Itertools; +use std::fmt::Display; + +// from the docs: +// For channel messages, either the name or integer ID of the channel. +// For direct messages, either a list containing integer user IDs +// or a list containing string Zulip API email addresses. +pub enum ToDirect { + ByIds(Vec), + ByNames(Vec), +} + +impl Display for ToDirect { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ToDirect::ByIds(ids) => write!(f, "[{}]", ids.iter().join(",")), + ToDirect::ByNames(names) => { + write!(f, "[{}]", names.join(",")) + } + } + } +} + +impl From> for ToDirect { + fn from(names: Vec) -> Self { + ToDirect::ByNames(names) + } +} + +impl From<&[String]> for ToDirect { + fn from(names: &[String]) -> Self { + names.to_vec().into() + } +} + +impl From<&[&str]> for ToDirect { + fn from(names: &[&str]) -> Self { + names + .iter() + .map(|s| s.to_string()) + .collect::>() + .into() + } +} + +impl From<&[&str; N]> for ToDirect { + fn from(names: &[&str; N]) -> Self { + names.as_slice().into() + } +} + +impl From> for ToDirect { + fn from(names: Vec<&str>) -> Self { + names.as_slice().into() + } +} + +impl From for ToDirect { + fn from(name: String) -> Self { + ToDirect::ByNames(vec![name]) + } +} + +impl From<&str> for ToDirect { + fn from(name: &str) -> Self { + name.to_string().into() + } +} + +impl From for ToDirect { + fn from(id: Id) -> Self { + ToDirect::ByIds(vec![id]) + } +} + +impl From<&[Id]> for ToDirect { + fn from(ids: &[Id]) -> Self { + ids.to_vec().into() + } +} + +impl From<&[Id; N]> for ToDirect { + fn from(ids: &[Id; N]) -> Self { + ids.as_slice().into() + } +} + +impl From> for ToDirect { + fn from(ids: Vec) -> Self { + ToDirect::ByIds(ids) + } +} + +pub enum ToChannel { + ByName(String), + ById(Id), +} + +impl Display for ToChannel { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ToChannel::ByName(name) => name.fmt(f), + ToChannel::ById(id) => id.fmt(f), + } + } +} + +impl From for ToChannel { + fn from(name: String) -> Self { + ToChannel::ByName(name) + } +} + +impl From<&str> for ToChannel { + fn from(name: &str) -> Self { + name.to_string().into() + } +} + +impl From for ToChannel { + fn from(id: Id) -> Self { + ToChannel::ById(id) + } +} diff --git a/deny.toml b/deny.toml index 5bd402997e..7a3323ce1b 100644 --- a/deny.toml +++ b/deny.toml @@ -104,6 +104,7 @@ allow = [ "Unicode-3.0", "OpenSSL", "Zlib", + "CDLA-Permissive-2.0", ] # The confidence threshold for detecting a license from license text. # The higher the value, the more closely the license text must be to the diff --git a/documentation/docs/components/operators/snippets/wg-exit-policy-install-output.mdx b/documentation/docs/components/operators/snippets/wg-exit-policy-install-output.mdx index 487e4027bd..ae026dc659 100644 --- a/documentation/docs/components/operators/snippets/wg-exit-policy-install-output.mdx +++ b/documentation/docs/components/operators/snippets/wg-exit-policy-install-output.mdx @@ -7,20 +7,32 @@ net.ipv6.conf.all.forwarding = 1 net.ipv4.ip_forward = 1 IP forwarding configured successfully. Creating Nym exit policy chain... -Creating chain NYM-EXIT... -Creating chain NYM-EXIT in ip6tables... -Linking NYM-EXIT to FORWARD chain... -Linking NYM-EXIT to IPv6 FORWARD chain... +Chain NYM-EXIT already exists. Flushing it... +Chain NYM-EXIT already exists in ip6tables. Flushing it... +NYM-EXIT all opt -- in * out nymwg 0.0.0.0/0 -> 0.0.0.0/0 +NYM-EXIT all opt in * out nymwg ::/0 -> ::/0 Setting up NAT rules... +MASQUERADE all opt -- in * out ens3 0.0.0.0/0 -> 0.0.0.0/0 IPv4 NAT rule already exists. +MASQUERADE all opt in * out ens3 ::/0 -> ::/0 IPv6 NAT rule already exists. +ACCEPT all opt -- in nymwg out ens3 0.0.0.0/0 -> 0.0.0.0/0 +ACCEPT all opt -- in ens3 out nymwg 0.0.0.0/0 -> 0.0.0.0/0 state RELATED,ESTABLISHED +ACCEPT all opt in nymwg out ens3 ::/0 -> ::/0 +ACCEPT all opt in ens3 out nymwg ::/0 -> ::/0 state RELATED,ESTABLISHED Configuring DNS and ICMP rules... -Added IPv6 ICMP rule (allow ping6). -Added IPv6 DNS rule (UDP). -Added IPv6 DNS rule (TCP). +ACCEPT icmp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 icmptype 8 +ACCEPT icmp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 icmptype 0 +ACCEPT icmpv6 opt in * out * ::/0 -> ::/0 +ACCEPT udp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 udp dpt:53 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpt:53 +ACCEPT udp opt in * out * ::/0 -> ::/0 udp dpt:53 +ACCEPT tcp opt in * out * ::/0 -> ::/0 tcp dpt:53 Applying Spamhaus blocklist... Downloading exit policy from https://nymtech.net/.wellknown/network-requester/exit-policy.txt Processing 429 blocklist rules... +REJECT all opt -- in * out * 0.0.0.0/0 -> 205.189.71.0/24 reject-with icmp-port-unreachable +REJECT all opt -- in * out * 0.0.0.0/0 -> 205.189.72.0/23 reject-with icmp-port-unreachable Blocklist applied successfully. Applying allowed ports... Adding rules for SILC (Port: 706) @@ -103,6 +115,11 @@ Adding rules for POP3OverTLS (Port: 995) Added: NYM-EXIT tcp port 995 Added: NYM-EXIT udp port 995 Added: NYM-EXIT udp port 995 +Adding rules for DarkFiTor (Port: 25551) + Added: NYM-EXIT tcp port 25551 + Added: NYM-EXIT tcp port 25551 + Added: NYM-EXIT udp port 25551 + Added: NYM-EXIT udp port 25551 Adding rules for MMCC (Port: 5050) Added: NYM-EXIT tcp port 5050 Added: NYM-EXIT tcp port 5050 @@ -268,6 +285,11 @@ Adding rules for Mumble (Port: 64738) Added: NYM-EXIT tcp port 64738 Added: NYM-EXIT udp port 64738 Added: NYM-EXIT udp port 64738 +Adding rules for DarkFi (Port: 26661) + Added: NYM-EXIT tcp port 26661 + Added: NYM-EXIT tcp port 26661 + Added: NYM-EXIT udp port 26661 + Added: NYM-EXIT udp port 26661 Adding rules for PPTP (Port: 1723) Added: NYM-EXIT tcp port 1723 Added: NYM-EXIT tcp port 1723 @@ -333,6 +355,11 @@ Adding rules for Kpasswd (Port: 464) Added: NYM-EXIT tcp port 464 Added: NYM-EXIT udp port 464 Added: NYM-EXIT udp port 464 +Adding rules for MoneroRPC (Port: 18089) + Added: NYM-EXIT tcp port 18089 + Added: NYM-EXIT tcp port 18089 + Added: NYM-EXIT udp port 18089 + Added: NYM-EXIT udp port 18089 Adding rules for RemoteHTTPS (Port: 981) Added: NYM-EXIT tcp port 981 Added: NYM-EXIT tcp port 981 @@ -398,6 +425,11 @@ Adding rules for GroupWise (Port: 1677) Added: NYM-EXIT tcp port 1677 Added: NYM-EXIT udp port 1677 Added: NYM-EXIT udp port 1677 +Adding rules for Monero (Port: 18080-18081) + Added: NYM-EXIT tcp port range 18080:18081 + Added: NYM-EXIT tcp port range 18080:18081 + Added: NYM-EXIT udp port range 18080:18081 + Added: NYM-EXIT udp port range 18080:18081 Adding rules for EnsimControlPanel (Port: 19638) Added: NYM-EXIT tcp port 19638 Added: NYM-EXIT tcp port 19638 diff --git a/documentation/docs/components/operators/snippets/wg-exit-policy-status-output.mdx b/documentation/docs/components/operators/snippets/wg-exit-policy-status-output.mdx index 7a1eaa5acf..8e8293a865 100644 --- a/documentation/docs/components/operators/snippets/wg-exit-policy-status-output.mdx +++ b/documentation/docs/components/operators/snippets/wg-exit-policy-status-output.mdx @@ -1,807 +1,795 @@ ```console -ESC[0;33mNym Exit Policy Status:ESC[0m -ESC[0;33m----------------------ESC[0m -ESC[0;32mNetwork Device:ESC[0m ens3 -ESC[0;32mWireguard Interface:ESC[0m nymwg +Nym Exit Policy Status: +---------------------- +Network Device: eth0 +Wireguard Interface: nymwg -ESC[0;33mInterface Details:ESC[0m -12: nymwg: mtu 1420 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000 - link/none +Interface Details: +87: nymwg: mtu 1420 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000 + link/none -ESC[0;33mIP Addresses:ESC[0m -12: nymwg: mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000 +IP Addresses: +87: nymwg: mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000 inet 10.1.0.1/32 brd 10.1.0.1 scope global nymwg valid_lft forever preferred_lft forever -12: nymwg: mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000 - inet6 fc01::1/112 scope global +87: nymwg: mtu 1420 qdisc noqueue state UNKNOWN group default qlen 1000 + inet6 fc01::1/112 scope global valid_lft forever preferred_lft forever -ESC[0;33mIptables Chains:ESC[0m +Iptables Chains: IPv4 Chain: Chain NYM-EXIT (1 references) - pkts bytes target prot opt in out source destination - 0 0 REJECT 0 -- * * 0.0.0.0/0 5.188.10.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 5.188.11.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 31.132.36.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 31.184.237.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 37.9.42.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 43.229.52.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 45.9.148.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 45.43.128.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 45.142.120.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.148.112.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.148.120.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.148.127.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.173.208.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 79.110.22.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.121.39.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.193.75.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.200.12.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.200.81.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.200.82.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.200.83.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.200.164.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.216.3.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.220.163.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.200.248.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.243.90.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.243.91.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.243.93.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.234.99.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 103.99.0.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 103.215.80.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 103.239.28.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.166.96.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.207.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.233.0.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.239.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.243.192.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.247.96.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.250.192.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.250.224.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 107.182.112.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 107.190.160.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 141.136.22.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 150.129.40.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 159.174.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 162.222.128.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 162.249.20.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 163.53.247.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 166.117.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 167.74.0.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 167.160.96.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 168.64.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 168.76.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 168.129.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 169.239.152.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 170.114.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 172.98.0.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 174.136.192.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 176.121.14.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.159.97.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.159.100.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.159.107.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.14.192.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.14.193.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.14.195.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.21.8.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.39.8.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.71.0.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.77.248.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.116.172.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.116.175.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.124.56.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.129.8.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.130.36.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.130.40.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.140.53.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.143.220.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.143.222.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.143.223.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.146.168.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.165.153.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.193.90.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.244.29.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.244.30.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.244.31.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 188.247.230.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.26.25.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.31.212.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.43.175.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.43.176.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.43.184.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.161.80.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.251.231.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 193.228.91.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 194.5.97.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 194.5.98.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 194.5.99.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 195.182.57.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 196.45.120.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 196.61.192.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 196.196.8.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 196.199.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 197.231.208.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.20.16.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.45.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.56.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.151.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.151.152.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.178.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.183.32.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.186.25.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.187.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.200.0.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.200.8.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 198.206.140.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.5.152.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.34.128.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.84.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.89.16.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.120.163.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.166.200.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.185.192.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.196.192.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.198.160.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.212.96.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.223.0.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.241.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.249.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.253.224.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 199.254.32.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.19.38.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.44.224.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.52.96.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.87.199.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.107.208.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.126.244.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.130.16.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.147.64.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.232.0.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.144.0.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.148.192.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.151.128.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.159.45.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.172.244.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.189.71.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.189.72.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.203.0.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.233.224.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 205.236.189.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.124.104.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.195.224.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.197.165.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.209.80.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.224.160.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.226.0.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.226.32.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 206.227.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 207.22.192.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 207.45.224.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 207.110.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 207.110.128.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 209.66.128.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 216.179.128.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 217.8.116.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 217.8.117.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 223.169.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 223.254.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 42.4.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 68.119.232.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 68.215.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 69.244.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 70.111.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 70.126.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 112.78.2.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 195.20.40.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 14.160.0.0/12 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 27.2.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 27.106.108.128/25 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 37.236.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.100.21.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 39.32.0.0/11 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 41.190.2.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 41.190.30.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 45.116.232.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.118.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.161.9.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 60.184.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 62.44.134.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 78.85.40.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 79.11.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 79.108.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 81.93.93.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 83.24.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 83.149.19.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 84.18.126.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.198.140.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.116.176.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.227.224.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.241.88.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 89.114.108.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.196.250.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 93.122.192.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 95.0.60.160/27 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 95.110.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 89.189.152.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 103.26.246.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 106.51.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 109.124.0.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 109.124.16.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 109.126.128.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 109.175.6.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 111.125.108.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 112.101.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 113.80.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 113.128.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 114.96.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 114.115.128.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 115.72.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 118.20.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.24.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 125.167.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 139.5.157.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 146.185.223.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 154.68.4.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 177.55.154.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 177.125.30.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 177.224.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.135.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 179.5.103.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 181.67.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 181.174.101.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 182.69.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 182.160.100.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 182.184.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 182.253.162.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 183.82.128.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 183.128.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.36.88.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.150.15.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 185.172.86.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 186.179.100.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 189.216.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 190.235.110.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 190.239.190.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.64.121.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 193.34.141.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 193.188.254.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 197.229.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 201.148.126.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 202.136.88.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 200.121.192.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 220.164.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 221.228.192.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 24.0.0.0/12 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 27.184.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.0.0.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 58.53.128.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 59.92.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 60.52.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 60.176.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 60.215.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 61.163.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 62.194.131.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 64.175.32.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 67.116.236.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 67.121.120.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 67.124.36.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 68.62.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 69.112.0.0/12 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 71.56.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 76.112.0.0/12 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 78.97.32.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 80.108.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 81.240.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 82.72.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 82.169.28.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 84.127.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 84.144.0.0/12 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 84.220.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.48.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.54.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.85.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.86.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.176.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 89.217.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.176.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.182.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 92.0.0.0/12 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 92.112.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 92.128.0.0/12 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 109.128.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 110.212.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 111.85.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 112.224.0.0/11 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 113.70.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 113.89.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 113.111.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 113.224.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 113.240.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 114.246.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 114.248.80.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 115.60.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 115.213.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 116.238.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 117.22.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 117.136.0.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 118.80.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 118.168.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 120.0.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 120.68.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 121.29.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 122.169.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 122.173.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.67.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.101.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.112.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.134.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.161.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.174.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.188.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 123.244.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 124.89.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 124.128.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 124.134.0.0/17 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 124.94.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 125.93.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 125.125.176.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 125.224.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 150.70.75.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 166.204.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.191.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.125.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 183.91.2.0/23 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 183.184.0.0/13 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 188.23.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 188.98.0.0/15 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 189.64.0.0/14 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 201.53.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 201.82.64.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 212.56.64.0/18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 218.202.219.0/24 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 220.152.128.0/22 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 220.178.0.0/19 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 221.11.32.0/20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 222.183.0.0/16 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 222.240.216.0/21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 82.165.159.132/31 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 91.208.144.164 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 209.182.193.155 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 213.205.38.29 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 5.79.71.205 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 5.79.71.225 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.129.41 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.129.213 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.144.42 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.147.11 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.151.95 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.153.71 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.153.115 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.168.194 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.169.101 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.170.84 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.174.35 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.179.9 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.182.164 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.184.75 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.186.110 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.186.114 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.188.186 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 38.229.191.189 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 46.244.21.4 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 50.21.181.152 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 50.63.202.35 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 52.5.245.208 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 64.71.166.50 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 64.71.188.178 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 67.215.255.139 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 74.200.48.169 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 74.208.153.9 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 74.208.164.166 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 74.208.64.191 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.17.31.122 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 85.17.31.82 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.18.146 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.149.145 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.149.153 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.18.112 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.18.141 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.190.153 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.190.154 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.190.157 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.20.192 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.24.200 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.253.18 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 87.106.26.9 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 95.211.230.75 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.42.225.122 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 104.244.14.252 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 109.70.26.37 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 144.217.74.156 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 146.148.124.166 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 148.81.111.111 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 151.80.148.103 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 176.58.104.168 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.162.203.202 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.162.203.211 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.162.203.226 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 178.162.217.107 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 184.105.76.250 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 184.105.192.2 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.0.72.20 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.0.72.21 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.169.69.25 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.42.116.41 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 192.42.119.41 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 193.166.255.170 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 193.166.255.171 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 204.11.56.48 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 208.91.197.46 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 212.227.20.93 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 212.227.20.116 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 212.227.20.164 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 213.165.83.176 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 216.218.135.114 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 216.218.185.162 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 216.218.208.114 reject-with icmp-port-unreachable - 0 0 REJECT 0 -- * * 0.0.0.0/0 216.66.15.109 reject-with icmp-port-unreachable - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:706 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:706 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5432 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5432 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2082:2083 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2082:2083 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:8232:8233 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:8232:8233 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1500 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1500 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:123 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:123 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1293 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1293 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:11371 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:11371 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:443 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:110 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:110 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1194 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1194 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3074 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:3074 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1521 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1521 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:2049 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:2049 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:88 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:88 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:995 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:995 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5050 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5050 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:43 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:43 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:991 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:991 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:143 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:143 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5228 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5228 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:445 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:445 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1755 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1755 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:993 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:993 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9001 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9001 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:5222:5223 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:5222:5223 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:20:21 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:20:21 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:60000:61000 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:60000:61000 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2102:2104 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2102:2104 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:873 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:873 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:27000:27050 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:27000:27050 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9418 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9418 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1863 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1863 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:8087:8088 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:8087:8088 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9030 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9030 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:4643 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:4643 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9339 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9339 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:902:904 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:902:904 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1533 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1533 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2095:2096 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2095:2096 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5190 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5190 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:749 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:749 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:4321 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:4321 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:10000 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:10000 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:53 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:53 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:19294 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:19294 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:220 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:220 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:8332:8333 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:8332:8333 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:64738 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:64738 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1723 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1723 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8443 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8443 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8888 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8888 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2086:2087 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2086:2087 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9735 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9735 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:554 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:554 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:853 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:853 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:22 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8082 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8082 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:992 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:992 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:25565 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:25565 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3690 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:3690 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:464 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:464 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:981 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:981 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9053 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9053 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:50002 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:50002 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9443 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9443 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:389 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:389 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:80:81 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:80:81 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:27017 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:27017 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:5000:5005 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:5000:5005 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1433 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1433 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8883 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8883 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:3306 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8767 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8767 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1677 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1677 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:19638 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:19638 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1220 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1220 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:79 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:79 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:989:990 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:989:990 - 0 0 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:636 - 0 0 ACCEPT 17 -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:636 - 0 0 REJECT 0 -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable + pkts bytes target prot opt in out source destination + 0 0 REJECT all -- * * 0.0.0.0/0 5.188.10.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 5.188.11.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 31.132.36.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 31.184.237.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 37.9.42.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 43.229.52.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 45.9.148.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 45.43.128.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 45.142.120.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.148.112.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.148.120.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.148.127.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.173.208.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 79.110.22.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.121.39.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.193.75.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.200.12.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.200.81.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.200.82.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.200.83.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.200.164.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.216.3.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.220.163.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.200.248.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.243.90.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.243.91.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.243.93.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.234.99.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 103.99.0.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 103.215.80.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 103.239.28.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.166.96.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.207.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.233.0.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.239.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.243.192.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.247.96.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.250.192.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.250.224.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 107.182.112.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 107.190.160.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 141.136.22.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 150.129.40.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 159.174.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 162.222.128.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 162.249.20.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 163.53.247.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 166.117.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 167.74.0.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 167.160.96.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 168.64.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 168.76.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 168.129.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 169.239.152.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 170.114.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 172.98.0.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 174.136.192.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 176.121.14.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.159.97.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.159.100.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.159.107.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.14.192.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.14.193.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.14.195.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.21.8.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.39.8.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.71.0.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.77.248.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.116.172.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.116.175.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.124.56.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.129.8.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.130.36.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.130.40.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.140.53.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.143.220.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.143.222.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.143.223.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.146.168.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.165.153.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.193.90.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.244.29.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.244.30.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.244.31.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 188.247.230.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.26.25.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.31.212.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.43.175.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.43.176.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.43.184.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.161.80.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.251.231.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 193.228.91.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 194.5.97.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 194.5.98.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 194.5.99.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 195.182.57.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 196.45.120.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 196.61.192.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 196.196.8.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 196.199.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 197.231.208.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.20.16.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.45.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.56.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.151.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.151.152.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.178.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.183.32.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.186.25.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.187.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.200.0.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.200.8.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 198.206.140.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.5.152.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.34.128.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.84.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.89.16.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.120.163.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.166.200.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.185.192.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.196.192.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.198.160.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.212.96.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.223.0.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.241.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.249.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.253.224.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 199.254.32.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.19.38.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.44.224.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.52.96.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.87.199.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.107.208.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.126.244.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.130.16.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.147.64.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.232.0.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.144.0.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.148.192.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.151.128.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.159.45.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.172.244.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.189.71.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.189.72.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.203.0.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.233.224.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 205.236.189.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.124.104.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.195.224.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.197.165.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.209.80.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.224.160.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.226.0.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.226.32.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 206.227.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 207.22.192.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 207.45.224.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 207.110.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 207.110.128.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 209.66.128.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 216.179.128.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 217.8.116.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 217.8.117.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 223.169.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 223.254.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 42.4.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 68.119.232.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 68.215.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 69.244.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 70.111.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 70.126.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 112.78.2.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 195.20.40.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 14.160.0.0/12 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 27.2.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 27.106.108.128/25 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 37.236.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.100.21.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 39.32.0.0/11 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 41.190.2.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 41.190.30.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 45.116.232.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.118.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.161.9.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 60.184.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 62.44.134.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 78.85.40.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 79.11.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 79.108.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 81.93.93.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 83.24.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 83.149.19.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 84.18.126.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.198.140.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.116.176.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.227.224.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.241.88.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 89.114.108.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.196.250.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 93.122.192.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 95.0.60.160/27 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 95.110.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 89.189.152.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 103.26.246.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 106.51.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 109.124.0.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 109.124.16.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 109.126.128.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 109.175.6.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 111.125.108.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 112.101.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 113.80.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 113.128.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 114.96.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 114.115.128.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 115.72.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 118.20.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.24.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 125.167.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 139.5.157.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 146.185.223.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 154.68.4.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 177.55.154.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 177.125.30.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 177.224.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.135.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 179.5.103.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 181.67.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 181.174.101.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 182.69.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 182.160.100.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 182.184.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 182.253.162.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 183.82.128.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 183.128.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.36.88.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.150.15.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 185.172.86.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 186.179.100.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 189.216.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 190.235.110.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 190.239.190.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.64.121.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 193.34.141.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 193.188.254.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 197.229.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 201.148.126.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 202.136.88.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 200.121.192.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 220.164.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 221.228.192.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 24.0.0.0/12 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 27.184.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.0.0.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 58.53.128.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 59.92.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 60.52.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 60.176.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 60.215.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 61.163.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 62.194.131.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 64.175.32.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 67.116.236.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 67.121.120.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 67.124.36.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 68.62.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 69.112.0.0/12 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 71.56.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 76.112.0.0/12 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 78.97.32.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 80.108.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 81.240.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 82.72.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 82.169.28.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 84.127.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 84.144.0.0/12 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 84.220.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.48.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.54.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.85.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.86.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.176.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 89.217.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.176.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.182.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 92.0.0.0/12 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 92.112.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 92.128.0.0/12 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 109.128.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 110.212.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 111.85.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 112.224.0.0/11 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 113.70.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 113.89.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 113.111.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 113.224.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 113.240.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 114.246.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 114.248.80.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 115.60.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 115.213.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 116.238.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 117.22.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 117.136.0.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 118.80.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 118.168.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 120.0.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 120.68.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 121.29.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 122.169.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 122.173.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.67.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.101.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.112.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.134.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.161.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.174.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.188.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 123.244.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 124.89.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 124.128.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 124.134.0.0/17 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 124.94.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 125.93.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 125.125.176.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 125.224.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 150.70.75.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 166.204.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.191.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.125.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 183.91.2.0/23 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 183.184.0.0/13 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 188.23.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 188.98.0.0/15 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 189.64.0.0/14 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 201.53.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 201.82.64.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 212.56.64.0/18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 218.202.219.0/24 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 220.152.128.0/22 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 220.178.0.0/19 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 221.11.32.0/20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 222.183.0.0/16 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 222.240.216.0/21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 82.165.159.132/31 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 91.208.144.164 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 209.182.193.155 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 213.205.38.29 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 5.79.71.205 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 5.79.71.225 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.129.41 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.129.213 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.144.42 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.147.11 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.151.95 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.153.71 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.153.115 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.168.194 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.169.101 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.170.84 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.174.35 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.179.9 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.182.164 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.184.75 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.186.110 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.186.114 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.188.186 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 38.229.191.189 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 46.244.21.4 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 50.21.181.152 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 50.63.202.35 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 52.5.245.208 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 64.71.166.50 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 64.71.188.178 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 67.215.255.139 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 74.200.48.169 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 74.208.153.9 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 74.208.164.166 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 74.208.64.191 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.17.31.122 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 85.17.31.82 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.18.146 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.149.145 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.149.153 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.18.112 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.18.141 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.190.153 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.190.154 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.190.157 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.20.192 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.24.200 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.253.18 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 87.106.26.9 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 95.211.230.75 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.42.225.122 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 104.244.14.252 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 109.70.26.37 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 144.217.74.156 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 146.148.124.166 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 148.81.111.111 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 151.80.148.103 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 176.58.104.168 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.162.203.202 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.162.203.211 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.162.203.226 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 178.162.217.107 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 184.105.76.250 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 184.105.192.2 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.0.72.20 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.0.72.21 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.169.69.25 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.42.116.41 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 192.42.119.41 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 193.166.255.170 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 193.166.255.171 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 204.11.56.48 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 208.91.197.46 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 212.227.20.93 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 212.227.20.116 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 212.227.20.164 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 213.165.83.176 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 216.218.135.114 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 216.218.185.162 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 216.218.208.114 reject-with icmp-port-unreachable + 0 0 REJECT all -- * * 0.0.0.0/0 216.66.15.109 reject-with icmp-port-unreachable + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:706 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:706 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5432 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5432 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2082:2083 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2082:2083 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:8232:8233 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:8232:8233 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1500 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1500 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:123 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:123 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1293 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1293 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:11371 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:11371 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:443 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:110 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:110 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1194 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1194 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3074 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:3074 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1521 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1521 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:2049 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:2049 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:88 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:88 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:995 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:995 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:25551 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:25551 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5050 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5050 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:43 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:43 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:991 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:991 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:143 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:143 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5228 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5228 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:445 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:445 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1755 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1755 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:993 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:993 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9001 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9001 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:5222:5223 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:5222:5223 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:20:21 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:20:21 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:60000:61000 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:60000:61000 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2102:2104 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2102:2104 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:873 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:873 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:27000:27050 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:27000:27050 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9418 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9418 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1863 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1863 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:8087:8088 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:8087:8088 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9030 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9030 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:4643 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:4643 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9339 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9339 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:902:904 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:902:904 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1533 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1533 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2095:2096 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2095:2096 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:5190 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:5190 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:749 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:749 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:4321 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:4321 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:10000 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:10000 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:53 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:53 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:19294 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:19294 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:220 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:220 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:8332:8333 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:8332:8333 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:64738 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:64738 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:26661 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:26661 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1723 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1723 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8443 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8443 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8888 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8888 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:2086:2087 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:2086:2087 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9735 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9735 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:554 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:554 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:853 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:853 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:22 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8082 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8082 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:992 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:992 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:25565 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:25565 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3690 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:3690 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:464 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:464 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:18089 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:18089 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:981 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:981 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9053 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9053 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:50002 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:50002 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:9443 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:9443 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:389 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:389 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:80:81 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:80:81 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:27017 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:27017 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:5000:5005 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:5000:5005 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1433 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1433 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8883 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8883 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:3306 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8767 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:8767 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1677 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1677 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:18080:18081 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:18080:18081 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:19638 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:19638 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:1220 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:1220 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:79 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:79 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpts:989:990 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpts:989:990 + 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:636 + 0 0 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0 udp dpt:636 + 0 0 REJECT all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable IPv6 Chain: Chain NYM-EXIT (1 references) - pkts bytes target prot opt in out source destination - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:706 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:706 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:5432 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:5432 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:2082:2083 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:2082:2083 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:8232:8233 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:8232:8233 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1500 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1500 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:123 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:123 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1293 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1293 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:11371 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:11371 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:443 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:443 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:110 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:110 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1194 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1194 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:3074 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:3074 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1521 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1521 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:2049 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:2049 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:88 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:88 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:995 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:995 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:5050 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:5050 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:43 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:43 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:991 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:991 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:143 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:143 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:5228 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:5228 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:445 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:445 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1755 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1755 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:993 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:993 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9001 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9001 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:5222:5223 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:5222:5223 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:20:21 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:20:21 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:60000:61000 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:60000:61000 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:2102:2104 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:2102:2104 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:873 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:873 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:27000:27050 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:27000:27050 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9418 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9418 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1863 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1863 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:8087:8088 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:8087:8088 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9030 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9030 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:4643 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:4643 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9339 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9339 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:902:904 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:902:904 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1533 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1533 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:5222:5223 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:5222:5223 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:20:21 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:20:21 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:60000:61000 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:60000:61000 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:2102:2104 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:2102:2104 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:873 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:873 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:27000:27050 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:27000:27050 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9418 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9418 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1863 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1863 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:8087:8088 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:8087:8088 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9030 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9030 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:4643 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:4643 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9339 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9339 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:902:904 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:902:904 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1533 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1533 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:2095:2096 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:2095:2096 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:5190 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:5190 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:749 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:749 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:4321 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:4321 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:10000 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:10000 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:53 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:53 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:19294 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:19294 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:220 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:220 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:8332:8333 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:8332:8333 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:64738 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:64738 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1723 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1723 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:8443 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:8443 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:8888 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:8888 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:2086:2087 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:2086:2087 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9735 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9735 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:554 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:554 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:853 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:853 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:22 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:22 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:8082 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:8082 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:992 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:992 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:25565 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:25565 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:3690 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:3690 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:464 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:464 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:981 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:981 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9053 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9053 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:50002 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:50002 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:9443 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:9443 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:389 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:389 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:80:81 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:80:81 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:27017 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:27017 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:5000:5005 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:5000:5005 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1433 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1433 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:8883 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:8883 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:3306 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:3306 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:8767 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:8767 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1677 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1677 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:19638 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:19638 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:1220 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:1220 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:79 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:79 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpts:989:990 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpts:989:990 - 0 0 ACCEPT 6 -- * * ::/0 ::/0 tcp dpt:636 - 0 0 ACCEPT 17 -- * * ::/0 ::/0 udp dpt:636 - 0 0 REJECT 0 -- * * ::/0 ::/0 reject-with icmp6-port-unreachable + pkts bytes target prot opt in out source destination + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:706 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:706 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:5432 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:5432 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:2082:2083 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:2082:2083 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:8232:8233 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:8232:8233 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1500 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1500 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:123 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:123 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1293 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1293 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:11371 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:11371 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:443 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:443 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:110 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:110 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1194 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1194 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:3074 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:3074 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1521 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1521 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:2049 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:2049 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:88 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:88 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:995 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:995 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:25551 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:25551 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:5050 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:5050 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:43 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:43 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:991 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:991 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:143 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:143 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:5228 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:5228 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:445 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:445 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1755 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1755 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:993 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:993 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:9001 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:9001 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:5222:5223 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:5222:5223 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:20:21 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:20:21 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:60000:61000 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:60000:61000 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:2102:2104 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:2102:2104 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:873 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:873 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:27000:27050 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:27000:27050 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:9418 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:9418 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1863 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1863 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:8087:8088 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:8087:8088 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:9030 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:9030 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:4643 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:4643 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:9339 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:9339 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:902:904 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:902:904 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1533 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1533 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:2095:2096 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:2095:2096 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:5190 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:5190 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:749 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:749 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:4321 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:4321 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:10000 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:10000 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:53 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:53 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:19294 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:19294 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:220 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:220 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:8332:8333 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:8332:8333 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:64738 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:64738 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:26661 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:26661 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1723 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1723 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:8443 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:8443 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:8888 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:8888 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:2086:2087 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:2086:2087 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:9735 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:9735 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:554 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:554 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:853 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:853 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:22 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:22 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:8082 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:8082 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:992 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:992 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:25565 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:25565 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:3690 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:3690 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:464 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:464 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:18089 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:18089 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:981 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:981 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:9053 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:9053 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:50002 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:50002 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:9443 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:9443 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:389 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:389 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:80:81 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:80:81 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:27017 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:27017 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:5000:5005 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:5000:5005 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1433 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1433 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:8883 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:8883 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:3306 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:3306 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:8767 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:8767 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1677 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1677 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:18080:18081 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:18080:18081 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:19638 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:19638 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:1220 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:1220 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:79 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:79 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:989:990 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpts:989:990 + 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:636 + 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:636 + 0 0 REJECT all * * ::/0 ::/0 reject-with icmp6-port-unreachable -ESC[0;33mIP Forwarding:ESC[0m +IP Forwarding: IPv4: 1 IPv6: 1 ``` diff --git a/documentation/docs/components/operators/snippets/wg-exit-policy-test-output.mdx b/documentation/docs/components/operators/snippets/wg-exit-policy-test-output.mdx index c7ee424647..184f858c83 100644 --- a/documentation/docs/components/operators/snippets/wg-exit-policy-test-output.mdx +++ b/documentation/docs/components/operators/snippets/wg-exit-policy-test-output.mdx @@ -2,41 +2,61 @@ Running Nym Exit Policy Verification Tests... Testing Port Range Rules... Testing FTP tcp port range 20-21 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:20:21 ✓ Rule exists: NYM-EXIT tcp port range 20:21 Testing HTTP tcp port range 80-81 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:80:81 ✓ Rule exists: NYM-EXIT tcp port range 80:81 Testing CPanel tcp port range 2082-2083 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:2082:2083 ✓ Rule exists: NYM-EXIT tcp port range 2082:2083 Testing XMPP tcp port range 5222-5223 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:5222:5223 ✓ Rule exists: NYM-EXIT tcp port range 5222:5223 Testing Steam (sampling) tcp port range 27000-27050 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:27000:27050 ✓ Rule exists: NYM-EXIT tcp port range 27000:27050 Testing FTP over TLS tcp port range 989-990 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:989:990 ✓ Rule exists: NYM-EXIT tcp port range 989:990 Testing RTP/VoIP tcp port range 5000-5005 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:5000:5005 ✓ Rule exists: NYM-EXIT tcp port range 5000:5005 Testing Simplify Media tcp port range 8087-8088 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:8087:8088 ✓ Rule exists: NYM-EXIT tcp port range 8087:8088 Testing Zcash tcp port range 8232-8233 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:8232:8233 ✓ Rule exists: NYM-EXIT tcp port range 8232:8233 Testing Bitcoin tcp port range 8332-8333 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:8332:8333 ✓ Rule exists: NYM-EXIT tcp port range 8332:8333 +Testing Monero tcp port range 18080-18081 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpts:18080:18081 +✓ Rule exists: NYM-EXIT tcp port range 18080:18081 Test test_port_range_rules PASSED Testing Critical Service Rules... +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpt:22 ✓ Rule exists: NYM-EXIT tcp port 22 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpt:53 ✓ Rule exists: NYM-EXIT tcp port 53 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpt:443 ✓ Rule exists: NYM-EXIT tcp port 443 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpt:853 ✓ Rule exists: NYM-EXIT tcp port 853 +ACCEPT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpt:1194 ✓ Rule exists: NYM-EXIT tcp port 1194 +ACCEPT udp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 udp dpt:53 ✓ Rule exists: NYM-EXIT udp port 53 +ACCEPT udp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 udp dpt:123 ✓ Rule exists: NYM-EXIT udp port 123 +ACCEPT udp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 udp dpt:1194 ✓ Rule exists: NYM-EXIT udp port 1194 Relevant existing rules for HTTP (port 80): Test test_critical_services PASSED This test takes some time, do not quit the process Testing Default Reject Rule... - ✓ Default REJECT rule exists Test test_default_reject_rule PASSED diff --git a/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-percent-stake.md b/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-percent-stake.md index 70cce5f91c..3dec107d5c 100644 --- a/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-percent-stake.md +++ b/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-percent-stake.md @@ -1 +1 @@ -0.80% +0.73% diff --git a/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-total-stake.md b/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-total-stake.md index 87215d763d..322660801f 100644 --- a/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-total-stake.md +++ b/documentation/docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-total-stake.md @@ -1 +1 @@ -35.841 +39.437 diff --git a/documentation/docs/components/outputs/api-scraping-outputs/time-now.md b/documentation/docs/components/outputs/api-scraping-outputs/time-now.md index 0dfafb6821..7a436498af 100644 --- a/documentation/docs/components/outputs/api-scraping-outputs/time-now.md +++ b/documentation/docs/components/outputs/api-scraping-outputs/time-now.md @@ -1 +1 @@ -Tuesday, July 22nd 2025, 11:37:27 UTC +Wednesday, July 30th 2025, 09:32:50 UTC \ No newline at end of file diff --git a/documentation/docs/components/outputs/csv2md-outputs/isp-sheet.md b/documentation/docs/components/outputs/csv2md-outputs/isp-sheet.md index b1d4cec752..e5b10cc72b 100644 --- a/documentation/docs/components/outputs/csv2md-outputs/isp-sheet.md +++ b/documentation/docs/components/outputs/csv2md-outputs/isp-sheet.md @@ -1,21 +1,44 @@ -| **ISP** | **Locations** | **Public IPv6** | **Crypto Payments** | **Comments** | **Last Updated** | -|:------------------------------------------------|:---------------------------------------------------------------------------------------------------------|:-------------------------------------|:---------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------| -| [AlexHost](https://alexhost.com) | Moldova, Bulgaria, Sweden, Netherlands | Yes, on by default | Yes | They allow TOR Bridges, Relays. Exit nodes are only allowed on dedicated servers (prices start from 26 EUR) | 07/2024 | -| [BitLaunch](https://bitlaunch.io) | Canada, USA, UK | No | Yes | Expensive. Digial Ocean through BitLanch has IPv6 | 05/2024 | -| [Cherry Servers](https://www.cherryservers.com) | Lithuania, Netherlands, USA, Singapore | No | Yes | Issued IP doesn’t match the location offered by the provider. | 05/2024 | -| [Flokinet](https://flokinet.is) | Netherlands, Iceland, Romania,France | Yes, needs a ticket and custom setup | yes, including XMR | Very slow customer support | 05/2024 | -| [HostSailor](https://hostsailor.com) | USA | Yes, based on ticket | Yes | The IPv6 setup needs custom research and is not documented | 05/2024 | -| [Hostiko](https://hostiko.com.ua) | Ukraine, Germany | Yes, on by default | Yes | Ukrainian provider. They allow Exit nodes on Germany boxes but limit the bandwidth, you also have to restrict certain ports like 25 and 587. Make sure you open a ticket. | 07/2024 | -| [Hostinger](https://hostinger.com) | France, Lithuania, India, USA, Brazil | Yes, out of the box | Yes | Crypto payments must be done per each server monthly or annually. | 05/2024 | -| [Hostslick](https://hostslick.com) | Netherlands, Germany | Yes, on by default | Yes | Good amount of bandwidth for the price. Make sure you open the ticket if you want to run Exit node | 07/2024 | -| [Incognet](https://incognet.io) | Netherlands and USA | Yes, on by default | Yes | They allow Tor exit nodes but you must adhere to their rules https://incognet.io/tor-exits | 07/2024 | -| [IsHosting](https://ishosting.com/en) | Brazil, Netherlands | Yes, based on ticket | Yes | Expensive | 05/2024 | -| [Linode](https://linode.com) | USA, Canada, Japan, India, Indonesia, Sweden, Netherlands, Germany, Brazil, France, UK, Australia, Italy | Yes out of the box | No, only through [BitLAunch](https://bitlaunch.io) | IPv6 sometimes need to be re-added in Networking tab, no reboot needed | 05/2024 | -| [LiteServer](https://liteserver.nl) | Netherlands | Yes, on by default | Yes | Very reliable Dutch provider. They do allow Relay nodes but for Exit nodes you need to contact them. Always check T&C https://liteserver.nl/legal | 07/2024 | -| [Mevspace](https://mevspace.com) | Poland | Yes, on by default | Yes | Flexible Polish providers with 3 DCs in Poland. They do allow Tor Exit nodes but you may need a dedicated server for this. Make sure you open a ticket to check. As of today's date, they have 48h for 1 EUR tariff | 07/2024 | -| [Misaka](https://www.misaka.io/) | South Africa | Yes, native support | No | Very Expensive | 05/2024 | -| [Njalla](https://nja.la) | Sweden | Yes | Yes | Privacy vandguards! The biggest VPS 45 is 3 cores only, but it works better than many “larger” servers on the market. | 05/2024 | -| [RDP](https://rdp.sh) | Netherlands, USA, Poland | Yes, on by default | Yes | German provider. Exit nodes are allowed, policy is here https://rdp.sh/docs/faq/tor ports 25,465,587 must be closed. Make sure you open a ticket before running an exit node. | 07/2024 | -| [TerraHost](https://terrahost.no) | Norway | Yes, on by default | Yes | Very reliable Norwegian provider. Only allow exit nodes on Dedicated servers subject to certain caveats (you must open a ticket). Always check T&C https://terrahost.no/avtalebetingelser | 07/2024 | -| [iHostArt](https://ihostart.com) | Romania | Yes, on by default | Yes | Super permissive provider. They do allow Tor Exit/Relay/Bridge. Pro-free speech etc. Recently, IPv6 geolocation was set to North Korea, so be aware. | 07/2024 | -| [vSys Host](https://vsys.host) | Ukraine, Netherlands, USA | Yes, on by default | Yes | Pretty permissive provider registered in Ukraine. Should allow Relay/Exit nodes but nothing in T&C, so better double check. | 07/2024 | +| **ISP** | **Locations** | **Public IPv6** | **Crypto Payments** | **Comments** | **Last Updated** | +|:---------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------|:---------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------| +| [AlexHost](https://alexhost.com) | Moldova, Bulgaria, Sweden, Netherlands | Yes, on by default | Yes | They allow TOR Bridges, Relays. Exit nodes are only allowed on dedicated servers (prices start from 26 EUR) | 07/2024 | +| [AmeriNoc](https://www.amerinoc.com) | USA | Yes | nan | nan | 07/2025 | +| [BitLaunch](https://bitlaunch.io) | Canada, USA, UK | No | Yes | Expensive. Digial Ocean through BitLanch has IPv6 | 05/2024 | +| [Cherry Servers](https://www.cherryservers.com) | Lithuania, Netherlands, USA, Singapore | No | Yes | Issued IP doesn’t match the location offered by the provider. | 05/2024 | +| [Colocall](https://www.colocall.net/) | Ukraine | Yes | nan | 07/2025 | nan | +| [DataPacket](https://www.datapacket.com/pricing) | NL, GR, SK, BE, RO, HU, DK, IE, DE, UA, PT, GB, ES, FR, IT, NO, CZ, BG, SE, AT, PL, HR, CH, USA, CO, AR, PE, MX, CL, TR, ZA, NG, IL, HK, AU, SG, JP | Yes | nan | nan | 07/2025 | +| [Dataclub](https://www.dataclub.eu/) | Latvia, Sweden, Netherlands | Yes | nan | nan | 07/2027 | +| [Flokinet](https://flokinet.is) | Netherlands, Iceland, Romania,France | Yes, needs a ticket and custom setup | yes, including XMR | Very slow customer support | 05/2024 | +| [FranTech](https://my.frantech.ca) | USA | Yes | nan | nan | 07/2025 | +| [Fsit](https://www.fsit.com/server/vps-vserver-kvm) | Swiss | Yes | Yes | nan | 07/2025 | +| [HostSailor](https://hostsailor.com) | USA | Yes, based on ticket | Yes | The IPv6 setup needs custom research and is not documented | 05/2024 | +| [Hostiko](https://hostiko.com.ua) | Ukraine, Germany | Yes, on by default | Yes | Ukrainian provider. They allow Exit nodes on Germany boxes but limit the bandwidth, you also have to restrict certain ports like 25 and 587. Make sure you open a ticket. | 07/2024 | +| [Hostinger](https://hostinger.com) | France, Lithuania, India, USA, Brazil | Yes, out of the box | Yes | Not fast enough, Crypto payments must be done per each server monthly or annually. | 07/2025 | +| [Hostroyale](https://hostroyale.com/hosting/dedicated-server/) | Various countries with different pricing | nan | Yes | nan | 07/2025 | +| [Hostslick](https://hostslick.com) | Netherlands, Germany | Yes, on by default | Yes | Good amount of bandwidth for the price. Make sure you open the ticket if you want to run Exit node | 07/2024 | +| [Incognet](https://incognet.io) | Netherlands and USA | Yes, on by default | Yes | They allow Tor exit nodes but you must adhere to their rules https://incognet.io/tor-exits | 07/2024 | +| [Incognet](https://incognet.io/kansas-city-dedicated-servers) | USA, Netherlands | Yes | nan | nan | 07/2025 | +| [Ionos](https://www.ionos.com/servers/amd-servers) | US, DE, UK, ESP, FR | nan | No | nan | 07/2025 | +| [IsHosting](https://ishosting.com/en) | Brazil, Netherlands | Yes, based on ticket | Yes | Expensive | 05/2024 | +| [Leaseweb](https://www.leaseweb.com/en/configure/vc/product/entityKey/DEDSER02_NEW_ORDER_BUSINESS_R740XD-24SFF-6134) | US, NL, DE, UK, CA, SG, JP, AUS, HK | nan | No | KYC mandatory | 07/2025 | +| [Linode](https://linode.com) | USA, Canada, Japan, India, Indonesia, Sweden, Netherlands, Germany, Brazil, France, UK, Australia, Italy | Yes out of the box | No, only through [BitLAunch](https://bitlaunch.io) | IPv6 sometimes need to be re-added in Networking tab, no reboot needed | 05/2024 | +| [LiteServer](https://liteserver.nl) | Netherlands | Yes, on by default | Yes | Very reliable Dutch provider. They do allow Relay nodes but for Exit nodes you need to contact them. Always check T&C https://liteserver.nl/legal | 07/2024 | +| [Lowendbox](https://lowendbox.com/category/dedicated-servers) | | | | Just an aggregator with good offers | 07/2025 | +| [M247](https://m247.com/eu/services/host/dedicated-servers/) | UK, Austria, Br, Sw, Jp, Poland, Fr, USA, Netherlands | Yes | No | nan | 07/2025 | +| [Mebilcom](https://www.melbicom.net/dedicatedserver/) | NL, US, DE, UAE, NG, ESP, IN, IT, FR, LT, SG, BG, LV, PL | nan | No | nan | 07/2025 | +| [Mevspace](https://mevspace.com) | Poland | Yes, on by default | Yes | Flexible Polish providers with 3 DCs in Poland. They do allow Tor Exit nodes but you may need a dedicated server for this. Make sure you open a ticket to check. As of today's date, they have 48h for 1 EUR tariff | 07/2024 | +| [Misaka](https://www.misaka.io/) | South Africa | Yes, native support | No | Very Expensive | 05/2024 | +| [NiceVPS](https://nicevps.net/) | Netherlands | Yes | nan | nan | 07/2025 | +| [Njalla](https://nja.la) | Sweden | Yes | Yes | Privacy vandguards! The biggest VPS 45 is 3 cores only, but it works better than many “larger” servers on the market. | 05/2024 | +| [OVH](https://us.ovhcloud.com/bare-metal/rise/rise-3/) | USA, DE, FR, UK, PL, CA | | No | Not all locations always available | 07/2025 | +| [Oneprovider](https://oneprovider.com/en/dedicated-servers/ipv6) | PL, FR, NL, UA, US, BG, RO, DK, ESP, NO, CZ, RS, IE, IT, UK, HU, CH, SK, AT, BE, BA, HK, JP, SG, LU, AU, SWE, UAE, BR, CR, MX, GR, CL, MA, AR | Yes | No | nan | 07/2025 | +| [PrivateLayer](https://privatelayer.com) | Swiss | Yes | Yes | Slow customer response | 07/2025 | +| [Privex](https://www.privex.io/tor-exit-policy/) | USA, Germany, Sweden | Yes | Yes | nan | 07/2025 | +| [Psychz](https://www.psychz.net) | US, UK, Brazil, Japan, Russia, South Africa and many more | Yes | nan | nan | 07/2025 | +| [RDP](https://rdp.sh) | Netherlands, USA, Poland | Yes, on by default | Yes | German provider. Exit nodes are allowed, policy is here https://rdp.sh/docs/faq/tor ports 25,465,587 must be closed. Make sure you open a ticket before running an exit node. | 07/2024 | +| [Servermania](https://www.servermania.com/dedicated-servers-hosting.htm) | USA, Canada | nan | No | nan | 07/2025 | +| [Svea](https://svea.net/vps) | Sweden | Yes | nan | nan | 07/2025 | +| [TerraHost](https://terrahost.no) | Norway | Yes, on by default | Yes | Very reliable Norwegian provider. Only allow exit nodes on Dedicated servers subject to certain caveats (you must open a ticket). Always check T&C https://terrahost.no/avtalebetingelser | 07/2024 | +| [Thundervm](https://thundervm.com/en/hosting/dedicated-server) | USA, UK, France, Italy, Switzerland, Netherlands | nan | Yes | | 07/2025 | +| [Zenlayer](https://www.zenlayer.com/bare-metal/) | [advertised over 50 locations](50+ https://www.zenlayer.com/global-network) | nan | nan | nan | 07/2025 | +| [iHostArt](https://ihostart.com) | Romania | Yes, on by default | Yes | Super permissive provider. They do allow Tor Exit/Relay/Bridge. Pro-free speech etc. Recently, IPv6 geolocation was set to North Korea, so be aware. | 07/2024 | +| [vSys Host](https://vsys.host) | Ukraine, Netherlands, USA | Yes, on by default | Yes | Pretty permissive provider registered in Ukraine. Should allow Relay/Exit nodes but nothing in T&C, so better double check. | 07/2024 | diff --git a/documentation/docs/data/csv/isp-sheet.csv b/documentation/docs/data/csv/isp-sheet.csv index f72973f924..9a39041c20 100644 --- a/documentation/docs/data/csv/isp-sheet.csv +++ b/documentation/docs/data/csv/isp-sheet.csv @@ -1,26 +1,43 @@ **ISP**,**Locations**,**Public IPv6**,**Crypto Payments**,**Comments**,**Last Updated** -[Flokinet](https://flokinet.is),"Netherlands, Iceland, Romania,France","Yes, needs a ticket and custom setup","yes, including XMR","Very slow customer support","05/2024" -[BitLaunch](https://bitlaunch.io),"Canada, USA, UK","No","Yes","Expensive. Digial Ocean through BitLanch has IPv6","05/2024" -[Hostinger](https://hostinger.com),"France, Lithuania, India, USA, Brazil","Yes, out of the box","Yes","Crypto payments must be done per each server monthly or annually.","05/2024" -[Linode](https://linode.com),"USA, Canada, Japan, India, Indonesia, Sweden, Netherlands, Germany, Brazil, France, UK, Australia, Italy","Yes out of the box","No, only through [BitLAunch](https://bitlaunch.io)","IPv6 sometimes need to be re-added in Networking tab, no reboot needed","05/2024" -[Cherry Servers](https://www.cherryservers.com),"Lithuania, Netherlands, USA, Singapore","No","Yes","Issued IP doesn’t match the location offered by the provider.","05/2024" -[Njalla](https://nja.la),"Sweden","Yes","Yes","Privacy vandguards! The biggest VPS 45 is 3 cores only, but it works better than many “larger” servers on the market.","05/2024" -[HostSailor](https://hostsailor.com),"USA","Yes, based on ticket","Yes","The IPv6 setup needs custom research and is not documented","05/2024" -[Misaka](https://www.misaka.io/),"South Africa","Yes, native support","No","Very Expensive","05/2024" -[IsHosting](https://ishosting.com/en),"Brazil, Netherlands","Yes, based on ticket","Yes","Expensive","05/2024" -[AlexHost](https://alexhost.com),"Moldova, Bulgaria, Sweden, Netherlands","Yes, on by default","Yes","They allow TOR Bridges, Relays. Exit nodes are only allowed on dedicated servers (prices start from 26 EUR)","07/2024" -[iHostArt](https://ihostart.com),"Romania","Yes, on by default","Yes","Super permissive provider. They do allow Tor Exit/Relay/Bridge. Pro-free speech etc. Recently, IPv6 geolocation was set to North Korea, so be aware.","07/2024" -[Incognet](https://incognet.io),"Netherlands and USA","Yes, on by default","Yes","They allow Tor exit nodes but you must adhere to their rules https://incognet.io/tor-exits","07/2024" -[vSys Host](https://vsys.host),"Ukraine, Netherlands, USA","Yes, on by default","Yes","Pretty permissive provider registered in Ukraine. Should allow Relay/Exit nodes but nothing in T&C, so better double check.","07/2024" -[LiteServer](https://liteserver.nl),"Netherlands","Yes, on by default","Yes","Very reliable Dutch provider. They do allow Relay nodes but for Exit nodes you need to contact them. Always check T&C https://liteserver.nl/legal","07/2024" -[TerraHost](https://terrahost.no),"Norway","Yes, on by default","Yes","Very reliable Norwegian provider. Only allow exit nodes on Dedicated servers subject to certain caveats (you must open a ticket). Always check T&C https://terrahost.no/avtalebetingelser","07/2024" -[Mevspace](https://mevspace.com),"Poland","Yes, on by default","Yes","Flexible Polish providers with 3 DCs in Poland. They do allow Tor Exit nodes but you may need a dedicated server for this. Make sure you open a ticket to check. As of today's date, they have 48h for 1 EUR tariff","07/2024" -[Hostiko](https://hostiko.com.ua),"Ukraine, Germany","Yes, on by default","Yes","Ukrainian provider. They allow Exit nodes on Germany boxes but limit the bandwidth, you also have to restrict certain ports like 25 and 587. Make sure you open a ticket.","07/2024" -[Hostslick](https://hostslick.com),"Netherlands, Germany","Yes, on by default","Yes","Good amount of bandwidth for the price. Make sure you open the ticket if you want to run Exit node","07/2024" -[RDP](https://rdp.sh),"Netherlands, USA, Poland","Yes, on by default","Yes","German provider. Exit nodes are allowed, policy is here https://rdp.sh/docs/faq/tor ports 25,465,587 must be closed. Make sure you open a ticket before running an exit node.","07/2024" - - - - - - +[Flokinet](https://flokinet.is),"Netherlands, Iceland, Romania,France","Yes, needs a ticket and custom setup","yes, including XMR",Very slow customer support,05/2024 +[BitLaunch](https://bitlaunch.io),"Canada, USA, UK",No,Yes,Expensive. Digial Ocean through BitLanch has IPv6,05/2024 +[Hostinger](https://hostinger.com),"France, Lithuania, India, USA, Brazil","Yes, out of the box",Yes,"Not fast enough, Crypto payments must be done per each server monthly or annually.",07/2025 +[Linode](https://linode.com),"USA, Canada, Japan, India, Indonesia, Sweden, Netherlands, Germany, Brazil, France, UK, Australia, Italy",Yes out of the box,"No, only through [BitLAunch](https://bitlaunch.io)","IPv6 sometimes need to be re-added in Networking tab, no reboot needed",05/2024 +[Cherry Servers](https://www.cherryservers.com),"Lithuania, Netherlands, USA, Singapore",No,Yes,Issued IP doesn’t match the location offered by the provider.,05/2024 +[Njalla](https://nja.la),Sweden,Yes,Yes,"Privacy vandguards! The biggest VPS 45 is 3 cores only, but it works better than many “larger” servers on the market.",05/2024 +[HostSailor](https://hostsailor.com),USA,"Yes, based on ticket",Yes,The IPv6 setup needs custom research and is not documented,05/2024 +[Misaka](https://www.misaka.io/),South Africa,"Yes, native support",No,Very Expensive,05/2024 +[IsHosting](https://ishosting.com/en),"Brazil, Netherlands","Yes, based on ticket",Yes,Expensive,05/2024 +[AlexHost](https://alexhost.com),"Moldova, Bulgaria, Sweden, Netherlands","Yes, on by default",Yes,"They allow TOR Bridges, Relays. Exit nodes are only allowed on dedicated servers (prices start from 26 EUR)",07/2024 +[iHostArt](https://ihostart.com),Romania,"Yes, on by default",Yes,"Super permissive provider. They do allow Tor Exit/Relay/Bridge. Pro-free speech etc. Recently, IPv6 geolocation was set to North Korea, so be aware.",07/2024 +[Incognet](https://incognet.io),Netherlands and USA,"Yes, on by default",Yes,They allow Tor exit nodes but you must adhere to their rules https://incognet.io/tor-exits,07/2024 +[vSys Host](https://vsys.host),"Ukraine, Netherlands, USA","Yes, on by default",Yes,"Pretty permissive provider registered in Ukraine. Should allow Relay/Exit nodes but nothing in T&C, so better double check.",07/2024 +[LiteServer](https://liteserver.nl),Netherlands,"Yes, on by default",Yes,Very reliable Dutch provider. They do allow Relay nodes but for Exit nodes you need to contact them. Always check T&C https://liteserver.nl/legal,07/2024 +[TerraHost](https://terrahost.no),Norway,"Yes, on by default",Yes,Very reliable Norwegian provider. Only allow exit nodes on Dedicated servers subject to certain caveats (you must open a ticket). Always check T&C https://terrahost.no/avtalebetingelser,07/2024 +[Mevspace](https://mevspace.com),Poland,"Yes, on by default",Yes,"Flexible Polish providers with 3 DCs in Poland. They do allow Tor Exit nodes but you may need a dedicated server for this. Make sure you open a ticket to check. As of today's date, they have 48h for 1 EUR tariff",07/2024 +[Hostiko](https://hostiko.com.ua),"Ukraine, Germany","Yes, on by default",Yes,"Ukrainian provider. They allow Exit nodes on Germany boxes but limit the bandwidth, you also have to restrict certain ports like 25 and 587. Make sure you open a ticket.",07/2024 +[Hostslick](https://hostslick.com),"Netherlands, Germany","Yes, on by default",Yes,Good amount of bandwidth for the price. Make sure you open the ticket if you want to run Exit node,07/2024 +[RDP](https://rdp.sh),"Netherlands, USA, Poland","Yes, on by default",Yes,"German provider. Exit nodes are allowed, policy is here https://rdp.sh/docs/faq/tor ports 25,465,587 must be closed. Make sure you open a ticket before running an exit node.",07/2024 +[Lowendbox](https://lowendbox.com/category/dedicated-servers), , , ,Just an aggregator with good offers,07/2025 +[Thundervm](https://thundervm.com/en/hosting/dedicated-server),"USA, UK, France, Italy, Switzerland, Netherlands",,Yes, ,07/2025 +[OVH](https://us.ovhcloud.com/bare-metal/rise/rise-3/),"USA, DE, FR, UK, PL, CA", ,No,Not all locations always available,07/2025 +[Mebilcom](https://www.melbicom.net/dedicatedserver/),"NL, US, DE, UAE, NG, ESP, IN, IT, FR, LT, SG, BG, LV, PL",,No,,07/2025 +[Servermania](https://www.servermania.com/dedicated-servers-hosting.htm),"USA, Canada",,No,,07/2025 +[Oneprovider](https://oneprovider.com/en/dedicated-servers/ipv6),"PL, FR, NL, UA, US, BG, RO, DK, ESP, NO, CZ, RS, IE, IT, UK, HU, CH, SK, AT, BE, BA, HK, JP, SG, LU, AU, SWE, UAE, BR, CR, MX, GR, CL, MA, AR",Yes,No,,07/2025 +[Ionos](https://www.ionos.com/servers/amd-servers),"US, DE, UK, ESP, FR",,No,,07/2025 +[Leaseweb](https://www.leaseweb.com/en/configure/vc/product/entityKey/DEDSER02_NEW_ORDER_BUSINESS_R740XD-24SFF-6134),"US, NL, DE, UK, CA, SG, JP, AUS, HK",,No,KYC mandatory,07/2025 +[M247](https://m247.com/eu/services/host/dedicated-servers/),"UK, Austria, Br, Sw, Jp, Poland, Fr, USA, Netherlands",Yes,No,,07/2025 +[Hostroyale](https://hostroyale.com/hosting/dedicated-server/),Various countries with different pricing,, Yes,,07/2025 +[DataPacket](https://www.datapacket.com/pricing),"NL, GR, SK, BE, RO, HU, DK, IE, DE, UA, PT, GB, ES, FR, IT, NO, CZ, BG, SE, AT, PL, HR, CH, USA, CO, AR, PE, MX, CL, TR, ZA, NG, IL, HK, AU, SG, JP",Yes,,,07/2025 +[Zenlayer](https://www.zenlayer.com/bare-metal/), [advertised over 50 locations](50+ https://www.zenlayer.com/global-network),,,,07/2025 +[PrivateLayer](https://privatelayer.com),Swiss,Yes,Yes,Slow customer response,07/2025 +[AmeriNoc](https://www.amerinoc.com),USA,Yes,,,07/2025 +[Colocall](https://www.colocall.net/),Ukraine,Yes,,07/2025, +[Incognet](https://incognet.io/kansas-city-dedicated-servers),"USA, Netherlands",Yes,,,07/2025 +[FranTech](https://my.frantech.ca),USA,Yes,,,07/2025 +[Psychz](https://www.psychz.net),"US, UK, Brazil, Japan, Russia, South Africa and many more",Yes,,,07/2025 +[Fsit](https://www.fsit.com/server/vps-vserver-kvm),Swiss,Yes,Yes,,07/2025 +[NiceVPS](https://nicevps.net/),Netherlands,Yes,,,07/2025 +[Dataclub](https://www.dataclub.eu/),"Latvia, Sweden, Netherlands",Yes,,,07/2027 +[Privex](https://www.privex.io/tor-exit-policy/),"USA, Germany, Sweden",Yes,Yes,,07/2025 +[Svea](https://svea.net/vps),Sweden,Yes,,,07/2025 diff --git a/documentation/docs/pages/operators/community-counsel/legal.mdx b/documentation/docs/pages/operators/community-counsel/legal.mdx index c916a899d6..f2f0d114d9 100644 --- a/documentation/docs/pages/operators/community-counsel/legal.mdx +++ b/documentation/docs/pages/operators/community-counsel/legal.mdx @@ -24,25 +24,23 @@ Write a message to your provider telling them about your intention to run a `nym #### Join Operators Legal Forum -This [Matrix channel]((https://matrix.to/#/!YfoUFsJjsXbWmijbPG:nymtech.chat?via=nymtech.chat&via=matrix.org&via=matrix.su4ka.icu)) is the best place to ask questions and share your experience with others. You can share screen prints of abuse reports and ask for support. +This [Matrix channel]((https://matrix.to/#/!YfoUFsJjsXbWmijbPG:nymtech.chat?via=nymtech.chat&via=matrix.org&via=matrix.su4ka.icu)) is the best place to ask questions and share your experience with others. You can share screen prints of abuse reports and ask for support. #### Join Operators Legal Clinic Do you have any questions directed for lawyers? Come and chat with Nym COO Alexis Roussel, every Wednesday 14:30 UTC for 60min in our [Operator Legal Forum channel on Matrix](https://matrix.to/#/!YfoUFsJjsXbWmijbPG:nymtech.chat?via=nymtech.chat&via=matrix.org&via=matrix.su4ka.icu). #### Use a friendly provider Nym operators community shares their experience with different ISPs on [this page](isp-list). At the same time, consider to move away from these provides: - + - Servinga / VPS2day (AS39378) - Frantech / Ponynet / BuyVM (AS53667) -- OVH SAS / OVHcloud (AS16276) - Online S.A.S. / Scaleway (AS12876) - Hetzner Online GmbH (AS24940) -- IONOS SE (AS8560) -- Psychz Networks (AS40676) - 1337 Services GmbH / RDP.sh (AS210558) +- Stark Industries Solutions Ltd. / PQ.Hosting / The.Hosting / UFO-AS (AS44477 / ASN 33993) #### Backup your nodes -Your only way to restore your node is when you have an access to `.nym` directory locally. Follow [node](../nodes/maintenance#backup-a-node) and [proxy configuration](../nodes/maintenance#backup-proxy-configuration) backup guides to be able to [restore your node](../nodes/maintenance#restoring-a-node) on another machine later on, without losing your delegation. +Your only way to restore your node is when you have an access to `.nym` directory locally. Follow [node](../nodes/maintenance#backup-a-node) and [proxy configuration](../nodes/maintenance#backup-proxy-configuration) backup guides to be able to [restore your node](../nodes/maintenance#restoring-a-node) on another machine later on, without losing your delegation. #### Use `nym-exit` prefix on your landing page URL We would like to ask operators to use [reverse proxy](../nodes/nym-node/configuration/proxy-configuration) with a [landing page](landing-pages). When assigning a domain please use a common convention with `nym-exit` in the beginning of the the page URL as this will create a reputation and reference. The entire address should have this new format: @@ -69,10 +67,10 @@ nym-exit.mysquad.org **The `NYM-EXIT` part in the beginning is what's important.** #### Chose the right TLD -When registering a domain, check [Top Level Domain (TLD)](https://www.techopedia.com/definition/1348/top-level-domain-tld) terms and conditions. For example `.icu` is a no go. Having a wrong TLD may lead to your domain being taken away from you when facing a DMCA report. +When registering a domain, check [Top Level Domain (TLD)](https://www.techopedia.com/definition/1348/top-level-domain-tld) terms and conditions. For example `.icu` is a no go. Having a wrong TLD may lead to your domain being taken away from you when facing a DMCA report. #### Respond to abuse reports -Make sure to read notifications from your account provider and if you receive an abuse report, respond to it in time. Here is a template explaining the essential legal background of Nym Node Exit Gateway. Don't forget to adjust the variables. +Make sure to read notifications from your account provider and if you receive an abuse report, respond to it in time. Here is a template explaining the essential legal background of Nym Node Exit Gateway. Don't forget to adjust the variables.
@@ -81,4 +79,3 @@ Make sure to read notifications from your account provider and if you receive an #### Help us to improve these pages Add your findings by opening a [Pull Request](add-content). - diff --git a/documentation/docs/pages/operators/nodes/nym-node/configuration.mdx b/documentation/docs/pages/operators/nodes/nym-node/configuration.mdx index ab425f8e4e..81044db705 100644 --- a/documentation/docs/pages/operators/nodes/nym-node/configuration.mdx +++ b/documentation/docs/pages/operators/nodes/nym-node/configuration.mdx @@ -454,7 +454,7 @@ The exit policy is same for all NRs, the content is shaped by an offchain govern There is a caveat though. NR is only routing TCP streams and therefore any other type of routing is *not* filtered thorugh the exit policy. To ensure that Nym Nodes follow the same exit policy when routing IP packets through wireguard and don't act as open proxies, the operators have to set up these rules via IP tables rules. -**Follow these steps, using a [setup script]i(https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh) and [testing scripts](https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/exit-policy-tests.sh) written by Nym quality assurance team, to setup exit policy for wireguard:** +**Follow these steps, using a [setup script](https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh) and [testing scripts](https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/exit-policy-tests.sh) written by Nym quality assurance team, to setup exit policy for wireguard:** diff --git a/documentation/docs/pages/operators/nodes/validator-setup.mdx b/documentation/docs/pages/operators/nodes/validator-setup.mdx index 21612c377d..8b7c3a8ac3 100644 --- a/documentation/docs/pages/operators/nodes/validator-setup.mdx +++ b/documentation/docs/pages/operators/nodes/validator-setup.mdx @@ -9,12 +9,12 @@ import { AccordionTemplate } from 'components/accordion-template.tsx'; > Nym has two main codebases: > - the [Nym platform](https://github.com/nymtech/nym), written in Rust. This contains all of our code except for the validators. -> - the [Nym validators](https://github.com/nymtech/nyxd), written in Go & maintained as a no-modification fork of [wasmd](https://github.com/CosmWasm/wasmd) +> - the [Nym validators](https://github.com/nymtech/nyxd), written in Go & maintained as fork of [wasmd](https://github.com/CosmWasm/wasmd) The validator is a Go application which implements it's functionalities using [Cosmos SDK](https://v1.cosmos.network/sdk). The underlying state-replication engine is powered by [CometBFT](https://cometbft.com/), where the consensus mechanism is based on the [Tendermint Consensus Algorithm](https://arxiv.org/abs/1807.04938). Finally, a [CosmWasm](https://cosmwasm.com) smart contract module controls crucial mixnet functionalities like decentralised directory service, node bonding, and delegated mixnet staking. -We are currently running mainnet with a closed set of reputable validators. To ensure decentralisation of Nyx chain, we are working on a mechanism to onboard new validators to the network. To join the waitlist, please drop an email to `validators [at] nymtech.net` with details of your setup, experience and any other relevent information +At present, our mainnet operates with a select group of reputed validators. We are not accepting new validators at this time. Any updates or changes to this policy will be promptly announced. ## Building your validator @@ -52,7 +52,7 @@ pacman -S git gcc jq - First remove any existing old Go installation and extract the archive you just downloaded into /usr/local: ```sh -rm -rf /usr/local/go && tar -C /usr/local -xzf go1.20.10.linux-amd64.tar.gz +rm -rf /usr/local/go && tar -C /usr/local -xzf go1.23.11.linux-amd64.tar.gz ``` - Then add /usr/local/go/bin to the PATH environment variable @@ -69,14 +69,14 @@ go version - Should return something like: ```sh -go version go1.20.10 linux/amd64 +go version go1.23.11 linux/amd64 ``` ### Download a precompiled validator binary -You can find pre-compiled binaries for Ubuntu `22.04` and `20.04` [here](https://github.com/nymtech/nyxd/releases). +You can find pre-compiled binaries for Ubuntu `22.04` and `24.04` [here](https://github.com/nymtech/nyxd/releases). ### Manually compiling your validator binary @@ -109,8 +109,9 @@ Usage: nyxd [command] Available Commands: + comet CometBFT subcommands completion Generate the autocompletion script for the specified shell - config Create or query an application CLI configuration file + config Utilities for managing application configuration debug Tool for helping with debugging your application export Export state to JSON genesis Application's genesis-related subcommands @@ -119,20 +120,20 @@ Available Commands: keys Manage your application's keys prune Prune app history states by keeping the recent heights and deleting old heights query Querying subcommands - rollback rollback cosmos-sdk and tendermint state by one height - rosetta spin up a rosetta server + rollback rollback Cosmos SDK and CometBFT state by one height + snapshots Manage local snapshots start Run the full node status Query remote node for status - tendermint Tendermint subcommands testnet subcommands for starting or configuring local testnets tx Transactions subcommands version Print the application binary version information Flags: -h, --help help for nyxd - --home string directory for config and data + --home string directory for config and data (default "/Users/neo/.nyxd") --log_format string The logging format (json|plain) (default "plain") - --log_level string The logging level (trace|debug|info|warn|error|fatal|panic) (default "info") + --log_level string The logging level (trace|debug|info|warn|error|fatal|panic|disabled or '*:,:') (default "info") + --log_no_color Disable colored logs --trace print out full stack trace on errors Use "nyxd [command] --help" for more information about a command. @@ -180,8 +181,9 @@ Usage: nyxd [command] Available Commands: + comet CometBFT subcommands completion Generate the autocompletion script for the specified shell - config Create or query an application CLI configuration file + config Utilities for managing application configuration debug Tool for helping with debugging your application export Export state to JSON genesis Application's genesis-related subcommands @@ -190,20 +192,20 @@ Available Commands: keys Manage your application's keys prune Prune app history states by keeping the recent heights and deleting old heights query Querying subcommands - rollback rollback cosmos-sdk and tendermint state by one height - rosetta spin up a rosetta server + rollback rollback Cosmos SDK and CometBFT state by one height + snapshots Manage local snapshots start Run the full node status Query remote node for status - tendermint Tendermint subcommands testnet subcommands for starting or configuring local testnets tx Transactions subcommands version Print the application binary version information Flags: -h, --help help for nyxd - --home string directory for config and data + --home string directory for config and data (default "/Users/neo/.nyxd") --log_format string The logging format (json|plain) (default "plain") - --log_level string The logging level (trace|debug|info|warn|error|fatal|panic) (default "info") + --log_level string The logging level (trace|debug|info|warn|error|fatal|panic|disabled or '*:,:') (default "info") + --log_no_color Disable colored logs --trace print out full stack trace on errors Use "nyxd [command] --help" for more information about a command. @@ -246,7 +248,7 @@ You can use the following command to download them for the correct network: wget -O $HOME/.nyxd/config/genesis.json https://nymtech.net/genesis/genesis.json # Sandbox testnet -curl https://rpc.sandbox.nymtech.net/snapshots/genesis.json | jq '.result.genesis' > $HOME/.nyxd/config/genesis.json +curl https://rpc.sandbox.nymtech.net/genesis | jq '.result.genesis' > $HOME/.nyxd/config/genesis.json ``` ### `config.toml` configuration @@ -512,7 +514,7 @@ nyxd tx slashing unjail --from="KEYRING_NAME" --chain-id=nyx --gas=auto - --gas-adjustment=1.4 + --gas-adjustment=1.5 --gas-prices=0.025unyx ``` @@ -523,7 +525,7 @@ nyxd tx slashing unjail --from="KEYRING_NAME" --chain-id=sandbox --gas=auto - --gas-adjustment=1.4 + --gas-adjustment=1.5 --gas-prices=0.025unyx ``` diff --git a/gateway/src/node/client_handling/websocket/connection_handler/authenticated.rs b/gateway/src/node/client_handling/websocket/connection_handler/authenticated.rs index e3b560ec94..a152092ef7 100644 --- a/gateway/src/node/client_handling/websocket/connection_handler/authenticated.rs +++ b/gateway/src/node/client_handling/websocket/connection_handler/authenticated.rs @@ -24,6 +24,8 @@ use nym_gateway_requests::{ SimpleGatewayRequestsError, }; use nym_gateway_storage::error::GatewayStorageError; +use nym_gateway_storage::traits::BandwidthGatewayStorage; +use nym_gateway_storage::traits::SharedKeyGatewayStorage; use nym_node_metrics::events::MetricsEvent; use nym_sphinx::forwarding::packet::MixPacket; use nym_statistics_common::{gateways::GatewaySessionEvent, types::SessionType}; @@ -190,7 +192,7 @@ impl AuthenticatedHandler { let handler = AuthenticatedHandler { bandwidth_storage_manager: BandwidthStorageManager::new( - fresh.shared_state.storage.clone(), + Box::new(fresh.shared_state.storage.clone()), ClientBandwidth::new(bandwidth.into()), client.id, fresh.shared_state.cfg.bandwidth, diff --git a/gateway/src/node/client_handling/websocket/connection_handler/fresh.rs b/gateway/src/node/client_handling/websocket/connection_handler/fresh.rs index bd66ee26f5..2edbf16b4c 100644 --- a/gateway/src/node/client_handling/websocket/connection_handler/fresh.rs +++ b/gateway/src/node/client_handling/websocket/connection_handler/fresh.rs @@ -27,6 +27,9 @@ use nym_gateway_requests::{ INITIAL_PROTOCOL_VERSION, }; use nym_gateway_storage::error::GatewayStorageError; +use nym_gateway_storage::traits::BandwidthGatewayStorage; +use nym_gateway_storage::traits::InboxGatewayStorage; +use nym_gateway_storage::traits::SharedKeyGatewayStorage; use nym_node_metrics::events::MetricsEvent; use nym_sphinx::DestinationAddressBytes; use nym_task::TaskClient; diff --git a/gateway/src/node/mod.rs b/gateway/src/node/mod.rs index c13df9f241..08c5bc886b 100644 --- a/gateway/src/node/mod.rs +++ b/gateway/src/node/mod.rs @@ -13,7 +13,6 @@ use nym_credential_verification::ecash::{ credential_sender::CredentialHandlerConfig, EcashManager, }; use nym_crypto::asymmetric::ed25519; -use nym_gateway_storage::models::WireguardPeer; use nym_ip_packet_router::IpPacketRouter; use nym_mixnet_client::forwarder::MixForwardingSender; use nym_network_defaults::NymNetworkDetails; @@ -38,7 +37,11 @@ mod stale_data_cleaner; use crate::node::stale_data_cleaner::StaleMessagesCleaner; pub use client_handling::active_clients::ActiveClientsStore; pub use nym_gateway_stats_storage::PersistentStatsStorage; -pub use nym_gateway_storage::{error::GatewayStorageError, GatewayStorage}; +pub use nym_gateway_storage::{ + error::GatewayStorageError, + traits::{BandwidthGatewayStorage, InboxGatewayStorage}, + GatewayStorage, +}; use nym_node_metrics::NymNodeMetrics; pub use nym_sdk::{NymApiTopologyProvider, NymApiTopologyProviderConfig, UserAgent}; @@ -93,7 +96,7 @@ pub struct GatewayTasksBuilder { // populated and cached as necessary ecash_manager: Option>, - wireguard_peers: Option>, + wireguard_peers: Option>, wireguard_networks: Option>, } @@ -357,12 +360,12 @@ impl GatewayTasksBuilder { async fn build_wireguard_peers_and_networks( &self, - ) -> Result<(Vec, Vec), GatewayError> { + ) -> Result<(Vec, Vec), GatewayError> { let mut used_private_network_ips = vec![]; let mut all_peers = vec![]; for wireguard_peer in self.storage.get_all_wireguard_peers().await?.into_iter() { let mut peer = defguard_wireguard_rs::host::Peer::try_from(wireguard_peer.clone())?; - let Some(peer) = peer.allowed_ips.pop() else { + let Some(allowed_ip) = peer.allowed_ips.pop() else { let peer_identity = &peer.public_key; warn!("Peer {peer_identity} has empty allowed ips. It will be removed",); self.storage @@ -370,8 +373,8 @@ impl GatewayTasksBuilder { .await?; continue; }; - used_private_network_ips.push(peer.ip); - all_peers.push(wireguard_peer); + used_private_network_ips.push(allowed_ip.ip); + all_peers.push(peer); } Ok((all_peers, used_private_network_ips)) @@ -379,7 +382,9 @@ impl GatewayTasksBuilder { // only used under linux #[allow(dead_code)] - async fn get_wireguard_peers(&mut self) -> Result, GatewayError> { + async fn get_wireguard_peers( + &mut self, + ) -> Result, GatewayError> { if let Some(cached) = self.wireguard_peers.take() { return Ok(cached); } @@ -432,8 +437,8 @@ impl GatewayTasksBuilder { opts.config.clone(), wireguard_data.inner.clone(), used_private_network_ips, + ecash_manager, ) - .with_ecash_verifier(ecash_manager) .with_custom_gateway_transceiver(transceiver) .with_shutdown(self.shutdown.fork("authenticator_sp")) .with_wait_for_gateway(true) diff --git a/nym-api/Cargo.toml b/nym-api/Cargo.toml index 1906ef30ba..464a3ea6e2 100644 --- a/nym-api/Cargo.toml +++ b/nym-api/Cargo.toml @@ -16,17 +16,12 @@ async-trait = { workspace = true } bs58 = { workspace = true } bip39 = { workspace = true } bincode.workspace = true +console-subscriber = { workspace = true, optional = true } # nym-api needs to be built with RUSTFLAGS="--cfg tokio_unstable" cfg-if = { workspace = true } clap = { workspace = true, features = ["cargo", "derive", "env"] } -console-subscriber = { workspace = true, optional = true } # validator-api needs to be built with RUSTFLAGS="--cfg tokio_unstable" dashmap = { workspace = true } -dirs = { workspace = true } futures = { workspace = true } -itertools = { workspace = true } humantime-serde = { workspace = true } -k256 = { workspace = true, features = [ - "ecdsa-core", -] } # needed for the Verifier trait; pull whatever version is used by other dependencies moka = { workspace = true } pin-project = { workspace = true } rand = { workspace = true } @@ -51,7 +46,6 @@ tendermint = { workspace = true } ts-rs = { workspace = true, optional = true } anyhow = { workspace = true } -getset = { workspace = true } sqlx = { workspace = true, features = [ "runtime-tokio-rustls", @@ -66,30 +60,19 @@ zeroize = { workspace = true } # for axum server axum = { workspace = true, features = ["tokio"] } -axum-extra = { workspace = true, features = ["typed-header"] } tower-http = { workspace = true, features = ["cors", "trace", "compression-br", "compression-deflate", "compression-gzip", "compression-zstd"] } utoipa = { workspace = true, features = ["axum_extras", "time"] } utoipauto = { workspace = true } utoipa-swagger-ui = { workspace = true, features = ["axum"] } tracing = { workspace = true } -## ephemera-specific -#actix-web = "4" -#array-bytes = "6.0.0" -#chrono = { version = "0.4.24", default-features = false, features = ["clock"] } -#futures-util = "0.3.25" -#serde_derive = "1.0.149" -#uuid = { version = "1.3.0", features = ["serde", "v4"] } - ## internal -#ephemera = { path = "../ephemera" } nym-bandwidth-controller = { path = "../common/bandwidth-controller" } nym-ecash-contract-common = { path = "../common/cosmwasm-smart-contracts/ecash-contract" } nym-ecash-time = { path = "../common/ecash-time", features = ["expiration"] } nym-coconut-dkg-common = { path = "../common/cosmwasm-smart-contracts/coconut-dkg" } nym-compact-ecash = { path = "../common/nym_offline_compact_ecash" } nym-credentials-interface = { path = "../common/credentials-interface" } -#nym-ephemera-common = { path = "../common/cosmwasm-smart-contracts/ephemera" } nym-config = { path = "../common/config" } cosmwasm-std = { workspace = true } nym-credential-storage = { path = "../common/credential-storage", features = [ @@ -102,11 +85,8 @@ cw3 = { workspace = true } cw4 = { workspace = true } nym-dkg = { path = "../common/dkg", features = ["cw-types"] } nym-gateway-client = { path = "../common/client-libs/gateway-client" } -nym-inclusion-probability = { path = "../common/inclusion-probability" } nym-mixnet-contract-common = { path = "../common/cosmwasm-smart-contracts/mixnet-contract", features = ["utoipa"] } -nym-vesting-contract-common = { path = "../common/cosmwasm-smart-contracts/vesting-contract" } nym-contracts-common = { path = "../common/cosmwasm-smart-contracts/contracts-common", features = ["naive_float", "utoipa"] } -nym-multisig-contract-common = { path = "../common/cosmwasm-smart-contracts/multisig-contract" } nym-sphinx = { path = "../common/nymsphinx" } nym-pemstore = { path = "../common/pemstore" } nym-task = { path = "../common/task" } @@ -121,7 +101,8 @@ nym-http-api-common = { path = "../common/http-api-common", features = ["utoipa" nym-serde-helpers = { path = "../common/serde-helpers", features = ["date"] } nym-ticketbooks-merkle = { path = "../common/ticketbooks-merkle" } nym-statistics-common = { path = "../common/statistics" } -chrono.workspace = true +nym-ecash-signer-check = { path = "../common/ecash-signer-check" } + [features] no-reward = [] diff --git a/nym-api/nym-api-requests/Cargo.toml b/nym-api/nym-api-requests/Cargo.toml index c0eb51d4d0..267cb731f7 100644 --- a/nym-api/nym-api-requests/Cargo.toml +++ b/nym-api/nym-api-requests/Cargo.toml @@ -10,7 +10,6 @@ license.workspace = true bs58 = { workspace = true } cosmrs = { workspace = true } cosmwasm-std = { workspace = true } -getset = { workspace = true } schemars = { workspace = true, features = ["preserve_order"] } serde = { workspace = true, features = ["derive"] } humantime-serde = { workspace = true } @@ -37,10 +36,13 @@ nym-ecash-time = { path = "../../common/ecash-time" } nym-compact-ecash = { path = "../../common/nym_offline_compact_ecash" } nym-contracts-common = { path = "../../common/cosmwasm-smart-contracts/contracts-common", features = ["naive_float"] } nym-mixnet-contract-common = { path = "../../common/cosmwasm-smart-contracts/mixnet-contract", features = ["utoipa"] } +nym-coconut-dkg-common = { path = "../../common/cosmwasm-smart-contracts/coconut-dkg" } nym-node-requests = { path = "../../nym-node/nym-node-requests", default-features = false, features = ["openapi"] } -nym-noise-keys = { path = "../../common/nymnoise/keys"} +nym-noise-keys = { path = "../../common/nymnoise/keys" } nym-network-defaults = { path = "../../common/network-defaults" } nym-ticketbooks-merkle = { path = "../../common/ticketbooks-merkle" } +nym-ecash-signer-check-types = { path = "../../common/ecash-signer-check-types" } + [dev-dependencies] rand_chacha = { workspace = true } diff --git a/nym-api/nym-api-requests/src/ecash/models.rs b/nym-api/nym-api-requests/src/ecash/models.rs index 3779d27e17..a69d0c1d33 100644 --- a/nym-api/nym-api-requests/src/ecash/models.rs +++ b/nym-api/nym-api-requests/src/ecash/models.rs @@ -1,7 +1,9 @@ // Copyright 2023-2024 - Nym Technologies SA // SPDX-License-Identifier: Apache-2.0 +use crate::signable::SignedMessage; use cosmrs::AccountId; +use nym_coconut_dkg_common::types::EpochId; use nym_compact_ecash::scheme::coin_indices_signatures::AnnotatedCoinIndexSignature; use nym_compact_ecash::scheme::expiration_date_signatures::AnnotatedExpirationDateSignature; use nym_compact_ecash::utils::try_deserialize_g1_projective; @@ -12,14 +14,13 @@ use nym_credentials_interface::{ VerificationKeyAuth, WithdrawalRequest, }; use nym_crypto::asymmetric::ed25519; -use nym_crypto::asymmetric::ed25519::serde_helpers::bs58_ed25519_signature; use nym_ticketbooks_merkle::{IssuedTicketbook, IssuedTicketbooksFullMerkleProof}; use serde::{Deserialize, Serialize}; use sha2::Digest; use std::collections::BTreeMap; use std::ops::Deref; use thiserror::Error; -use time::Date; +use time::{Date, OffsetDateTime}; use utoipa::ToSchema; #[derive(Serialize, Deserialize, Clone, ToSchema)] @@ -541,74 +542,6 @@ pub struct CommitedDeposit { pub merkle_index: usize, } -// -// - -// make sure only our types can implement this trait (to ensure infallible serialisation) -mod private { - use crate::ecash::models::{ - IssuedTicketbooksChallengeCommitmentRequestBody, - IssuedTicketbooksChallengeCommitmentResponseBody, IssuedTicketbooksDataRequestBody, - IssuedTicketbooksDataResponseBody, IssuedTicketbooksForResponseBody, - }; - - pub trait Sealed {} - - // requests - impl Sealed for IssuedTicketbooksChallengeCommitmentRequestBody {} - impl Sealed for IssuedTicketbooksDataRequestBody {} - - // responses - impl Sealed for IssuedTicketbooksChallengeCommitmentResponseBody {} - impl Sealed for IssuedTicketbooksForResponseBody {} - impl Sealed for IssuedTicketbooksDataResponseBody {} -} - -// the trait is not public as it's only defined on types that are guaranteed to not panic when serialised -pub trait SignableMessageBody: Serialize + private::Sealed { - fn sign(self, key: &ed25519::PrivateKey) -> SignedMessage - where - Self: Sized, - { - let signature = key.sign(self.plaintext()); - SignedMessage { - body: self, - signature, - } - } - - fn plaintext(&self) -> Vec { - #[allow(clippy::unwrap_used)] - // SAFETY: all types that implement this trait have valid serialisations - serde_json::to_vec(&self).unwrap() - } -} - -impl SignableMessageBody for T where T: Serialize + private::Sealed {} - -#[derive(Clone, Serialize, Deserialize, Debug, ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct SignedMessage { - pub body: T, - #[schema(value_type = String)] - #[serde(with = "bs58_ed25519_signature")] - pub signature: ed25519::Signature, -} - -impl SignedMessage { - pub fn verify_signature(&self, pub_key: &ed25519::PublicKey) -> bool - where - T: SignableMessageBody, - { - let plaintext = self.body.plaintext(); - if plaintext.is_empty() { - return false; - } - - pub_key.verify(&plaintext, &self.signature).is_ok() - } -} - pub type IssuedTicketbooksDataRequest = SignedMessage; pub type IssuedTicketbooksChallengeCommitmentRequest = SignedMessage; @@ -826,6 +759,31 @@ pub struct IssuedTicketbooksForCount { pub count: u32, } +pub type EcashSignerStatusResponse = SignedMessage; + +#[derive(Serialize, Deserialize, ToSchema, Clone, Debug)] +#[serde(rename_all = "camelCase")] +// includes all pre-requisites for successful (assuming valid request) `/blind-sign` +pub struct EcashSignerStatusResponseBody { + #[serde(with = "time::serde::rfc3339")] + #[schema(value_type = String)] + pub current_time: OffsetDateTime, + + /// Current, perceived, dkg epoch id + pub dkg_ecash_epoch_id: EpochId, + + /// Flag indicating whether the operator has explicitly disabled signer functionalities in the api + pub signer_disabled: bool, + + /// Flag indicating whether this api thinks it's a valid ecash signer for the current epoch + pub is_ecash_signer: bool, + + /// Flag indicating whether this api thinks it has valid signing keys. + /// It might be a valid signer that's not disabled, but the keys might have accidentally been + /// removed due to invalid data migration. + pub has_signing_keys: bool, +} + #[cfg(test)] mod tests { use super::*; diff --git a/nym-api/nym-api-requests/src/lib.rs b/nym-api/nym-api-requests/src/lib.rs index 681f1c6b0f..371ab9ba56 100644 --- a/nym-api/nym-api-requests/src/lib.rs +++ b/nym-api/nym-api-requests/src/lib.rs @@ -11,6 +11,7 @@ pub mod legacy; pub mod models; pub mod nym_nodes; pub mod pagination; +pub mod signable; // The response type we fetch from the network details endpoint. #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/nym-api/nym-api-requests/src/models.rs b/nym-api/nym-api-requests/src/models.rs deleted file mode 100644 index 3d4447dfff..0000000000 --- a/nym-api/nym-api-requests/src/models.rs +++ /dev/null @@ -1,2107 +0,0 @@ -// Copyright 2022-2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -#![allow(deprecated)] - -use crate::helpers::unix_epoch; -use crate::helpers::PlaceholderJsonSchemaImpl; -use crate::legacy::{ - LegacyGatewayBondWithId, LegacyMixNodeBondWithLayer, LegacyMixNodeDetailsWithLayer, -}; -use crate::nym_nodes::SemiSkimmedNode; -use crate::nym_nodes::{BasicEntryInformation, NodeRole, SkimmedNode}; -use crate::pagination::PaginatedResponse; -use cosmwasm_std::{Addr, Coin, Decimal, Uint128}; -use nym_contracts_common::NaiveFloat; -use nym_crypto::asymmetric::ed25519::{self, serde_helpers::bs58_ed25519_pubkey}; -use nym_crypto::asymmetric::x25519::{self, serde_helpers::bs58_x25519_pubkey}; -use nym_mixnet_contract_common::nym_node::Role; -use nym_mixnet_contract_common::reward_params::{Performance, RewardingParams}; -use nym_mixnet_contract_common::rewarding::RewardEstimate; -use nym_mixnet_contract_common::{GatewayBond, IdentityKey, Interval, MixNode, NodeId, Percent}; -use nym_network_defaults::{DEFAULT_MIX_LISTENING_PORT, DEFAULT_VERLOC_LISTENING_PORT}; -use nym_node_requests::api::v1::authenticator::models::Authenticator; -use nym_node_requests::api::v1::gateway::models::Wireguard; -use nym_node_requests::api::v1::ip_packet_router::models::IpPacketRouter; -use nym_node_requests::api::v1::node::models::{AuxiliaryDetails, NodeRoles}; -use nym_noise_keys::VersionedNoiseKey; -use schemars::gen::SchemaGenerator; -use schemars::schema::{InstanceType, Schema, SchemaObject}; -use schemars::JsonSchema; -use serde::{Deserialize, Deserializer, Serialize}; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::fmt::{Debug, Display, Formatter}; -use std::net::IpAddr; -use std::ops::{Deref, DerefMut}; -use std::{fmt, time::Duration}; -use thiserror::Error; -use time::{Date, OffsetDateTime}; -use tracing::{error, warn}; -use utoipa::{IntoParams, ToResponse, ToSchema}; - -pub use nym_mixnet_contract_common::{EpochId, KeyRotationId, KeyRotationState}; -pub use nym_node_requests::api::v1::node::models::BinaryBuildInformationOwned; - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)] -pub struct RequestError { - message: String, -} - -impl RequestError { - pub fn new>(msg: S) -> Self { - RequestError { - message: msg.into(), - } - } - - pub fn message(&self) -> &str { - &self.message - } - - pub fn empty() -> Self { - Self { - message: String::new(), - } - } -} - -impl Display for RequestError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - Display::fmt(&self.message, f) - } -} - -#[derive( - Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, ToSchema, Default, -)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/MixnodeStatus.ts" - ) -)] -#[serde(rename_all = "snake_case")] -pub enum MixnodeStatus { - Active, // in both the active set and the rewarded set - Standby, // only in the rewarded set - Inactive, // in neither the rewarded set nor the active set, but is bonded - #[default] - NotFound, // doesn't even exist in the bonded set -} -impl MixnodeStatus { - pub fn is_active(&self) -> bool { - *self == MixnodeStatus::Active - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/MixnodeCoreStatusResponse.ts" - ) -)] -pub struct MixnodeCoreStatusResponse { - pub mix_id: NodeId, - pub count: i64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/GatewayCoreStatusResponse.ts" - ) -)] -pub struct GatewayCoreStatusResponse { - pub identity: String, - pub count: i64, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/MixnodeStatusResponse.ts" - ) -)] -pub struct MixnodeStatusResponse { - pub status: MixnodeStatus, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct NodePerformance { - #[schema(value_type = String)] - pub most_recent: Performance, - #[schema(value_type = String)] - pub last_hour: Performance, - #[schema(value_type = String)] - pub last_24h: Performance, -} - -#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, JsonSchema, ToSchema)] -#[serde(rename_all = "camelCase")] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts(export, export_to = "ts-packages/types/src/types/rust/DisplayRole.ts") -)] -pub enum DisplayRole { - EntryGateway, - Layer1, - Layer2, - Layer3, - ExitGateway, - Standby, -} - -impl From for DisplayRole { - fn from(role: Role) -> Self { - match role { - Role::EntryGateway => DisplayRole::EntryGateway, - Role::Layer1 => DisplayRole::Layer1, - Role::Layer2 => DisplayRole::Layer2, - Role::Layer3 => DisplayRole::Layer3, - Role::ExitGateway => DisplayRole::ExitGateway, - Role::Standby => DisplayRole::Standby, - } - } -} - -impl From for Role { - fn from(role: DisplayRole) -> Self { - match role { - DisplayRole::EntryGateway => Role::EntryGateway, - DisplayRole::Layer1 => Role::Layer1, - DisplayRole::Layer2 => Role::Layer2, - DisplayRole::Layer3 => Role::Layer3, - DisplayRole::ExitGateway => Role::ExitGateway, - DisplayRole::Standby => Role::Standby, - } - } -} - -// imo for now there's no point in exposing more than that, -// nym-api shouldn't be calculating apy or stake saturation for you. -// it should just return its own metrics (performance) and then you can do with it as you wish -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/NodeAnnotation.ts" - ) -)] -pub struct NodeAnnotation { - #[cfg_attr(feature = "generate-ts", ts(type = "string"))] - // legacy - #[schema(value_type = String)] - pub last_24h_performance: Performance, - pub current_role: Option, - - pub detailed_performance: DetailedNodePerformance, -} - -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/DetailedNodePerformance.ts" - ) -)] -#[non_exhaustive] -pub struct DetailedNodePerformance { - /// routing_score * config_score - pub performance_score: f64, - - pub routing_score: RoutingScore, - pub config_score: ConfigScore, -} - -impl DetailedNodePerformance { - pub fn new( - performance_score: f64, - routing_score: RoutingScore, - config_score: ConfigScore, - ) -> DetailedNodePerformance { - Self { - performance_score, - routing_score, - config_score, - } - } - - pub fn to_rewarding_performance(&self) -> Performance { - Performance::naive_try_from_f64(self.performance_score).unwrap_or_default() - } -} - -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts(export, export_to = "ts-packages/types/src/types/rust/RoutingScore.ts") -)] -#[non_exhaustive] -pub struct RoutingScore { - /// Total score after taking all the criteria into consideration - pub score: f64, -} - -impl RoutingScore { - pub fn new(score: f64) -> RoutingScore { - Self { score } - } - - pub const fn zero() -> RoutingScore { - RoutingScore { score: 0.0 } - } - - pub fn legacy_performance(&self) -> Performance { - Performance::naive_try_from_f64(self.score).unwrap_or_default() - } -} - -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts(export, export_to = "ts-packages/types/src/types/rust/ConfigScore.ts") -)] -#[non_exhaustive] -pub struct ConfigScore { - /// Total score after taking all the criteria into consideration - pub score: f64, - - pub versions_behind: Option, - pub self_described_api_available: bool, - pub accepted_terms_and_conditions: bool, - pub runs_nym_node_binary: bool, -} - -impl ConfigScore { - pub fn new( - score: f64, - versions_behind: u32, - accepted_terms_and_conditions: bool, - runs_nym_node_binary: bool, - ) -> ConfigScore { - Self { - score, - versions_behind: Some(versions_behind), - self_described_api_available: true, - accepted_terms_and_conditions, - runs_nym_node_binary, - } - } - - pub fn bad_semver() -> ConfigScore { - ConfigScore { - score: 0.0, - versions_behind: None, - self_described_api_available: true, - accepted_terms_and_conditions: false, - runs_nym_node_binary: false, - } - } - - pub fn unavailable() -> ConfigScore { - ConfigScore { - score: 0.0, - versions_behind: None, - self_described_api_available: false, - accepted_terms_and_conditions: false, - runs_nym_node_binary: false, - } - } -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/AnnotationResponse.ts" - ) -)] -pub struct AnnotationResponse { - #[schema(value_type = u32)] - pub node_id: NodeId, - pub annotation: Option, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/NodePerformanceResponse.ts" - ) -)] -pub struct NodePerformanceResponse { - #[schema(value_type = u32)] - pub node_id: NodeId, - pub performance: Option, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/NodeDatePerformanceResponse.ts" - ) -)] -pub struct NodeDatePerformanceResponse { - #[schema(value_type = u32)] - pub node_id: NodeId, - #[schema(value_type = String, example = "1970-01-01")] - #[schemars(with = "String")] - #[cfg_attr(feature = "generate-ts", ts(type = "string"))] - pub date: Date, - pub performance: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[schema(title = "LegacyMixNodeDetailsWithLayer")] -pub struct LegacyMixNodeDetailsWithLayerSchema { - /// Basic bond information of this mixnode, such as owner address, original pledge, etc. - #[schema(example = "unimplemented schema")] - pub bond_information: String, - - /// Details used for computation of rewarding related data. - #[schema(example = "unimplemented schema")] - pub rewarding_details: String, - - /// Adjustments to the mixnode that are ought to happen during future epoch transitions. - #[schema(example = "unimplemented schema")] - pub pending_changes: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct MixNodeBondAnnotated { - #[schema(value_type = LegacyMixNodeDetailsWithLayerSchema)] - pub mixnode_details: LegacyMixNodeDetailsWithLayer, - #[schema(value_type = String)] - pub stake_saturation: StakeSaturation, - #[schema(value_type = String)] - pub uncapped_stake_saturation: StakeSaturation, - // NOTE: the performance field is deprecated in favour of node_performance - #[schema(value_type = String)] - pub performance: Performance, - pub node_performance: NodePerformance, - #[schema(value_type = String)] - pub estimated_operator_apy: Decimal, - #[schema(value_type = String)] - pub estimated_delegators_apy: Decimal, - pub blacklisted: bool, - - // a rather temporary thing until we query self-described endpoints of mixnodes - #[serde(default)] - #[schema(value_type = Vec)] - pub ip_addresses: Vec, -} - -#[derive(Debug, Error)] -pub enum MalformedNodeBond { - #[error("the associated ed25519 identity key is malformed")] - InvalidEd25519Key, - - #[error("the associated x25519 sphinx key is malformed")] - InvalidX25519Key, -} - -impl MixNodeBondAnnotated { - pub fn mix_node(&self) -> &MixNode { - &self.mixnode_details.bond_information.mix_node - } - - pub fn mix_id(&self) -> NodeId { - self.mixnode_details.mix_id() - } - - pub fn identity_key(&self) -> &str { - self.mixnode_details.bond_information.identity() - } - - pub fn owner(&self) -> &Addr { - self.mixnode_details.bond_information.owner() - } - - pub fn version(&self) -> &str { - &self.mixnode_details.bond_information.mix_node.version - } - - pub fn try_to_skimmed_node(&self, role: NodeRole) -> Result { - Ok(SkimmedNode { - node_id: self.mix_id(), - ed25519_identity_pubkey: self - .identity_key() - .parse() - .map_err(|_| MalformedNodeBond::InvalidEd25519Key)?, - ip_addresses: self.ip_addresses.clone(), - mix_port: self.mix_node().mix_port, - x25519_sphinx_pubkey: self - .mix_node() - .sphinx_key - .parse() - .map_err(|_| MalformedNodeBond::InvalidX25519Key)?, - role, - supported_roles: DeclaredRoles { - mixnode: true, - entry: false, - exit_nr: false, - exit_ipr: false, - }, - entry: None, - performance: self.node_performance.last_24h, - }) - } - - pub fn try_to_semi_skimmed_node( - &self, - role: NodeRole, - ) -> Result { - let skimmed_node = self.try_to_skimmed_node(role)?; - Ok(SemiSkimmedNode { - basic: skimmed_node, - x25519_noise_versioned_key: None, // legacy node won't ever support Noise - }) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct GatewayBondAnnotated { - pub gateway_bond: LegacyGatewayBondWithId, - - #[serde(default)] - pub self_described: Option, - - // NOTE: the performance field is deprecated in favour of node_performance - #[schema(value_type = String)] - pub performance: Performance, - pub node_performance: NodePerformance, - pub blacklisted: bool, - - #[serde(default)] - #[schema(value_type = Vec)] - pub ip_addresses: Vec, -} - -impl GatewayBondAnnotated { - pub fn version(&self) -> &str { - &self.gateway_bond.gateway.version - } - - pub fn identity(&self) -> &String { - self.gateway_bond.bond.identity() - } - - pub fn owner(&self) -> &Addr { - self.gateway_bond.bond.owner() - } - - pub fn try_to_skimmed_node(&self, role: NodeRole) -> Result { - Ok(SkimmedNode { - node_id: self.gateway_bond.node_id, - ip_addresses: self.ip_addresses.clone(), - ed25519_identity_pubkey: self - .gateway_bond - .gateway - .identity_key - .parse() - .map_err(|_| MalformedNodeBond::InvalidEd25519Key)?, - mix_port: self.gateway_bond.bond.gateway.mix_port, - x25519_sphinx_pubkey: self - .gateway_bond - .gateway - .sphinx_key - .parse() - .map_err(|_| MalformedNodeBond::InvalidX25519Key)?, - role, - supported_roles: DeclaredRoles { - mixnode: false, - entry: true, - exit_nr: false, - exit_ipr: false, - }, - entry: Some(BasicEntryInformation { - hostname: None, - ws_port: self.gateway_bond.bond.gateway.clients_port, - wss_port: None, - }), - performance: self.node_performance.last_24h, - }) - } - - pub fn try_to_semi_skimmed_node( - &self, - role: NodeRole, - ) -> Result { - let skimmed_node = self.try_to_skimmed_node(role)?; - Ok(SemiSkimmedNode { - basic: skimmed_node, - x25519_noise_versioned_key: None, // legacy node won't ever support Noise - }) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct GatewayDescription { - // for now only expose what we need. this struct will evolve in the future (or be incorporated into nym-node properly) -} - -#[derive(Debug, Serialize, Deserialize, JsonSchema, ToSchema, IntoParams)] -pub struct ComputeRewardEstParam { - #[schema(value_type = Option)] - #[param(value_type = Option)] - pub performance: Option, - pub active_in_rewarded_set: Option, - pub pledge_amount: Option, - pub total_delegation: Option, - #[schema(value_type = Option)] - #[param(value_type = Option)] - pub interval_operating_cost: Option, - #[schema(value_type = Option)] - #[param(value_type = Option)] - pub profit_margin_percent: Option, -} - -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/RewardEstimationResponse.ts" - ) -)] -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct RewardEstimationResponse { - pub estimation: RewardEstimate, - pub reward_params: RewardingParams, - pub epoch: Interval, - #[cfg_attr(feature = "generate-ts", ts(type = "number"))] - pub as_at: i64, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct UptimeResponse { - #[schema(value_type = u32)] - pub mix_id: NodeId, - // The same as node_performance.last_24h. Legacy - pub avg_uptime: u8, - pub node_performance: NodePerformance, -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct GatewayUptimeResponse { - pub identity: String, - // The same as node_performance.last_24h. Legacy - pub avg_uptime: u8, - pub node_performance: NodePerformance, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/StakeSaturationResponse.ts" - ) -)] -pub struct StakeSaturationResponse { - #[cfg_attr(feature = "generate-ts", ts(type = "string"))] - #[schema(value_type = String)] - pub saturation: StakeSaturation, - - #[cfg_attr(feature = "generate-ts", ts(type = "string"))] - #[schema(value_type = String)] - pub uncapped_saturation: StakeSaturation, - pub as_at: i64, -} - -pub type StakeSaturation = Decimal; - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/SelectionChance.ts" - ) -)] -#[deprecated] -pub enum SelectionChance { - High, - Good, - Low, -} - -impl From for SelectionChance { - fn from(p: f64) -> SelectionChance { - match p { - p if p >= 0.7 => SelectionChance::High, - p if p >= 0.3 => SelectionChance::Good, - _ => SelectionChance::Low, - } - } -} - -impl From for SelectionChance { - fn from(p: Decimal) -> Self { - match p { - p if p >= Decimal::from_ratio(70u32, 100u32) => SelectionChance::High, - p if p >= Decimal::from_ratio(30u32, 100u32) => SelectionChance::Good, - _ => SelectionChance::Low, - } - } -} - -impl fmt::Display for SelectionChance { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - SelectionChance::High => write!(f, "High"), - SelectionChance::Good => write!(f, "Good"), - SelectionChance::Low => write!(f, "Low"), - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/InclusionProbabilityResponse.ts" - ) -)] -#[deprecated] -pub struct InclusionProbabilityResponse { - pub in_active: SelectionChance, - pub in_reserve: SelectionChance, -} - -impl fmt::Display for InclusionProbabilityResponse { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "in_active: {}, in_reserve: {}", - self.in_active, self.in_reserve - ) - } -} - -#[deprecated] -#[derive(Clone, Serialize, schemars::JsonSchema, ToSchema)] -pub struct AllInclusionProbabilitiesResponse { - pub inclusion_probabilities: Vec, - pub samples: u64, - pub elapsed: Duration, - pub delta_max: f64, - pub delta_l2: f64, - pub as_at: i64, -} - -#[deprecated] -#[derive(Clone, Serialize, schemars::JsonSchema, ToSchema)] -pub struct InclusionProbability { - #[schema(value_type = u32)] - pub mix_id: NodeId, - pub in_active: f64, - pub in_reserve: f64, -} - -type Uptime = u8; - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct MixnodeStatusReportResponse { - pub mix_id: NodeId, - pub identity: IdentityKey, - pub owner: String, - #[schema(value_type = u8)] - pub most_recent: Uptime, - #[schema(value_type = u8)] - pub last_hour: Uptime, - #[schema(value_type = u8)] - pub last_day: Uptime, -} - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct GatewayStatusReportResponse { - pub identity: String, - pub owner: String, - #[schema(value_type = u8)] - pub most_recent: Uptime, - #[schema(value_type = u8)] - pub last_hour: Uptime, - #[schema(value_type = u8)] - pub last_day: Uptime, -} - -#[derive(Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/PerformanceHistoryResponse.ts" - ) -)] -pub struct PerformanceHistoryResponse { - #[schema(value_type = u32)] - pub node_id: NodeId, - pub history: PaginatedResponse, -} - -#[derive(Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/UptimeHistoryResponse.ts" - ) -)] -pub struct UptimeHistoryResponse { - #[schema(value_type = u32)] - pub node_id: NodeId, - pub history: PaginatedResponse, -} - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/HistoricalUptimeResponse.ts" - ) -)] -pub struct HistoricalUptimeResponse { - #[schema(value_type = String, example = "1970-01-01")] - #[schemars(with = "String")] - #[cfg_attr(feature = "generate-ts", ts(type = "string"))] - pub date: Date, - - pub uptime: Uptime, -} - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/HistoricalPerformanceResponse.ts" - ) -)] -pub struct HistoricalPerformanceResponse { - #[schema(value_type = String, example = "1970-01-01")] - #[schemars(with = "String")] - #[cfg_attr(feature = "generate-ts", ts(type = "string"))] - pub date: Date, - - pub performance: f64, -} - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct OldHistoricalUptimeResponse { - pub date: String, - #[schema(value_type = u8)] - pub uptime: Uptime, -} - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct MixnodeUptimeHistoryResponse { - pub mix_id: NodeId, - pub identity: String, - pub owner: String, - pub history: Vec, -} - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct GatewayUptimeHistoryResponse { - pub identity: String, - pub owner: String, - pub history: Vec, -} - -#[derive(ToSchema)] -#[schema(title = "Coin")] -pub struct CoinSchema { - pub denom: String, - #[schema(value_type = String)] - pub amount: Uint128, -} - -#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema, ToResponse)] -pub struct CirculatingSupplyResponse { - #[schema(value_type = CoinSchema)] - pub total_supply: Coin, - #[schema(value_type = CoinSchema)] - pub mixmining_reserve: Coin, - #[schema(value_type = CoinSchema)] - pub vesting_tokens: Coin, - #[schema(value_type = CoinSchema)] - pub circulating_supply: Coin, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct HostInformation { - #[schema(value_type = Vec)] - pub ip_address: Vec, - pub hostname: Option, - pub keys: HostKeys, -} - -impl From for HostInformation { - fn from(value: nym_node_requests::api::v1::node::models::HostInformation) -> Self { - HostInformation { - ip_address: value.ip_address, - hostname: value.hostname, - keys: value.keys.into(), - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct HostKeys { - #[serde(with = "bs58_ed25519_pubkey")] - #[schemars(with = "String")] - #[schema(value_type = String)] - pub ed25519: ed25519::PublicKey, - - #[deprecated(note = "use the current_x25519_sphinx_key with explicit rotation information")] - #[serde(with = "bs58_x25519_pubkey")] - #[schemars(with = "String")] - #[schema(value_type = String)] - pub x25519: x25519::PublicKey, - - pub current_x25519_sphinx_key: SphinxKey, - - #[serde(default)] - pub pre_announced_x25519_sphinx_key: Option, - - #[serde(default)] - pub x25519_versioned_noise: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct SphinxKey { - pub rotation_id: u32, - - #[serde(with = "bs58_x25519_pubkey")] - #[schemars(with = "String")] - #[schema(value_type = String)] - pub public_key: x25519::PublicKey, -} - -impl From for SphinxKey { - fn from(value: nym_node_requests::api::v1::node::models::SphinxKey) -> Self { - SphinxKey { - rotation_id: value.rotation_id, - public_key: value.public_key, - } - } -} - -impl From for HostKeys { - fn from(value: nym_node_requests::api::v1::node::models::HostKeys) -> Self { - HostKeys { - ed25519: value.ed25519_identity, - x25519: value.x25519_sphinx, - current_x25519_sphinx_key: value.primary_x25519_sphinx_key.into(), - pre_announced_x25519_sphinx_key: value.pre_announced_x25519_sphinx_key.map(Into::into), - x25519_versioned_noise: value.x25519_versioned_noise, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct WebSockets { - pub ws_port: u16, - - pub wss_port: Option, -} - -impl From for WebSockets { - fn from(value: nym_node_requests::api::v1::gateway::models::WebSockets) -> Self { - WebSockets { - ws_port: value.ws_port, - wss_port: value.wss_port, - } - } -} - -pub fn de_rfc3339_or_default<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - Ok(time::serde::rfc3339::deserialize(deserializer).unwrap_or_else(|_| unix_epoch())) -} - -// for all intents and purposes it's just OffsetDateTime, but we need JsonSchema... -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, ToSchema)] -pub struct OffsetDateTimeJsonSchemaWrapper( - #[serde( - default = "unix_epoch", - with = "crate::helpers::overengineered_offset_date_time_serde" - )] - #[schema(inline)] - pub OffsetDateTime, -); - -impl Default for OffsetDateTimeJsonSchemaWrapper { - fn default() -> Self { - OffsetDateTimeJsonSchemaWrapper(unix_epoch()) - } -} - -impl Display for OffsetDateTimeJsonSchemaWrapper { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - Display::fmt(&self.0, f) - } -} - -impl From for OffsetDateTime { - fn from(value: OffsetDateTimeJsonSchemaWrapper) -> Self { - value.0 - } -} - -impl From for OffsetDateTimeJsonSchemaWrapper { - fn from(value: OffsetDateTime) -> Self { - OffsetDateTimeJsonSchemaWrapper(value) - } -} - -impl Deref for OffsetDateTimeJsonSchemaWrapper { - type Target = OffsetDateTime; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl DerefMut for OffsetDateTimeJsonSchemaWrapper { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -// implementation taken from: https://github.com/GREsau/schemars/pull/207 -impl JsonSchema for OffsetDateTimeJsonSchemaWrapper { - fn is_referenceable() -> bool { - false - } - - fn schema_name() -> String { - "DateTime".into() - } - - fn json_schema(_: &mut SchemaGenerator) -> Schema { - SchemaObject { - instance_type: Some(InstanceType::String.into()), - format: Some("date-time".into()), - ..Default::default() - } - .into() - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct NymNodeDescription { - #[schema(value_type = u32)] - pub node_id: NodeId, - pub contract_node_type: DescribedNodeType, - pub description: NymNodeData, -} - -impl NymNodeDescription { - pub fn version(&self) -> &str { - &self.description.build_information.build_version - } - - pub fn entry_information(&self) -> BasicEntryInformation { - BasicEntryInformation { - hostname: self.description.host_information.hostname.clone(), - ws_port: self.description.mixnet_websockets.ws_port, - wss_port: self.description.mixnet_websockets.wss_port, - } - } - - pub fn ed25519_identity_key(&self) -> ed25519::PublicKey { - self.description.host_information.keys.ed25519 - } - - pub fn current_sphinx_key(&self, current_rotation_id: u32) -> x25519::PublicKey { - let keys = &self.description.host_information.keys; - - if keys.current_x25519_sphinx_key.rotation_id == u32::MAX { - // legacy case (i.e. node doesn't support rotation) - return keys.current_x25519_sphinx_key.public_key; - } - - if current_rotation_id == keys.current_x25519_sphinx_key.rotation_id { - // it's the 'current' key - return keys.current_x25519_sphinx_key.public_key; - } - - if let Some(pre_announced) = &keys.pre_announced_x25519_sphinx_key { - if pre_announced.rotation_id == current_rotation_id { - return pre_announced.public_key; - } - } - - warn!( - "unexpected key rotation {current_rotation_id} for node {}", - self.node_id - ); - // this should never be reached, but just in case, return the fallback option - keys.current_x25519_sphinx_key.public_key - } - - pub fn to_skimmed_node( - &self, - current_rotation_id: u32, - role: NodeRole, - performance: Performance, - ) -> SkimmedNode { - let keys = &self.description.host_information.keys; - let entry = if self.description.declared_role.entry { - Some(self.entry_information()) - } else { - None - }; - - SkimmedNode { - node_id: self.node_id, - ed25519_identity_pubkey: keys.ed25519, - ip_addresses: self.description.host_information.ip_address.clone(), - mix_port: self.description.mix_port(), - x25519_sphinx_pubkey: self.current_sphinx_key(current_rotation_id), - // we can't use the declared roles, we have to take whatever was provided in the contract. - // why? say this node COULD operate as an exit, but it might be the case the contract decided - // to assign it an ENTRY role only. we have to use that one instead. - role, - supported_roles: self.description.declared_role, - entry, - performance, - } - } - - pub fn to_semi_skimmed_node( - &self, - current_rotation_id: u32, - role: NodeRole, - performance: Performance, - ) -> SemiSkimmedNode { - let skimmed_node = self.to_skimmed_node(current_rotation_id, role, performance); - - SemiSkimmedNode { - basic: skimmed_node, - x25519_noise_versioned_key: self - .description - .host_information - .keys - .x25519_versioned_noise, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -#[serde(rename_all = "snake_case")] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/DescribedNodeType.ts" - ) -)] -pub enum DescribedNodeType { - LegacyMixnode, - LegacyGateway, - NymNode, -} - -impl DescribedNodeType { - pub fn is_nym_node(&self) -> bool { - matches!(self, DescribedNodeType::NymNode) - } -} - -#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] -#[cfg_attr( - feature = "generate-ts", - ts( - export, - export_to = "ts-packages/types/src/types/rust/DeclaredRoles.ts" - ) -)] -pub struct DeclaredRoles { - pub mixnode: bool, - pub entry: bool, - pub exit_nr: bool, - pub exit_ipr: bool, -} - -impl DeclaredRoles { - pub fn can_operate_exit_gateway(&self) -> bool { - self.exit_ipr && self.exit_nr - } -} - -impl From for DeclaredRoles { - fn from(value: NodeRoles) -> Self { - DeclaredRoles { - mixnode: value.mixnode_enabled, - entry: value.gateway_enabled, - exit_nr: value.gateway_enabled && value.network_requester_enabled, - exit_ipr: value.gateway_enabled && value.ip_packet_router_enabled, - } - } -} - -// this struct is getting quite bloated... -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct NymNodeData { - #[serde(default)] - pub last_polled: OffsetDateTimeJsonSchemaWrapper, - - pub host_information: HostInformation, - - #[serde(default)] - pub declared_role: DeclaredRoles, - - #[serde(default)] - pub auxiliary_details: AuxiliaryDetails, - - // TODO: do we really care about ALL build info or just the version? - pub build_information: BinaryBuildInformationOwned, - - #[serde(default)] - pub network_requester: Option, - - #[serde(default)] - pub ip_packet_router: Option, - - #[serde(default)] - pub authenticator: Option, - - #[serde(default)] - pub wireguard: Option, - - // for now we only care about their ws/wss situation, nothing more - pub mixnet_websockets: WebSockets, -} - -impl NymNodeData { - pub fn mix_port(&self) -> u16 { - self.auxiliary_details - .announce_ports - .mix_port - .unwrap_or(DEFAULT_MIX_LISTENING_PORT) - } - - pub fn verloc_port(&self) -> u16 { - self.auxiliary_details - .announce_ports - .verloc_port - .unwrap_or(DEFAULT_VERLOC_LISTENING_PORT) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct LegacyDescribedGateway { - pub bond: GatewayBond, - pub self_described: Option, -} - -impl From for LegacyDescribedGateway { - fn from(bond: LegacyGatewayBondWithId) -> Self { - LegacyDescribedGateway { - bond: bond.bond, - self_described: None, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct LegacyDescribedMixNode { - pub bond: LegacyMixNodeBondWithLayer, - pub self_described: Option, -} - -impl From for LegacyDescribedMixNode { - fn from(bond: LegacyMixNodeBondWithLayer) -> Self { - LegacyDescribedMixNode { - bond, - self_described: None, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct NetworkRequesterDetails { - /// address of the embedded network requester - pub address: String, - - /// flag indicating whether this network requester uses the exit policy rather than the deprecated allow list - pub uses_exit_policy: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct IpPacketRouterDetails { - /// address of the embedded ip packet router - pub address: String, -} - -// works for current simple case. -impl From for IpPacketRouterDetails { - fn from(value: IpPacketRouter) -> Self { - IpPacketRouterDetails { - address: value.address, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct AuthenticatorDetails { - /// address of the embedded authenticator - pub address: String, -} - -// works for current simple case. -impl From for AuthenticatorDetails { - fn from(value: Authenticator) -> Self { - AuthenticatorDetails { - address: value.address, - } - } -} -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct WireguardDetails { - pub port: u16, - pub public_key: String, -} - -// works for current simple case. -impl From for WireguardDetails { - fn from(value: Wireguard) -> Self { - WireguardDetails { - port: value.port, - public_key: value.public_key, - } - } -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct ApiHealthResponse { - pub status: ApiStatus, - #[serde(default)] - pub chain_status: ChainStatus, - pub uptime: u64, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -#[serde(rename_all = "lowercase")] -pub enum ApiStatus { - Up, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, Default, schemars::JsonSchema, ToSchema)] -#[serde(rename_all = "snake_case")] -pub enum ChainStatus { - Synced, - #[default] - Unknown, - Stalled { - #[serde( - serialize_with = "humantime_serde::serialize", - deserialize_with = "humantime_serde::deserialize" - )] - approximate_amount: Duration, - }, -} - -impl ApiHealthResponse { - pub fn new_healthy(uptime: Duration) -> Self { - ApiHealthResponse { - status: ApiStatus::Up, - chain_status: ChainStatus::Synced, - uptime: uptime.as_secs(), - } - } -} - -impl ApiStatus { - pub fn is_up(&self) -> bool { - matches!(self, ApiStatus::Up) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct SignerInformationResponse { - pub cosmos_address: String, - - pub identity: String, - - pub announce_address: String, - - pub verification_key: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, Default, ToSchema)] -pub struct TestNode { - pub node_id: Option, - pub identity_key: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct TestRoute { - pub gateway: TestNode, - pub layer1: TestNode, - pub layer2: TestNode, - pub layer3: TestNode, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct PartialTestResult { - pub monitor_run_id: i64, - pub timestamp: i64, - pub overall_reliability_for_all_routes_in_monitor_run: Option, - pub test_routes: TestRoute, -} - -pub type MixnodeTestResultResponse = PaginatedResponse; -pub type GatewayTestResultResponse = PaginatedResponse; - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct NetworkMonitorRunDetailsResponse { - pub monitor_run_id: i64, - pub network_reliability: f64, - pub total_sent: usize, - pub total_received: usize, - - // integer score to number of nodes with that score - pub mixnode_results: BTreeMap, - pub gateway_results: BTreeMap, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct NoiseDetails { - pub key: VersionedNoiseKey, - - pub mixnet_port: u16, - - #[schema(value_type = Vec)] - pub ip_addresses: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct NodeRefreshBody { - #[serde(with = "bs58_ed25519_pubkey")] - #[schemars(with = "String")] - #[schema(value_type = String)] - pub node_identity: ed25519::PublicKey, - - // a poor man's nonce - pub request_timestamp: i64, - - #[schemars(with = "PlaceholderJsonSchemaImpl")] - #[schema(value_type = String)] - pub signature: ed25519::Signature, -} - -impl NodeRefreshBody { - pub fn plaintext(node_identity: ed25519::PublicKey, request_timestamp: i64) -> Vec { - node_identity - .to_bytes() - .into_iter() - .chain(request_timestamp.to_be_bytes()) - .chain(b"describe-cache-refresh-request".iter().copied()) - .collect() - } - - pub fn new(private_key: &ed25519::PrivateKey) -> Self { - let node_identity = private_key.public_key(); - let request_timestamp = OffsetDateTime::now_utc().unix_timestamp(); - let signature = private_key.sign(Self::plaintext(node_identity, request_timestamp)); - NodeRefreshBody { - node_identity, - request_timestamp, - signature, - } - } - - pub fn verify_signature(&self) -> bool { - self.node_identity - .verify( - Self::plaintext(self.node_identity, self.request_timestamp), - &self.signature, - ) - .is_ok() - } - - pub fn is_stale(&self) -> bool { - let Ok(encoded) = OffsetDateTime::from_unix_timestamp(self.request_timestamp) else { - return true; - }; - let now = OffsetDateTime::now_utc(); - - if encoded > now { - return true; - } - - if (encoded + Duration::from_secs(30)) < now { - return true; - } - - false - } -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct KeyRotationInfoResponse { - #[serde(flatten)] - pub details: KeyRotationDetails, - - // helper field that holds calculated data based on the `details` field - // this is to expose the information in a format more easily accessible by humans - // without having to do any calculations - pub progress: KeyRotationProgressInfo, -} - -impl From for KeyRotationInfoResponse { - fn from(details: KeyRotationDetails) -> Self { - KeyRotationInfoResponse { - details, - progress: KeyRotationProgressInfo { - current_key_rotation_id: details.current_key_rotation_id(), - current_rotation_starting_epoch: details.current_rotation_starting_epoch_id(), - current_rotation_ending_epoch: details.current_rotation_starting_epoch_id() - + details.key_rotation_state.validity_epochs - - 1, - }, - } - } -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct KeyRotationProgressInfo { - pub current_key_rotation_id: u32, - - pub current_rotation_starting_epoch: u32, - - pub current_rotation_ending_epoch: u32, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct KeyRotationDetails { - pub key_rotation_state: KeyRotationState, - - #[schema(value_type = u32)] - pub current_absolute_epoch_id: EpochId, - - #[serde(with = "time::serde::rfc3339")] - #[schemars(with = "String")] - #[schema(value_type = String)] - pub current_epoch_start: OffsetDateTime, - - pub epoch_duration: Duration, -} - -impl KeyRotationDetails { - pub fn current_key_rotation_id(&self) -> u32 { - self.key_rotation_state - .key_rotation_id(self.current_absolute_epoch_id) - } - - pub fn next_rotation_starting_epoch_id(&self) -> EpochId { - self.key_rotation_state - .next_rotation_starting_epoch_id(self.current_absolute_epoch_id) - } - - pub fn current_rotation_starting_epoch_id(&self) -> EpochId { - self.key_rotation_state - .current_rotation_starting_epoch_id(self.current_absolute_epoch_id) - } - - fn current_epoch_progress(&self, now: OffsetDateTime) -> f32 { - let elapsed = (now - self.current_epoch_start).as_seconds_f32(); - elapsed / self.epoch_duration.as_secs_f32() - } - - pub fn is_epoch_stuck(&self) -> bool { - let now = OffsetDateTime::now_utc(); - let progress = self.current_epoch_progress(now); - if progress > 1. { - let into_next = 1. - progress; - // if epoch hasn't progressed for more than 20% of its duration, mark is as stuck - if into_next > 0.2 { - let diff_time = - Duration::from_secs_f32(into_next * self.epoch_duration.as_secs_f32()); - let expected_epoch_end = self.current_epoch_start + self.epoch_duration; - warn!("the current epoch is expected to have been over by {expected_epoch_end}. it's already {} overdue!", humantime_serde::re::humantime::format_duration(diff_time)); - return true; - } - } - - false - } - - // based on the current **TIME**, determine what's the expected current rotation id - pub fn expected_current_rotation_id(&self) -> KeyRotationId { - let now = OffsetDateTime::now_utc(); - let current_end = now + self.epoch_duration; - if now < current_end { - return self - .key_rotation_state - .key_rotation_id(self.current_absolute_epoch_id); - } - - let diff = now - current_end; - let passed_epochs = diff / self.epoch_duration; - let expected_current_epoch = self.current_absolute_epoch_id + passed_epochs.floor() as u32; - - self.key_rotation_state - .key_rotation_id(expected_current_epoch) - } - - pub fn until_next_rotation(&self) -> Option { - let current_epoch_progress = self.current_epoch_progress(OffsetDateTime::now_utc()); - if current_epoch_progress > 1. { - return None; - } - - let next_rotation_epoch = self.next_rotation_starting_epoch_id(); - let full_remaining = - (next_rotation_epoch - self.current_absolute_epoch_id).checked_add(1)?; - - let epochs_until_next_rotation = (1. - current_epoch_progress) + full_remaining as f32; - - Some(Duration::from_secs_f32( - epochs_until_next_rotation * self.epoch_duration.as_secs_f32(), - )) - } - - pub fn epoch_start_time(&self, absolute_epoch_id: EpochId) -> OffsetDateTime { - match absolute_epoch_id.cmp(&self.current_absolute_epoch_id) { - Ordering::Less => { - let diff = self.current_absolute_epoch_id - absolute_epoch_id; - self.current_epoch_start - diff * self.epoch_duration - } - Ordering::Equal => self.current_epoch_start, - Ordering::Greater => { - let diff = absolute_epoch_id - self.current_absolute_epoch_id; - self.current_epoch_start + diff * self.epoch_duration - } - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] -pub struct RewardedSetResponse { - #[serde(default)] - #[schema(value_type = u32)] - pub epoch_id: EpochId, - - pub entry_gateways: Vec, - - pub exit_gateways: Vec, - - pub layer1: Vec, - - pub layer2: Vec, - - pub layer3: Vec, - - pub standby: Vec, -} - -impl From for nym_mixnet_contract_common::EpochRewardedSet { - fn from(res: RewardedSetResponse) -> Self { - nym_mixnet_contract_common::EpochRewardedSet { - epoch_id: res.epoch_id, - assignment: nym_mixnet_contract_common::RewardedSet { - entry_gateways: res.entry_gateways, - exit_gateways: res.exit_gateways, - layer1: res.layer1, - layer2: res.layer2, - layer3: res.layer3, - standby: res.standby, - }, - } - } -} - -impl From for RewardedSetResponse { - fn from(r: nym_mixnet_contract_common::EpochRewardedSet) -> Self { - RewardedSetResponse { - epoch_id: r.epoch_id, - entry_gateways: r.assignment.entry_gateways, - exit_gateways: r.assignment.exit_gateways, - layer1: r.assignment.layer1, - layer2: r.assignment.layer2, - layer3: r.assignment.layer3, - standby: r.assignment.standby, - } - } -} - -#[derive(Clone, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct ChainStatusResponse { - pub connected_nyxd: String, - pub status: DetailedChainStatus, -} - -#[derive(Clone, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct DetailedChainStatus { - pub abci: crate::models::tendermint_types::AbciInfo, - pub latest_block: BlockInfo, -} - -#[derive(Clone, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct BlockInfo { - pub block_id: BlockId, - pub block: FullBlockInfo, - // if necessary we might put block data here later too -} - -impl From for BlockInfo { - fn from(value: tendermint_rpc::endpoint::block::Response) -> Self { - BlockInfo { - block_id: value.block_id.into(), - block: FullBlockInfo { - header: value.block.header.into(), - }, - } - } -} - -#[derive(Clone, Serialize, Deserialize, JsonSchema, ToSchema)] -pub struct FullBlockInfo { - pub header: BlockHeader, -} - -// copy tendermint types definitions whilst deriving schema types on them and dropping unwanted fields -pub mod tendermint_types { - use schemars::JsonSchema; - use serde::{Deserialize, Serialize}; - use tendermint::abci::response::Info; - use tendermint::block::header::Version; - use tendermint::{block, Hash}; - use utoipa::ToSchema; - - #[derive(Clone, Serialize, Deserialize, JsonSchema, ToSchema)] - pub struct AbciInfo { - /// Some arbitrary information. - pub data: String, - - /// The application software semantic version. - pub version: String, - - /// The application protocol version. - pub app_version: u64, - - /// The latest block for which the app has called [`Commit`]. - pub last_block_height: u64, - - /// The latest result of [`Commit`]. - pub last_block_app_hash: String, - } - - impl From for AbciInfo { - fn from(value: Info) -> Self { - AbciInfo { - data: value.data, - version: value.version, - app_version: value.app_version, - last_block_height: value.last_block_height.value(), - last_block_app_hash: value.last_block_app_hash.to_string(), - } - } - } - - /// `Version` contains the protocol version for the blockchain and the - /// application. - /// - /// - #[derive( - Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, ToSchema, - )] - pub struct HeaderVersion { - /// Block version - pub block: u64, - - /// App version - pub app: u64, - } - - impl From for HeaderVersion { - fn from(value: Version) -> Self { - HeaderVersion { - block: value.block, - app: value.app, - } - } - } - - /// Block identifiers which contain two distinct Merkle roots of the block, - /// as well as the number of parts in the block. - /// - /// - /// - /// Default implementation is an empty Id as defined by the Go implementation in - /// . - /// - /// If the Hash is empty in BlockId, the BlockId should be empty (encoded to None). - /// This is implemented outside of this struct. Use the Default trait to check for an empty BlockId. - /// See: - #[derive( - Serialize, - Deserialize, - Copy, - Clone, - Debug, - Default, - Hash, - Eq, - PartialEq, - PartialOrd, - Ord, - JsonSchema, - ToSchema, - )] - pub struct BlockId { - /// The block's main hash is the Merkle root of all the fields in the - /// block header. - #[schemars(with = "String")] - #[schema(value_type = String)] - pub hash: Hash, - - /// Parts header (if available) is used for secure gossipping of the block - /// during consensus. It is the Merkle root of the complete serialized block - /// cut into parts. - /// - /// PartSet is used to split a byteslice of data into parts (pieces) for - /// transmission. By splitting data into smaller parts and computing a - /// Merkle root hash on the list, you can verify that a part is - /// legitimately part of the complete data, and the part can be forwarded - /// to other peers before all the parts are known. In short, it's a fast - /// way to propagate a large file over a gossip network. - /// - /// - /// - /// PartSetHeader in protobuf is defined as never nil using the gogoproto - /// annotations. This does not translate to Rust, but we can indicate this - /// in the domain type. - pub part_set_header: PartSetHeader, - } - - impl From for BlockId { - fn from(value: block::Id) -> Self { - BlockId { - hash: value.hash, - part_set_header: value.part_set_header.into(), - } - } - } - - /// Block parts header - #[derive( - Clone, - Copy, - Debug, - Default, - Hash, - Eq, - PartialEq, - PartialOrd, - Ord, - Deserialize, - Serialize, - JsonSchema, - ToSchema, - )] - #[non_exhaustive] - pub struct PartSetHeader { - /// Number of parts in this block - pub total: u32, - - /// Hash of the parts set header, - #[schemars(with = "String")] - #[schema(value_type = String)] - pub hash: Hash, - } - - impl From for PartSetHeader { - fn from(value: block::parts::Header) -> Self { - PartSetHeader { - total: value.total, - hash: value.hash, - } - } - } - - /// Block `Header` values contain metadata about the block and about the - /// consensus, as well as commitments to the data in the current block, the - /// previous block, and the results returned by the application. - /// - /// - #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)] - pub struct BlockHeader { - /// Header version - pub version: HeaderVersion, - - /// Chain ID - pub chain_id: String, - - /// Current block height - pub height: u64, - - /// Current timestamp - #[schemars(with = "String")] - #[schema(value_type = String)] - pub time: tendermint::Time, - - /// Previous block info - pub last_block_id: Option, - - /// Commit from validators from the last block - #[schemars(with = "Option")] - #[schema(value_type = Option)] - pub last_commit_hash: Option, - - /// Merkle root of transaction hashes - #[schemars(with = "Option")] - #[schema(value_type = Option)] - pub data_hash: Option, - - /// Validators for the current block - #[schemars(with = "String")] - #[schema(value_type = String)] - pub validators_hash: Hash, - - /// Validators for the next block - #[schemars(with = "String")] - #[schema(value_type = String)] - pub next_validators_hash: Hash, - - /// Consensus params for the current block - #[schemars(with = "String")] - #[schema(value_type = String)] - pub consensus_hash: Hash, - - /// State after txs from the previous block - #[schemars(with = "String")] - #[schema(value_type = String)] - pub app_hash: Hash, - - /// Root hash of all results from the txs from the previous block - #[schemars(with = "Option")] - #[schema(value_type = Option)] - pub last_results_hash: Option, - - /// Hash of evidence included in the block - #[schemars(with = "Option")] - #[schema(value_type = Option)] - pub evidence_hash: Option, - - /// Original proposer of the block - #[serde(with = "nym_serde_helpers::hex")] - #[schemars(with = "String")] - #[schema(value_type = String)] - pub proposer_address: Vec, - } - - impl From for BlockHeader { - fn from(value: block::Header) -> Self { - BlockHeader { - version: value.version.into(), - chain_id: value.chain_id.to_string(), - height: value.height.value(), - time: value.time, - last_block_id: value.last_block_id.map(Into::into), - last_commit_hash: value.last_commit_hash, - data_hash: value.data_hash, - validators_hash: value.validators_hash, - next_validators_hash: value.next_validators_hash, - consensus_hash: value.consensus_hash, - app_hash: Hash::try_from(value.app_hash.as_bytes().to_vec()).unwrap_or_default(), - last_results_hash: value.last_results_hash, - evidence_hash: value.evidence_hash, - proposer_address: value.proposer_address.as_bytes().to_vec(), - } - } - } -} - -use crate::models::tendermint_types::{BlockHeader, BlockId}; -pub use config_score::*; - -pub mod config_score { - use nym_contracts_common::NaiveFloat; - use serde::{Deserialize, Serialize}; - use std::cmp::Ordering; - use utoipa::ToSchema; - - #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] - pub struct ConfigScoreDataResponse { - pub parameters: ConfigScoreParams, - pub version_history: Vec, - } - - #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema, PartialEq)] - pub struct HistoricalNymNodeVersionEntry { - /// The unique, ordered, id of this particular entry - pub id: u32, - - /// Data associated with this particular version - pub version_information: HistoricalNymNodeVersion, - } - - impl PartialOrd for HistoricalNymNodeVersionEntry { - fn partial_cmp(&self, other: &Self) -> Option { - // we only care about id for the purposes of ordering as they should have unique data - self.id.partial_cmp(&other.id) - } - } - - impl From - for HistoricalNymNodeVersionEntry - { - fn from(value: nym_mixnet_contract_common::HistoricalNymNodeVersionEntry) -> Self { - HistoricalNymNodeVersionEntry { - id: value.id, - version_information: value.version_information.into(), - } - } - } - - #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema, PartialEq)] - pub struct HistoricalNymNodeVersion { - /// Version of the nym node that is going to be used for determining the version score of a node. - /// note: value stored here is pre-validated `semver::Version` - pub semver: String, - - /// Block height of when this version has been added to the contract - pub introduced_at_height: u64, - // for now ignore that field. it will give nothing useful to the users - // pub difference_since_genesis: TotalVersionDifference, - } - - impl From for HistoricalNymNodeVersion { - fn from(value: nym_mixnet_contract_common::HistoricalNymNodeVersion) -> Self { - HistoricalNymNodeVersion { - semver: value.semver, - introduced_at_height: value.introduced_at_height, - } - } - } - - #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] - pub struct ConfigScoreParams { - /// Defines weights for calculating numbers of versions behind the current release. - pub version_weights: OutdatedVersionWeights, - - /// Defines the parameters of the formula for calculating the version score - pub version_score_formula_params: VersionScoreFormulaParams, - } - - /// Defines weights for calculating numbers of versions behind the current release. - #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] - pub struct OutdatedVersionWeights { - pub major: u32, - pub minor: u32, - pub patch: u32, - pub prerelease: u32, - } - - /// Given the formula of version_score = penalty ^ (versions_behind_factor ^ penalty_scaling) - /// define the relevant parameters - #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] - pub struct VersionScoreFormulaParams { - pub penalty: f64, - pub penalty_scaling: f64, - } - - impl From for ConfigScoreParams { - fn from(value: nym_mixnet_contract_common::ConfigScoreParams) -> Self { - ConfigScoreParams { - version_weights: value.version_weights.into(), - version_score_formula_params: value.version_score_formula_params.into(), - } - } - } - - impl From for OutdatedVersionWeights { - fn from(value: nym_mixnet_contract_common::OutdatedVersionWeights) -> Self { - OutdatedVersionWeights { - major: value.major, - minor: value.minor, - patch: value.patch, - prerelease: value.prerelease, - } - } - } - - impl From for VersionScoreFormulaParams { - fn from(value: nym_mixnet_contract_common::VersionScoreFormulaParams) -> Self { - VersionScoreFormulaParams { - penalty: value.penalty.naive_to_f64(), - penalty_scaling: value.penalty_scaling.naive_to_f64(), - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn offset_date_time_json_schema_wrapper_serde_backwards_compat() { - let mut dummy = OffsetDateTimeJsonSchemaWrapper::default(); - dummy.0 += Duration::from_millis(1); - let ser = serde_json::to_string(&dummy).unwrap(); - - assert_eq!("\"1970-01-01 00:00:00.001 +00:00:00\"", ser); - - let human_readable = "\"2024-05-23 07:41:02.756283766 +00:00:00\""; - let rfc3339 = "\"2002-10-02T15:00:00Z\""; - let rfc3339_offset = "\"2002-10-02T10:00:00-05:00\""; - - let de = serde_json::from_str::(human_readable).unwrap(); - assert_eq!(de.0.unix_timestamp(), 1716450062); - - let de = serde_json::from_str::(rfc3339).unwrap(); - assert_eq!(de.0.unix_timestamp(), 1033570800); - - let de = serde_json::from_str::(rfc3339_offset).unwrap(); - assert_eq!(de.0.unix_timestamp(), 1033570800); - - let de = serde_json::from_str::("\"nonsense\"").unwrap(); - assert_eq!(de.0.unix_timestamp(), 0); - } -} diff --git a/nym-api/nym-api-requests/src/models/api_status.rs b/nym-api/nym-api-requests/src/models/api_status.rs new file mode 100644 index 0000000000..c10b9e3bae --- /dev/null +++ b/nym-api/nym-api-requests/src/models/api_status.rs @@ -0,0 +1,68 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use serde::{Deserialize, Serialize}; +use std::time::Duration; +use utoipa::ToSchema; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct ApiHealthResponse { + pub status: ApiStatus, + #[serde(default)] + pub chain_status: ChainStatus, + pub uptime: u64, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +#[serde(rename_all = "lowercase")] +pub enum ApiStatus { + Up, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, Default, schemars::JsonSchema, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ChainStatus { + Synced, + #[default] + Unknown, + Stalled { + #[serde( + serialize_with = "humantime_serde::serialize", + deserialize_with = "humantime_serde::deserialize" + )] + approximate_amount: Duration, + }, +} + +impl ChainStatus { + pub fn is_synced(&self) -> bool { + matches!(self, ChainStatus::Synced) + } +} + +impl ApiHealthResponse { + pub fn new_healthy(uptime: Duration) -> Self { + ApiHealthResponse { + status: ApiStatus::Up, + chain_status: ChainStatus::Synced, + uptime: uptime.as_secs(), + } + } +} + +impl ApiStatus { + pub fn is_up(&self) -> bool { + matches!(self, ApiStatus::Up) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct SignerInformationResponse { + pub cosmos_address: String, + + pub identity: String, + + pub announce_address: String, + + pub verification_key: Option, +} diff --git a/nym-api/nym-api-requests/src/models/circulating_supply.rs b/nym-api/nym-api-requests/src/models/circulating_supply.rs new file mode 100644 index 0000000000..f191f0ccd2 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/circulating_supply.rs @@ -0,0 +1,19 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use super::CoinSchema; +use cosmwasm_std::Coin; +use serde::{Deserialize, Serialize}; +use utoipa::{ToResponse, ToSchema}; + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema, ToResponse)] +pub struct CirculatingSupplyResponse { + #[schema(value_type = CoinSchema)] + pub total_supply: Coin, + #[schema(value_type = CoinSchema)] + pub mixmining_reserve: Coin, + #[schema(value_type = CoinSchema)] + pub vesting_tokens: Coin, + #[schema(value_type = CoinSchema)] + pub circulating_supply: Coin, +} diff --git a/nym-api/nym-api-requests/src/models/described.rs b/nym-api/nym-api-requests/src/models/described.rs new file mode 100644 index 0000000000..666cca1996 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/described.rs @@ -0,0 +1,375 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::models::{BinaryBuildInformationOwned, OffsetDateTimeJsonSchemaWrapper}; +use crate::nym_nodes::{BasicEntryInformation, NodeRole, SemiSkimmedNode, SkimmedNode}; +use nym_crypto::asymmetric::ed25519::serde_helpers::bs58_ed25519_pubkey; +use nym_crypto::asymmetric::x25519::serde_helpers::bs58_x25519_pubkey; +use nym_crypto::asymmetric::{ed25519, x25519}; +use nym_mixnet_contract_common::reward_params::Performance; +use nym_mixnet_contract_common::NodeId; +use nym_network_defaults::{DEFAULT_MIX_LISTENING_PORT, DEFAULT_VERLOC_LISTENING_PORT}; +use nym_node_requests::api::v1::authenticator::models::Authenticator; +use nym_node_requests::api::v1::gateway::models::Wireguard; +use nym_node_requests::api::v1::ip_packet_router::models::IpPacketRouter; +use nym_node_requests::api::v1::node::models::{AuxiliaryDetails, NodeRoles}; +use nym_noise_keys::VersionedNoiseKey; +use serde::{Deserialize, Serialize}; +use std::net::IpAddr; +use tracing::warn; +use utoipa::ToSchema; + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct HostInformation { + #[schema(value_type = Vec)] + pub ip_address: Vec, + pub hostname: Option, + pub keys: HostKeys, +} + +impl From for HostInformation { + fn from(value: nym_node_requests::api::v1::node::models::HostInformation) -> Self { + HostInformation { + ip_address: value.ip_address, + hostname: value.hostname, + keys: value.keys.into(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct HostKeys { + #[serde(with = "bs58_ed25519_pubkey")] + #[schemars(with = "String")] + #[schema(value_type = String)] + pub ed25519: ed25519::PublicKey, + + #[deprecated(note = "use the current_x25519_sphinx_key with explicit rotation information")] + #[serde(with = "bs58_x25519_pubkey")] + #[schemars(with = "String")] + #[schema(value_type = String)] + pub x25519: x25519::PublicKey, + + pub current_x25519_sphinx_key: SphinxKey, + + #[serde(default)] + pub pre_announced_x25519_sphinx_key: Option, + + #[serde(default)] + pub x25519_versioned_noise: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct SphinxKey { + pub rotation_id: u32, + + #[serde(with = "bs58_x25519_pubkey")] + #[schemars(with = "String")] + #[schema(value_type = String)] + pub public_key: x25519::PublicKey, +} + +impl From for SphinxKey { + fn from(value: nym_node_requests::api::v1::node::models::SphinxKey) -> Self { + SphinxKey { + rotation_id: value.rotation_id, + public_key: value.public_key, + } + } +} + +impl From for HostKeys { + fn from(value: nym_node_requests::api::v1::node::models::HostKeys) -> Self { + HostKeys { + ed25519: value.ed25519_identity, + x25519: value.x25519_sphinx, + current_x25519_sphinx_key: value.primary_x25519_sphinx_key.into(), + pre_announced_x25519_sphinx_key: value.pre_announced_x25519_sphinx_key.map(Into::into), + x25519_versioned_noise: value.x25519_versioned_noise, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct WebSockets { + pub ws_port: u16, + + pub wss_port: Option, +} + +impl From for WebSockets { + fn from(value: nym_node_requests::api::v1::gateway::models::WebSockets) -> Self { + WebSockets { + ws_port: value.ws_port, + wss_port: value.wss_port, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct NoiseDetails { + pub key: VersionedNoiseKey, + + pub mixnet_port: u16, + + #[schema(value_type = Vec)] + pub ip_addresses: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct NymNodeDescription { + #[schema(value_type = u32)] + pub node_id: NodeId, + pub contract_node_type: DescribedNodeType, + pub description: NymNodeData, +} + +impl NymNodeDescription { + pub fn version(&self) -> &str { + &self.description.build_information.build_version + } + + pub fn entry_information(&self) -> BasicEntryInformation { + BasicEntryInformation { + hostname: self.description.host_information.hostname.clone(), + ws_port: self.description.mixnet_websockets.ws_port, + wss_port: self.description.mixnet_websockets.wss_port, + } + } + + pub fn ed25519_identity_key(&self) -> ed25519::PublicKey { + self.description.host_information.keys.ed25519 + } + + pub fn current_sphinx_key(&self, current_rotation_id: u32) -> x25519::PublicKey { + let keys = &self.description.host_information.keys; + + if keys.current_x25519_sphinx_key.rotation_id == u32::MAX { + // legacy case (i.e. node doesn't support rotation) + return keys.current_x25519_sphinx_key.public_key; + } + + if current_rotation_id == keys.current_x25519_sphinx_key.rotation_id { + // it's the 'current' key + return keys.current_x25519_sphinx_key.public_key; + } + + if let Some(pre_announced) = &keys.pre_announced_x25519_sphinx_key { + if pre_announced.rotation_id == current_rotation_id { + return pre_announced.public_key; + } + } + + warn!( + "unexpected key rotation {current_rotation_id} for node {}", + self.node_id + ); + // this should never be reached, but just in case, return the fallback option + keys.current_x25519_sphinx_key.public_key + } + + pub fn to_skimmed_node( + &self, + current_rotation_id: u32, + role: NodeRole, + performance: Performance, + ) -> SkimmedNode { + let keys = &self.description.host_information.keys; + let entry = if self.description.declared_role.entry { + Some(self.entry_information()) + } else { + None + }; + + SkimmedNode { + node_id: self.node_id, + ed25519_identity_pubkey: keys.ed25519, + ip_addresses: self.description.host_information.ip_address.clone(), + mix_port: self.description.mix_port(), + x25519_sphinx_pubkey: self.current_sphinx_key(current_rotation_id), + // we can't use the declared roles, we have to take whatever was provided in the contract. + // why? say this node COULD operate as an exit, but it might be the case the contract decided + // to assign it an ENTRY role only. we have to use that one instead. + role, + supported_roles: self.description.declared_role, + entry, + performance, + } + } + + pub fn to_semi_skimmed_node( + &self, + current_rotation_id: u32, + role: NodeRole, + performance: Performance, + ) -> SemiSkimmedNode { + let skimmed_node = self.to_skimmed_node(current_rotation_id, role, performance); + + SemiSkimmedNode { + basic: skimmed_node, + x25519_noise_versioned_key: self + .description + .host_information + .keys + .x25519_versioned_noise, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +#[serde(rename_all = "snake_case")] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/DescribedNodeType.ts" + ) +)] +pub enum DescribedNodeType { + LegacyMixnode, + LegacyGateway, + NymNode, +} + +impl DescribedNodeType { + pub fn is_nym_node(&self) -> bool { + matches!(self, DescribedNodeType::NymNode) + } +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/DeclaredRoles.ts" + ) +)] +pub struct DeclaredRoles { + pub mixnode: bool, + pub entry: bool, + pub exit_nr: bool, + pub exit_ipr: bool, +} + +impl DeclaredRoles { + pub fn can_operate_exit_gateway(&self) -> bool { + self.exit_ipr && self.exit_nr + } +} + +impl From for DeclaredRoles { + fn from(value: NodeRoles) -> Self { + DeclaredRoles { + mixnode: value.mixnode_enabled, + entry: value.gateway_enabled, + exit_nr: value.gateway_enabled && value.network_requester_enabled, + exit_ipr: value.gateway_enabled && value.ip_packet_router_enabled, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct NetworkRequesterDetails { + /// address of the embedded network requester + pub address: String, + + /// flag indicating whether this network requester uses the exit policy rather than the deprecated allow list + pub uses_exit_policy: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct IpPacketRouterDetails { + /// address of the embedded ip packet router + pub address: String, +} + +// works for current simple case. +impl From for IpPacketRouterDetails { + fn from(value: IpPacketRouter) -> Self { + IpPacketRouterDetails { + address: value.address, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct AuthenticatorDetails { + /// address of the embedded authenticator + pub address: String, +} + +// works for current simple case. +impl From for AuthenticatorDetails { + fn from(value: Authenticator) -> Self { + AuthenticatorDetails { + address: value.address, + } + } +} +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct WireguardDetails { + pub port: u16, + pub public_key: String, +} + +// works for current simple case. +impl From for WireguardDetails { + fn from(value: Wireguard) -> Self { + WireguardDetails { + port: value.port, + public_key: value.public_key, + } + } +} + +// this struct is getting quite bloated... +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct NymNodeData { + #[serde(default)] + pub last_polled: OffsetDateTimeJsonSchemaWrapper, + + pub host_information: HostInformation, + + #[serde(default)] + pub declared_role: DeclaredRoles, + + #[serde(default)] + pub auxiliary_details: AuxiliaryDetails, + + // TODO: do we really care about ALL build info or just the version? + pub build_information: BinaryBuildInformationOwned, + + #[serde(default)] + pub network_requester: Option, + + #[serde(default)] + pub ip_packet_router: Option, + + #[serde(default)] + pub authenticator: Option, + + #[serde(default)] + pub wireguard: Option, + + // for now we only care about their ws/wss situation, nothing more + pub mixnet_websockets: WebSockets, +} + +impl NymNodeData { + pub fn mix_port(&self) -> u16 { + self.auxiliary_details + .announce_ports + .mix_port + .unwrap_or(DEFAULT_MIX_LISTENING_PORT) + } + + pub fn verloc_port(&self) -> u16 { + self.auxiliary_details + .announce_ports + .verloc_port + .unwrap_or(DEFAULT_VERLOC_LISTENING_PORT) + } +} diff --git a/nym-api/nym-api-requests/src/models/legacy.rs b/nym-api/nym-api-requests/src/models/legacy.rs new file mode 100644 index 0000000000..c6cb6b2a78 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/legacy.rs @@ -0,0 +1,364 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use super::{CoinSchema, DeclaredRoles}; +use crate::legacy::{ + LegacyGatewayBondWithId, LegacyMixNodeBondWithLayer, LegacyMixNodeDetailsWithLayer, +}; +use crate::models::{NodePerformance, NymNodeData, StakeSaturation}; +use crate::nym_nodes::{BasicEntryInformation, NodeRole, SemiSkimmedNode, SkimmedNode}; +use cosmwasm_std::{Addr, Coin, Decimal}; +use nym_contracts_common::Percent; +use nym_mixnet_contract_common::reward_params::Performance; +use nym_mixnet_contract_common::rewarding::RewardEstimate; +use nym_mixnet_contract_common::{GatewayBond, Interval, MixNode, NodeId, RewardingParams}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::net::IpAddr; +use std::time::Duration; +use thiserror::Error; +use utoipa::{IntoParams, ToSchema}; + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct LegacyDescribedGateway { + pub bond: GatewayBond, + pub self_described: Option, +} + +impl From for LegacyDescribedGateway { + fn from(bond: LegacyGatewayBondWithId) -> Self { + LegacyDescribedGateway { + bond: bond.bond, + self_described: None, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct LegacyDescribedMixNode { + pub bond: LegacyMixNodeBondWithLayer, + pub self_described: Option, +} + +impl From for LegacyDescribedMixNode { + fn from(bond: LegacyMixNodeBondWithLayer) -> Self { + LegacyDescribedMixNode { + bond, + self_described: None, + } + } +} + +#[deprecated] +#[derive(Clone, Serialize, schemars::JsonSchema, ToSchema)] +pub struct InclusionProbability { + #[schema(value_type = u32)] + pub mix_id: NodeId, + pub in_active: f64, + pub in_reserve: f64, +} + +#[deprecated] +#[derive(Clone, Serialize, schemars::JsonSchema, ToSchema)] +pub struct AllInclusionProbabilitiesResponse { + pub inclusion_probabilities: Vec, + pub samples: u64, + pub elapsed: Duration, + pub delta_max: f64, + pub delta_l2: f64, + pub as_at: i64, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/SelectionChance.ts" + ) +)] +#[deprecated] +pub enum SelectionChance { + High, + Good, + Low, +} + +impl From for SelectionChance { + fn from(p: f64) -> SelectionChance { + match p { + p if p >= 0.7 => SelectionChance::High, + p if p >= 0.3 => SelectionChance::Good, + _ => SelectionChance::Low, + } + } +} + +impl From for SelectionChance { + fn from(p: Decimal) -> Self { + match p { + p if p >= Decimal::from_ratio(70u32, 100u32) => SelectionChance::High, + p if p >= Decimal::from_ratio(30u32, 100u32) => SelectionChance::Good, + _ => SelectionChance::Low, + } + } +} + +impl fmt::Display for SelectionChance { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SelectionChance::High => write!(f, "High"), + SelectionChance::Good => write!(f, "Good"), + SelectionChance::Low => write!(f, "Low"), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/InclusionProbabilityResponse.ts" + ) +)] +#[deprecated] +pub struct InclusionProbabilityResponse { + pub in_active: SelectionChance, + pub in_reserve: SelectionChance, +} + +impl fmt::Display for InclusionProbabilityResponse { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "in_active: {}, in_reserve: {}", + self.in_active, self.in_reserve + ) + } +} + +#[derive(Debug, Serialize, Deserialize, JsonSchema, ToSchema, IntoParams)] +pub struct ComputeRewardEstParam { + #[schema(value_type = Option)] + #[param(value_type = Option)] + pub performance: Option, + pub active_in_rewarded_set: Option, + pub pledge_amount: Option, + pub total_delegation: Option, + #[schema(value_type = Option)] + #[param(value_type = Option)] + pub interval_operating_cost: Option, + #[schema(value_type = Option)] + #[param(value_type = Option)] + pub profit_margin_percent: Option, +} + +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/RewardEstimationResponse.ts" + ) +)] +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct RewardEstimationResponse { + pub estimation: RewardEstimate, + pub reward_params: RewardingParams, + pub epoch: Interval, + #[cfg_attr(feature = "generate-ts", ts(type = "number"))] + pub as_at: i64, +} + +impl MixNodeBondAnnotated { + pub fn mix_node(&self) -> &MixNode { + &self.mixnode_details.bond_information.mix_node + } + + pub fn mix_id(&self) -> NodeId { + self.mixnode_details.mix_id() + } + + pub fn identity_key(&self) -> &str { + self.mixnode_details.bond_information.identity() + } + + pub fn owner(&self) -> &Addr { + self.mixnode_details.bond_information.owner() + } + + pub fn version(&self) -> &str { + &self.mixnode_details.bond_information.mix_node.version + } + + pub fn try_to_skimmed_node(&self, role: NodeRole) -> Result { + Ok(SkimmedNode { + node_id: self.mix_id(), + ed25519_identity_pubkey: self + .identity_key() + .parse() + .map_err(|_| MalformedNodeBond::InvalidEd25519Key)?, + ip_addresses: self.ip_addresses.clone(), + mix_port: self.mix_node().mix_port, + x25519_sphinx_pubkey: self + .mix_node() + .sphinx_key + .parse() + .map_err(|_| MalformedNodeBond::InvalidX25519Key)?, + role, + supported_roles: DeclaredRoles { + mixnode: true, + entry: false, + exit_nr: false, + exit_ipr: false, + }, + entry: None, + performance: self.node_performance.last_24h, + }) + } + + pub fn try_to_semi_skimmed_node( + &self, + role: NodeRole, + ) -> Result { + let skimmed_node = self.try_to_skimmed_node(role)?; + Ok(SemiSkimmedNode { + basic: skimmed_node, + x25519_noise_versioned_key: None, // legacy node won't ever support Noise + }) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct GatewayBondAnnotated { + pub gateway_bond: LegacyGatewayBondWithId, + + #[serde(default)] + pub self_described: Option, + + // NOTE: the performance field is deprecated in favour of node_performance + #[schema(value_type = String)] + pub performance: Performance, + pub node_performance: NodePerformance, + pub blacklisted: bool, + + #[serde(default)] + #[schema(value_type = Vec)] + pub ip_addresses: Vec, +} + +impl GatewayBondAnnotated { + pub fn version(&self) -> &str { + &self.gateway_bond.gateway.version + } + + pub fn identity(&self) -> &String { + self.gateway_bond.bond.identity() + } + + pub fn owner(&self) -> &Addr { + self.gateway_bond.bond.owner() + } + + pub fn try_to_skimmed_node(&self, role: NodeRole) -> Result { + Ok(SkimmedNode { + node_id: self.gateway_bond.node_id, + ip_addresses: self.ip_addresses.clone(), + ed25519_identity_pubkey: self + .gateway_bond + .gateway + .identity_key + .parse() + .map_err(|_| MalformedNodeBond::InvalidEd25519Key)?, + mix_port: self.gateway_bond.bond.gateway.mix_port, + x25519_sphinx_pubkey: self + .gateway_bond + .gateway + .sphinx_key + .parse() + .map_err(|_| MalformedNodeBond::InvalidX25519Key)?, + role, + supported_roles: DeclaredRoles { + mixnode: false, + entry: true, + exit_nr: false, + exit_ipr: false, + }, + entry: Some(BasicEntryInformation { + hostname: None, + ws_port: self.gateway_bond.bond.gateway.clients_port, + wss_port: None, + }), + performance: self.node_performance.last_24h, + }) + } + + pub fn try_to_semi_skimmed_node( + &self, + role: NodeRole, + ) -> Result { + let skimmed_node = self.try_to_skimmed_node(role)?; + Ok(SemiSkimmedNode { + basic: skimmed_node, + x25519_noise_versioned_key: None, // legacy node won't ever support Noise + }) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct GatewayDescription { + // for now only expose what we need. this struct will evolve in the future (or be incorporated into nym-node properly) +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[schema(title = "LegacyMixNodeDetailsWithLayer")] +pub struct LegacyMixNodeDetailsWithLayerSchema { + /// Basic bond information of this mixnode, such as owner address, original pledge, etc. + #[schema(example = "unimplemented schema")] + pub bond_information: String, + + /// Details used for computation of rewarding related data. + #[schema(example = "unimplemented schema")] + pub rewarding_details: String, + + /// Adjustments to the mixnode that are ought to happen during future epoch transitions. + #[schema(example = "unimplemented schema")] + pub pending_changes: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct MixNodeBondAnnotated { + #[schema(value_type = LegacyMixNodeDetailsWithLayerSchema)] + pub mixnode_details: LegacyMixNodeDetailsWithLayer, + #[schema(value_type = String)] + pub stake_saturation: StakeSaturation, + #[schema(value_type = String)] + pub uncapped_stake_saturation: StakeSaturation, + // NOTE: the performance field is deprecated in favour of node_performance + #[schema(value_type = String)] + pub performance: Performance, + pub node_performance: NodePerformance, + #[schema(value_type = String)] + pub estimated_operator_apy: Decimal, + #[schema(value_type = String)] + pub estimated_delegators_apy: Decimal, + pub blacklisted: bool, + + // a rather temporary thing until we query self-described endpoints of mixnodes + #[serde(default)] + #[schema(value_type = Vec)] + pub ip_addresses: Vec, +} + +#[derive(Debug, Error)] +pub enum MalformedNodeBond { + #[error("the associated ed25519 identity key is malformed")] + InvalidEd25519Key, + + #[error("the associated x25519 sphinx key is malformed")] + InvalidX25519Key, +} diff --git a/nym-api/nym-api-requests/src/models/mixnet.rs b/nym-api/nym-api-requests/src/models/mixnet.rs new file mode 100644 index 0000000000..42f8bf1a72 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/mixnet.rs @@ -0,0 +1,242 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use nym_mixnet_contract_common::nym_node::Role; +use nym_mixnet_contract_common::{EpochId, KeyRotationId, KeyRotationState, NodeId}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::cmp::Ordering; +use std::time::Duration; +use time::OffsetDateTime; +use tracing::warn; +use utoipa::ToSchema; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct KeyRotationInfoResponse { + #[serde(flatten)] + pub details: KeyRotationDetails, + + // helper field that holds calculated data based on the `details` field + // this is to expose the information in a format more easily accessible by humans + // without having to do any calculations + pub progress: KeyRotationProgressInfo, +} + +impl From for KeyRotationInfoResponse { + fn from(details: KeyRotationDetails) -> Self { + KeyRotationInfoResponse { + details, + progress: KeyRotationProgressInfo { + current_key_rotation_id: details.current_key_rotation_id(), + current_rotation_starting_epoch: details.current_rotation_starting_epoch_id(), + current_rotation_ending_epoch: details.current_rotation_starting_epoch_id() + + details.key_rotation_state.validity_epochs + - 1, + }, + } + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct KeyRotationProgressInfo { + pub current_key_rotation_id: u32, + + pub current_rotation_starting_epoch: u32, + + pub current_rotation_ending_epoch: u32, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct KeyRotationDetails { + pub key_rotation_state: KeyRotationState, + + #[schema(value_type = u32)] + pub current_absolute_epoch_id: EpochId, + + #[serde(with = "time::serde::rfc3339")] + #[schemars(with = "String")] + #[schema(value_type = String)] + pub current_epoch_start: OffsetDateTime, + + pub epoch_duration: Duration, +} + +impl KeyRotationDetails { + pub fn current_key_rotation_id(&self) -> u32 { + self.key_rotation_state + .key_rotation_id(self.current_absolute_epoch_id) + } + + pub fn next_rotation_starting_epoch_id(&self) -> EpochId { + self.key_rotation_state + .next_rotation_starting_epoch_id(self.current_absolute_epoch_id) + } + + pub fn current_rotation_starting_epoch_id(&self) -> EpochId { + self.key_rotation_state + .current_rotation_starting_epoch_id(self.current_absolute_epoch_id) + } + + fn current_epoch_progress(&self, now: OffsetDateTime) -> f32 { + let elapsed = (now - self.current_epoch_start).as_seconds_f32(); + elapsed / self.epoch_duration.as_secs_f32() + } + + pub fn is_epoch_stuck(&self) -> bool { + let now = OffsetDateTime::now_utc(); + let progress = self.current_epoch_progress(now); + if progress > 1. { + let into_next = 1. - progress; + // if epoch hasn't progressed for more than 20% of its duration, mark is as stuck + if into_next > 0.2 { + let diff_time = + Duration::from_secs_f32(into_next * self.epoch_duration.as_secs_f32()); + let expected_epoch_end = self.current_epoch_start + self.epoch_duration; + warn!("the current epoch is expected to have been over by {expected_epoch_end}. it's already {} overdue!", humantime_serde::re::humantime::format_duration(diff_time)); + return true; + } + } + + false + } + + // based on the current **TIME**, determine what's the expected current rotation id + pub fn expected_current_rotation_id(&self) -> KeyRotationId { + let now = OffsetDateTime::now_utc(); + let current_end = now + self.epoch_duration; + if now < current_end { + return self + .key_rotation_state + .key_rotation_id(self.current_absolute_epoch_id); + } + + let diff = now - current_end; + let passed_epochs = diff / self.epoch_duration; + let expected_current_epoch = self.current_absolute_epoch_id + passed_epochs.floor() as u32; + + self.key_rotation_state + .key_rotation_id(expected_current_epoch) + } + + pub fn until_next_rotation(&self) -> Option { + let current_epoch_progress = self.current_epoch_progress(OffsetDateTime::now_utc()); + if current_epoch_progress > 1. { + return None; + } + + let next_rotation_epoch = self.next_rotation_starting_epoch_id(); + let full_remaining = + (next_rotation_epoch - self.current_absolute_epoch_id).checked_add(1)?; + + let epochs_until_next_rotation = (1. - current_epoch_progress) + full_remaining as f32; + + Some(Duration::from_secs_f32( + epochs_until_next_rotation * self.epoch_duration.as_secs_f32(), + )) + } + + pub fn epoch_start_time(&self, absolute_epoch_id: EpochId) -> OffsetDateTime { + match absolute_epoch_id.cmp(&self.current_absolute_epoch_id) { + Ordering::Less => { + let diff = self.current_absolute_epoch_id - absolute_epoch_id; + self.current_epoch_start - diff * self.epoch_duration + } + Ordering::Equal => self.current_epoch_start, + Ordering::Greater => { + let diff = absolute_epoch_id - self.current_absolute_epoch_id; + self.current_epoch_start + diff * self.epoch_duration + } + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct RewardedSetResponse { + #[serde(default)] + #[schema(value_type = u32)] + pub epoch_id: EpochId, + + pub entry_gateways: Vec, + + pub exit_gateways: Vec, + + pub layer1: Vec, + + pub layer2: Vec, + + pub layer3: Vec, + + pub standby: Vec, +} + +impl From for nym_mixnet_contract_common::EpochRewardedSet { + fn from(res: RewardedSetResponse) -> Self { + nym_mixnet_contract_common::EpochRewardedSet { + epoch_id: res.epoch_id, + assignment: nym_mixnet_contract_common::RewardedSet { + entry_gateways: res.entry_gateways, + exit_gateways: res.exit_gateways, + layer1: res.layer1, + layer2: res.layer2, + layer3: res.layer3, + standby: res.standby, + }, + } + } +} + +impl From for RewardedSetResponse { + fn from(r: nym_mixnet_contract_common::EpochRewardedSet) -> Self { + RewardedSetResponse { + epoch_id: r.epoch_id, + entry_gateways: r.assignment.entry_gateways, + exit_gateways: r.assignment.exit_gateways, + layer1: r.assignment.layer1, + layer2: r.assignment.layer2, + layer3: r.assignment.layer3, + standby: r.assignment.standby, + } + } +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, JsonSchema, ToSchema)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts(export, export_to = "ts-packages/types/src/types/rust/DisplayRole.ts") +)] +pub enum DisplayRole { + EntryGateway, + Layer1, + Layer2, + Layer3, + ExitGateway, + Standby, +} + +impl From for DisplayRole { + fn from(role: Role) -> Self { + match role { + Role::EntryGateway => DisplayRole::EntryGateway, + Role::Layer1 => DisplayRole::Layer1, + Role::Layer2 => DisplayRole::Layer2, + Role::Layer3 => DisplayRole::Layer3, + Role::ExitGateway => DisplayRole::ExitGateway, + Role::Standby => DisplayRole::Standby, + } + } +} + +impl From for Role { + fn from(role: DisplayRole) -> Self { + match role { + DisplayRole::EntryGateway => Role::EntryGateway, + DisplayRole::Layer1 => Role::Layer1, + DisplayRole::Layer2 => Role::Layer2, + DisplayRole::Layer3 => Role::Layer3, + DisplayRole::ExitGateway => Role::ExitGateway, + DisplayRole::Standby => Role::Standby, + } + } +} diff --git a/nym-api/nym-api-requests/src/models/mod.rs b/nym-api/nym-api-requests/src/models/mod.rs new file mode 100644 index 0000000000..76074be659 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/mod.rs @@ -0,0 +1,62 @@ +// Copyright 2022-2024 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +#![allow(deprecated)] + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::fmt; +use std::fmt::{Display, Formatter}; + +pub mod api_status; +pub mod circulating_supply; +pub mod described; +pub mod legacy; +pub mod mixnet; +pub mod network; +pub mod network_monitor; +pub mod node_status; +pub mod schema_helpers; + +// don't break existing imports +pub use api_status::*; +pub use circulating_supply::*; +pub use described::*; +pub use legacy::*; +pub use mixnet::*; +pub use network::*; +pub use network_monitor::*; +pub use node_status::*; +pub use schema_helpers::*; + +pub use nym_mixnet_contract_common::{EpochId, KeyRotationId, KeyRotationState}; +pub use nym_node_requests::api::v1::node::models::BinaryBuildInformationOwned; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)] +pub struct RequestError { + message: String, +} + +impl RequestError { + pub fn new>(msg: S) -> Self { + RequestError { + message: msg.into(), + } + } + + pub fn message(&self) -> &str { + &self.message + } + + pub fn empty() -> Self { + Self { + message: String::new(), + } + } +} + +impl Display for RequestError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + Display::fmt(&self.message, f) + } +} diff --git a/nym-api/nym-api-requests/src/models/network.rs b/nym-api/nym-api-requests/src/models/network.rs new file mode 100644 index 0000000000..e998656c67 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/network.rs @@ -0,0 +1,562 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::ecash::models::EcashSignerStatusResponse; +use crate::models::tendermint_types::{BlockHeader, BlockId}; +use crate::models::{ChainStatus, SignerInformationResponse}; +use crate::signable::SignedMessage; +use nym_coconut_dkg_common::types::EpochId; +use nym_crypto::asymmetric::ed25519::PublicKey; +use nym_ecash_signer_check_types::helper_traits::{ + ChainResponse, LegacyChainResponse, LegacySignerResponse, SignerResponse, TimestampedResponse, + Verifiable, +}; +use nym_ecash_signer_check_types::status::SignerResult; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::time::Duration; +use time::OffsetDateTime; +use utoipa::ToSchema; + +pub type ChainBlocksStatusResponse = SignedMessage; +pub type SignersStatusResponse = SignedMessage; +pub type DetailedSignersStatusResponse = SignedMessage; + +#[derive(Serialize, Deserialize, ToSchema, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct SignersStatusResponseBody { + #[serde(with = "time::serde::rfc3339")] + #[schema(value_type = String)] + pub as_at: OffsetDateTime, + + pub overview: SignersStatusOverview, + + pub results: Vec, +} + +pub type TypedSignerResult = SignerResult< + SignerInformationResponse, + EcashSignerStatusResponse, + ChainStatusResponse, + ChainBlocksStatusResponse, +>; + +#[derive(Serialize, Deserialize, ToSchema, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct MinimalSignerResult { + pub announce_address: String, + pub owner_address: String, + pub node_index: u64, + pub public_key: String, + + pub local_chain_working: bool, + pub credential_issuance_available: bool, +} + +impl From<&TypedSignerResult> for MinimalSignerResult { + fn from(result: &TypedSignerResult) -> MinimalSignerResult { + MinimalSignerResult { + announce_address: result.information.announce_address.clone(), + owner_address: result.information.owner_address.clone(), + node_index: result.information.node_index, + public_key: result.information.public_key.clone(), + local_chain_working: result.chain_available(), + credential_issuance_available: result.signing_available(), + } + } +} + +#[derive(Serialize, Deserialize, ToSchema, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct DetailedSignersStatusResponseBody { + #[serde(with = "time::serde::rfc3339")] + #[schema(value_type = String)] + pub as_at: OffsetDateTime, + + pub overview: SignersStatusOverview, + + pub details: Vec, +} + +#[derive(Serialize, Deserialize, ToSchema, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct SignersStatusOverview { + #[schema(value_type = Option)] + pub epoch_id: Option, + + pub signing_threshold: Option, + pub threshold_available: Option, + + pub total_signers: usize, + pub unreachable_signers: usize, + pub malformed_signers: usize, + + // unreachable or outdated + pub unknown_local_chain_status: usize, + pub working_local_chain: usize, + + // i.e. provided signature + pub provably_stalled_local_chain: usize, + pub unprovably_stalled_local_chain: usize, + + // unreachable or outdated + pub unknown_credential_issuance_status: usize, + pub working_credential_issuance: usize, + + // i.e. provided signature + pub provably_unavailable_credential_issuance: usize, + pub unprovably_unavailable_credential_issuance: usize, +} + +impl SignersStatusOverview { + pub fn new(results: &[TypedSignerResult], signing_threshold: Option) -> Self { + let epoch_id = results.first().map(|r| r.dkg_epoch_id); + + let mut unreachable_signers = 0; + let mut malformed_signers = 0; + let mut unknown_local_chain_status = 0; + let mut working_local_chain = 0; + let mut provably_stalled_local_chain = 0; + let mut unprovably_stalled_local_chain = 0; + let mut unknown_credential_issuance_status = 0; + let mut working_credential_issuance = 0; + let mut provably_unavailable_credential_issuance = 0; + let mut unprovably_unavailable_credential_issuance = 0; + + for result in results { + if result.signer_unreachable() { + unreachable_signers += 1; + } + if result.malformed_details() { + malformed_signers += 1; + } + + if result.unknown_chain_status() { + unknown_local_chain_status += 1; + } + if result.chain_available() { + working_local_chain += 1; + } + if result.chain_provably_stalled() { + provably_stalled_local_chain += 1; + } + if result.chain_unprovably_stalled() { + unprovably_stalled_local_chain += 1; + } + + if result.unknown_signing_status() { + unknown_credential_issuance_status += 1; + } + if result.signing_available() { + working_credential_issuance += 1; + } + if result.signing_provably_unavailable() { + provably_unavailable_credential_issuance += 1; + } + if result.signing_unprovably_unavailable() { + unprovably_unavailable_credential_issuance += 1; + } + } + + SignersStatusOverview { + epoch_id, + signing_threshold, + threshold_available: signing_threshold.map(|threshold| { + (working_local_chain as u64) >= threshold + && (working_credential_issuance as u64) >= threshold + }), + total_signers: results.len(), + unreachable_signers, + malformed_signers, + unknown_local_chain_status, + working_local_chain, + provably_stalled_local_chain, + unprovably_stalled_local_chain, + unknown_credential_issuance_status, + working_credential_issuance, + provably_unavailable_credential_issuance, + unprovably_unavailable_credential_issuance, + } + } +} + +#[derive(Serialize, Deserialize, ToSchema, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ChainBlocksStatusResponseBody { + #[serde(with = "time::serde::rfc3339")] + #[schema(value_type = String)] + pub current_time: OffsetDateTime, + + pub latest_cached_block: Option, + + // explicit indication of THIS signer whether it thinks the chain is stalled + pub chain_status: ChainStatus, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct ChainStatusResponse { + pub connected_nyxd: String, + pub status: DetailedChainStatus, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct DetailedChainStatus { + pub abci: crate::models::tendermint_types::AbciInfo, + pub latest_block: BlockInfo, +} + +impl DetailedChainStatus { + pub fn stall_status(&self, now: OffsetDateTime, threshold: Duration) -> ChainStatus { + let block_time: OffsetDateTime = self.latest_block.block.header.time.into(); + let diff = now - block_time; + if diff > threshold { + ChainStatus::Stalled { + approximate_amount: diff.unsigned_abs(), + } + } else { + ChainStatus::Synced + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct BlockInfo { + pub block_id: BlockId, + pub block: FullBlockInfo, + // if necessary we might put block data here later too +} + +impl From for BlockInfo { + fn from(value: tendermint_rpc::endpoint::block::Response) -> Self { + BlockInfo { + block_id: value.block_id.into(), + block: FullBlockInfo { + header: value.block.header.into(), + }, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct FullBlockInfo { + pub header: BlockHeader, +} + +// copy tendermint types definitions whilst deriving schema types on them and dropping unwanted fields +pub mod tendermint_types { + use schemars::JsonSchema; + use serde::{Deserialize, Serialize}; + use tendermint::abci::response::Info; + use tendermint::block::header::Version; + use tendermint::{block, Hash}; + use utoipa::ToSchema; + + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] + pub struct AbciInfo { + /// Some arbitrary information. + pub data: String, + + /// The application software semantic version. + pub version: String, + + /// The application protocol version. + pub app_version: u64, + + /// The latest block for which the app has called [`Commit`]. + pub last_block_height: u64, + + /// The latest result of [`Commit`]. + pub last_block_app_hash: String, + } + + impl From for AbciInfo { + fn from(value: Info) -> Self { + AbciInfo { + data: value.data, + version: value.version, + app_version: value.app_version, + last_block_height: value.last_block_height.value(), + last_block_app_hash: value.last_block_app_hash.to_string(), + } + } + } + + /// `Version` contains the protocol version for the blockchain and the + /// application. + /// + /// + #[derive( + Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, ToSchema, + )] + pub struct HeaderVersion { + /// Block version + pub block: u64, + + /// App version + pub app: u64, + } + + impl From for HeaderVersion { + fn from(value: Version) -> Self { + HeaderVersion { + block: value.block, + app: value.app, + } + } + } + + /// Block identifiers which contain two distinct Merkle roots of the block, + /// as well as the number of parts in the block. + /// + /// + /// + /// Default implementation is an empty Id as defined by the Go implementation in + /// . + /// + /// If the Hash is empty in BlockId, the BlockId should be empty (encoded to None). + /// This is implemented outside of this struct. Use the Default trait to check for an empty BlockId. + /// See: + #[derive( + Serialize, + Deserialize, + Copy, + Clone, + Debug, + Default, + Hash, + Eq, + PartialEq, + PartialOrd, + Ord, + JsonSchema, + ToSchema, + )] + pub struct BlockId { + /// The block's main hash is the Merkle root of all the fields in the + /// block header. + #[schemars(with = "String")] + #[schema(value_type = String)] + pub hash: Hash, + + /// Parts header (if available) is used for secure gossipping of the block + /// during consensus. It is the Merkle root of the complete serialized block + /// cut into parts. + /// + /// PartSet is used to split a byteslice of data into parts (pieces) for + /// transmission. By splitting data into smaller parts and computing a + /// Merkle root hash on the list, you can verify that a part is + /// legitimately part of the complete data, and the part can be forwarded + /// to other peers before all the parts are known. In short, it's a fast + /// way to propagate a large file over a gossip network. + /// + /// + /// + /// PartSetHeader in protobuf is defined as never nil using the gogoproto + /// annotations. This does not translate to Rust, but we can indicate this + /// in the domain type. + pub part_set_header: PartSetHeader, + } + + impl From for BlockId { + fn from(value: block::Id) -> Self { + BlockId { + hash: value.hash, + part_set_header: value.part_set_header.into(), + } + } + } + + /// Block parts header + #[derive( + Clone, + Copy, + Debug, + Default, + Hash, + Eq, + PartialEq, + PartialOrd, + Ord, + Deserialize, + Serialize, + JsonSchema, + ToSchema, + )] + #[non_exhaustive] + pub struct PartSetHeader { + /// Number of parts in this block + pub total: u32, + + /// Hash of the parts set header, + #[schemars(with = "String")] + #[schema(value_type = String)] + pub hash: Hash, + } + + impl From for PartSetHeader { + fn from(value: block::parts::Header) -> Self { + PartSetHeader { + total: value.total, + hash: value.hash, + } + } + } + + /// Block `Header` values contain metadata about the block and about the + /// consensus, as well as commitments to the data in the current block, the + /// previous block, and the results returned by the application. + /// + /// + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)] + pub struct BlockHeader { + /// Header version + pub version: HeaderVersion, + + /// Chain ID + pub chain_id: String, + + /// Current block height + pub height: u64, + + /// Current timestamp + #[schemars(with = "String")] + #[schema(value_type = String)] + pub time: tendermint::Time, + + /// Previous block info + pub last_block_id: Option, + + /// Commit from validators from the last block + #[schemars(with = "Option")] + #[schema(value_type = Option)] + pub last_commit_hash: Option, + + /// Merkle root of transaction hashes + #[schemars(with = "Option")] + #[schema(value_type = Option)] + pub data_hash: Option, + + /// Validators for the current block + #[schemars(with = "String")] + #[schema(value_type = String)] + pub validators_hash: Hash, + + /// Validators for the next block + #[schemars(with = "String")] + #[schema(value_type = String)] + pub next_validators_hash: Hash, + + /// Consensus params for the current block + #[schemars(with = "String")] + #[schema(value_type = String)] + pub consensus_hash: Hash, + + /// State after txs from the previous block + #[schemars(with = "String")] + #[schema(value_type = String)] + pub app_hash: Hash, + + /// Root hash of all results from the txs from the previous block + #[schemars(with = "Option")] + #[schema(value_type = Option)] + pub last_results_hash: Option, + + /// Hash of evidence included in the block + #[schemars(with = "Option")] + #[schema(value_type = Option)] + pub evidence_hash: Option, + + /// Original proposer of the block + #[serde(with = "nym_serde_helpers::hex")] + #[schemars(with = "String")] + #[schema(value_type = String)] + pub proposer_address: Vec, + } + + impl From for BlockHeader { + fn from(value: block::Header) -> Self { + BlockHeader { + version: value.version.into(), + chain_id: value.chain_id.to_string(), + height: value.height.value(), + time: value.time, + last_block_id: value.last_block_id.map(Into::into), + last_commit_hash: value.last_commit_hash, + data_hash: value.data_hash, + validators_hash: value.validators_hash, + next_validators_hash: value.next_validators_hash, + consensus_hash: value.consensus_hash, + app_hash: Hash::try_from(value.app_hash.as_bytes().to_vec()).unwrap_or_default(), + last_results_hash: value.last_results_hash, + evidence_hash: value.evidence_hash, + proposer_address: value.proposer_address.as_bytes().to_vec(), + } + } + } +} + +// implement required traits for the signer responses + +impl LegacyChainResponse for ChainStatusResponse { + fn chain_synced(&self, now: OffsetDateTime, stall_threshold: Duration) -> bool { + self.status.stall_status(now, stall_threshold).is_synced() + } +} + +impl Verifiable for ChainBlocksStatusResponse { + fn verify_signature(&self, pub_key: &PublicKey) -> bool { + self.verify_signature(pub_key) + } +} + +impl TimestampedResponse for ChainBlocksStatusResponse { + fn timestamp(&self) -> OffsetDateTime { + self.body.current_time + } +} + +impl ChainResponse for ChainBlocksStatusResponse { + fn chain_synced(&self) -> bool { + self.body.chain_status.is_synced() + } +} + +impl LegacySignerResponse for SignerInformationResponse { + fn signer_identity(&self) -> &str { + &self.identity + } + + fn signer_verification_key(&self) -> &Option { + &self.verification_key + } +} + +impl Verifiable for EcashSignerStatusResponse { + fn verify_signature(&self, pub_key: &PublicKey) -> bool { + self.verify_signature(pub_key) + } +} + +impl TimestampedResponse for EcashSignerStatusResponse { + fn timestamp(&self) -> OffsetDateTime { + self.body.current_time + } +} + +impl SignerResponse for EcashSignerStatusResponse { + fn has_signing_keys(&self) -> bool { + self.body.has_signing_keys + } + + fn signer_disabled(&self) -> bool { + self.body.signer_disabled + } + + fn is_ecash_signer(&self) -> bool { + self.body.is_ecash_signer + } + + fn dkg_ecash_epoch_id(&self) -> EpochId { + self.body.dkg_ecash_epoch_id + } +} diff --git a/nym-api/nym-api-requests/src/models/network_monitor.rs b/nym-api/nym-api-requests/src/models/network_monitor.rs new file mode 100644 index 0000000000..c253bd28ca --- /dev/null +++ b/nym-api/nym-api-requests/src/models/network_monitor.rs @@ -0,0 +1,74 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::pagination::PaginatedResponse; +use nym_mixnet_contract_common::NodeId; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use utoipa::ToSchema; + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, Default, ToSchema)] +pub struct TestNode { + pub node_id: Option, + pub identity_key: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct TestRoute { + pub gateway: TestNode, + pub layer1: TestNode, + pub layer2: TestNode, + pub layer3: TestNode, +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct PartialTestResult { + pub monitor_run_id: i64, + pub timestamp: i64, + pub overall_reliability_for_all_routes_in_monitor_run: Option, + pub test_routes: TestRoute, +} + +pub type MixnodeTestResultResponse = PaginatedResponse; +pub type GatewayTestResultResponse = PaginatedResponse; + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct NetworkMonitorRunDetailsResponse { + pub monitor_run_id: i64, + pub network_reliability: f64, + pub total_sent: usize, + pub total_received: usize, + + // integer score to number of nodes with that score + pub mixnode_results: BTreeMap, + pub gateway_results: BTreeMap, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/MixnodeCoreStatusResponse.ts" + ) +)] +pub struct MixnodeCoreStatusResponse { + pub mix_id: NodeId, + pub count: i64, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/GatewayCoreStatusResponse.ts" + ) +)] +pub struct GatewayCoreStatusResponse { + pub identity: String, + pub count: i64, +} diff --git a/nym-api/nym-api-requests/src/models/node_status.rs b/nym-api/nym-api-requests/src/models/node_status.rs new file mode 100644 index 0000000000..03bd0ce2d8 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/node_status.rs @@ -0,0 +1,587 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::helpers::PlaceholderJsonSchemaImpl; +use crate::pagination::PaginatedResponse; +use cosmwasm_std::Decimal; +use nym_contracts_common::{IdentityKey, NaiveFloat}; +use nym_crypto::asymmetric::ed25519; +use nym_crypto::asymmetric::ed25519::serde_helpers::bs58_ed25519_pubkey; +use nym_mixnet_contract_common::reward_params::Performance; +use nym_mixnet_contract_common::NodeId; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::time::Duration; +use time::{Date, OffsetDateTime}; +use utoipa::ToSchema; + +use crate::models::DisplayRole; +pub use config_score::*; + +pub type StakeSaturation = Decimal; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/StakeSaturationResponse.ts" + ) +)] +pub struct StakeSaturationResponse { + #[cfg_attr(feature = "generate-ts", ts(type = "string"))] + #[schema(value_type = String)] + pub saturation: StakeSaturation, + + #[cfg_attr(feature = "generate-ts", ts(type = "string"))] + #[schema(value_type = String)] + pub uncapped_saturation: StakeSaturation, + pub as_at: i64, +} + +pub mod config_score { + use nym_contracts_common::NaiveFloat; + use serde::{Deserialize, Serialize}; + use std::cmp::Ordering; + use utoipa::ToSchema; + + #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] + pub struct ConfigScoreDataResponse { + pub parameters: ConfigScoreParams, + pub version_history: Vec, + } + + #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema, PartialEq)] + pub struct HistoricalNymNodeVersionEntry { + /// The unique, ordered, id of this particular entry + pub id: u32, + + /// Data associated with this particular version + pub version_information: HistoricalNymNodeVersion, + } + + impl PartialOrd for HistoricalNymNodeVersionEntry { + fn partial_cmp(&self, other: &Self) -> Option { + // we only care about id for the purposes of ordering as they should have unique data + self.id.partial_cmp(&other.id) + } + } + + impl From + for HistoricalNymNodeVersionEntry + { + fn from(value: nym_mixnet_contract_common::HistoricalNymNodeVersionEntry) -> Self { + HistoricalNymNodeVersionEntry { + id: value.id, + version_information: value.version_information.into(), + } + } + } + + #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema, PartialEq)] + pub struct HistoricalNymNodeVersion { + /// Version of the nym node that is going to be used for determining the version score of a node. + /// note: value stored here is pre-validated `semver::Version` + pub semver: String, + + /// Block height of when this version has been added to the contract + pub introduced_at_height: u64, + // for now ignore that field. it will give nothing useful to the users + // pub difference_since_genesis: TotalVersionDifference, + } + + impl From for HistoricalNymNodeVersion { + fn from(value: nym_mixnet_contract_common::HistoricalNymNodeVersion) -> Self { + HistoricalNymNodeVersion { + semver: value.semver, + introduced_at_height: value.introduced_at_height, + } + } + } + + #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] + pub struct ConfigScoreParams { + /// Defines weights for calculating numbers of versions behind the current release. + pub version_weights: OutdatedVersionWeights, + + /// Defines the parameters of the formula for calculating the version score + pub version_score_formula_params: VersionScoreFormulaParams, + } + + /// Defines weights for calculating numbers of versions behind the current release. + #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] + pub struct OutdatedVersionWeights { + pub major: u32, + pub minor: u32, + pub patch: u32, + pub prerelease: u32, + } + + /// Given the formula of version_score = penalty ^ (versions_behind_factor ^ penalty_scaling) + /// define the relevant parameters + #[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] + pub struct VersionScoreFormulaParams { + pub penalty: f64, + pub penalty_scaling: f64, + } + + impl From for ConfigScoreParams { + fn from(value: nym_mixnet_contract_common::ConfigScoreParams) -> Self { + ConfigScoreParams { + version_weights: value.version_weights.into(), + version_score_formula_params: value.version_score_formula_params.into(), + } + } + } + + impl From for OutdatedVersionWeights { + fn from(value: nym_mixnet_contract_common::OutdatedVersionWeights) -> Self { + OutdatedVersionWeights { + major: value.major, + minor: value.minor, + patch: value.patch, + prerelease: value.prerelease, + } + } + } + + impl From for VersionScoreFormulaParams { + fn from(value: nym_mixnet_contract_common::VersionScoreFormulaParams) -> Self { + VersionScoreFormulaParams { + penalty: value.penalty.naive_to_f64(), + penalty_scaling: value.penalty_scaling.naive_to_f64(), + } + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct NodeRefreshBody { + #[serde(with = "bs58_ed25519_pubkey")] + #[schemars(with = "String")] + #[schema(value_type = String)] + pub node_identity: ed25519::PublicKey, + + // a poor man's nonce + pub request_timestamp: i64, + + #[schemars(with = "PlaceholderJsonSchemaImpl")] + #[schema(value_type = String)] + pub signature: ed25519::Signature, +} + +impl NodeRefreshBody { + pub fn plaintext(node_identity: ed25519::PublicKey, request_timestamp: i64) -> Vec { + node_identity + .to_bytes() + .into_iter() + .chain(request_timestamp.to_be_bytes()) + .chain(b"describe-cache-refresh-request".iter().copied()) + .collect() + } + + pub fn new(private_key: &ed25519::PrivateKey) -> Self { + let node_identity = private_key.public_key(); + let request_timestamp = OffsetDateTime::now_utc().unix_timestamp(); + let signature = private_key.sign(Self::plaintext(node_identity, request_timestamp)); + NodeRefreshBody { + node_identity, + request_timestamp, + signature, + } + } + + pub fn verify_signature(&self) -> bool { + self.node_identity + .verify( + Self::plaintext(self.node_identity, self.request_timestamp), + &self.signature, + ) + .is_ok() + } + + pub fn is_stale(&self) -> bool { + let Ok(encoded) = OffsetDateTime::from_unix_timestamp(self.request_timestamp) else { + return true; + }; + let now = OffsetDateTime::now_utc(); + + if encoded > now { + return true; + } + + if (encoded + Duration::from_secs(30)) < now { + return true; + } + + false + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct UptimeResponse { + #[schema(value_type = u32)] + pub mix_id: NodeId, + // The same as node_performance.last_24h. Legacy + pub avg_uptime: u8, + pub node_performance: NodePerformance, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct GatewayUptimeResponse { + pub identity: String, + // The same as node_performance.last_24h. Legacy + pub avg_uptime: u8, + pub node_performance: NodePerformance, +} + +type Uptime = u8; + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct MixnodeStatusReportResponse { + pub mix_id: NodeId, + pub identity: IdentityKey, + pub owner: String, + #[schema(value_type = u8)] + pub most_recent: Uptime, + #[schema(value_type = u8)] + pub last_hour: Uptime, + #[schema(value_type = u8)] + pub last_day: Uptime, +} + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct GatewayStatusReportResponse { + pub identity: String, + pub owner: String, + #[schema(value_type = u8)] + pub most_recent: Uptime, + #[schema(value_type = u8)] + pub last_hour: Uptime, + #[schema(value_type = u8)] + pub last_day: Uptime, +} + +#[derive(Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/PerformanceHistoryResponse.ts" + ) +)] +pub struct PerformanceHistoryResponse { + #[schema(value_type = u32)] + pub node_id: NodeId, + pub history: PaginatedResponse, +} + +#[derive(Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/UptimeHistoryResponse.ts" + ) +)] +pub struct UptimeHistoryResponse { + #[schema(value_type = u32)] + pub node_id: NodeId, + pub history: PaginatedResponse, +} + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/HistoricalUptimeResponse.ts" + ) +)] +pub struct HistoricalUptimeResponse { + #[schema(value_type = String, example = "1970-01-01")] + #[schemars(with = "String")] + #[cfg_attr(feature = "generate-ts", ts(type = "string"))] + pub date: Date, + + pub uptime: Uptime, +} + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/HistoricalPerformanceResponse.ts" + ) +)] +pub struct HistoricalPerformanceResponse { + #[schema(value_type = String, example = "1970-01-01")] + #[schemars(with = "String")] + #[cfg_attr(feature = "generate-ts", ts(type = "string"))] + pub date: Date, + + pub performance: f64, +} + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct OldHistoricalUptimeResponse { + pub date: String, + #[schema(value_type = u8)] + pub uptime: Uptime, +} + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct MixnodeUptimeHistoryResponse { + pub mix_id: NodeId, + pub identity: String, + pub owner: String, + pub history: Vec, +} + +#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema, ToSchema)] +pub struct GatewayUptimeHistoryResponse { + pub identity: String, + pub owner: String, + pub history: Vec, +} + +#[derive( + Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema, ToSchema, Default, +)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/MixnodeStatus.ts" + ) +)] +#[serde(rename_all = "snake_case")] +pub enum MixnodeStatus { + Active, // in both the active set and the rewarded set + Standby, // only in the rewarded set + Inactive, // in neither the rewarded set nor the active set, but is bonded + #[default] + NotFound, // doesn't even exist in the bonded set +} +impl MixnodeStatus { + pub fn is_active(&self) -> bool { + *self == MixnodeStatus::Active + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/MixnodeStatusResponse.ts" + ) +)] +pub struct MixnodeStatusResponse { + pub status: MixnodeStatus, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] +pub struct NodePerformance { + #[schema(value_type = String)] + pub most_recent: Performance, + #[schema(value_type = String)] + pub last_hour: Performance, + #[schema(value_type = String)] + pub last_24h: Performance, +} + +// imo for now there's no point in exposing more than that, +// nym-api shouldn't be calculating apy or stake saturation for you. +// it should just return its own metrics (performance) and then you can do with it as you wish +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/NodeAnnotation.ts" + ) +)] +pub struct NodeAnnotation { + #[cfg_attr(feature = "generate-ts", ts(type = "string"))] + // legacy + #[schema(value_type = String)] + pub last_24h_performance: Performance, + pub current_role: Option, + + pub detailed_performance: DetailedNodePerformance, +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/DetailedNodePerformance.ts" + ) +)] +#[non_exhaustive] +pub struct DetailedNodePerformance { + /// routing_score * config_score + pub performance_score: f64, + + pub routing_score: RoutingScore, + pub config_score: ConfigScore, +} + +impl DetailedNodePerformance { + pub fn new( + performance_score: f64, + routing_score: RoutingScore, + config_score: ConfigScore, + ) -> DetailedNodePerformance { + Self { + performance_score, + routing_score, + config_score, + } + } + + pub fn to_rewarding_performance(&self) -> Performance { + Performance::naive_try_from_f64(self.performance_score).unwrap_or_default() + } +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts(export, export_to = "ts-packages/types/src/types/rust/RoutingScore.ts") +)] +#[non_exhaustive] +pub struct RoutingScore { + /// Total score after taking all the criteria into consideration + pub score: f64, +} + +impl RoutingScore { + pub fn new(score: f64) -> RoutingScore { + Self { score } + } + + pub const fn zero() -> RoutingScore { + RoutingScore { score: 0.0 } + } + + pub fn legacy_performance(&self) -> Performance { + Performance::naive_try_from_f64(self.score).unwrap_or_default() + } +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts(export, export_to = "ts-packages/types/src/types/rust/ConfigScore.ts") +)] +#[non_exhaustive] +pub struct ConfigScore { + /// Total score after taking all the criteria into consideration + pub score: f64, + + pub versions_behind: Option, + pub self_described_api_available: bool, + pub accepted_terms_and_conditions: bool, + pub runs_nym_node_binary: bool, +} + +impl ConfigScore { + pub fn new( + score: f64, + versions_behind: u32, + accepted_terms_and_conditions: bool, + runs_nym_node_binary: bool, + ) -> ConfigScore { + Self { + score, + versions_behind: Some(versions_behind), + self_described_api_available: true, + accepted_terms_and_conditions, + runs_nym_node_binary, + } + } + + pub fn bad_semver() -> ConfigScore { + ConfigScore { + score: 0.0, + versions_behind: None, + self_described_api_available: true, + accepted_terms_and_conditions: false, + runs_nym_node_binary: false, + } + } + + pub fn unavailable() -> ConfigScore { + ConfigScore { + score: 0.0, + versions_behind: None, + self_described_api_available: false, + accepted_terms_and_conditions: false, + runs_nym_node_binary: false, + } + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/AnnotationResponse.ts" + ) +)] +pub struct AnnotationResponse { + #[schema(value_type = u32)] + pub node_id: NodeId, + pub annotation: Option, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/NodePerformanceResponse.ts" + ) +)] +pub struct NodePerformanceResponse { + #[schema(value_type = u32)] + pub node_id: NodeId, + pub performance: Option, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)] +#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))] +#[cfg_attr( + feature = "generate-ts", + ts( + export, + export_to = "ts-packages/types/src/types/rust/NodeDatePerformanceResponse.ts" + ) +)] +pub struct NodeDatePerformanceResponse { + #[schema(value_type = u32)] + pub node_id: NodeId, + #[schema(value_type = String, example = "1970-01-01")] + #[schemars(with = "String")] + #[cfg_attr(feature = "generate-ts", ts(type = "string"))] + pub date: Date, + pub performance: Option, +} diff --git a/nym-api/nym-api-requests/src/models/schema_helpers.rs b/nym-api/nym-api-requests/src/models/schema_helpers.rs new file mode 100644 index 0000000000..d42c18fc44 --- /dev/null +++ b/nym-api/nym-api-requests/src/models/schema_helpers.rs @@ -0,0 +1,128 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use crate::helpers::unix_epoch; +use cosmwasm_std::Uint128; +use schemars::schema::{InstanceType, Schema, SchemaObject}; +use schemars::{JsonSchema, SchemaGenerator}; +use serde::{Deserialize, Deserializer, Serialize}; +use std::fmt; +use std::fmt::{Display, Formatter}; +use std::ops::{Deref, DerefMut}; +use time::OffsetDateTime; +use utoipa::ToSchema; + +#[derive(ToSchema)] +#[schema(title = "Coin")] +pub struct CoinSchema { + pub denom: String, + #[schema(value_type = String)] + pub amount: Uint128, +} + +pub fn de_rfc3339_or_default<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + Ok(time::serde::rfc3339::deserialize(deserializer).unwrap_or_else(|_| unix_epoch())) +} + +// for all intents and purposes it's just OffsetDateTime, but we need JsonSchema... +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, ToSchema)] +pub struct OffsetDateTimeJsonSchemaWrapper( + #[serde( + default = "unix_epoch", + with = "crate::helpers::overengineered_offset_date_time_serde" + )] + #[schema(inline)] + pub OffsetDateTime, +); + +impl Default for OffsetDateTimeJsonSchemaWrapper { + fn default() -> Self { + OffsetDateTimeJsonSchemaWrapper(unix_epoch()) + } +} + +impl Display for OffsetDateTimeJsonSchemaWrapper { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + Display::fmt(&self.0, f) + } +} + +impl From for OffsetDateTime { + fn from(value: OffsetDateTimeJsonSchemaWrapper) -> Self { + value.0 + } +} + +impl From for OffsetDateTimeJsonSchemaWrapper { + fn from(value: OffsetDateTime) -> Self { + OffsetDateTimeJsonSchemaWrapper(value) + } +} + +impl Deref for OffsetDateTimeJsonSchemaWrapper { + type Target = OffsetDateTime; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for OffsetDateTimeJsonSchemaWrapper { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +// implementation taken from: https://github.com/GREsau/schemars/pull/207 +impl JsonSchema for OffsetDateTimeJsonSchemaWrapper { + fn is_referenceable() -> bool { + false + } + + fn schema_name() -> String { + "DateTime".into() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + SchemaObject { + instance_type: Some(InstanceType::String.into()), + format: Some("date-time".into()), + ..Default::default() + } + .into() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn offset_date_time_json_schema_wrapper_serde_backwards_compat() { + let mut dummy = OffsetDateTimeJsonSchemaWrapper::default(); + dummy.0 += Duration::from_millis(1); + let ser = serde_json::to_string(&dummy).unwrap(); + + assert_eq!("\"1970-01-01 00:00:00.001 +00:00:00\"", ser); + + let human_readable = "\"2024-05-23 07:41:02.756283766 +00:00:00\""; + let rfc3339 = "\"2002-10-02T15:00:00Z\""; + let rfc3339_offset = "\"2002-10-02T10:00:00-05:00\""; + + let de = serde_json::from_str::(human_readable).unwrap(); + assert_eq!(de.0.unix_timestamp(), 1716450062); + + let de = serde_json::from_str::(rfc3339).unwrap(); + assert_eq!(de.0.unix_timestamp(), 1033570800); + + let de = serde_json::from_str::(rfc3339_offset).unwrap(); + assert_eq!(de.0.unix_timestamp(), 1033570800); + + let de = serde_json::from_str::("\"nonsense\"").unwrap(); + assert_eq!(de.0.unix_timestamp(), 0); + } +} diff --git a/nym-api/nym-api-requests/src/signable.rs b/nym-api/nym-api-requests/src/signable.rs new file mode 100644 index 0000000000..5b1bb90584 --- /dev/null +++ b/nym-api/nym-api-requests/src/signable.rs @@ -0,0 +1,75 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: Apache-2.0 + +use nym_crypto::asymmetric::ed25519; +use nym_crypto::asymmetric::ed25519::serde_helpers::bs58_ed25519_signature; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +// the trait is not public as it's only defined on types that are guaranteed to not panic when serialised +pub trait SignableMessageBody: Serialize + sealed::Sealed { + fn sign(self, key: &ed25519::PrivateKey) -> SignedMessage + where + Self: Sized, + { + let signature = key.sign(self.plaintext()); + SignedMessage { + body: self, + signature, + } + } + + fn plaintext(&self) -> Vec { + #[allow(clippy::unwrap_used)] + // SAFETY: all types that implement this trait have valid serialisations + serde_json::to_vec(&self).unwrap() + } +} + +impl SignableMessageBody for T where T: Serialize + sealed::Sealed {} + +#[derive(Clone, Serialize, Deserialize, Debug, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SignedMessage { + pub body: T, + #[schema(value_type = String)] + #[serde(with = "bs58_ed25519_signature")] + pub signature: ed25519::Signature, +} + +impl SignedMessage { + pub fn verify_signature(&self, pub_key: &ed25519::PublicKey) -> bool + where + T: SignableMessageBody, + { + let plaintext = self.body.plaintext(); + if plaintext.is_empty() { + return false; + } + + pub_key.verify(&plaintext, &self.signature).is_ok() + } +} + +// make sure only our types can implement this trait (to ensure infallible serialisation) +pub(crate) mod sealed { + use crate::ecash::models::*; + use crate::models::{ + ChainBlocksStatusResponseBody, DetailedSignersStatusResponseBody, SignersStatusResponseBody, + }; + + pub trait Sealed {} + + // requests + impl Sealed for IssuedTicketbooksChallengeCommitmentRequestBody {} + impl Sealed for IssuedTicketbooksDataRequestBody {} + + // responses + impl Sealed for IssuedTicketbooksChallengeCommitmentResponseBody {} + impl Sealed for IssuedTicketbooksForResponseBody {} + impl Sealed for IssuedTicketbooksDataResponseBody {} + impl Sealed for EcashSignerStatusResponseBody {} + impl Sealed for ChainBlocksStatusResponseBody {} + impl Sealed for SignersStatusResponseBody {} + impl Sealed for DetailedSignersStatusResponseBody {} +} diff --git a/nym-api/src/ecash/api_routes/handlers.rs b/nym-api/src/ecash/api_routes/handlers.rs index 9114ebba9f..5b7edfefbe 100644 --- a/nym-api/src/ecash/api_routes/handlers.rs +++ b/nym-api/src/ecash/api_routes/handlers.rs @@ -4,8 +4,10 @@ use crate::ecash::api_routes::aggregation::aggregation_routes; use crate::ecash::api_routes::issued::issued_routes; use crate::ecash::api_routes::partial_signing::partial_signing_routes; +use crate::ecash::api_routes::signer_status::signer_status; use crate::ecash::api_routes::spending::spending_routes; use crate::support::http::state::AppState; +use axum::routing::get; use axum::Router; pub(crate) fn ecash_routes() -> Router { @@ -14,4 +16,5 @@ pub(crate) fn ecash_routes() -> Router { .merge(issued_routes()) .merge(partial_signing_routes()) .merge(spending_routes()) + .route("/signer-status", get(signer_status)) } diff --git a/nym-api/src/ecash/api_routes/issued.rs b/nym-api/src/ecash/api_routes/issued.rs index fd63ccdfe1..914b087b97 100644 --- a/nym-api/src/ecash/api_routes/issued.rs +++ b/nym-api/src/ecash/api_routes/issued.rs @@ -11,8 +11,9 @@ use nym_api_requests::ecash::models::{ IssuedTicketbooksChallengeCommitmentRequest, IssuedTicketbooksChallengeCommitmentResponse, IssuedTicketbooksCountResponse, IssuedTicketbooksDataRequest, IssuedTicketbooksDataResponse, IssuedTicketbooksForCountResponse, IssuedTicketbooksForResponse, - IssuedTicketbooksOnCountResponse, SignableMessageBody, + IssuedTicketbooksOnCountResponse, }; +use nym_api_requests::signable::SignableMessageBody; use nym_http_api_common::{FormattedResponse, OutputParams}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; diff --git a/nym-api/src/ecash/api_routes/mod.rs b/nym-api/src/ecash/api_routes/mod.rs index 18bdf01d4e..2588905654 100644 --- a/nym-api/src/ecash/api_routes/mod.rs +++ b/nym-api/src/ecash/api_routes/mod.rs @@ -6,4 +6,5 @@ pub(crate) mod handlers; mod helpers; pub(crate) mod issued; pub(crate) mod partial_signing; +pub(crate) mod signer_status; pub(crate) mod spending; diff --git a/nym-api/src/ecash/api_routes/signer_status.rs b/nym-api/src/ecash/api_routes/signer_status.rs new file mode 100644 index 0000000000..739482cd35 --- /dev/null +++ b/nym-api/src/ecash/api_routes/signer_status.rs @@ -0,0 +1,45 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use crate::ecash::state::EcashState; +use crate::node_status_api::models::ApiResult; +use axum::extract::{Query, State}; +use nym_api_requests::ecash::models::{EcashSignerStatusResponse, EcashSignerStatusResponseBody}; +use nym_api_requests::signable::SignableMessageBody; +use nym_http_api_common::{FormattedResponse, OutputParams}; +use std::sync::Arc; +use time::OffsetDateTime; + +#[utoipa::path( + tag = "Ecash", + get, + path = "/signer-status", + context_path = "/v1/ecash", + responses( + (status = 200, content( + (EcashSignerStatusResponse = "application/json"), + (EcashSignerStatusResponse = "application/yaml"), + (EcashSignerStatusResponse = "application/bincode") + )), + ), + params(OutputParams) +)] +pub(crate) async fn signer_status( + Query(params): Query, + State(state): State>, +) -> ApiResult> { + let output = params.get_output(); + + let dkg_ecash_epoch_id = state.current_dkg_epoch().await?; + + Ok(output.to_response( + EcashSignerStatusResponseBody { + current_time: OffsetDateTime::now_utc(), + dkg_ecash_epoch_id, + signer_disabled: state.local.explicitly_disabled, + is_ecash_signer: state.is_dkg_signer(dkg_ecash_epoch_id).await?, + has_signing_keys: state.ecash_signing_key().await.is_ok(), + } + .sign(state.local.identity_keypair.private_key()), + )) +} diff --git a/nym-api/src/ecash/state/mod.rs b/nym-api/src/ecash/state/mod.rs index d9ac0e5dce..644a4b32fa 100644 --- a/nym-api/src/ecash/state/mod.rs +++ b/nym-api/src/ecash/state/mod.rs @@ -50,7 +50,6 @@ use nym_validator_client::nyxd::AccountId; use nym_validator_client::EcashApiClient; use rand::{thread_rng, RngCore}; use std::collections::HashMap; -use std::ops::Deref; use time::{Date, OffsetDateTime}; use tokio::sync::{RwLockReadGuard, RwLockWriteGuard}; use tokio::task::JoinHandle; @@ -162,14 +161,11 @@ impl EcashState { } } - /// Ensures that this nym-api is one of ecash signers for the current epoch - pub(crate) async fn ensure_signer(&self) -> Result<()> { - if self.local.explicitly_disabled { - return Err(EcashError::NotASigner); - } - - let epoch_id = self.aux.current_epoch().await?; + pub(crate) async fn current_dkg_epoch(&self) -> Result { + self.aux.current_epoch().await + } + pub(crate) async fn is_dkg_signer(&self, epoch_id: EpochId) -> Result { let is_epoch_signer = self .local .active_signer @@ -183,8 +179,19 @@ impl EcashState { Ok(ecash_signers.iter().any(|c| c.cosmos_address == address)) }) .await?; + Ok(*is_epoch_signer) + } - if !is_epoch_signer.deref() { + /// Ensures that this nym-api is one of ecash signers for the current epoch + pub(crate) async fn ensure_signer(&self) -> Result<()> { + if self.local.explicitly_disabled { + return Err(EcashError::NotASigner); + } + + let epoch_id = self.current_dkg_epoch().await?; + let is_epoch_signer = self.is_dkg_signer(epoch_id).await?; + + if !is_epoch_signer { return Err(EcashError::NotASigner); } diff --git a/nym-api/src/ecash/tests/mod.rs b/nym-api/src/ecash/tests/mod.rs index faa142c2ea..2152ae7274 100644 --- a/nym-api/src/ecash/tests/mod.rs +++ b/nym-api/src/ecash/tests/mod.rs @@ -32,9 +32,10 @@ use cw3::{Proposal, ProposalResponse, Vote, VoteInfo, VoteResponse, Votes}; use cw4::{Cw4Contract, MemberResponse}; use nym_api_requests::ecash::models::{ IssuedTicketbooksChallengeCommitmentRequestBody, IssuedTicketbooksChallengeCommitmentResponse, - IssuedTicketbooksForResponse, SignableMessageBody, + IssuedTicketbooksForResponse, }; use nym_api_requests::ecash::{BlindSignRequestBody, BlindedSignatureResponse}; +use nym_api_requests::signable::SignableMessageBody; use nym_coconut_dkg_common::dealer::{ DealerDetails, DealerDetailsResponse, DealerType, RegisteredDealerDetails, }; @@ -1277,6 +1278,7 @@ impl TestFixture { AppState { nyxd_client, chain_status_cache: ChainStatusCache::new(Duration::from_secs(42)), + ecash_signers_cache: Default::default(), address_info_cache: AddressInfoCache::new(Duration::from_secs(42), 1000), forced_refresh: ForcedRefresh::new(true), mixnet_contract_cache: MixnetContractCache::new(), diff --git a/nym-api/src/main.rs b/nym-api/src/main.rs index c07a6c2e8f..a36027bd3c 100644 --- a/nym-api/src/main.rs +++ b/nym-api/src/main.rs @@ -8,7 +8,6 @@ use ::nym_config::defaults::setup_env; use clap::Parser; use mixnet_contract_cache::cache::MixnetContractCache; use node_status_api::NodeStatusCache; -use nym_bin_common::logging::setup_tracing_logger; use support::nyxd; use tracing::{info, trace}; @@ -23,6 +22,7 @@ pub(crate) mod node_describe_cache; mod node_performance; pub(crate) mod node_status_api; pub(crate) mod nym_nodes; +mod signers_cache; mod status; pub(crate) mod support; mod unstable_routes; @@ -32,10 +32,10 @@ async fn main() -> Result<(), anyhow::Error> { cfg_if::cfg_if! {if #[cfg(feature = "console-subscriber")] { // instrument tokio console subscriber needs RUSTFLAGS="--cfg tokio_unstable" at build time console_subscriber::init(); + } else { + nym_bin_common::logging::setup_tracing_logger(); }} - setup_tracing_logger(); - info!("Starting nym api..."); let args = cli::Cli::parse(); diff --git a/nym-api/src/network/handlers.rs b/nym-api/src/network/handlers.rs index 4d6c8e01f7..ef9396beff 100644 --- a/nym-api/src/network/handlers.rs +++ b/nym-api/src/network/handlers.rs @@ -3,13 +3,19 @@ use crate::network::models::{ContractInformation, NetworkDetails}; use crate::node_status_api::models::AxumResult; +use crate::signers_cache::handlers::signers_routes; +use crate::support::config::CHAIN_STALL_THRESHOLD; use crate::support::http::state::AppState; use axum::extract::{Query, State}; use axum::Router; -use nym_api_requests::models::ChainStatusResponse; +use nym_api_requests::models::{ + ChainBlocksStatusResponse, ChainBlocksStatusResponseBody, ChainStatus, ChainStatusResponse, +}; +use nym_api_requests::signable::SignableMessageBody; use nym_contracts_common::ContractBuildInformation; use nym_http_api_common::{FormattedResponse, OutputParams}; use std::collections::HashMap; +use time::OffsetDateTime; use tower_http::compression::CompressionLayer; use utoipa::ToSchema; @@ -17,18 +23,24 @@ pub(crate) fn nym_network_routes() -> Router { Router::new() .route("/details", axum::routing::get(network_details)) .route("/chain-status", axum::routing::get(chain_status)) + .route( + "/chain-blocks-status", + axum::routing::get(chain_blocks_status), + ) .route("/nym-contracts", axum::routing::get(nym_contracts)) .route( "/nym-contracts-detailed", axum::routing::get(nym_contracts_detailed), ) + .nest("/signers", signers_routes()) .layer(CompressionLayer::new()) } #[utoipa::path( tag = "network", get, - path = "/v1/network/details", + context_path = "/v1/network", + path = "/details", responses( (status = 200, content( (NetworkDetails = "application/json"), @@ -50,7 +62,8 @@ async fn network_details( #[utoipa::path( tag = "network", get, - path = "/v1/network/chain-status", + context_path = "/v1/network", + path = "/chain-status", responses( (status = 200, content( (ChainStatusResponse = "application/json"), @@ -79,6 +92,47 @@ async fn chain_status( })) } +#[utoipa::path( + tag = "network", + get, + context_path = "/v1/network", + path = "/chain-blocks-status", + responses( + (status = 200, content( + (ChainBlocksStatusResponse = "application/json"), + (ChainBlocksStatusResponse = "application/yaml"), + (ChainBlocksStatusResponse = "application/bincode") + )) + ), + params(OutputParams) +)] +async fn chain_blocks_status( + Query(params): Query, + State(state): State, +) -> FormattedResponse { + let output = params.get_output(); + + let current_time = OffsetDateTime::now_utc(); + let latest_cached_block = state + .chain_status_cache + .get_or_refresh(&state.nyxd_client) + .await + .ok(); + let chain_status = latest_cached_block + .as_ref() + .map(|detailed| detailed.stall_status(current_time, CHAIN_STALL_THRESHOLD)) + .unwrap_or(ChainStatus::Unknown); + + output.to_response( + ChainBlocksStatusResponseBody { + current_time, + latest_cached_block, + chain_status, + } + .sign(state.private_signing_key()), + ) +} + // it's used for schema generation so dead_code is fine #[allow(dead_code)] #[derive(ToSchema)] @@ -90,7 +144,7 @@ pub(crate) struct ContractVersionSchemaResponse { /// version is any string that this implementation knows. It may be simple counter "1", "2". /// or semantic version on release tags "v0.7.0", or some custom feature flag list. /// the only code that needs to understand the version parsing is code that knows how to - /// migrate from the given contract (and is tied to it's implementation somehow) + /// migrate from the given contract (and is tied to its implementation somehow) pub version: String, } @@ -104,7 +158,8 @@ pub struct ContractInformationContractVersion { #[utoipa::path( tag = "network", get, - path = "/v1/network/nym-contracts", + context_path = "/v1/network", + path = "/nym-contracts", responses( (status = 200, content( (HashMap = "application/json"), @@ -151,7 +206,8 @@ pub struct ContractInformationBuildInformation { #[utoipa::path( tag = "network", get, - path = "/v1/network/nym-contracts-detailed", + context_path = "/v1/network", + path = "/nym-contracts-detailed", responses( (status = 200, content( (HashMap = "application/json"), diff --git a/nym-api/src/signers_cache/cache/data.rs b/nym-api/src/signers_cache/cache/data.rs new file mode 100644 index 0000000000..5111033b0b --- /dev/null +++ b/nym-api/src/signers_cache/cache/data.rs @@ -0,0 +1,2 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only diff --git a/nym-api/src/signers_cache/cache/mod.rs b/nym-api/src/signers_cache/cache/mod.rs new file mode 100644 index 0000000000..a44ab4da1b --- /dev/null +++ b/nym-api/src/signers_cache/cache/mod.rs @@ -0,0 +1,11 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use nym_ecash_signer_check::SignersTestResult; + +pub(crate) mod data; +pub(crate) mod refresher; + +pub(crate) struct SignersCacheData { + pub(crate) signers_results: SignersTestResult, +} diff --git a/nym-api/src/signers_cache/cache/refresher.rs b/nym-api/src/signers_cache/cache/refresher.rs new file mode 100644 index 0000000000..aa0a341a6f --- /dev/null +++ b/nym-api/src/signers_cache/cache/refresher.rs @@ -0,0 +1,33 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use crate::signers_cache::cache::SignersCacheData; +use crate::support::caching::refresher::CacheItemProvider; +use crate::support::nyxd::Client; +use async_trait::async_trait; +use nym_ecash_signer_check::{check_signers_with_client, SignerCheckError}; + +pub(crate) struct SignersCacheDataProvider { + nyxd_client: Client, +} + +#[async_trait] +impl CacheItemProvider for SignersCacheDataProvider { + type Item = SignersCacheData; + type Error = SignerCheckError; + + async fn try_refresh(&mut self) -> Result, Self::Error> { + self.refresh().await.map(Some) + } +} + +impl SignersCacheDataProvider { + pub(crate) fn new(nyxd_client: Client) -> Self { + SignersCacheDataProvider { nyxd_client } + } + + async fn refresh(&self) -> Result { + let signers_results = check_signers_with_client(&self.nyxd_client).await?; + Ok(SignersCacheData { signers_results }) + } +} diff --git a/nym-api/src/signers_cache/handlers.rs b/nym-api/src/signers_cache/handlers.rs new file mode 100644 index 0000000000..23046caad1 --- /dev/null +++ b/nym-api/src/signers_cache/handlers.rs @@ -0,0 +1,95 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use crate::node_status_api::models::ApiResult; +use crate::support::http::state::AppState; +use axum::extract::{Query, State}; +use axum::routing::get; +use axum::Router; +use nym_api_requests::models::{ + DetailedSignersStatusResponse, DetailedSignersStatusResponseBody, SignersStatusOverview, + SignersStatusResponse, SignersStatusResponseBody, +}; +use nym_api_requests::signable::SignableMessageBody; +use nym_http_api_common::{FormattedResponse, OutputParams}; + +pub(crate) fn signers_routes() -> Router { + Router::new() + .route("/status", get(signers_status)) + .route("/status-detailed", get(signers_status_detailed)) +} + +#[utoipa::path( + tag = "network", + get, + context_path = "/v1/network/signers", + path = "/status", + responses( + (status = 200, content( + (SignersStatusResponse = "application/json"), + (SignersStatusResponse = "application/yaml"), + (SignersStatusResponse = "application/bincode") + )) + ), + params(OutputParams) +)] +pub(crate) async fn signers_status( + Query(params): Query, + State(state): State, +) -> ApiResult> { + let output = params.get_output(); + + let cached = state.ecash_signers_cache.get().await?; + let as_at = cached.timestamp(); + Ok(output.to_response( + SignersStatusResponseBody { + as_at, + overview: SignersStatusOverview::new( + &cached.signers_results.results, + cached.signers_results.threshold, + ), + results: cached + .signers_results + .results + .iter() + .map(Into::into) + .collect(), + } + .sign(state.private_signing_key()), + )) +} + +#[utoipa::path( + tag = "network", + get, + context_path = "/v1/network/signers", + path = "/status-detailed", + responses( + (status = 200, content( + (DetailedSignersStatusResponse = "application/json"), + (DetailedSignersStatusResponse = "application/yaml"), + (DetailedSignersStatusResponse = "application/bincode") + )) + ), + params(OutputParams) +)] +pub(crate) async fn signers_status_detailed( + Query(params): Query, + State(state): State, +) -> ApiResult> { + let output = params.get_output(); + + let cached = state.ecash_signers_cache.get().await?; + let as_at = cached.timestamp(); + Ok(output.to_response( + DetailedSignersStatusResponseBody { + as_at, + overview: SignersStatusOverview::new( + &cached.signers_results.results, + cached.signers_results.threshold, + ), + details: cached.signers_results.results.clone(), + } + .sign(state.private_signing_key()), + )) +} diff --git a/nym-api/src/signers_cache/mod.rs b/nym-api/src/signers_cache/mod.rs new file mode 100644 index 0000000000..f79e1a1f1d --- /dev/null +++ b/nym-api/src/signers_cache/mod.rs @@ -0,0 +1,30 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use crate::signers_cache::cache::refresher::SignersCacheDataProvider; +use crate::signers_cache::cache::SignersCacheData; +use crate::support::caching::cache::SharedCache; +use crate::support::caching::refresher::CacheRefresher; +use crate::support::{config, nyxd}; +use nym_task::TaskManager; + +pub(crate) mod cache; +pub(crate) mod handlers; + +pub(crate) fn start_refresher( + config: &config::SignersCache, + nyxd_client: nyxd::Client, + task_manager: &TaskManager, +) -> SharedCache { + let refresher = CacheRefresher::new( + SignersCacheDataProvider::new(nyxd_client), + config.debug.refresh_interval, + ) + .named("signers-cache-refresher"); + let shared_cache = refresher.get_shared_cache(); + refresher.start_with_delay( + task_manager.subscribe_named("signers-cache-refresher"), + config.debug.refresher_start_delay, + ); + shared_cache +} diff --git a/nym-api/src/status/handlers.rs b/nym-api/src/status/handlers.rs index 6745a7934e..aa1d5101b2 100644 --- a/nym-api/src/status/handlers.rs +++ b/nym-api/src/status/handlers.rs @@ -3,6 +3,7 @@ use crate::node_status_api::models::{AxumErrorResponse, AxumResult}; use crate::status::ApiStatusState; +use crate::support::config::CHAIN_STALL_THRESHOLD; use crate::support::http::state::AppState; use axum::extract::{Query, State}; use axum::Router; @@ -12,7 +13,6 @@ use nym_api_requests::models::{ use nym_bin_common::build_information::BinaryBuildInformationOwned; use nym_compact_ecash::Base58; use nym_http_api_common::{FormattedResponse, OutputParams}; -use std::time::Duration; use time::OffsetDateTime; pub(crate) fn api_status_routes() -> Router { @@ -42,8 +42,6 @@ async fn health( Query(output): Query, State(state): State, ) -> FormattedResponse { - const CHAIN_STALL_THRESHOLD: Duration = Duration::from_secs(5 * 60); - let output = output.output.unwrap_or_default(); let uptime = state.api_status.startup_time.elapsed(); @@ -54,15 +52,7 @@ async fn health( { Ok(res) => { let now = OffsetDateTime::now_utc(); - let block_time: OffsetDateTime = res.latest_block.block.header.time.into(); - let diff = now - block_time; - if diff > CHAIN_STALL_THRESHOLD { - ChainStatus::Stalled { - approximate_amount: diff.unsigned_abs(), - } - } else { - ChainStatus::Synced - } + res.stall_status(now, CHAIN_STALL_THRESHOLD) } Err(_) => ChainStatus::Unknown, }; diff --git a/nym-api/src/support/caching/refresher.rs b/nym-api/src/support/caching/refresher.rs index b26a918f73..cfb412e449 100644 --- a/nym-api/src/support/caching/refresher.rs +++ b/nym-api/src/support/caching/refresher.rs @@ -60,6 +60,11 @@ pub(crate) trait CacheItemProvider { async fn try_refresh(&mut self) -> Result, Self::Error>; } +// Generics explanation: +// T: the actual type held in the cache +// E: Error type associated with refresh failure +// S: data type retrieved during update operation. it must be convertible into T +// (so that initial state could be established or when no `custom_fn` is set) impl CacheRefresher where E: std::error::Error, @@ -107,6 +112,8 @@ where } } + /// Rather than performing default behaviour of overwriting all existing values in the cache, + /// provide a custom update function that will define the update behaviour. #[must_use] pub(crate) fn with_update_fn( mut self, @@ -259,6 +266,26 @@ where tokio::spawn(async move { self.run(task_client).await }); } + pub fn start_with_delay(mut self, mut task_client: TaskClient, delay: Duration) + where + T: Send + Sync + 'static, + E: Send + Sync + 'static, + S: Send + Sync + 'static, + { + tokio::spawn(async move { + let sleep = tokio::time::sleep(delay); + tokio::select! { + biased; + _ = task_client.recv() => { + trace!("{}: Received shutdown", self.name); + return + } + _ = sleep => {}, + } + self.run(task_client).await + }); + } + pub fn start_with_watcher(self, task_client: TaskClient) -> CacheUpdateWatcher where T: Send + Sync + 'static, diff --git a/nym-api/src/support/cli/run.rs b/nym-api/src/support/cli/run.rs index bed8c6efaf..eb8f609ee4 100644 --- a/nym-api/src/support/cli/run.rs +++ b/nym-api/src/support/cli/run.rs @@ -34,7 +34,7 @@ use crate::support::storage::NymApiStorage; use crate::unstable_routes::v1::account::cache::AddressInfoCache; use crate::{ ecash, epoch_operations, mixnet_contract_cache, network_monitor, node_describe_cache, - node_performance, node_status_api, + node_performance, node_status_api, signers_cache, }; use anyhow::{bail, Context}; use nym_config::defaults::NymNetworkDetails; @@ -202,10 +202,18 @@ async fn start_nym_api_tasks(config: &Config) -> anyhow::Result None }; + // check if signers cache is enabled, and if so, start the refresher + let ecash_signers_cache = if config.signers_cache.enabled { + signers_cache::start_refresher(&config.signers_cache, nyxd_client.clone(), &task_manager) + } else { + SharedCache::new() + }; + ecash_state.spawn_background_cleaner(); let router = router.with_state(AppState { nyxd_client: nyxd_client.clone(), chain_status_cache: ChainStatusCache::new(DEFAULT_CHAIN_STATUS_CACHE_TTL), + ecash_signers_cache, address_info_cache: AddressInfoCache::new( config.address_cache.time_to_live, config.address_cache.capacity, diff --git a/nym-api/src/support/config/mod.rs b/nym-api/src/support/config/mod.rs index 8be4ee0bc0..612de6d815 100644 --- a/nym-api/src/support/config/mod.rs +++ b/nym-api/src/support/config/mod.rs @@ -63,12 +63,17 @@ pub(crate) const DEFAULT_NODE_DESCRIBE_CACHE_INTERVAL: Duration = Duration::from pub(crate) const DEFAULT_NODE_DESCRIBE_BATCH_SIZE: usize = 50; // TODO: make it configurable -pub(crate) const DEFAULT_CHAIN_STATUS_CACHE_TTL: Duration = Duration::from_secs(60); +pub(crate) const DEFAULT_CHAIN_STATUS_CACHE_TTL: Duration = Duration::from_secs(30); +pub(crate) const CHAIN_STALL_THRESHOLD: Duration = Duration::from_secs(5 * 60); // contract info is changed very infrequently (essentially once per release cycle) // so this default is more than enough pub(crate) const DEFAULT_CONTRACT_DETAILS_CACHE_TTL: Duration = Duration::from_secs(60 * 60); +pub(crate) const DEFAULT_NODE_SIGNERS_CACHE_REFRESH_INTERVAL: Duration = Duration::from_secs(600); +pub(crate) const DEFAULT_NODE_SIGNERS_CACHE_REFRESHER_START_DELAY: Duration = + Duration::from_secs(30); + const DEFAULT_MONITOR_THRESHOLD: u8 = 60; const DEFAULT_MIN_MIXNODE_RELIABILITY: u8 = 50; const DEFAULT_MIN_GATEWAY_RELIABILITY: u8 = 20; @@ -126,6 +131,9 @@ pub struct Config { pub rewarding: Rewarding, + #[serde(default)] + pub signers_cache: SignersCache, + #[serde(alias = "coconut_signer")] pub ecash_signer: EcashSigner, @@ -151,6 +159,7 @@ impl Config { describe_cache: Default::default(), contracts_info_cache: Default::default(), rewarding: Default::default(), + signers_cache: Default::default(), ecash_signer: EcashSigner::new_default(id.as_ref()), address_cache: Default::default(), } @@ -413,6 +422,44 @@ impl Default for PerformanceProviderDebug { } } +#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)] +pub struct SignersCache { + pub enabled: bool, + + pub debug: SignersCacheDebug, +} + +impl Default for SignersCache { + fn default() -> Self { + SignersCache { + enabled: true, + debug: Default::default(), + } + } +} + +#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)] +pub struct SignersCacheDebug { + // TODO: make it into a decaying function so that if multiple signers are down, + // the refresh interval would decrease + #[serde(with = "humantime_serde")] + pub refresh_interval: Duration, + + // give it some time so that the actual api on THIS singer could start + // and it wouldn't self-report itself as being down + #[serde(with = "humantime_serde")] + pub refresher_start_delay: Duration, +} + +impl Default for SignersCacheDebug { + fn default() -> Self { + SignersCacheDebug { + refresh_interval: DEFAULT_NODE_SIGNERS_CACHE_REFRESH_INTERVAL, + refresher_start_delay: DEFAULT_NODE_SIGNERS_CACHE_REFRESHER_START_DELAY, + } + } +} + #[derive(Debug, PartialEq, Eq)] pub struct AddressCacheConfig { pub time_to_live: Duration, diff --git a/nym-api/src/support/http/state/mod.rs b/nym-api/src/support/http/state/mod.rs index ec0d2ca9bb..7a9bb8abb9 100644 --- a/nym-api/src/support/http/state/mod.rs +++ b/nym-api/src/support/http/state/mod.rs @@ -8,6 +8,7 @@ use crate::node_describe_cache::cache::DescribedNodes; use crate::node_status_api::handlers::unstable; use crate::node_status_api::models::AxumErrorResponse; use crate::node_status_api::NodeStatusCache; +use crate::signers_cache::cache::SignersCacheData; use crate::status::ApiStatusState; use crate::support::caching::cache::SharedCache; use crate::support::caching::Cache; @@ -20,6 +21,7 @@ use crate::unstable_routes::v1::account::cache::AddressInfoCache; use crate::unstable_routes::v1::account::models::NyxAccountDetails; use axum::extract::FromRef; use nym_api_requests::models::{GatewayBondAnnotated, MixNodeBondAnnotated, NodeAnnotation}; +use nym_crypto::asymmetric::ed25519; use nym_mixnet_contract_common::NodeId; use nym_topology::CachedEpochRewardedSet; use std::collections::HashMap; @@ -41,6 +43,10 @@ pub(crate) struct AppState { /// Note, it is not updated on every request. It follows the embedded ttl. pub(crate) chain_status_cache: ChainStatusCache, + /// Holds cached state of the statuses of all [ecash] signers on the network - + /// their perceived chain statuses and signing capabilities. + pub(crate) ecash_signers_cache: SharedCache, + /// Holds mapping between a nyx address and tokens/delegations it holds pub(crate) address_info_cache: AddressInfoCache, @@ -100,7 +106,19 @@ impl FromRef for MixnetContractCache { } } +impl FromRef for SharedCache { + fn from_ref(app_state: &AppState) -> Self { + app_state.ecash_signers_cache.clone() + } +} + impl AppState { + pub(crate) fn private_signing_key(&self) -> &ed25519::PrivateKey { + // even though we have to go through ecash state, the key is always available + // (moving it would involve some refactoring that's not worth it now) + self.ecash_state.local.identity_keypair.private_key() + } + pub(crate) fn nym_contract_cache(&self) -> &MixnetContractCache { &self.mixnet_contract_cache } diff --git a/nym-api/tests/public-api/nym_nodes.rs b/nym-api/tests/public-api/nym_nodes.rs index dda646b3b8..425a115620 100644 --- a/nym-api/tests/public-api/nym_nodes.rs +++ b/nym-api/tests/public-api/nym_nodes.rs @@ -1,5 +1,5 @@ use crate::utils::{base_url, get_any_node_id, make_request, test_client, validate_json_response}; -use chrono::Utc; +use time::OffsetDateTime; #[tokio::test] async fn test_get_bonded_nodes() -> Result<(), String> { @@ -83,7 +83,7 @@ async fn test_get_annotation_for_node() -> Result<(), String> { #[tokio::test] async fn test_get_historical_performance() -> Result<(), String> { let id = get_any_node_id().await?; - let date = Utc::now().date_naive().to_string(); + let date = OffsetDateTime::now_utc().date().to_string(); let url = format!("{}/v1/nym-nodes/historical-performance/{}", base_url()?, id); let res = test_client() .get(&url) diff --git a/nym-node/src/cli/commands/debug/mod.rs b/nym-node/src/cli/commands/debug/mod.rs new file mode 100644 index 0000000000..9fc1175a80 --- /dev/null +++ b/nym-node/src/cli/commands/debug/mod.rs @@ -0,0 +1,4 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +pub(crate) mod reset_providers_dbs; diff --git a/nym-node/src/cli/commands/debug/reset_providers_dbs.rs b/nym-node/src/cli/commands/debug/reset_providers_dbs.rs new file mode 100644 index 0000000000..39130686ae --- /dev/null +++ b/nym-node/src/cli/commands/debug/reset_providers_dbs.rs @@ -0,0 +1,36 @@ +// Copyright 2025 - Nym Technologies SA +// SPDX-License-Identifier: GPL-3.0-only + +use crate::cli::helpers::ConfigArgs; +use crate::config::upgrade_helpers::try_load_current_config; +use crate::node::helpers::load_ed25519_identity_public_key; +use crate::node::ServiceProvidersData; +use nym_network_requester::{CustomGatewayDetails, GatewayDetails, GatewayRegistration}; +use std::fs; + +#[derive(Debug, clap::Args)] +pub struct Args { + #[clap(flatten)] + pub(crate) config: ConfigArgs, +} + +pub async fn execute(args: Args) -> anyhow::Result<()> { + let config = try_load_current_config(args.config.config_path()).await?; + + let public_key = load_ed25519_identity_public_key( + &config.storage_paths.keys.public_ed25519_identity_key_file, + )?; + + let storage_paths = &config.service_providers.storage_paths; + for db_path in [ + &storage_paths.authenticator.gateway_registrations, + &storage_paths.ip_packet_router.gateway_registrations, + &storage_paths.network_requester.gateway_registrations, + ] { + fs::remove_file(db_path)?; + let gateway_details: GatewayRegistration = + GatewayDetails::Custom(CustomGatewayDetails::new(public_key)).into(); + ServiceProvidersData::initialise_client_gateway_storage(db_path, &gateway_details).await?; + } + Ok(()) +} diff --git a/nym-node/src/cli/commands/mod.rs b/nym-node/src/cli/commands/mod.rs index 345a2143e7..6bab14a818 100644 --- a/nym-node/src/cli/commands/mod.rs +++ b/nym-node/src/cli/commands/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod bonding_information; pub(super) mod build_info; +pub(super) mod debug; pub(super) mod migrate; pub(crate) mod node_details; pub(crate) mod reset_sphinx_keys; diff --git a/nym-node/src/cli/mod.rs b/nym-node/src/cli/mod.rs index eb51abc817..b480743922 100644 --- a/nym-node/src/cli/mod.rs +++ b/nym-node/src/cli/mod.rs @@ -2,11 +2,12 @@ // SPDX-License-Identifier: GPL-3.0-only use crate::cli::commands::{ - bonding_information, build_info, migrate, node_details, reset_sphinx_keys, run, sign, + bonding_information, build_info, debug, migrate, node_details, reset_sphinx_keys, run, sign, test_throughput, }; use crate::env::vars::{NYMNODE_CONFIG_ENV_FILE_ARG, NYMNODE_NO_BANNER_ARG}; -use clap::{Parser, Subcommand}; +use crate::logging::setup_tracing_logger; +use clap::{Args, Parser, Subcommand}; use nym_bin_common::bin_info; use std::future::Future; use std::sync::OnceLock; @@ -71,6 +72,11 @@ impl Cli { Commands::UnsafeResetSphinxKeys(args) => { { Self::execute_async(reset_sphinx_keys::execute(args))? }? } + Commands::Debug(debug) => match debug.command { + DebugCommands::ResetProvidersGatewayDbs(args) => { + { Self::execute_async(debug::reset_providers_dbs::execute(args))? }? + } + }, } Ok(()) } @@ -99,12 +105,28 @@ pub(crate) enum Commands { /// UNSAFE: reset existing sphinx keys and attempt to generate fresh one for the current network state UnsafeResetSphinxKeys(reset_sphinx_keys::Args), + /// Commands exposed for debug purposes, usually not meant to be used by operators + #[clap(hide = true)] + Debug(Debug), + /// Attempt to approximate the maximum mixnet throughput if nym-node /// was running on this machine in mixnet mode #[clap(hide = true)] TestThroughput(test_throughput::Args), } +#[derive(Debug, Args)] +pub(crate) struct Debug { + #[clap(subcommand)] + pub(crate) command: DebugCommands, +} + +#[derive(Subcommand, Debug)] +pub(crate) enum DebugCommands { + /// Reset the internal GatewaysDetailsStores of all service providers in case they got corrupted + ResetProvidersGatewayDbs(debug::reset_providers_dbs::Args), +} + #[cfg(test)] mod tests { use super::*; diff --git a/nym-node/src/node/mixnet/shared/final_hop.rs b/nym-node/src/node/mixnet/shared/final_hop.rs index d38fc99d9f..cb6bc0ea64 100644 --- a/nym-node/src/node/mixnet/shared/final_hop.rs +++ b/nym-node/src/node/mixnet/shared/final_hop.rs @@ -1,7 +1,9 @@ // Copyright 2024 - Nym Technologies SA // SPDX-License-Identifier: GPL-3.0-only -use nym_gateway::node::{ActiveClientsStore, GatewayStorage, GatewayStorageError}; +use nym_gateway::node::{ + ActiveClientsStore, GatewayStorage, GatewayStorageError, InboxGatewayStorage, +}; use nym_sphinx_types::DestinationAddressBytes; use tracing::debug; diff --git a/nym-node/src/node/mod.rs b/nym-node/src/node/mod.rs index c240686b8a..6ec9105482 100644 --- a/nym-node/src/node/mod.rs +++ b/nym-node/src/node/mod.rs @@ -164,7 +164,7 @@ impl ServiceProvidersData { Ok(()) } - async fn initialise_client_gateway_storage( + pub(crate) async fn initialise_client_gateway_storage( storage_path: &Path, registration: &GatewayRegistration, ) -> Result<(), ServiceProvidersError> { diff --git a/nym-validator-rewarder/src/rewarder/ticketbook_issuance/verifier.rs b/nym-validator-rewarder/src/rewarder/ticketbook_issuance/verifier.rs index fd04e18de0..cb0964caf3 100644 --- a/nym-validator-rewarder/src/rewarder/ticketbook_issuance/verifier.rs +++ b/nym-validator-rewarder/src/rewarder/ticketbook_issuance/verifier.rs @@ -15,9 +15,9 @@ use nym_validator_client::ecash::models::{ CommitedDeposit, DepositId, IssuedTicketbooksChallengeCommitmentRequestBody, IssuedTicketbooksChallengeCommitmentResponse, IssuedTicketbooksDataRequestBody, IssuedTicketbooksDataResponse, IssuedTicketbooksDataResponseBody, IssuedTicketbooksForResponse, - SignableMessageBody, SignedMessage, }; use nym_validator_client::nyxd::AccountId; +use nym_validator_client::signable::{SignableMessageBody, SignedMessage}; use rand::distributions::{Distribution, WeightedIndex}; use rand::prelude::SliceRandom; use rand::thread_rng; diff --git a/nym-wallet/Cargo.lock b/nym-wallet/Cargo.lock index cd657d1561..2b9ac7375d 100644 --- a/nym-wallet/Cargo.lock +++ b/nym-wallet/Cargo.lock @@ -2541,18 +2541,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "getset" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3586f256131df87204eb733da72e3d3eb4f343c639f4b7be279ac7c48baeafe" -dependencies = [ - "proc-macro-error2", - "proc-macro2", - "quote", - "syn 2.0.100", -] - [[package]] name = "ghash" version = "0.5.1" @@ -4020,14 +4008,15 @@ dependencies = [ "cosmrs", "cosmwasm-std", "ecdsa", - "getset", "hex", "humantime-serde", + "nym-coconut-dkg-common", "nym-compact-ecash", "nym-config", "nym-contracts-common", "nym-credentials-interface", "nym-crypto", + "nym-ecash-signer-check-types", "nym-ecash-time", "nym-mixnet-contract-common", "nym-network-defaults", @@ -4170,6 +4159,21 @@ dependencies = [ "thiserror 2.0.12", ] +[[package]] +name = "nym-ecash-signer-check-types" +version = "0.1.0" +dependencies = [ + "nym-coconut-dkg-common", + "nym-crypto", + "semver", + "serde", + "thiserror 2.0.12", + "time", + "tracing", + "url", + "utoipa", +] + [[package]] name = "nym-ecash-time" version = "0.1.0" @@ -5413,28 +5417,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "proc-macro-error2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" -dependencies = [ - "proc-macro-error-attr2", - "proc-macro2", - "quote", - "syn 2.0.100", -] - [[package]] name = "proc-macro-hack" version = "0.5.20+deprecated" diff --git a/scripts/wireguard-exit-policy/exit-policy-tests.sh b/scripts/wireguard-exit-policy/exit-policy-tests.sh index c7127c8cdd..5ae10b177c 100644 --- a/scripts/wireguard-exit-policy/exit-policy-tests.sh +++ b/scripts/wireguard-exit-policy/exit-policy-tests.sh @@ -47,6 +47,7 @@ test_port_range_rules() { "8087-8088:tcp:Simplify Media" "8232-8233:tcp:Zcash" "8332-8333:tcp:Bitcoin" + "18080-18081:tcp:Monero" ) local total_failures=0 @@ -148,7 +149,7 @@ test_critical_services() { # Verify default reject rule exists test_default_reject_rule() { echo -e "${YELLOW}This test takes some time, do not quit the process${NC}" - echo + echo echo -e "${YELLOW}Testing Default Reject Rule...${NC}" # Try different patterns to detect the reject rule @@ -236,4 +237,4 @@ if [[ $EUID -ne 0 ]]; then fi # Run the tests -run_all_tests "$@" \ No newline at end of file +run_all_tests "$@" diff --git a/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh b/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh index 5b8c4bc2e5..bce3d09711 100644 --- a/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh +++ b/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh @@ -357,9 +357,13 @@ apply_port_allowlist() { ["Lightning"]="9735" ["NDMP"]="10000" ["OpenPGP"]="11371" + ["Monero"]="18080-18081" + ["MoneroRPC"]="18089" ["GoogleVoice"]="19294" ["EnsimControlPanel"]="19638" + ["DarkFiTor"]="25551" ["Minecraft"]="25565" + ["DarkFi"]="26661" ["Steam"]="27000-27050" ["ElectrumSSL"]="50002" ["MOSH"]="60000-61000" @@ -672,4 +676,4 @@ main() { esac } -main "$@" \ No newline at end of file +main "$@" diff --git a/service-providers/authenticator/Cargo.toml b/service-providers/authenticator/Cargo.toml index 0c4347bb8d..85e4dc7021 100644 --- a/service-providers/authenticator/Cargo.toml +++ b/service-providers/authenticator/Cargo.toml @@ -54,3 +54,6 @@ nym-wireguard-types = { path = "../../common/wireguard-types" } [dev-dependencies] mock_instant = "0.5.3" +time = { workspace = true } + +nym-wireguard = { path = "../../common/wireguard", features = ["mock"] } diff --git a/service-providers/authenticator/src/authenticator.rs b/service-providers/authenticator/src/authenticator.rs index 268d96c1ef..2790ddddcb 100644 --- a/service-providers/authenticator/src/authenticator.rs +++ b/service-providers/authenticator/src/authenticator.rs @@ -31,7 +31,7 @@ pub struct Authenticator { custom_topology_provider: Option>, custom_gateway_transceiver: Option>, wireguard_gateway_data: WireguardGatewayData, - ecash_verifier: Option>, + ecash_verifier: Arc, used_private_network_ips: Vec, shutdown: Option, on_start: Option>, @@ -42,13 +42,14 @@ impl Authenticator { config: Config, wireguard_gateway_data: WireguardGatewayData, used_private_network_ips: Vec, + ecash_verifier: Arc, ) -> Self { Self { config, wait_for_gateway: false, custom_topology_provider: None, custom_gateway_transceiver: None, - ecash_verifier: None, + ecash_verifier, wireguard_gateway_data, used_private_network_ips, shutdown: None, @@ -56,13 +57,6 @@ impl Authenticator { } } - #[must_use] - #[allow(unused)] - pub fn with_ecash_verifier(mut self, ecash_verifier: Arc) -> Self { - self.ecash_verifier = Some(ecash_verifier); - self - } - #[must_use] #[allow(unused)] pub fn with_shutdown(mut self, shutdown: TaskClient) -> Self { diff --git a/service-providers/authenticator/src/cli/add_gateway.rs b/service-providers/authenticator/src/cli/add_gateway.rs deleted file mode 100644 index 397a8be01e..0000000000 --- a/service-providers/authenticator/src/cli/add_gateway.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_bin_common::output_format::OutputFormat; -use nym_client_core::cli_helpers::client_add_gateway::{add_gateway, CommonClientAddGatewayArgs}; - -#[derive(clap::Args)] -pub(crate) struct Args { - #[command(flatten)] - common_args: CommonClientAddGatewayArgs, - - #[arg(short, long, default_value_t = OutputFormat::default())] - output: OutputFormat, -} - -impl AsRef for Args { - fn as_ref(&self) -> &CommonClientAddGatewayArgs { - &self.common_args - } -} - -pub(crate) async fn execute(args: Args) -> Result<(), AuthenticatorError> { - let output = args.output; - let res = add_gateway::(args, None).await?; - - println!("{}", output.format(&res)); - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/build_info.rs b/service-providers/authenticator/src/cli/build_info.rs deleted file mode 100644 index 7351753134..0000000000 --- a/service-providers/authenticator/src/cli/build_info.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use clap::Args; -use nym_bin_common::bin_info_owned; -use nym_bin_common::output_format::OutputFormat; - -#[derive(Args)] -pub(crate) struct BuildInfo { - #[arg(short, long, default_value_t = OutputFormat::default())] - output: OutputFormat, -} - -pub(crate) fn execute(args: BuildInfo) { - println!("{}", args.output.format(&bin_info_owned!())) -} diff --git a/service-providers/authenticator/src/cli/ecash/import_coin_index_signatures.rs b/service-providers/authenticator/src/cli/ecash/import_coin_index_signatures.rs deleted file mode 100644 index c3b1aa922e..0000000000 --- a/service-providers/authenticator/src/cli/ecash/import_coin_index_signatures.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_client_core::cli_helpers::client_import_coin_index_signatures::{ - import_coin_index_signatures, CommonClientImportCoinIndexSignaturesArgs, -}; - -pub(crate) async fn execute( - args: CommonClientImportCoinIndexSignaturesArgs, -) -> Result<(), AuthenticatorError> { - import_coin_index_signatures::(args).await?; - println!("successfully imported coin index signatures!"); - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/ecash/import_credential.rs b/service-providers/authenticator/src/cli/ecash/import_credential.rs deleted file mode 100644 index e525eac518..0000000000 --- a/service-providers/authenticator/src/cli/ecash/import_credential.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_client_core::cli_helpers::client_import_credential::{ - import_credential, CommonClientImportTicketBookArgs, -}; - -pub async fn execute(args: CommonClientImportTicketBookArgs) -> Result<(), AuthenticatorError> { - import_credential::(args).await?; - println!("successfully imported credential!"); - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/ecash/import_expiration_date_signatures.rs b/service-providers/authenticator/src/cli/ecash/import_expiration_date_signatures.rs deleted file mode 100644 index 7db61d5238..0000000000 --- a/service-providers/authenticator/src/cli/ecash/import_expiration_date_signatures.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_client_core::cli_helpers::client_import_expiration_date_signatures::{ - import_expiration_date_signatures, CommonClientImportExpirationDateSignaturesArgs, -}; - -pub(crate) async fn execute( - args: CommonClientImportExpirationDateSignaturesArgs, -) -> Result<(), AuthenticatorError> { - import_expiration_date_signatures::(args).await?; - println!("successfully imported expiration date signatures!"); - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/ecash/import_master_verification_key.rs b/service-providers/authenticator/src/cli/ecash/import_master_verification_key.rs deleted file mode 100644 index d53ddacf4c..0000000000 --- a/service-providers/authenticator/src/cli/ecash/import_master_verification_key.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_client_core::cli_helpers::client_import_master_verification_key::{ - import_master_verification_key, CommonClientImportMasterVerificationKeyArgs, -}; - -pub(crate) async fn execute( - args: CommonClientImportMasterVerificationKeyArgs, -) -> Result<(), AuthenticatorError> { - import_master_verification_key::(args).await?; - println!("successfully imported master verification key!"); - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/ecash/mod.rs b/service-providers/authenticator/src/cli/ecash/mod.rs deleted file mode 100644 index 9272ed013c..0000000000 --- a/service-providers/authenticator/src/cli/ecash/mod.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use clap::{Args, Subcommand}; -use nym_authenticator::error::AuthenticatorError; -use nym_client_core::cli_helpers::client_import_coin_index_signatures::CommonClientImportCoinIndexSignaturesArgs; -use nym_client_core::cli_helpers::client_import_credential::CommonClientImportTicketBookArgs; -use nym_client_core::cli_helpers::client_import_expiration_date_signatures::CommonClientImportExpirationDateSignaturesArgs; -use nym_client_core::cli_helpers::client_import_master_verification_key::CommonClientImportMasterVerificationKeyArgs; - -pub(crate) mod import_coin_index_signatures; -pub(crate) mod import_credential; -pub(crate) mod import_expiration_date_signatures; -pub(crate) mod import_master_verification_key; -pub(crate) mod show_ticketbooks; - -#[derive(Args)] -#[clap(args_conflicts_with_subcommands = true, subcommand_required = true)] -pub struct Ecash { - #[clap(subcommand)] - pub command: EcashCommands, -} - -impl Ecash { - pub async fn execute(self) -> Result<(), AuthenticatorError> { - match self.command { - EcashCommands::ShowTicketBooks(args) => show_ticketbooks::execute(args).await?, - EcashCommands::ImportTicketBook(args) => import_credential::execute(args).await?, - EcashCommands::ImportCoinIndexSignatures(args) => { - import_coin_index_signatures::execute(args).await? - } - EcashCommands::ImportExpirationDateSignatures(args) => { - import_expiration_date_signatures::execute(args).await? - } - EcashCommands::ImportMasterVerificationKey(args) => { - import_master_verification_key::execute(args).await? - } - } - Ok(()) - } -} - -#[derive(Subcommand)] -pub enum EcashCommands { - /// Display information associated with the imported ticketbooks, - ShowTicketBooks(show_ticketbooks::Args), - - /// Import a pre-generated ticketbook - ImportTicketBook(CommonClientImportTicketBookArgs), - - /// Import coin index signatures needed for ticketbooks - ImportCoinIndexSignatures(CommonClientImportCoinIndexSignaturesArgs), - - /// Import expiration date signatures needed for ticketbooks - ImportExpirationDateSignatures(CommonClientImportExpirationDateSignaturesArgs), - - /// Import master verification key needed for ticketbooks - ImportMasterVerificationKey(CommonClientImportMasterVerificationKeyArgs), -} diff --git a/service-providers/authenticator/src/cli/ecash/show_ticketbooks.rs b/service-providers/authenticator/src/cli/ecash/show_ticketbooks.rs deleted file mode 100644 index ca31d39802..0000000000 --- a/service-providers/authenticator/src/cli/ecash/show_ticketbooks.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_bin_common::output_format::OutputFormat; -use nym_client_core::cli_helpers::client_show_ticketbooks::{ - show_ticketbooks, CommonShowTicketbooksArgs, -}; - -#[derive(clap::Args)] -pub(crate) struct Args { - #[command(flatten)] - common_args: CommonShowTicketbooksArgs, - - #[arg(short, long, default_value_t = OutputFormat::default())] - output: OutputFormat, -} - -impl AsRef for Args { - fn as_ref(&self) -> &CommonShowTicketbooksArgs { - &self.common_args - } -} - -pub(crate) async fn execute(args: Args) -> Result<(), AuthenticatorError> { - let output = args.output; - let res = show_ticketbooks::(args).await?; - - println!("{}", output.format(&res)); - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/init.rs b/service-providers/authenticator/src/cli/init.rs deleted file mode 100644 index 217c3160d0..0000000000 --- a/service-providers/authenticator/src/cli/init.rs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::{override_config, CliAuthenticatorClient, OverrideConfig}; -use clap::Args; -use nym_authenticator::{ - config::{default_config_directory, default_config_filepath, default_data_directory, Config}, - error::AuthenticatorError, -}; -use nym_bin_common::output_format::OutputFormat; -use nym_client_core::cli_helpers::client_init::{ - initialise_client, CommonClientInitArgs, InitResultsWithConfig, InitialisableClient, -}; -use serde::Serialize; -use std::{fmt::Display, fs, path::PathBuf}; - -impl InitialisableClient for CliAuthenticatorClient { - type InitArgs = Init; - - fn initialise_storage_paths(id: &str) -> Result<(), Self::Error> { - fs::create_dir_all(default_data_directory(id))?; - fs::create_dir_all(default_config_directory(id))?; - Ok(()) - } - - fn default_config_path(id: &str) -> PathBuf { - default_config_filepath(id) - } - - fn construct_config(init_args: &Self::InitArgs) -> Self::Config { - override_config( - Config::new(&init_args.common_args.id), - OverrideConfig::from(init_args.clone()), - ) - } -} - -#[derive(Args, Clone, Debug)] -pub(crate) struct Init { - #[command(flatten)] - common_args: CommonClientInitArgs, - - #[clap(short, long, default_value_t = OutputFormat::default())] - output: OutputFormat, -} - -impl From for OverrideConfig { - fn from(init_config: Init) -> Self { - OverrideConfig { - nym_apis: init_config.common_args.nym_apis, - nyxd_urls: init_config.common_args.nyxd_urls, - enabled_credentials_mode: init_config.common_args.enabled_credentials_mode, - } - } -} - -impl AsRef for Init { - fn as_ref(&self) -> &CommonClientInitArgs { - &self.common_args - } -} - -#[derive(Debug, Serialize)] -pub struct InitResults { - #[serde(flatten)] - client_core: nym_client_core::init::types::InitResults, - client_address: String, -} - -impl InitResults { - fn new(res: InitResultsWithConfig) -> Self { - Self { - client_address: res.init_results.address.to_string(), - client_core: res.init_results, - } - } -} - -impl Display for InitResults { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - writeln!(f, "{}", self.client_core)?; - write!(f, "Address of this authenticator: {}", self.client_address) - } -} - -pub(crate) async fn execute(args: Init) -> Result<(), AuthenticatorError> { - eprintln!("Initialising client..."); - - let output = args.output; - let res = initialise_client::(args, None).await?; - - let init_results = InitResults::new(res); - println!("{}", output.format(&init_results)); - - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/list_gateways.rs b/service-providers/authenticator/src/cli/list_gateways.rs deleted file mode 100644 index 9297d5cd5b..0000000000 --- a/service-providers/authenticator/src/cli/list_gateways.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_bin_common::output_format::OutputFormat; -use nym_client_core::cli_helpers::client_list_gateways::{ - list_gateways, CommonClientListGatewaysArgs, -}; - -#[derive(clap::Args)] -pub(crate) struct Args { - #[command(flatten)] - common_args: CommonClientListGatewaysArgs, - - #[arg(short, long, default_value_t = OutputFormat::default())] - output: OutputFormat, -} - -impl AsRef for Args { - fn as_ref(&self) -> &CommonClientListGatewaysArgs { - &self.common_args - } -} - -pub(crate) async fn execute(args: Args) -> Result<(), AuthenticatorError> { - let output = args.output; - let res = list_gateways::(args).await?; - - println!("{}", output.format(&res)); - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/mod.rs b/service-providers/authenticator/src/cli/mod.rs deleted file mode 100644 index 08aca6f720..0000000000 --- a/service-providers/authenticator/src/cli/mod.rs +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::ecash::Ecash; -use clap::{CommandFactory, Parser, Subcommand}; -use log::error; -use nym_authenticator::{ - config::{helpers::try_upgrade_config, BaseClientConfig, Config}, - error::AuthenticatorError, -}; -use nym_bin_common::bin_info; -use nym_bin_common::completions::{fig_generate, ArgShell}; -use nym_client_core::cli_helpers::CliClient; -use std::sync::OnceLock; - -mod add_gateway; -mod build_info; -pub mod ecash; -mod init; -mod list_gateways; -mod peer_handler; -mod request; -mod run; -mod sign; -mod switch_gateway; - -pub(crate) struct CliAuthenticatorClient; - -impl CliClient for CliAuthenticatorClient { - const NAME: &'static str = "authenticator"; - type Error = AuthenticatorError; - type Config = Config; - - async fn try_upgrade_outdated_config(id: &str) -> Result<(), Self::Error> { - try_upgrade_config(id).await - } - - async fn try_load_current_config(id: &str) -> Result { - try_load_current_config(id).await - } -} - -fn pretty_build_info_static() -> &'static str { - static PRETTY_BUILD_INFORMATION: OnceLock = OnceLock::new(); - PRETTY_BUILD_INFORMATION.get_or_init(|| bin_info!().pretty_print()) -} - -#[derive(Parser)] -#[command(author = "Nymtech", version, about, long_version = pretty_build_info_static())] -pub(crate) struct Cli { - /// Path pointing to an env file that configures the client. - #[arg(short, long)] - pub(crate) config_env_file: Option, - - /// Flag used for disabling the printed banner in tty. - #[arg(long)] - pub(crate) no_banner: bool, - - #[command(subcommand)] - command: Commands, -} - -#[allow(clippy::large_enum_variant)] -#[derive(Subcommand)] -pub(crate) enum Commands { - /// Initialize an authenticator. Do this first! - Init(init::Init), - - /// Run the authenticator with the provided configuration and optionally override - /// parameters. - Run(run::Run), - - /// Make a dummy request to a running authenticator - Request(request::Request), - - /// Ecash-related functionalities - Ecash(Ecash), - - /// List all registered with gateways - ListGateways(list_gateways::Args), - - /// Add new gateway to this client - AddGateway(add_gateway::Args), - - /// Change the currently active gateway. Note that you must have already registered with the new gateway! - SwitchGateway(switch_gateway::Args), - - /// Sign to prove ownership of this authenticator - Sign(sign::Sign), - - /// Show build information of this binary - BuildInfo(build_info::BuildInfo), - - /// Generate shell completions - Completions(ArgShell), - - /// Generate Fig specification - GenerateFigSpec, -} - -// Configuration that can be overridden. -pub(crate) struct OverrideConfig { - nym_apis: Option>, - nyxd_urls: Option>, - enabled_credentials_mode: Option, -} - -pub(crate) fn override_config(config: Config, args: OverrideConfig) -> Config { - config - .with_optional_base_custom_env( - BaseClientConfig::with_custom_nym_apis, - args.nym_apis, - nym_network_defaults::var_names::NYM_API, - nym_config::parse_urls, - ) - .with_optional_base_custom_env( - BaseClientConfig::with_custom_nyxd, - args.nyxd_urls, - nym_network_defaults::var_names::NYXD, - nym_config::parse_urls, - ) - .with_optional_base( - BaseClientConfig::with_disabled_credentials, - args.enabled_credentials_mode.map(|b| !b), - ) -} - -pub(crate) async fn execute(args: Cli) -> Result<(), AuthenticatorError> { - let bin_name = "nym-authenticator"; - - match args.command { - Commands::Init(m) => init::execute(m).await?, - Commands::Run(m) => run::execute(&m).await?, - Commands::Request(r) => request::execute(&r).await?, - Commands::Ecash(ecash) => ecash.execute().await?, - Commands::ListGateways(args) => list_gateways::execute(args).await?, - Commands::AddGateway(args) => add_gateway::execute(args).await?, - Commands::SwitchGateway(args) => switch_gateway::execute(args).await?, - Commands::Sign(m) => sign::execute(&m).await?, - Commands::BuildInfo(m) => build_info::execute(m), - Commands::Completions(s) => s.generate(&mut Cli::command(), bin_name), - Commands::GenerateFigSpec => fig_generate(&mut Cli::command(), bin_name), - } - Ok(()) -} - -async fn try_load_current_config(id: &str) -> Result { - // try to load the config as is - if let Ok(cfg) = Config::read_from_default_path(id) { - return if !cfg.validate() { - Err(AuthenticatorError::ConfigValidationFailure) - } else { - Ok(cfg) - }; - } - - // we couldn't load it - try upgrading it from older revisions - try_upgrade_config(id).await?; - - let config = match Config::read_from_default_path(id) { - Ok(cfg) => cfg, - Err(err) => { - error!("Failed to load config for {id}. Are you sure you have run `init` before? (Error was: {err})"); - return Err(AuthenticatorError::FailedToLoadConfig(id.to_string())); - } - }; - - if !config.validate() { - return Err(AuthenticatorError::ConfigValidationFailure); - } - - Ok(config) -} diff --git a/service-providers/authenticator/src/cli/peer_handler.rs b/service-providers/authenticator/src/cli/peer_handler.rs deleted file mode 100644 index 402c09815a..0000000000 --- a/service-providers/authenticator/src/cli/peer_handler.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use nym_sdk::TaskClient; -use nym_wireguard::peer_controller::{ - AddPeerControlResponse, GetClientBandwidthControlResponse, PeerControlRequest, - QueryBandwidthControlResponse, QueryPeerControlResponse, RemovePeerControlResponse, -}; -use tokio::sync::mpsc; - -pub struct DummyHandler { - peer_rx: mpsc::Receiver, - task_client: TaskClient, -} - -impl DummyHandler { - pub fn new(peer_rx: mpsc::Receiver, task_client: TaskClient) -> Self { - DummyHandler { - peer_rx, - task_client, - } - } - - pub async fn run(mut self) { - while !self.task_client.is_shutdown() { - tokio::select! { - msg = self.peer_rx.recv() => { - if let Some(msg) = msg { - match msg { - PeerControlRequest::AddPeer { peer, client_id, response_tx } => { - log::info!("[DUMMY] Adding peer {peer:?} with client id {client_id:?}"); - response_tx.send(AddPeerControlResponse { success: true }).ok(); - } - PeerControlRequest::RemovePeer { key, response_tx } => { - log::info!("[DUMMY] Removing peer {key:?}"); - response_tx.send(RemovePeerControlResponse { success: true }).ok(); - } - PeerControlRequest::QueryPeer{key, response_tx} => { - log::info!("[DUMMY] Querying peer {key:?}"); - response_tx.send(QueryPeerControlResponse { success: true, peer: None }).ok(); - } - PeerControlRequest::QueryBandwidth{key, response_tx} => { - log::info!("[DUMMY] Querying bandwidth for peer {key:?}"); - response_tx.send(QueryBandwidthControlResponse { success: true, bandwidth_data: None }).ok(); - } - PeerControlRequest::GetClientBandwidth{key, response_tx} => { - log::info!("[DUMMY] Getting client bandwidth for peer {key:?}"); - response_tx.send(GetClientBandwidthControlResponse {client_bandwidth: None }).ok(); - } - } - } else { - break; - } - } - - _ = self.task_client.recv() => { - log::trace!("DummyHandler: Received shutdown"); - } - } - } - log::debug!("DummyHandler: Exiting"); - } -} diff --git a/service-providers/authenticator/src/cli/request.rs b/service-providers/authenticator/src/cli/request.rs deleted file mode 100644 index 9ceb3f6143..0000000000 --- a/service-providers/authenticator/src/cli/request.rs +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::try_load_current_config; -use crate::cli::AuthenticatorError; -use crate::cli::{override_config, OverrideConfig}; -use clap::{Args, Subcommand}; -use nym_authenticator_requests::latest::{ - registration::{ClientMac, FinalMessage, GatewayClient, InitMessage, IpPair}, - request::{AuthenticatorRequest, AuthenticatorRequestData}, -}; -use nym_client_core::cli_helpers::client_run::CommonClientRunArgs; -use nym_sdk::mixnet::{MixnetMessageSender, Recipient, TransmissionLane}; -use nym_task::TaskHandle; -use nym_wireguard_types::PeerPublicKey; -use std::net::{Ipv4Addr, Ipv6Addr}; -use std::str::FromStr; -use std::time::Duration; -use tokio::time::sleep; - -#[allow(clippy::struct_excessive_bools)] -#[derive(Args, Clone)] -pub(crate) struct Request { - #[command(flatten)] - common_args: CommonClientRunArgs, - - #[command(subcommand)] - request: RequestType, - - authenticator_recipient: String, -} - -impl From for OverrideConfig { - fn from(request_config: Request) -> Self { - OverrideConfig { - nym_apis: None, - nyxd_urls: request_config.common_args.nyxd_urls, - enabled_credentials_mode: request_config.common_args.enabled_credentials_mode, - } - } -} - -#[derive(Clone, Subcommand)] -pub(crate) enum RequestType { - Initial(Initial), - Final(Final), - QueryBandwidth(QueryBandwidth), -} - -#[derive(Args, Clone, Debug)] -pub(crate) struct Initial { - pub_key: String, -} - -#[derive(Args, Clone, Debug)] -pub(crate) struct Final { - pub_key: String, - private_ipv4: String, - private_ipv6: String, - mac: String, -} - -#[derive(Args, Clone, Debug)] -pub(crate) struct QueryBandwidth { - pub_key: String, -} - -impl TryFrom for AuthenticatorRequestData { - type Error = AuthenticatorError; - - fn try_from(value: RequestType) -> Result { - let ret = match value { - RequestType::Initial(req) => AuthenticatorRequestData::Initial(InitMessage::new( - PeerPublicKey::from_str(&req.pub_key)?, - )), - RequestType::Final(req) => AuthenticatorRequestData::Final(Box::new(FinalMessage { - gateway_client: GatewayClient { - pub_key: PeerPublicKey::from_str(&req.pub_key)?, - private_ips: IpPair::new( - Ipv4Addr::from_str(&req.private_ipv4)?, - Ipv6Addr::from_str(&req.private_ipv6)?, - ), - mac: ClientMac::from_str(&req.mac)?, - }, - credential: None, - })), - RequestType::QueryBandwidth(req) => { - AuthenticatorRequestData::QueryBandwidth(PeerPublicKey::from_str(&req.pub_key)?) - } - }; - Ok(ret) - } -} - -pub(crate) async fn execute(args: &Request) -> Result<(), AuthenticatorError> { - let mut config = try_load_current_config(&args.common_args.id).await?; - config = override_config(config, OverrideConfig::from(args.clone())); - - let shutdown = TaskHandle::default(); - let mixnet_client = nym_authenticator::mixnet_client::create_mixnet_client( - &config.base, - shutdown.get_handle().named("nym_sdk::MixnetClient"), - None, - None, - false, - &config.storage_paths.common_paths, - ) - .await?; - - let request_data = AuthenticatorRequestData::try_from(args.request.clone())?; - let authenticator_recipient = Recipient::from_str(&args.authenticator_recipient)?; - let (request, _) = match request_data { - AuthenticatorRequestData::Initial(init_message) => { - AuthenticatorRequest::new_initial_request(init_message) - } - AuthenticatorRequestData::Final(final_message) => { - AuthenticatorRequest::new_final_request(*final_message) - } - AuthenticatorRequestData::QueryBandwidth(query_message) => { - AuthenticatorRequest::new_query_request(query_message) - } - AuthenticatorRequestData::TopUpBandwidth(top_up_message) => { - AuthenticatorRequest::new_topup_request(*top_up_message) - } - }; - mixnet_client - .split_sender() - .send(nym_sdk::mixnet::InputMessage::new_regular( - authenticator_recipient, - request.to_bytes().unwrap(), - TransmissionLane::General, - None, - )) - .await - .map_err(|source| AuthenticatorError::FailedToSendPacketToMixnet { - source: Box::new(source), - })?; - - log::info!("Sent request, sleeping 60 seconds or until killed"); - sleep(Duration::from_secs(60)).await; - - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/run.rs b/service-providers/authenticator/src/cli/run.rs deleted file mode 100644 index d6b273f5b1..0000000000 --- a/service-providers/authenticator/src/cli/run.rs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::peer_handler::DummyHandler; -use crate::cli::try_load_current_config; -use crate::cli::{override_config, OverrideConfig}; -use clap::Args; -use nym_authenticator::error::AuthenticatorError; -use nym_client_core::cli_helpers::client_run::CommonClientRunArgs; -use nym_crypto::asymmetric::x25519::KeyPair; -use nym_task::TaskHandle; -use nym_wireguard::WireguardGatewayData; -use rand::rngs::OsRng; -use std::sync::Arc; - -#[allow(clippy::struct_excessive_bools)] -#[derive(Args, Clone)] -pub(crate) struct Run { - #[command(flatten)] - common_args: CommonClientRunArgs, -} - -impl From for OverrideConfig { - fn from(run_config: Run) -> Self { - OverrideConfig { - nym_apis: None, - nyxd_urls: run_config.common_args.nyxd_urls, - enabled_credentials_mode: run_config.common_args.enabled_credentials_mode, - } - } -} - -pub(crate) async fn execute(args: &Run) -> Result<(), AuthenticatorError> { - let mut config = try_load_current_config(&args.common_args.id).await?; - config = override_config(config, OverrideConfig::from(args.clone())); - log::debug!("Using config: {config:#?}"); - - log::info!("Starting authenticator service provider"); - let (wireguard_gateway_data, peer_rx) = WireguardGatewayData::new( - config.authenticator.clone().into(), - Arc::new(KeyPair::new(&mut OsRng)), - ); - let task_handler = TaskHandle::default(); - let handler = DummyHandler::new(peer_rx, task_handler.fork("peer_handler")); - tokio::spawn(async move { - handler.run().await; - }); - - let mut server = nym_authenticator::Authenticator::new(config, wireguard_gateway_data, vec![]); - if let Some(custom_mixnet) = &args.common_args.custom_mixnet { - server = server.with_stored_topology(custom_mixnet)? - } - - server.run_service_provider().await -} diff --git a/service-providers/authenticator/src/cli/sign.rs b/service-providers/authenticator/src/cli/sign.rs deleted file mode 100644 index 30bd8ed1d1..0000000000 --- a/service-providers/authenticator/src/cli/sign.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::try_load_current_config; -use clap::Args; -use nym_authenticator::error::AuthenticatorError; -use nym_bin_common::output_format::OutputFormat; -use nym_client_core::client::key_manager::persistence::OnDiskKeys; -use nym_client_core::error::ClientCoreError; -use nym_crypto::asymmetric::ed25519; -use nym_types::helpers::ConsoleSigningOutput; - -#[derive(Args, Clone)] -pub(crate) struct Sign { - /// The id of the mixnode you want to sign with - #[arg(long)] - id: String, - - /// Signs a transaction-specific payload, that is going to be sent to the smart contract, with your identity key - #[arg(long)] - contract_msg: String, - - #[arg(short, long, default_value_t = OutputFormat::default())] - output: OutputFormat, -} - -fn print_signed_contract_msg( - private_key: &ed25519::PrivateKey, - raw_msg: &str, - output: OutputFormat, -) { - let trimmed = raw_msg.trim(); - eprintln!(">>> attempting to sign {trimmed}"); - - let Ok(decoded) = bs58::decode(trimmed).into_vec() else { - println!("it seems you have incorrectly copied the message to sign. Make sure you didn't accidentally skip any characters"); - return; - }; - - eprintln!(">>> decoding the message..."); - - // we don't really care about what particular information is embedded inside of it, - // we just want to know if user correctly copied the string, i.e. whether it's a valid bs58 encoded json - if serde_json::from_slice::(&decoded).is_err() { - println!("it seems you have incorrectly copied the message to sign. Make sure you didn't accidentally skip any characters"); - return; - }; - - // if this is a valid json, it MUST be a valid string - let decoded_string = String::from_utf8(decoded.clone()).unwrap(); - let signature = private_key.sign(&decoded).to_base58_string(); - - let sign_output = ConsoleSigningOutput::new(decoded_string, signature); - println!("{}", output.format(&sign_output)); -} - -pub(crate) async fn execute(args: &Sign) -> Result<(), AuthenticatorError> { - let config = try_load_current_config(&args.id).await?; - - let key_store = OnDiskKeys::new(config.storage_paths.common_paths.keys); - let identity_keypair = key_store.load_identity_keypair().map_err(|source| { - AuthenticatorError::ClientCoreError(ClientCoreError::KeyStoreError { - source: Box::new(source), - }) - })?; - - print_signed_contract_msg( - identity_keypair.private_key(), - &args.contract_msg, - args.output, - ); - - Ok(()) -} diff --git a/service-providers/authenticator/src/cli/switch_gateway.rs b/service-providers/authenticator/src/cli/switch_gateway.rs deleted file mode 100644 index 24ce8d48e2..0000000000 --- a/service-providers/authenticator/src/cli/switch_gateway.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -use crate::cli::CliAuthenticatorClient; -use nym_authenticator::error::AuthenticatorError; -use nym_client_core::cli_helpers::client_switch_gateway::{ - switch_gateway, CommonClientSwitchGatewaysArgs, -}; - -#[derive(clap::Args, Clone, Debug)] -pub struct Args { - #[command(flatten)] - common_args: CommonClientSwitchGatewaysArgs, -} - -impl AsRef for Args { - fn as_ref(&self) -> &CommonClientSwitchGatewaysArgs { - &self.common_args - } -} - -pub(crate) async fn execute(args: Args) -> Result<(), AuthenticatorError> { - switch_gateway::(args).await -} diff --git a/service-providers/authenticator/src/error.rs b/service-providers/authenticator/src/error.rs index d6672a4076..7774fc1e48 100644 --- a/service-providers/authenticator/src/error.rs +++ b/service-providers/authenticator/src/error.rs @@ -17,6 +17,9 @@ pub enum AuthenticatorError { #[error("{0}")] CredentialVerificationError(#[from] nym_credential_verification::Error), + #[error("invalid credential type")] + InvalidCredentialType, + #[error("the entity wrapping the network requester has disconnected")] DisconnectedParent, @@ -77,13 +80,7 @@ pub enum AuthenticatorError { #[error("peers can't be interacted with anymore")] PeerInteractionStopped, - #[error("operation is not supported")] - UnsupportedOperation, - - #[error("operation unavailable for older client")] - OldClient, - - #[error("storage should have the requested bandwidht entry")] + #[error("storage should have the requested bandwidth entry")] MissingClientBandwidthEntry, #[error("unknown version number")] @@ -103,6 +100,9 @@ pub enum AuthenticatorError { #[error("{0}")] RecipientFormatting(#[from] nym_sdk::mixnet::RecipientFormattingError), + + #[error("no credential received")] + NoCredentialReceived, } pub type Result = std::result::Result; diff --git a/service-providers/authenticator/src/main.rs b/service-providers/authenticator/src/main.rs deleted file mode 100644 index 0883e64a99..0000000000 --- a/service-providers/authenticator/src/main.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2024 - Nym Technologies SA -// SPDX-License-Identifier: Apache-2.0 - -mod cli; - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - use clap::Parser; - - let args = cli::Cli::parse(); - nym_bin_common::logging::setup_tracing_logger(); - nym_network_defaults::setup_env(args.config_env_file.as_ref()); - - if !args.no_banner { - nym_bin_common::logging::maybe_print_banner(clap::crate_name!(), clap::crate_version!()); - } - - cli::execute(args).await?; - Ok(()) -} diff --git a/service-providers/authenticator/src/mixnet_listener.rs b/service-providers/authenticator/src/mixnet_listener.rs index b28df22982..b8a7221d2e 100644 --- a/service-providers/authenticator/src/mixnet_listener.rs +++ b/service-providers/authenticator/src/mixnet_listener.rs @@ -23,13 +23,15 @@ use nym_authenticator_requests::{ }, v1, v2, v3, v4, v5, CURRENT_VERSION, }; +use nym_credential_verification::ecash::traits::EcashManager; use nym_credential_verification::{ - bandwidth_storage_manager::BandwidthStorageManager, ecash::EcashManager, - BandwidthFlushingBehaviourConfig, ClientBandwidth, CredentialVerifier, + bandwidth_storage_manager::BandwidthStorageManager, BandwidthFlushingBehaviourConfig, + ClientBandwidth, CredentialVerifier, }; -use nym_credentials_interface::CredentialSpendingData; +use nym_credentials_interface::{CredentialSpendingData, TicketType}; use nym_crypto::asymmetric::x25519::KeyPair; use nym_gateway_requests::models::CredentialSpendingRequest; +use nym_gateway_storage::models::PersistedBandwidth; use nym_sdk::mixnet::{ AnonymousSenderTag, InputMessage, MixnetMessageSender, Recipient, TransmissionLane, }; @@ -74,7 +76,7 @@ pub(crate) struct MixnetListener { pub(crate) peer_manager: PeerManager, - pub(crate) ecash_verifier: Option>, + pub(crate) ecash_verifier: Arc, pub(crate) timeout_check_interval: IntervalStream, @@ -88,7 +90,7 @@ impl MixnetListener { wireguard_gateway_data: WireguardGatewayData, mixnet_client: nym_sdk::mixnet::MixnetClient, task_handle: TaskHandle, - ecash_verifier: Option>, + ecash_verifier: Arc, ) -> Self { let timeout_check_interval = IntervalStream::new(tokio::time::interval(DEFAULT_REGISTRATION_TIMEOUT_CHECK)); @@ -500,38 +502,37 @@ impl MixnetListener { 128, )); - // If gateway does ecash verification and client sends a credential, we do the additional - // credential verification. Later this will become mandatory. - if let (Some(ecash_verifier), Some(credential)) = - (self.ecash_verifier.clone(), final_message.credential()) + let Some(credential) = final_message.credential() else { + return Err(AuthenticatorError::NoCredentialReceived); + }; + let client_id = self + .ecash_verifier + .storage() + .insert_wireguard_peer( + &peer, + TicketType::try_from_encoded(credential.payment.t_type) + .map_err(|_| AuthenticatorError::InvalidCredentialType)? + .into(), + ) + .await?; + if let Err(e) = + credential_verification(self.ecash_verifier.clone(), credential, client_id).await { - let client_id = ecash_verifier + self.ecash_verifier .storage() - .insert_wireguard_peer(&peer, true) - .await? - .ok_or(AuthenticatorError::InternalError( - "peer with ticket shouldn't have been used before without a ticket".to_string(), - ))?; - if let Err(e) = - Self::credential_verification(ecash_verifier.clone(), credential, client_id).await - { - ecash_verifier - .storage() - .remove_wireguard_peer(&peer.public_key.to_string()) - .await?; - return Err(e); - } - let public_key = peer.public_key.to_string(); - if let Err(e) = self.peer_manager.add_peer(peer, Some(client_id)).await { - ecash_verifier - .storage() - .remove_wireguard_peer(&public_key) - .await?; - return Err(e); - } - } else { - self.peer_manager.add_peer(peer, None).await?; + .remove_wireguard_peer(&peer.public_key.to_string()) + .await?; + return Err(e); } + let public_key = peer.public_key.to_string(); + if let Err(e) = self.peer_manager.add_peer(peer).await { + self.ecash_verifier + .storage() + .remove_wireguard_peer(&public_key) + .await?; + return Err(e); + } + registred_and_free .registration_in_progres .remove(&final_message.pub_key()); @@ -596,37 +597,6 @@ impl MixnetListener { Ok((bytes, reply_to)) } - async fn credential_verification( - ecash_verifier: Arc, - credential: CredentialSpendingData, - client_id: i64, - ) -> Result { - ecash_verifier - .storage() - .create_bandwidth_entry(client_id) - .await?; - let bandwidth = ecash_verifier - .storage() - .get_available_bandwidth(client_id) - .await? - .ok_or(AuthenticatorError::InternalError( - "bandwidth entry should have just been created".to_string(), - ))?; - let client_bandwidth = ClientBandwidth::new(bandwidth.into()); - let mut verifier = CredentialVerifier::new( - CredentialSpendingRequest::new(credential), - ecash_verifier.clone(), - BandwidthStorageManager::new( - ecash_verifier.storage().clone(), - client_bandwidth, - client_id, - BandwidthFlushingBehaviourConfig::default(), - true, - ), - ); - Ok(verifier.verify().await?) - } - async fn on_query_bandwidth_request( &mut self, msg: Box, @@ -634,12 +604,12 @@ impl MixnetListener { request_id: u64, reply_to: Option, ) -> AuthenticatorHandleResult { - let bandwidth_data = self.peer_manager.query_bandwidth(msg).await?; + let bandwidth_data = self.peer_manager.query_bandwidth(msg.pub_key()).await?; let bytes = match AuthenticatorVersion::from(protocol) { AuthenticatorVersion::V1 => { v1::response::AuthenticatorResponse::new_remaining_bandwidth( bandwidth_data.map(|data| v1::registration::RemainingBandwidthData { - available_bandwidth: data.available_bandwidth as u64, + available_bandwidth: data as u64, suspended: false, }), reply_to.ok_or(AuthenticatorError::MissingReplyToForOldClient)?, @@ -652,8 +622,10 @@ impl MixnetListener { } AuthenticatorVersion::V2 => { v2::response::AuthenticatorResponse::new_remaining_bandwidth( - bandwidth_data.map(|data| v2::registration::RemainingBandwidthData { - available_bandwidth: data.available_bandwidth, + bandwidth_data.map(|available_bandwidth| { + v2::registration::RemainingBandwidthData { + available_bandwidth, + } }), reply_to.ok_or(AuthenticatorError::MissingReplyToForOldClient)?, request_id, @@ -665,8 +637,10 @@ impl MixnetListener { } AuthenticatorVersion::V3 => { v3::response::AuthenticatorResponse::new_remaining_bandwidth( - bandwidth_data.map(|data| v3::registration::RemainingBandwidthData { - available_bandwidth: data.available_bandwidth, + bandwidth_data.map(|available_bandwidth| { + v3::registration::RemainingBandwidthData { + available_bandwidth, + } }), reply_to.ok_or(AuthenticatorError::MissingReplyToForOldClient)?, request_id, @@ -678,8 +652,10 @@ impl MixnetListener { } AuthenticatorVersion::V4 => { v4::response::AuthenticatorResponse::new_remaining_bandwidth( - bandwidth_data.map(|data| v4::registration::RemainingBandwidthData { - available_bandwidth: data.available_bandwidth, + bandwidth_data.map(|available_bandwidth| { + v4::registration::RemainingBandwidthData { + available_bandwidth, + } }), reply_to.ok_or(AuthenticatorError::MissingReplyToForOldClient)?, request_id, @@ -691,8 +667,10 @@ impl MixnetListener { } AuthenticatorVersion::V5 => { v5::response::AuthenticatorResponse::new_remaining_bandwidth( - bandwidth_data.map(|data| v5::registration::RemainingBandwidthData { - available_bandwidth: data.available_bandwidth, + bandwidth_data.map(|available_bandwidth| { + v5::registration::RemainingBandwidthData { + available_bandwidth, + } }), request_id, ) @@ -713,17 +691,13 @@ impl MixnetListener { request_id: u64, reply_to: Option, ) -> AuthenticatorHandleResult { - let Some(ecash_verifier) = self.ecash_verifier.clone() else { - return Err(AuthenticatorError::UnsupportedOperation); - }; - - let client_id = ecash_verifier + let client_id = self + .ecash_verifier .storage() .get_wireguard_peer(&msg.pub_key().to_string()) .await? .ok_or(AuthenticatorError::MissingClientBandwidthEntry)? - .client_id - .ok_or(AuthenticatorError::OldClient)?; + .client_id; let client_bandwidth = self .peer_manager .query_client_bandwidth(msg.pub_key()) @@ -737,9 +711,9 @@ impl MixnetListener { let credential = msg.credential(); let mut verifier = CredentialVerifier::new( CredentialSpendingRequest::new(credential.clone()), - ecash_verifier.clone(), + self.ecash_verifier.clone(), BandwidthStorageManager::new( - ecash_verifier.storage().clone(), + self.ecash_verifier.storage(), client_bandwidth, client_id, BandwidthFlushingBehaviourConfig::default(), @@ -907,6 +881,45 @@ impl MixnetListener { } } +pub async fn credential_storage_preparation( + ecash_verifier: Arc, + client_id: i64, +) -> Result { + ecash_verifier + .storage() + .create_bandwidth_entry(client_id) + .await?; + let bandwidth = ecash_verifier + .storage() + .get_available_bandwidth(client_id) + .await? + .ok_or(AuthenticatorError::InternalError( + "bandwidth entry should have just been created".to_string(), + ))?; + Ok(bandwidth) +} + +async fn credential_verification( + ecash_verifier: Arc, + credential: CredentialSpendingData, + client_id: i64, +) -> Result { + let bandwidth = credential_storage_preparation(ecash_verifier.clone(), client_id).await?; + let client_bandwidth = ClientBandwidth::new(bandwidth.into()); + let mut verifier = CredentialVerifier::new( + CredentialSpendingRequest::new(credential), + ecash_verifier.clone(), + BandwidthStorageManager::new( + ecash_verifier.storage(), + client_bandwidth, + client_id, + BandwidthFlushingBehaviourConfig::default(), + true, + ), + ); + Ok(verifier.verify().await?) +} + fn deserialize_request(reconstructed: &ReconstructedMessage) -> Result { let request_version = *reconstructed .message diff --git a/service-providers/authenticator/src/peer_manager.rs b/service-providers/authenticator/src/peer_manager.rs index 2cb5ac137b..3d4c86a95d 100644 --- a/service-providers/authenticator/src/peer_manager.rs +++ b/service-providers/authenticator/src/peer_manager.rs @@ -4,15 +4,11 @@ use crate::error::*; use defguard_wireguard_rs::{host::Peer, key::Key}; use futures::channel::oneshot; -use nym_authenticator_requests::{ - latest::registration::{GatewayClient, RemainingBandwidthData}, - traits::QueryBandwidthMessage, -}; use nym_credential_verification::ClientBandwidth; use nym_wireguard::{ peer_controller::{ AddPeerControlResponse, GetClientBandwidthControlResponse, PeerControlRequest, - QueryBandwidthControlResponse, QueryPeerControlResponse, RemovePeerControlResponse, + QueryPeerControlResponse, RemovePeerControlResponse, }, WireguardGatewayData, }; @@ -28,13 +24,9 @@ impl PeerManager { wireguard_gateway_data, } } - pub async fn add_peer(&mut self, peer: Peer, client_id: Option) -> Result<()> { + pub async fn add_peer(&mut self, peer: Peer) -> Result<()> { let (response_tx, response_rx) = oneshot::channel(); - let msg = PeerControlRequest::AddPeer { - peer, - client_id, - response_tx, - }; + let msg = PeerControlRequest::AddPeer { peer, response_tx }; self.wireguard_gateway_data .peer_tx() .send(msg) @@ -52,8 +44,8 @@ impl PeerManager { Ok(()) } - pub async fn _remove_peer(&mut self, client: &GatewayClient) -> Result<()> { - let key = Key::new(client.pub_key().to_bytes()); + pub async fn _remove_peer(&mut self, pub_key: PeerPublicKey) -> Result<()> { + let key = Key::new(pub_key.to_bytes()); let (response_tx, response_rx) = oneshot::channel(); let msg = PeerControlRequest::RemovePeer { key, response_tx }; self.wireguard_gateway_data @@ -63,7 +55,7 @@ impl PeerManager { .map_err(|_| AuthenticatorError::PeerInteractionStopped)?; let RemovePeerControlResponse { success } = response_rx.await.map_err(|_| { - AuthenticatorError::InternalError("no response for add peer".to_string()) + AuthenticatorError::InternalError("no response for remove peer".to_string()) })?; if !success { return Err(AuthenticatorError::InternalError( @@ -94,31 +86,13 @@ impl PeerManager { Ok(peer) } - pub async fn query_bandwidth( - &mut self, - msg: Box, - ) -> Result> { - let key = Key::new(msg.pub_key().to_bytes()); - let (response_tx, response_rx) = oneshot::channel(); - let msg = PeerControlRequest::QueryBandwidth { key, response_tx }; - self.wireguard_gateway_data - .peer_tx() - .send(msg) - .await - .map_err(|_| AuthenticatorError::PeerInteractionStopped)?; - - let QueryBandwidthControlResponse { - success, - bandwidth_data, - } = response_rx.await.map_err(|_| { - AuthenticatorError::InternalError("no response for query bandwidth".to_string()) - })?; - if !success { - return Err(AuthenticatorError::InternalError( - "querying bandwidth could not be performed".to_string(), - )); - } - Ok(bandwidth_data) + pub async fn query_bandwidth(&mut self, public_key: PeerPublicKey) -> Result> { + let res = if let Some(client_bandwidth) = self.query_client_bandwidth(public_key).await? { + Some(client_bandwidth.available().await) + } else { + None + }; + Ok(res) } pub async fn query_client_bandwidth( @@ -143,3 +117,243 @@ impl PeerManager { Ok(client_bandwidth) } } + +#[cfg(test)] +mod tests { + use std::{str::FromStr, sync::Arc}; + + use nym_credential_verification::{ + bandwidth_storage_manager::BandwidthStorageManager, ecash::MockEcashManager, + }; + use nym_credentials_interface::Bandwidth; + use nym_crypto::asymmetric::x25519::KeyPair; + use nym_gateway_storage::traits::{mock::MockGatewayStorage, BandwidthGatewayStorage}; + use nym_wireguard::peer_controller::{start_controller, stop_controller}; + use rand::rngs::OsRng; + use time::{Duration, OffsetDateTime}; + use tokio::sync::RwLock; + + use crate::{config::Authenticator, mixnet_listener::credential_storage_preparation}; + + use super::*; + + #[tokio::test] + async fn add_peer() { + let (wireguard_data, request_rx) = WireguardGatewayData::new( + Authenticator::default().into(), + Arc::new(KeyPair::new(&mut OsRng)), + ); + let mut peer_manager = PeerManager::new(wireguard_data); + let (storage, task_manager) = start_controller( + peer_manager.wireguard_gateway_data.peer_tx().clone(), + request_rx, + ); + let peer = Peer::default(); + let ecash_manager = MockEcashManager::new(Box::new(storage.clone())); + + assert!(peer_manager.add_peer(peer.clone()).await.is_err()); + + let client_id = storage + .insert_wireguard_peer(&peer, FromStr::from_str("entry_wireguard").unwrap()) + .await + .unwrap(); + assert!(peer_manager.add_peer(peer.clone()).await.is_err()); + + credential_storage_preparation(Arc::new(ecash_manager), client_id) + .await + .unwrap(); + peer_manager.add_peer(peer.clone()).await.unwrap(); + + stop_controller(task_manager).await; + } + + async fn helper_add_peer( + storage: &Arc>, + peer_manager: &mut PeerManager, + ) -> i64 { + let peer = Peer::default(); + let ecash_manager = MockEcashManager::new(Box::new(storage.clone())); + let client_id = storage + .insert_wireguard_peer(&peer, FromStr::from_str("entry_wireguard").unwrap()) + .await + .unwrap(); + credential_storage_preparation(Arc::new(ecash_manager), client_id) + .await + .unwrap(); + peer_manager.add_peer(peer.clone()).await.unwrap(); + + client_id + } + + #[tokio::test] + async fn remove_peer() { + let (wireguard_data, request_rx) = WireguardGatewayData::new( + Authenticator::default().into(), + Arc::new(KeyPair::new(&mut OsRng)), + ); + let mut peer_manager = PeerManager::new(wireguard_data); + let key = Key::default(); + let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap(); + let (storage, task_manager) = start_controller( + peer_manager.wireguard_gateway_data.peer_tx().clone(), + request_rx, + ); + + helper_add_peer(&storage, &mut peer_manager).await; + peer_manager._remove_peer(public_key).await.unwrap(); + + stop_controller(task_manager).await; + } + + #[tokio::test] + async fn query_peer() { + let (wireguard_data, request_rx) = WireguardGatewayData::new( + Authenticator::default().into(), + Arc::new(KeyPair::new(&mut OsRng)), + ); + let mut peer_manager = PeerManager::new(wireguard_data); + let key = Key::default(); + let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap(); + let (storage, task_manager) = start_controller( + peer_manager.wireguard_gateway_data.peer_tx().clone(), + request_rx, + ); + + assert!(peer_manager.query_peer(public_key).await.unwrap().is_none()); + + helper_add_peer(&storage, &mut peer_manager).await; + let peer = peer_manager.query_peer(public_key).await.unwrap().unwrap(); + assert_eq!(peer.public_key, key); + + stop_controller(task_manager).await; + } + + #[tokio::test] + async fn query_bandwidth() { + let (wireguard_data, request_rx) = WireguardGatewayData::new( + Authenticator::default().into(), + Arc::new(KeyPair::new(&mut OsRng)), + ); + let mut peer_manager = PeerManager::new(wireguard_data); + let key = Key::default(); + let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap(); + let (storage, task_manager) = start_controller( + peer_manager.wireguard_gateway_data.peer_tx().clone(), + request_rx, + ); + + assert!(peer_manager + .query_bandwidth(public_key) + .await + .unwrap() + .is_none()); + + helper_add_peer(&storage, &mut peer_manager).await; + let available_bandwidth = peer_manager + .query_bandwidth(public_key) + .await + .unwrap() + .unwrap(); + assert_eq!(available_bandwidth, 0); + + stop_controller(task_manager).await; + } + + #[tokio::test] + async fn query_client_bandwidth() { + let (wireguard_data, request_rx) = WireguardGatewayData::new( + Authenticator::default().into(), + Arc::new(KeyPair::new(&mut OsRng)), + ); + let mut peer_manager = PeerManager::new(wireguard_data); + let key = Key::default(); + let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap(); + let (storage, task_manager) = start_controller( + peer_manager.wireguard_gateway_data.peer_tx().clone(), + request_rx, + ); + + assert!(peer_manager + .query_client_bandwidth(public_key) + .await + .unwrap() + .is_none()); + + helper_add_peer(&storage, &mut peer_manager).await; + let available_bandwidth = peer_manager + .query_client_bandwidth(public_key) + .await + .unwrap() + .unwrap() + .available() + .await; + assert_eq!(available_bandwidth, 0); + + stop_controller(task_manager).await; + } + + #[tokio::test] + async fn increase_decrease_bandwidth() { + let (wireguard_data, request_rx) = WireguardGatewayData::new( + Authenticator::default().into(), + Arc::new(KeyPair::new(&mut OsRng)), + ); + let mut peer_manager = PeerManager::new(wireguard_data); + let key = Key::default(); + let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap(); + let top_up = 42; + let consume = 4; + let (storage, task_manager) = start_controller( + peer_manager.wireguard_gateway_data.peer_tx().clone(), + request_rx, + ); + + let client_id = helper_add_peer(&storage, &mut peer_manager).await; + let client_bandwidth = peer_manager + .query_client_bandwidth(public_key) + .await + .unwrap() + .unwrap(); + + let mut bw_manager = BandwidthStorageManager::new( + Box::new(storage), + client_bandwidth.clone(), + client_id, + Default::default(), + true, + ); + bw_manager + .increase_bandwidth( + Bandwidth::new_unchecked(top_up as u64), + OffsetDateTime::now_utc() + .checked_add(Duration::minutes(1)) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(client_bandwidth.available().await, top_up); + assert_eq!( + peer_manager + .query_bandwidth(public_key) + .await + .unwrap() + .unwrap(), + top_up + ); + + bw_manager.try_use_bandwidth(consume).await.unwrap(); + let remaining = top_up - consume; + assert_eq!(client_bandwidth.available().await, remaining); + assert_eq!( + peer_manager + .query_bandwidth(public_key) + .await + .unwrap() + .unwrap(), + remaining + ); + + stop_controller(task_manager).await; + } +} diff --git a/tools/internal/testnet-manager/src/manager/dkg_skip.rs b/tools/internal/testnet-manager/src/manager/dkg_skip.rs index ea33af03fb..9f87a468fa 100644 --- a/tools/internal/testnet-manager/src/manager/dkg_skip.rs +++ b/tools/internal/testnet-manager/src/manager/dkg_skip.rs @@ -412,10 +412,10 @@ impl NetworkManager { let mut receivers = Vec::new(); for signer in &ctx.ecash_signers { - // send 101nym to the admin + // send 250nym to the admin receivers.push(( signer.data.cosmos_account.address.clone(), - admin.mix_coins(101_000000), + admin.mix_coins(250_000000), )) }