Compare commits

..

5 Commits

Author SHA1 Message Date
benedetta davico 8dbcd7d07c TEMP gh runner fix 2024-12-03 10:28:27 +01:00
Bogdan-Ștefan Neacşu 60c21a8d1d Fix backwards compat mac generation (#5202) 2024-12-02 19:52:59 +02:00
Jędrzej Stuczyński feefde9022 Bugfix/credential proxy sequencing (#5187)
* using common middleware for all http servers

* improved span handling in credential-proxy

* ensure increase in sequence number upon making deposit

* added explicit connect options for the db

* fixed further instances of incorrect span instrumentation

* batch deposit requests together to improve concurrency

* ignore cancelled requests

* updated credential proxy version to 0.1.4

* adjusted Dockerfile with new binary location

* log binary version on startup

* reduce default log level

* guard against unavaiable commit sha

* apply review comments: dont exit(0), instead just shutdown normally

* add skip_webhook parameter to obtain-async

* removing dead code
2024-12-02 14:52:35 +00:00
benedetta davico 645be5fa22 Update ci-build-upload-binaries.yml 2024-12-02 14:03:44 +01:00
benedetta davico ac56717b23 Update ci-build-upload-binaries.yml 2024-12-02 13:48:05 +01:00
164 changed files with 1829 additions and 2667 deletions
@@ -21,7 +21,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ arc-ubuntu-20.04 ]
platform: [ arc-ubuntu-22.04 ]
runs-on: ${{ matrix.platform }}
env:
@@ -8,7 +8,7 @@ on:
description: Which gateway probe git ref to build the image with
env:
WORKING_DIRECTORY: "nym-node-status-api/nym-node-status-agent"
WORKING_DIRECTORY: "nym-node-status-agent"
CONTAINER_NAME: "node-status-agent"
jobs:
@@ -58,4 +58,4 @@ jobs:
- name: BuildAndPushImageOnHarbor
run: |
docker build --build-arg GIT_REF=${{ github.event.inputs.gateway_probe_git_ref }} -f ${{ env.WORKING_DIRECTORY }}/Dockerfile . -t harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }}:${{ steps.get_version.outputs.result }}-${{ steps.cleanup_gateway_probe_ref.outputs.git_ref }}
docker push harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }} --all-tags
docker push harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }} --all-tags
+1 -1
View File
@@ -3,7 +3,7 @@ on:
workflow_dispatch:
env:
WORKING_DIRECTORY: "nym-node-status-api/nym-node-status-api"
WORKING_DIRECTORY: "nym-node-status-api"
CONTAINER_NAME: "node-status-api"
jobs:
@@ -29,7 +29,7 @@ jobs:
uses: mikefarah/yq@v4.44.5
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/nym-credential-proxy/Cargo.toml
- name: Remove existing tag if exists
run: |
Generated
+27 -27
View File
@@ -4752,14 +4752,12 @@ dependencies = [
"nym-coconut-dkg-common",
"nym-config",
"nym-contracts-common",
"nym-credential-proxy-requests",
"nym-credential-storage",
"nym-credential-utils",
"nym-credentials",
"nym-credentials-interface",
"nym-crypto",
"nym-ecash-contract-common",
"nym-ecash-time",
"nym-id",
"nym-mixnet-contract-common",
"nym-multisig-contract-common",
@@ -5009,6 +5007,16 @@ dependencies = [
"nym-multisig-contract-common",
]
[[package]]
name = "nym-common-models"
version = "0.1.0"
dependencies = [
"anyhow",
"bincode",
"nym-crypto",
"serde",
]
[[package]]
name = "nym-compact-ecash"
version = "0.1.0"
@@ -5085,7 +5093,7 @@ dependencies = [
[[package]]
name = "nym-credential-proxy"
version = "0.1.3"
version = "0.1.6"
dependencies = [
"anyhow",
"async-trait",
@@ -5105,6 +5113,7 @@ dependencies = [
"nym-credentials",
"nym-credentials-interface",
"nym-crypto",
"nym-ecash-contract-common",
"nym-http-api-common",
"nym-network-defaults",
"nym-validator-client",
@@ -5536,7 +5545,6 @@ version = "0.1.0"
dependencies = [
"nym-credentials-interface",
"nym-sphinx",
"nym-statistics-common",
"sqlx",
"thiserror",
"time",
@@ -5613,12 +5621,15 @@ dependencies = [
"axum-client-ip",
"bytes",
"colored",
"futures",
"mime",
"serde",
"serde_json",
"serde_yaml",
"tower 0.4.13",
"tracing",
"utoipa",
"zeroize",
]
[[package]]
@@ -6049,23 +6060,30 @@ name = "nym-node-status-agent"
version = "1.0.0-rc.1"
dependencies = [
"anyhow",
"bincode",
"chrono",
"clap 4.5.20",
"nym-bin-common",
"nym-common-models",
"nym-crypto",
"nym-node-status-client",
"rand",
"reqwest 0.12.4",
"serde",
"serde_json",
"tempfile",
"tokio",
"tokio-util",
"tracing",
"tracing-subscriber",
]
[[package]]
name = "nym-node-status-api"
version = "1.0.0-rc.4"
version = "1.0.0-rc.2"
dependencies = [
"anyhow",
"axum 0.7.7",
"bincode",
"chrono",
"clap 4.5.20",
"cosmwasm-std",
@@ -6073,13 +6091,11 @@ dependencies = [
"futures-util",
"moka",
"nym-bin-common",
"nym-common-models",
"nym-crypto",
"nym-explorer-client",
"nym-network-defaults",
"nym-node-requests",
"nym-node-status-client",
"nym-serde-helpers",
"nym-statistics-common",
"nym-task",
"nym-validator-client",
"regex",
@@ -6091,7 +6107,6 @@ dependencies = [
"strum 0.26.3",
"strum_macros 0.26.4",
"thiserror",
"time",
"tokio",
"tokio-util",
"tower-http",
@@ -6103,21 +6118,6 @@ dependencies = [
"utoipauto",
]
[[package]]
name = "nym-node-status-client"
version = "0.1.0"
dependencies = [
"anyhow",
"bincode",
"chrono",
"nym-crypto",
"nym-http-api-client",
"reqwest 0.12.4",
"serde",
"serde_json",
"tracing",
]
[[package]]
name = "nym-node-tester-utils"
version = "0.1.0"
@@ -7024,9 +7024,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
version = "0.9.104"
version = "0.9.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45abf306cbf99debc8195b66b7346498d7b10c210de50418b5ccd7ceba08c741"
checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2"
dependencies = [
"cc",
"libc",
+6 -5
View File
@@ -61,6 +61,7 @@ members = [
"common/ip-packet-requests",
"common/ledger",
"common/mixnode-common",
"common/models",
"common/network-defaults",
"common/node-tester-utils",
"common/nonexhaustive-delayqueue",
@@ -125,9 +126,8 @@ members = [
"nym-node",
"nym-node/nym-node-http-api",
"nym-node/nym-node-requests",
"nym-node-status-api/nym-node-status-agent",
"nym-node-status-api/nym-node-status-api",
"nym-node-status-api/nym-node-status-client",
"nym-node-status-api",
"nym-node-status-agent",
"nym-outfox",
"nym-validator-rewarder",
"tools/echo-server",
@@ -155,6 +155,7 @@ members = [
default-members = [
"clients/native",
"clients/socks5",
"common/models",
"explorer-api",
"gateway",
"mixnode",
@@ -162,9 +163,9 @@ default-members = [
"nym-credential-proxy/nym-credential-proxy",
"nym-data-observatory",
"nym-node",
"nym-node-status-api/nym-node-status-agent",
"nym-node-status-api/nym-node-status-api",
"nym-node-status-api",
"nym-validator-rewarder",
"nym-node-status-api",
"service-providers/authenticator",
"service-providers/ip-packet-router",
"service-providers/network-requester",
@@ -17,7 +17,7 @@ use nym_validator_client::coconut::all_ecash_api_clients;
use nym_validator_client::nym_api::EpochId;
use nym_validator_client::nyxd::contract_traits::EcashSigningClient;
use nym_validator_client::nyxd::contract_traits::{DkgQueryClient, EcashQueryClient};
use nym_validator_client::nyxd::cosmwasm_client::ToSingletonContractData;
use nym_validator_client::nyxd::cosmwasm_client::ContractResponseData;
use nym_validator_client::EcashApiClient;
use rand::rngs::OsRng;
@@ -13,6 +13,44 @@ use tracing::error;
pub use cosmrs::abci::MsgResponse;
pub fn parse_singleton_u32_from_contract_response(b: Vec<u8>) -> Result<u32, NyxdError> {
if b.len() != 4 {
return Err(NyxdError::MalformedResponseData {
got: b.len(),
expected: 4,
});
}
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
pub fn parse_singleton_u64_from_contract_response(b: Vec<u8>) -> Result<u64, NyxdError> {
if b.len() != 8 {
return Err(NyxdError::MalformedResponseData {
got: b.len(),
expected: 8,
});
}
Ok(u64::from_be_bytes([
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
]))
}
#[derive(Debug, Clone)]
pub struct ParsedContractResponse {
pub message_index: usize,
pub response: Vec<u8>,
}
impl ParsedContractResponse {
pub fn parse_singleton_u32_contract_data(self) -> Result<u32, NyxdError> {
parse_singleton_u32_from_contract_response(self.response)
}
pub fn parse_singleton_u64_contract_data(self) -> Result<u64, NyxdError> {
parse_singleton_u64_from_contract_response(self.response)
}
}
pub fn parse_msg_responses(data: Bytes) -> Vec<MsgResponse> {
// it seems that currently, on wasmd 0.43 + tendermint-rs 0.37 + cosmrs 0.17.0-pre
// the data is left in undecoded base64 form, but I'd imagine this might change so if the decoding fails,
@@ -34,35 +72,25 @@ pub fn parse_msg_responses(data: Bytes) -> Vec<MsgResponse> {
}
// requires there's a single response message
pub trait ToSingletonContractData: Sized {
pub trait ContractResponseData: Sized {
fn parse_singleton_u32_contract_data(&self) -> Result<u32, NyxdError> {
let b = self.to_singleton_contract_data()?;
if b.len() != 4 {
return Err(NyxdError::MalformedResponseData {
got: b.len(),
expected: 4,
});
}
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
parse_singleton_u32_from_contract_response(b)
}
fn parse_singleton_u64_contract_data(&self) -> Result<u64, NyxdError> {
let b = self.to_singleton_contract_data()?;
if b.len() != 8 {
return Err(NyxdError::MalformedResponseData {
got: b.len(),
expected: 8,
});
}
Ok(u64::from_be_bytes([
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
]))
parse_singleton_u64_from_contract_response(b)
}
fn to_singleton_contract_data(&self) -> Result<Vec<u8>, NyxdError>;
fn to_unchecked_contract_data(&self) -> Result<Vec<Vec<u8>>, NyxdError>;
fn to_contract_data(&self) -> Result<Vec<ParsedContractResponse>, NyxdError>;
}
impl ToSingletonContractData for ExecuteResult {
impl ContractResponseData for ExecuteResult {
fn to_singleton_contract_data(&self) -> Result<Vec<u8>, NyxdError> {
if self.msg_responses.len() != 1 {
return Err(NyxdError::UnexpectedNumberOfMsgResponses {
@@ -72,6 +100,30 @@ impl ToSingletonContractData for ExecuteResult {
self.msg_responses[0].to_contract_response_data()
}
fn to_unchecked_contract_data(&self) -> Result<Vec<Vec<u8>>, NyxdError> {
self.msg_responses
.iter()
.map(ToContractResponseData::to_contract_response_data)
.collect()
}
fn to_contract_data(&self) -> Result<Vec<ParsedContractResponse>, NyxdError> {
let mut response = Vec::new();
for (message_index, msg) in self.msg_responses.iter().enumerate() {
// unfortunately `Name` trait has not been derived for `MsgExecuteContractResponse`,
// so we have to make an explicit string comparison instead
if msg.type_url == "/cosmwasm.wasm.v1.MsgExecuteContractResponse" {
response.push(ParsedContractResponse {
message_index,
response: msg.to_contract_response_data()?,
})
}
}
Ok(response)
}
}
pub trait ToContractResponseData: Sized {
@@ -23,7 +23,7 @@ use tendermint_rpc::endpoint::*;
use tendermint_rpc::query::Query;
use tendermint_rpc::{Error as TendermintRpcError, Order, Paging, SimpleRequest};
pub use helpers::{ToContractResponseData, ToSingletonContractData};
pub use helpers::{ContractResponseData, ToContractResponseData};
#[cfg(feature = "http-client")]
use crate::http_client;
-2
View File
@@ -48,7 +48,6 @@ nym-vesting-contract-common = { path = "../cosmwasm-smart-contracts/vesting-cont
nym-coconut-dkg-common = { path = "../cosmwasm-smart-contracts/coconut-dkg" }
nym-multisig-contract-common = { path = "../cosmwasm-smart-contracts/multisig-contract" }
nym-ecash-contract-common = { path = "../cosmwasm-smart-contracts/ecash-contract" }
nym-ecash-time = { path = "../../common/ecash-time" }
nym-sphinx = { path = "../../common/nymsphinx" }
nym-client-core = { path = "../../common/client-core" }
nym-config = { path = "../../common/config" }
@@ -57,7 +56,6 @@ nym-credentials-interface = { path = "../../common/credentials-interface" }
nym-credential-storage = { path = "../../common/credential-storage" }
nym-credential-utils = { path = "../../common/credential-utils" }
nym-id = { path = "../nym-id" }
nym-credential-proxy-requests = { path = "../../nym-credential-proxy/nym-credential-proxy-requests" }
nym-pemstore = { path = "../../common/pemstore", version = "0.3.0" }
nym-types = { path = "../../common/types" }
@@ -1,41 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use clap::Parser;
use log::trace;
use nym_credentials_interface::{generate_keypair_user, generate_keypair_user_from_seed, Base58};
use serde::{Deserialize, Serialize};
use std::io::stdout;
#[derive(Serialize, Deserialize)]
pub struct Bs58EncodedKeys {
pub secret_key: String,
pub public_key: String,
}
#[derive(Debug, Parser)]
pub struct Args {
/// Secret value that's used for deriving underlying ecash keypair
#[clap(long)]
pub(crate) bs58_encoded_client_secret: Option<String>,
}
pub fn generate_ecash_keypair(args: Args) -> anyhow::Result<()> {
trace!("args: {args:?}");
let keypair = if let Some(secret) = args.bs58_encoded_client_secret {
let seed = bs58::decode(&secret).into_vec()?;
generate_keypair_user_from_seed(&seed)
} else {
generate_keypair_user()
};
let encoded = Bs58EncodedKeys {
secret_key: keypair.secret_key().to_bs58(),
public_key: keypair.public_key().to_bs58(),
};
serde_json::to_writer_pretty(stdout(), &encoded)?;
Ok(())
}
-23
View File
@@ -1,23 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use clap::{Args, Subcommand};
pub mod generate_keypair;
pub mod withdrawal_request;
#[derive(Debug, Args)]
#[clap(args_conflicts_with_subcommands = true, subcommand_required = true)]
pub struct InternalEcash {
#[clap(subcommand)]
pub command: InternalEcashCommands,
}
#[derive(Debug, Subcommand)]
pub enum InternalEcashCommands {
/// Generate a dummy withdrawal request
GenerateWithdrawalRequest(withdrawal_request::Args),
/// Generate dummy ecash keypair
GenerateKeypair(generate_keypair::Args),
}
@@ -1,78 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use clap::Parser;
use log::trace;
use nym_credential_proxy_requests::api::v1::ticketbook::models::TicketbookRequest;
use nym_credentials_interface::{
generate_keypair_user, withdrawal_request, Base58, SecretKeyUser, TicketType,
};
use nym_ecash_time::{ecash_default_expiration_date, EcashTime};
use serde::{Deserialize, Serialize};
use std::io::stdout;
use time::macros::format_description;
use time::Date;
use zeroize::Zeroizing;
fn parse_date(raw: &str) -> Result<Date, time::error::Parse> {
let format = format_description!("[year]-[month]-[day]");
Date::parse(raw, &format)
}
#[derive(Serialize, Deserialize)]
pub struct Bs58EncodedOutput {
pub ecash_proxy_request: TicketbookRequest,
pub ecash_secret: String,
/// Needed to later unblind shares
pub ecash_request_info_bs58: String,
}
#[derive(Debug, Parser)]
pub struct Args {
/// Specify which type of ticketbook
#[clap(long, default_value_t = TicketType::V1MixnetEntry)]
pub(crate) ticketbook_type: TicketType,
/// Set expiration date for the ticketbook
#[clap(long, value_parser = parse_date, default_value_t = ecash_default_expiration_date())]
pub(crate) expiration_date: Date,
/// Provide ecash secret key (or generate a fresh one)
#[clap(long)]
pub(crate) ecash_secret_key_bs58: Option<String>,
}
pub async fn generate_withdrawal_request(args: Args) -> anyhow::Result<()> {
trace!("args: {args:?}");
let ecash_keypair = if let Some(secret_key) = args.ecash_secret_key_bs58 {
let secret_key = Zeroizing::new(bs58::decode(Zeroizing::new(secret_key)).into_vec()?);
let sk = SecretKeyUser::from_bytes(&secret_key)?;
sk.into()
} else {
generate_keypair_user()
};
let (withdrawal_request, request_info) = withdrawal_request(
ecash_keypair.secret_key(),
args.expiration_date.ecash_unix_timestamp(),
args.ticketbook_type.encode(),
)?;
let encoded = Bs58EncodedOutput {
ecash_proxy_request: TicketbookRequest {
withdrawal_request: withdrawal_request.into(),
ecash_pubkey: ecash_keypair.public_key(),
expiration_date: args.expiration_date,
ticketbook_type: args.ticketbook_type,
is_freepass_request: false,
},
ecash_secret: ecash_keypair.secret_key().to_bs58(),
ecash_request_info_bs58: request_info.to_bs58(),
};
serde_json::to_writer_pretty(stdout(), &encoded)?;
Ok(())
}
-19
View File
@@ -1,19 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use clap::{Args, Subcommand};
pub mod ecash;
#[derive(Debug, Args)]
#[clap(args_conflicts_with_subcommands = true, subcommand_required = true)]
pub struct Internal {
#[clap(subcommand)]
pub command: InternalCommands,
}
#[derive(Debug, Subcommand)]
pub enum InternalCommands {
/// Ecash related internal commands
Ecash(ecash::InternalEcash),
}
-1
View File
@@ -3,6 +3,5 @@
pub mod context;
pub mod ecash;
pub mod internal;
pub mod utils;
pub mod validator;
@@ -18,7 +18,7 @@ use nym_validator_client::nym_api::EpochId;
use nym_validator_client::nyxd::contract_traits::{
EcashSigningClient, MultisigQueryClient, MultisigSigningClient, PagedMultisigQueryClient,
};
use nym_validator_client::nyxd::cosmwasm_client::ToSingletonContractData;
use nym_validator_client::nyxd::cosmwasm_client::ContractResponseData;
use nym_validator_client::nyxd::cw3::Status;
use nym_validator_client::nyxd::AccountId;
use nym_validator_client::EcashApiClient;
-1
View File
@@ -22,7 +22,6 @@ tracing = { workspace = true }
nym-sphinx = { path = "../nymsphinx" }
nym-credentials-interface = { path = "../credentials-interface" }
nym-statistics-common = { path = "../statistics" }
[build-dependencies]
+1 -2
View File
@@ -2,9 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-only
use error::StatsStorageError;
use models::{ActiveSession, FinishedSession, StoredFinishedSession};
use models::{ActiveSession, FinishedSession, SessionType, StoredFinishedSession};
use nym_sphinx::DestinationAddressBytes;
use nym_statistics_common::gateways::SessionType;
use sessions::SessionManager;
use sqlx::ConnectOptions;
use std::path::Path;
+36 -1
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: GPL-3.0-only
use nym_credentials_interface::TicketType;
use nym_statistics_common::gateways::SessionType;
use sqlx::prelude::FromRow;
use time::{Duration, OffsetDateTime};
@@ -26,6 +25,42 @@ pub struct FinishedSession {
pub typ: SessionType,
}
#[derive(PartialEq)]
pub enum SessionType {
Vpn,
Mixnet,
Unknown,
}
impl SessionType {
pub fn to_string(&self) -> &str {
match self {
Self::Vpn => "vpn",
Self::Mixnet => "mixnet",
Self::Unknown => "unknown",
}
}
pub fn from_string(s: &str) -> Self {
match s {
"vpn" => Self::Vpn,
"mixnet" => Self::Mixnet,
_ => Self::Unknown,
}
}
}
impl From<TicketType> for SessionType {
fn from(value: TicketType) -> Self {
match value {
TicketType::V1MixnetEntry => Self::Mixnet,
TicketType::V1MixnetExit => Self::Mixnet,
TicketType::V1WireguardEntry => Self::Vpn,
TicketType::V1WireguardExit => Self::Vpn,
}
}
}
#[derive(FromRow)]
pub(crate) struct StoredActiveSession {
start_time: OffsetDateTime,
+3
View File
@@ -15,12 +15,15 @@ axum-client-ip.workspace = true
axum.workspace = true
bytes = { workspace = true }
colored.workspace = true
futures = { workspace = true }
mime = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
serde_yaml = { workspace = true }
tower = { workspace = true }
tracing.workspace = true
utoipa = { workspace = true, optional = true }
zeroize = { workspace = true }
[features]
utoipa = ["dep:utoipa"]
+1 -1
View File
@@ -7,7 +7,7 @@ use axum::Json;
use bytes::{BufMut, BytesMut};
use serde::{Deserialize, Serialize};
pub mod logging;
pub mod middleware;
#[derive(Debug, Clone)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
@@ -1,5 +1,5 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-License-Identifier: Apache-2.0
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::IntoResponse;
@@ -1,5 +1,5 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-License-Identifier: Apache-2.0
use axum::extract::Request;
use axum::http::header::{HOST, USER_AGENT};
@@ -11,6 +11,7 @@ use colored::Colorize;
use std::time::Instant;
use tracing::info;
/// Simple logger for requests
pub async fn logger(
InsecureClientIp(addr): InsecureClientIp,
request: Request,
@@ -0,0 +1,5 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod bearer_auth;
pub mod logging;
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "nym-common-models"
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]
anyhow = { workspace = true }
bincode = { workspace = true }
nym-crypto = { path = "../crypto", features = ["asymmetric", "serde"] }
serde = { workspace = true, features = ["derive"] }
+1
View File
@@ -0,0 +1 @@
pub mod ns_api;
@@ -1,9 +1,7 @@
use nym_crypto::asymmetric::ed25519::{PublicKey, Signature};
use nym_crypto::asymmetric::ed25519::{PublicKey, Signature, SignatureError};
use serde::{Deserialize, Serialize};
pub mod get_testrun {
use crate::auth::SignedRequest;
use super::*;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Payload {
@@ -42,8 +40,6 @@ pub struct TestrunAssignment {
}
pub mod submit_results {
use crate::auth::SignedRequest;
use super::*;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Payload {
@@ -74,3 +70,32 @@ pub mod submit_results {
}
}
}
pub trait SignedRequest {
type Payload: serde::Serialize;
fn public_key(&self) -> &PublicKey;
fn signature(&self) -> &Signature;
fn payload(&self) -> &Self::Payload;
}
pub trait VerifiableRequest: SignedRequest {
type Error: From<bincode::Error> + From<SignatureError>;
fn verify_signature(&self) -> Result<(), Self::Error> {
bincode::serialize(self.payload())
.map_err(Self::Error::from)
.and_then(|serialized| {
self.public_key()
.verify(serialized, self.signature())
.map_err(Self::Error::from)
})
}
}
impl<T> VerifiableRequest for T
where
T: SignedRequest,
{
type Error = anyhow::Error;
}
@@ -530,15 +530,6 @@ impl From<KeyPairUser> for SecretKeyUser {
}
}
impl From<SecretKeyUser> for KeyPairUser {
fn from(value: SecretKeyUser) -> Self {
KeyPairUser {
public_key: value.public_key(),
secret_key: value,
}
}
}
impl KeyPairUser {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
+1 -2
View File
@@ -1,13 +1,12 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
//! Encoding and decoding node routing information.
//! Encodoing and decoding node routing information.
//!
//! This module is responsible for encoding and decoding node routing information, so that
//! they could be later put into an appropriate field in a sphinx header.
//! Currently, that routing information is an IP address, but in principle it can be anything
//! for as long as it's going to fit in the field.
use nym_crypto::asymmetric::identity;
use nym_sphinx_types::{NodeAddressBytes, NODE_ADDRESS_LENGTH};
-36
View File
@@ -87,39 +87,3 @@ pub enum SessionEvent {
client: DestinationAddressBytes,
},
}
#[derive(PartialEq)]
pub enum SessionType {
Vpn,
Mixnet,
Unknown,
}
impl SessionType {
pub fn to_string(&self) -> &str {
match self {
Self::Vpn => "vpn",
Self::Mixnet => "mixnet",
Self::Unknown => "unknown",
}
}
pub fn from_string(s: &str) -> Self {
match s {
"vpn" => Self::Vpn,
"mixnet" => Self::Mixnet,
_ => Self::Unknown,
}
}
}
impl From<TicketType> for SessionType {
fn from(value: TicketType) -> Self {
match value {
TicketType::V1MixnetEntry => Self::Mixnet,
TicketType::V1MixnetExit => Self::Mixnet,
TicketType::V1WireguardEntry => Self::Vpn,
TicketType::V1WireguardExit => Self::Vpn,
}
}
}
@@ -1 +1 @@
Monday, November 25th 2024, 13:24:04 UTC
Wednesday, November 20th 2024, 15:53:00 UTC
@@ -1,4 +1,5 @@
```sh
2024-11-20T15:53:01.702819Z  INFO nym-api/src/main.rs:40: Starting nym api...
Usage: nym-api [OPTIONS] <COMMAND>
Commands:
@@ -9,9 +10,9 @@ Commands:
Options:
-c, --config-env-file <CONFIG_ENV_FILE>
Path pointing to an env file that configures the Nym API
Path pointing to an env file that configures the Nym API [env: NYMAPI_CONFIG_ENV_FILE_ARG=]
--no-banner
A no-op flag included for consistency with other binaries (and compatibility with nymvisor, oops)
A no-op flag included for consistency with other binaries (and compatibility with nymvisor, oops) [env: NYMAPI_NO_BANNER_ARG=]
-h, --help
Print help
-V, --version
@@ -44,6 +44,8 @@ Options:
Specify whether detailed system crypto hardware information should be exposed. default: true [env: NYMNODE_HTTP_EXPOSE_CRYPTO_HARDWARE=] [possible values: true, false]
--mixnet-bind-address <MIXNET_BIND_ADDRESS>
Address this node will bind to for listening for mixnet packets default: `0.0.0.0:1789` [env: NYMNODE_MIXNET_BIND_ADDRESS=]
--mixnet-announce-port <MIXNET_ANNOUNCE_PORT>
If applicable, custom port announced in the self-described API that other clients and nodes will use. Useful when the node is behind a proxy [env: NYMNODE_MIXNET_ANNOUNCE_PORT=]
--nym-api-urls <NYM_API_URLS>
Addresses to nym APIs from which the node gets the view of the network [env: NYMNODE_NYM_APIS=]
--nyxd-urls <NYXD_URLS>
@@ -52,14 +54,14 @@ Options:
Specifies whether the wireguard service is enabled on this node [env: NYMNODE_WG_ENABLED=] [possible values: true, false]
--wireguard-bind-address <WIREGUARD_BIND_ADDRESS>
Socket address this node will use for binding its wireguard interface. default: `0.0.0.0:51822` [env: NYMNODE_WG_BIND_ADDRESS=]
--wireguard-private-ip <WIREGUARD_PRIVATE_IP>
Private IP address of the wireguard gateway. default: `10.1.0.1` [env: NYMNODE_WG_IP=]
--wireguard-announced-port <WIREGUARD_ANNOUNCED_PORT>
Port announced to external clients wishing to connect to the wireguard interface. Useful in the instances where the node is behind a proxy [env: NYMNODE_WG_ANNOUNCED_PORT=]
--wireguard-private-network-prefix <WIREGUARD_PRIVATE_NETWORK_PREFIX>
The prefix denoting the maximum number of the clients that can be connected via Wireguard. The maximum value for IPv4 is 32 and for IPv6 is 128 [env: NYMNODE_WG_PRIVATE_NETWORK_PREFIX=]
--verloc-bind-address <VERLOC_BIND_ADDRESS>
Socket address this node will use for binding its verloc API. default: `0.0.0.0:1790` [env: NYMNODE_VERLOC_BIND_ADDRESS=]
--verloc-announce-port <VERLOC_ANNOUNCE_PORT>
If applicable, custom port announced in the self-described API that other clients and nodes will use. Useful when the node is behind a proxy [env: NYMNODE_VERLOC_ANNOUNCE_PORT=]
--entry-bind-address <ENTRY_BIND_ADDRESS>
Socket address this node will use for binding its client websocket API. default: `0.0.0.0:9000` [env: NYMNODE_ENTRY_BIND_ADDRESS=]
--announce-ws-port <ANNOUNCE_WS_PORT>
+17 -168
View File
@@ -33,157 +33,6 @@ This page displays a full list of all the changes during our release cycle from
<VarInfo />
## `magura-drift`
Second patch to `v2024.13-magura` release version.
- [Release binaries](https://github.com/nymtech/nym/releases/tag/nym-binaries-v2024.13-magura-drift)
- [`nym-node`](nodes/nym-node.mdx) version `1.1.12`
```sh
nym-node
Binary Name: nym-node
Build Timestamp: 2024-11-29T13:10:51.813092288Z
Build Version: 1.1.12
Commit SHA: 4a9a5579c40ad956163ea02e01d7b53aef2ac8ef
Commit Date: 2024-11-29T14:06:32.000000000+01:00
Commit Branch: HEAD
rustc Version: 1.83.0
rustc Channel: stable
cargo Profile: release
```
- This patch adds a peer storage manager to fix issues causing external clients to be blocked, ensuring they can successfully connect to different nodes.
## `v2024.13-magura-patched`
- [Release binaries](https://github.com/nymtech/nym/releases/tag/nym-binaries-v2024.13-magura-patched)
- [`nym-node`](nodes/nym-node.mdx) version `1.1.11`
```sh
nym-node
Binary Name: nym-node
Build Timestamp: 2024-11-22T14:30:48.067329245Z
Build Version: 1.1.11
Commit SHA: 01c7b2819ee3d328deccd303b4113ff415d7e276
Commit Date: 2024-11-22T10:50:59.000000000+01:00
Commit Branch: HEAD
rustc Version: 1.82.0
rustc Channel: stable
cargo Profile: release
```
<Callout type="warning" emoji="⚠️">
After changes coming along with `v2024.13-magura` (`nym-node v1.1.10`), Nym Explorer is no longer picking all values correctly. Instead of fixing this outdated explorer, we are working on a new one, coming out soon.
[Nym Harbourmaster](https://harbourmaster.nymtech.net) has cache of 90min, expect your values to be updated with delay. We are aware of some issues with Nym Harbourmaster and working hard to resolve them in the upcoming explorer v2. To check your routing values in real time, you can use [`nym-gateway-probe`](nodes/performance-and-testing/gateway-probe).
</Callout>
### Operators Updates & Tools
- Updated [`network_tunnel_manager.sh`](https://github.com/nymtech/nym/blob/develop/scripts/network_tunnel_manager.sh) (moved to our monorepo) helps operators to configure their IP tables rules for `nymtun` and `wireguard` routing.
- **Please re-run [routing configuration steps](https://nymtech.net/docs/operators/nodes/nym-node/configuration#routing-configuration) to update your routing settings.**
- We found out that some operators have a wrong value for wireguard IP. Follow these steps to ensure your value is set to `10.1.0.1` (default on new nodes):
<Steps>
###### 1. Open your node config file:
```sh
nano $HOME/.nym/nym-nodes/<ID>/config/config.toml
# change <ID> for your local nym moniker for example:
# nano $HOME/.nym/nym-nodes/default-nym-node/config/config.toml
```
###### 2. Control or change the value of wireguard private IP
- Scroll down to section starting with `[wireguard]`
- Find line `private_ip` and ensure it's set to value `10.1.0.1`
- The section will look like this:
```toml
[wireguard]
# Specifies whether the wireguard service is enabled on this node.
enabled = true
# Socket address this node will use for binding its wireguard interface.
# default: `0.0.0.0:51822`
bind_address = '0.0.0.0:51822'
# Private IP address of the wireguard gateway.
# default: `10.1.0.1`
private_ip = '10.1.0.1'
```
###### 3. Save, exit and restart the service
- If you used `nano` editor - press `ctrl` + `x` and confirm the changes
- Run these commands to update the service with new values and restart your node process:
```sh
systemctl daemon-reload && service nym-node restart
```
</Steps>
- New manual how to [run `nym-node` as non-root](nodes/nym-node/configuration#running-nym-node-as-a-non-root)
- Since `v2024.13-magura`, operators do not update their node version in the wallet. [Manual upgrading steps](nodes/maintenance/manual-upgrade.mdx) has been updated accordingly.
- CLI tool [`node_api_check.py`](nodes/performance-and-testing/node-api-check.mdx), helping operators to collect all API values about their nodes locally, is not up to date with the API changes introduced with `v2024.13-magura` release version. Please treat it as unstable before we fix it.
#### Error Log
In case you encounter this error:
```
[ERROR] nym-node/src/node/mod.rs:628: the exit gateway subtask has failed with the following message: failed to start authenticator: internal wireguard error no private IP set for peer..
```
You can follow these steps to make a workaround:
<br />
<AccordionTemplate name="Authenticator error fix">
<Steps>
###### 1. Find the error
- In the node logs, locate the ERROR message which says `the exit gateway subtask has failed with the following message: failed to start authenticator: internal wireguard error no private IP set for peer KN5GPvkC+p6G/SM4PD2Z3ObAtRGiDjHPRnQOPpbdUQk=`
- Copy the end part of that peer, later denoted as `<WG_PEER_STRING_END>` (in our example `GiDjHPRnQOPpbdUQk=`) to use later in the sql commands
###### 2. Fix the issue in sqlite3 db
<Callout type="warning" emoji="⚠️">
Be careful when running commands within sqlite database.
</Callout>
- Navigate to the data directory:
```sh
cd $HOME/.nym/nym-nodes/<ID>/data
```
- Enter the database:
```sh
sqlite3 clients.sqlite
```
- Run these commands:
```sh
# Change with your unique <PEER_STRING_END>
select * from wireguard_peer where public_key like "%<WG_PEER_STRING_END>%"
# Make sure that only ONE line is returned and it contains the key
delete from wireguard_peer where public_key like "%<WG_PEER_STRING_END>%";
```
- Confirm that peer has been removed by running this again:
```sh
select * from wireguard_peer where public_key like "%<WG_PEER_STRING_END>%";
```
###### 3. Exit and restart the service
Run `.quit` and:
```sh
systemctl restart nym-node.service
```
</Steps>
</AccordionTemplate>
## `v2024.13-magura`
Magura release represents a bigger milestone in [project Smoosh](archive/faq/smoosh-faq.mdx) development where `nym-node` is one binary able to perform any function in Nym Mixnet. This release is especially crucial for operators, please pay attention to the section [*Operators Updates & Tooling*](#operators-updates--tooling) below.
@@ -221,15 +70,15 @@ cargo Profile: release
- [Switch over the last set of jobs to arc runners](https://github.com/nymtech/nym/pull/4938): Switch over the remaining GH jobs using 16-core runners to self-hosted arc runners. Since we can't currently use Docker on the ubuntu-20.04 runners, remove the matrix notification steps
<AccordionTemplate name={<TestingSteps/>}>
<AccordionTemplate name={<TestingSteps/>}>
Confirm that the deployment workflows work through manual testing
- [x] cd-docs
- [x] publish-sdk-npm
</AccordionTemplate>
- [V2 performance monitoring feature flag](https://github.com/nymtech/nym/pull/4943): Feature flag to use v2 network monitor results in rewarding
- [V2 performance monitoring feature flag](https://github.com/nymtech/nym/pull/4943): Feature flag to use v2 network monitor results in rewarding
- [Add `utoipa` feature to nym-node](https://github.com/nymtech/nym/pull/4945): `cargo build -p nym-node` was failing, since its depending on `QueryParams` having `utoipa` traits derived
- [Add `utoipa` feature to nym-node](https://github.com/nymtech/nym/pull/4945): `cargo build -p nym-node` was failing, since its depending on `QueryParams` having `utoipa` traits derived
- [Ticket type storage](https://github.com/nymtech/nym/pull/4947)
@@ -254,8 +103,8 @@ Confirm that the deployment workflows work through manual testing
- [chore: remove unused rocket code](https://github.com/nymtech/nym/pull/4968)
- [add Dockerfile for nym node](https://github.com/nymtech/nym/pull/4972)
- [`Product Data` Add session type based on ecash ticket received](https://github.com/nymtech/nym/pull/4974): Fire an `EcashTicket` event for the `GatewayStatisticsCollector`, when an Ecash ticket is being accepted. This allows to mark an active session as being a mixnet session or a vpn session. It also changes the format of the related self-described data, to accommodate that new session type.
- [`Product Data` Add session type based on ecash ticket received](https://github.com/nymtech/nym/pull/4974): Fire an `EcashTicket` event for the `GatewayStatisticsCollector`, when an Ecash ticket is being accepted. This allows to mark an active session as being a mixnet session or a vpn session. It also changes the format of the related self-described data, to accommodate that new session type.
- [Top up bandwidth](https://github.com/nymtech/nym/pull/4975)
@@ -298,7 +147,7 @@ Confirm that the deployment workflows work through manual testing
- log gw identity key
- better agent testrun logging
- log responses on server side
- change response code for agents
- change response code for agents
- update sqlx data
- fix agent - probe gw bug
@@ -316,7 +165,7 @@ Confirm that the deployment workflows work through manual testing
- [Allow custom http port to be reset](https://github.com/nymtech/nym/pull/5073)
- [Fix gateway decreasing bandwidth](https://github.com/nymtech/nym/pull/5075): Make sure to update the storage after each decrease with the new values. Also set the storage values to 0 on restart for existing peers, as kernel peers can't have those values set to 0
- [Fix gateway decreasing bandwidth](https://github.com/nymtech/nym/pull/5075): Make sure to update the storage after each decrease with the new values. Also set the storage values to 0 on restart for existing peers, as kernel peers can't have those values set to 0
- [Fix expiration date as today + 7 days](https://github.com/nymtech/nym/pull/5076)
@@ -338,7 +187,7 @@ Confirm that the deployment workflows work through manual testing
- [Add NYM_VPN_API to env files](https://github.com/nymtech/nym/pull/5099)
- [Feature/force refresh node](https://github.com/nymtech/nym/pull/5101): currently if nodes update their role from say mixnode to entry-gateway, it might take quite a while for `nym-api` to pick up the change and thus they might be losing performance. With this change, the node will be force refreshed on its startup
- [Feature/force refresh node](https://github.com/nymtech/nym/pull/5101): currently if nodes update their role from say mixnode to entry-gateway, it might take quite a while for `nym-api` to pick up the change and thus they might be losing performance. With this change, the node will be force refreshed on its startup
- [`nym-credential-proxy-requests`: reqwest use rustls-tls](https://github.com/nymtech/nym/pull/5116)
@@ -356,7 +205,7 @@ Confirm that the deployment workflows work through manual testing
- [Fix critical issues SI84 and SI85 from Cure53](https://github.com/nymtech/nym/pull/4758): This pull request fixes the following issues:
- NYM-01-009 WP5: BLS12-381 EC signature bypasses in Coconut library (Critical)
- NYM-01-014 WP5: Partial signature bypass in offline eCash (Critical)
- [bugfix: correctly paginate through 'search_tx' endpoint](https://github.com/nymtech/nym/pull/4936): when `results.append(&mut res.txs);` was called, `res.txs` was always empty thus it was impossible to return more than page size number of results
- [Fix broken build after merge](https://github.com/nymtech/nym/pull/4937)
@@ -365,7 +214,7 @@ Confirm that the deployment workflows work through manual testing
- dedicated commands to request specific blocks for processing
- decreased websocket failure timeout
- ensuring we do actually have sufficient number of blocks to process rewarding for given epoch
- additional error logging
- additional error logging
- [bugfix: fix expected return type on /v1/gateways endpoint](https://github.com/nymtech/nym/pull/4965)
@@ -375,7 +224,7 @@ Confirm that the deployment workflows work through manual testing
- Faulty aggregation to invalid offline eCash signatures
- Signature forgery of Pointcheval-Sanders schema
- [bugfix: client memory leak](https://github.com/nymtech/nym/pull/4991): This fixes memory leaks in all the clients. however, they were most prominent in `nym-api` during network monitoring due to the sheer amount of packets being pushed
- [bugfix: client memory leak](https://github.com/nymtech/nym/pull/4991): This fixes memory leaks in all the clients. however, they were most prominent in `nym-api` during network monitoring due to the sheer amount of packets being pushed
- [Fix rustfmt in nym-credential-proxy](https://github.com/nymtech/nym/pull/4992)
@@ -430,7 +279,7 @@ Confirm that the deployment workflows work through manual testing
- [bugfix: make sure to assign correct node_id and identity during 'gateway_details' table migration](https://github.com/nymtech/nym/pull/5142)
- [bugifx: assign 'node_id' when converting from 'GatewayDetails' to 'TestNode'](https://github.com/nymtech/nym/pull/5143)
### Operators Updates & Tooling
<Callout type="warning" emoji="⚠️">
@@ -443,7 +292,7 @@ Confirm that the deployment workflows work through manual testing
- **[Operators release & rewards roadmap](tokenomics/mixnet-rewards.mdx#roadmap)**
- **New [Operators landing page](https://nymtech.net/operators)**
- **New [Operators landing pag e](https://nymtech.net/operators)
- [Nym Harbourmaster](https://harbourmaster.nymtech.net) had a new tab `NODE SEARCH` where operators can easily search nodes by identity keys and owner accounts and get all public information listed.
@@ -486,7 +335,7 @@ Confirm that the deployment workflows work through manual testing
- Confirm the transaction
###### 5. Welcome to new episode of `nym-node`!
###### 5. Welcome to new episode of `nym-node`!
</ Steps>
</AccordionTemplate>
@@ -511,13 +360,13 @@ Confirm that the deployment workflows work through manual testing
- Currently in *Native rewarding*, the rewards are split equally across the [rewarded set of nodes](https://validator.nymtech.net/api/v1/epoch/reward_params) (which now = active set and it's size is 240 nodes) for both Mixnet mode and dVPN mode. Every node being assigned 1 / 240 work factor (hence *naive rewarding*).
#### Directory Services v2.1: API & Mixnet Contract Changes
#### Directory Services v2.1: API & Mixnet Contract Changes
Magura release brings [breaking changes on API](https://github.com/nymtech/nym/pull/4903) logic of Nym. New APIs will only communicate with `nym-node` from this release and newer. Also old version of APIs won't be able to communicate with the new version of `nym-node`. We are also moving towards completely removing Nym Explorer API, which now has been only used to report nodes location.
Magura release brings [breaking changes on API](https://github.com/nymtech/nym/pull/4903) logic of Nym. New APIs will only communicate with `nym-node` from this release and newer. Also old version of APIs won't be able to communicate with the new version of `nym-node`. We are also moving towards completely removing Nym Explorer API, which now has been only used to report nodes location.
Any new bonded node will provide only the bare minimum information: host, identity key and optionally custom port of its HTTP api - we highly recommend to set that one up to `8080`. Everything else will be discovered via the self-described API for maximum flexibility. This also includes the sphinx key, meaning if the API is not exposed, the node will be unable to route any traffic. Furthermore, this allows to arbitrary change of `nym-node` from mixnode into a gateway modes (and vice versa) without losing any delegations.
The contract changes also mean any node functionality can get rewards. Rather than just with assigned mixing roles, gateways now also added into the pool. However, to be eligible for gateway rewarding, one must [migrate into a `nym-node`](#wallet-changes) on a smart contract level (or bond a new node).
The contract changes also mean any node functionality can get rewards. Rather than just with assigned mixing roles, gateways now also added into the pool. However, to be eligible for gateway rewarding, one must [migrate into a `nym-node`](#wallet-changes) on a smart contract level (or bond a new node).
##### API High Level Changes
@@ -14,27 +14,30 @@ This page explains how to upgrade [`nym-node`](#nym-node-upgrade) or [`validator
## Nym node Upgrade
Since `v2024.13-magura` (`nym-node v1.1.10`), **operators NO longer update node information in the Mixnet smart contract** (wallet version information), **only upgrade node binary** (on VPS), resulting in `~/.nym/nym-nodes/<ID>/config/config.toml` update.
**Upgrading your node is a straight forward two-step process:**
<Steps>
#### 1. Updating the binary and `~/.nym/nym-nodes/<ID>/config/config.toml` on your VPS
#### 2. Updating the node information in the [mixnet smart contract](https://nymtech.net/docs/nyx/mixnet-contract.html). This is the information that is present on the [mixnet explorer](https://explorer.nymtech.net).
</Steps>
Below are detailed steps how to do it:
<Steps>
###### 1. Upgrade `nym-node` binary
###### 1. Upgrading node binary and information in config file
- Pause your node process.
- If you run your node as `systemd` service (recommended), run: `service nym-node stop`
- Otherwise open the terminal window with your node logs and press once `ctrl + c` and wait for the node to terminate gracefully
- Otherwise open the terminal window with your node logs and press `ctrl + c`
- Replace the existing `nym-node` binary with the newest binary (which you can either [compile yourself](../../binaries/building-nym.mdx) or [download](../../binaries/pre-built-binaries.mdx).
- To verify node version, run `./nym-node --version`
###### 2. Restart the node
- [Re-run with the same values](../nym-node/setup.mdx#initialise--run) as you use to run your `nym-node`. If you want keep changes in your config file, use flag `-w` (`--write-changes`), **This will just update the config file, it will not overwrite existing keys**.
- If you automated your node with `systemd` (recommended), make sure you have all needed flags in `ExecStart` line of the service config file, and run:
- If you automated your node with `systemd` (recommended) run:
```sh
systemctl daemon-reload
service nym-node start
@@ -45,19 +48,25 @@ service nym-node start
journalctl -f -u nym-node.service
```
###### 2. Updating your node information in the smart contract
###### 3. Check if your node is reporting the version correctly
Follow these steps to update the information about your `nym-node` which is publicly available from the [`nym-api`](https://validator.nymtech.net/api/swagger/index.html) and information displayed on the [Mixnet explorer](https://explorer.nymtech.net).
- Open [Nym Harbourbourmaster](https://harbourmaster.nymtech.net), search your node and verify that everything is working as expected and your node shows expected version.
You can either do this graphically via the Desktop Wallet, or the CLI.
<div>
<Tabs items={[
<strong>Desktop Wallet (recommended)</strong>,
<strong>CLI (superusers)</strong>,
]} defaultIndex="0">
<MyTab><DesktopWalletUpdate/></MyTab>
<MyTab><CliUpdate/></MyTab>
</Tabs>
</div>
</Steps>
<Callout type="warning" emoji="⚠️">
After changes coming along with `v2024.13-magura` (`nym-node v1.1.10`), Nym Explorer is no longer picking all values correctly. Instead of fixing this outdated explorer, we are working on a new one, coming out soon.
[Nym Harbourmaster](https://harbourmaster.nymtech.net) has cache of 90min, expect your values to be updated with delay. We are aware of some issues with Nym Harbourmaster and working hard to resolve them in the upcoming explorer v2. To check your routing values in real time, you can use [`nym-gateway-probe`](../performance-and-testing/gateway-probe).
</Callout>
## Validator Upgrade
Upgrading from `v0.31.1` -> `v0.32.0` process is fairly simple. Grab the `v0.32.0` release tarball from the [`nyxd` releases page](https://github.com/nymtech/nyxd/releases), and untar it. Inside are two files:
@@ -83,3 +92,4 @@ The most common reason for your validator being jailed is that it runs out of me
Running the command `df -H` will return the size of the various partitions of your VPS.
If the `/dev/sda` partition is almost full, try pruning some of the `.gz` syslog archives and restart your validator process.
@@ -120,7 +120,7 @@ From `nym-wallet` version `1.2.15` onward the application allows and prompts ope
###### 2. Verify the binary and extract it if needed
- Download [`hashes.json`](https://github.com/nymtech/nym/releases/download/nym-wallet-v1.2.15/hashes.json)
- Download [`hashes.json`]https://github.com/nymtech/nym/releases/download/nym-wallet-v1.2.15/hashes.json
- Open it with your text editor or print it's content with `cat hashes.json`
- Run `sha256sum <WALLET_BINARY>` for example `sha256sum ./nym-wallet_1.2.15_amd64.AppImage`
- If your have to extract it (like `.tar.gz`) do it
@@ -426,95 +426,6 @@ journalctl -u nym-node.service -f -n 100
Make sure that you get the validation of all connectivity. If there are still any problems, please refer to [troubleshooting section](../../troubleshooting/vps-isp.mdx#incorrect-gateway-network-check).
## Running `nym-node` as a non-root
Some operators prefer to run `nym-node` without root privileges. It's possible but still `nym-node` binary needs higher privileges for network-level operations demanding these permissions. Below is a guide how to go about such setup:
<Callout type="warning" emoji="⚠️">
Copying nodes database and the `.nym/` directories from `/root/.nym` to `/home/<USER>/.nym/` should be treated as experimental, therefore we would advise this section for operators starting new nodes, rather than tweaking an existing one. We will publish a detailed guide for changing permissions of an existing node soon.
</Callout>
<Steps>
###### 1. Setup a new user
- Define a variable `user_name` using your desired user name:
```sh
user_name="<USER>"
```
- Run:
```sh
user_home="/home/$user_name"
if ! id "$user_name" &>/dev/null; then
sudo adduser --home "$user_home" --disabled-login --gecos "" "$user_name"
else
echo "user $user_name already exists"
fi
```
- And follow by:
```sh
sudo usermod -aG sudo "$user_name"
```
- Optional: Add to sudoers group:
```sh
echo "$user_name ALL=(ALL) NOPASSWD:ALL" | sudo tee -a /etc/sudoers.d/$user_name
```
###### 2. Grant needed permissions for network-level operations
While `nym-node` will be set as a user process, it requires higher privileges for network-level operations, set them up with this command:
```sh
sudo setcap 'cap_net_bind_service=+ep cap_net_admin=+ep' nym-node
```
**After replacing or upgrading the binary, you must reapply these permissions each time!**
###### 3. Edit service config file
- Add these new lines to your `/etc/systemd/system/nym-node.service` [service config file](#systemd)
- `After=network.target`
- `Group=<USER>`
- `Type=simple`
- Your service file will then look like this:
```ini
[Unit]
Description=Nym Node
After=network.target
StartLimitInterval=350
StartLimitBurst=10
[Service]
User=<USER>
Group=<USER>
Type=simple
LimitNOFILE=65536
ExecStart=<PATH>/nym-node run <ARGUMENTS> # add all the flags you use to run your node
KillSignal=SIGINT
Restart=on-failure
RestartSec=30
[Install]
WantedBy=multi-user.target
```
###### 4. Reload and restart the service
```sh
systemctl daemon-reload && service nym-node restart
```
- If you want to follow the logs, run:
```sh
journalctl -u nym-node -f
```
</Steps>
## Next Steps
@@ -17,16 +17,15 @@ This documentation page provides a guide on how to set up and run a [NYM NODE](.
```sh
nym-node
Binary Name: nym-node
Build Timestamp: 2024-11-29T13:10:51.813092288Z
Build Version: 1.1.12
Commit SHA: 4a9a5579c40ad956163ea02e01d7b53aef2ac8ef
Commit Date: 2024-11-29T14:06:32.000000000+01:00
Build Timestamp: 2024-11-18T17:02:50.947941194Z
Build Version: 1.1.10
Commit SHA: b49ef643df86f0c670672429812c632fbbaf6cf1
Commit Date: 2024-11-18T17:56:57.000000000+01:00
Commit Branch: HEAD
rustc Version: 1.83.0
rustc Version: 1.82.0
rustc Channel: stable
cargo Profile: release
```
{/* COMMENTING THIS OUT ASS WE HAVE TO FIGURE OUT HOW TO SHOW THE LATEST VERSION FROM MASTER BRANCH
<BuildInfo />
*/}
@@ -8,10 +8,6 @@ import NodeApiCheckQueryHelp from 'components/outputs/command-outputs/node-api-c
# Node API Check
<Callout type="warning" emoji="⚠️">
CLI tool `node_api_check.py`, helping operators to collect all API values about their nodes locally, is not up to date with the API changes introduced with `v2024.13-magura` release version. Please treat it as unstable before we fix it.
</Callout>
<VarInfo />
Operating a `nym-node` is not a *"set and forget"* endeavor, it takes some work. To diagnose node network performance through querying APIs, is a good knowledge to have. These are the main places to look for API endpoints regarding `nym-node`:
@@ -97,9 +93,9 @@ python --version
</Tabs>
</div>
###### 2. Install `node_api_check.py` and make executable
###### 2. Install `node_api_check.py` and make executable
To run the program you neet to have [`node_api_check.py`](https://github.com/nymtech/nym/tree/develop/scripts/node_api_check.py) and [`api_endpoints.json`](https://github.com/nymtech/nym/tree/develop/scripts/api_endpoints.json).
To run the program you neet to have [`node_api_check.py`](https://github.com/nymtech/nym/tree/develop/scripts/node_api_check.py) and [`api_endpoints.json`](https://github.com/nymtech/nym/tree/develop/scripts/api_endpoints.json).
- If you [compiled from source](../../binaries/building-nym.mdx), you already have both of these files. Note that the latest version of this program may be on `develop` branch.
@@ -163,3 +159,4 @@ Another command is `version_count` where at least one `nym-node` version is requ
```sh
./node_api_check version_count 1.1.0 1.1.1 1.1.2 1.1.3 --markdown
```
@@ -232,9 +232,6 @@ username soft nofile 4096
Then reboot your server and restart your node.
## Running `nym-node` as a non-root
Some operators prefer to run `nym-node` without root privileges. It's possible but still `nym-node` binary needs higher privileges for network-level operations demanding these permissions. If you are starting a new `nym-node` and want to run it as a non-root, follow [this guide](../nym-node/configuration#running-nym-node-as-a-non-root) before you proceed with the node setup sections.
## Ports reference tables
@@ -161,7 +161,7 @@ In dVPN (2-hop) mode every node which meets the performance criteria, including
In both cases, the selection algorithm also looks whether the node runs with [Terms & Conditions](nodes/nym-node/setup.mdx#terms--conditions) accepted **AND** if it's not a legacy binary version. In case either of these criterias are not met, the node will have be excluded from the rewarded set selection.
To read more about rewards calculation, please see next page [*Nym Operators Rewards*](tokenomics/mixnet-rewards.md).
To read more about rewards calculation, please see next page [*Nym Operators Rewards*](mixnet-rewards.md).
## Query Validator API
@@ -153,7 +153,7 @@ The entire active set selection probablity:
For a comparison we made an example with 5 nodes, where first number is node performance and second stake saturation (assuming all of them `config_score` = 1 and not 0):
<br />
<AccordionTemplate name="✏️ Example: Reward set selection probability calculation">
<AccordionTemplate name="✏️ Example: Reward set selection">
> node_1 = 1.00 ^ 20 \* 1.0 = 1 <br />
> node_2 = 1.00 ^ 20 \* 0.5 = 0.5 <br />
> node_3 = 0.99 ^ 20 \* 1.0 = 0.818 <br />
+1 -1
View File
@@ -17,7 +17,7 @@ use axum::response::Redirect;
use axum::routing::get;
use axum::Router;
use core::net::SocketAddr;
use nym_http_api_common::logging::logger;
use nym_http_api_common::middleware::logging::logger;
use tokio::net::TcpListener;
use tokio_util::sync::WaitForCancellationFutureOwned;
use tower_http::cors::CorsLayer;
@@ -34,7 +34,6 @@ nym-serde-helpers = { path = "../../common/serde-helpers", features = ["bs58"] }
workspace = true
features = ["tokio"]
[features]
default = ["query-types"]
query-types = ["nym-http-api-common"]
@@ -268,6 +268,9 @@ pub struct WebhookTicketbookWalletSharesRequest {
pub struct TicketbookObtainQueryParams {
pub output: Option<Output>,
#[serde(default)]
pub skip_webhook: bool,
pub include_master_verification_key: bool,
pub include_coin_index_signatures: bool,
@@ -1,6 +1,6 @@
[package]
name = "nym-credential-proxy"
version = "0.1.3"
version = "0.1.6"
authors.workspace = true
repository.workspace = true
homepage.workspace = true
@@ -48,6 +48,7 @@ nym-config = { path = "../../common/config" }
nym-crypto = { path = "../../common/crypto", features = ["asymmetric", "rand", "serde"] }
nym-credentials = { path = "../../common/credentials" }
nym-credentials-interface = { path = "../../common/credentials-interface" }
nym-ecash-contract-common = { path = "../../common/cosmwasm-smart-contracts/ecash-contract" }
nym-http-api-common = { path = "../../common/http-api-common", features = ["utoipa"] }
nym-validator-client = { path = "../../common/client-libs/validator-client" }
nym-network-defaults = { path = "../../common/network-defaults" }
@@ -30,6 +30,6 @@ RUN apt update && apt install -yy curl ca-certificates
WORKDIR /nym
COPY --from=builder /usr/src/nym/nym-credential-proxy/target/release/nym-credential-proxy ./
COPY --from=builder /usr/src/nym/target/release/nym-credential-proxy ./
ENTRYPOINT [ "/nym/nym-credential-proxy" ]
@@ -55,6 +55,15 @@ pub struct Cli {
)]
pub(crate) http_auth_token: String,
/// Specify the maximum number of deposits the credential proxy can make in a single transaction
/// (default: 32)
#[clap(
long,
env = "NYM_CREDENTIAL_PROXY_MAX_CONCURRENT_DEPOSITS",
default_value_t = 32
)]
pub(crate) max_concurrent_deposits: usize,
#[clap(long, env = "NYM_CREDENTIAL_PROXY_PERSISTENT_STORAGE_STORAGE")]
pub(crate) persistent_storage_path: Option<PathBuf>,
}
@@ -1,6 +1,7 @@
// Copyright 2024 Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use crate::deposit_maker::{DepositRequest, DepositResponse};
use crate::error::VpnApiError;
use crate::http::state::ApiState;
use crate::storage::models::BlindedShares;
@@ -14,21 +15,48 @@ use nym_credentials::IssuanceTicketBook;
use nym_credentials_interface::Base58;
use nym_crypto::asymmetric::ed25519;
use nym_validator_client::ecash::BlindSignRequestBody;
use nym_validator_client::nyxd::contract_traits::EcashSigningClient;
use nym_validator_client::nyxd::cosmwasm_client::ToSingletonContractData;
use nym_validator_client::nyxd::Coin;
use rand::rngs::OsRng;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use time::OffsetDateTime;
use tokio::sync::Mutex;
use tokio::time::timeout;
use tracing::{debug, error, info, instrument};
use tokio::sync::{oneshot, Mutex};
use tokio::time::{timeout, Instant};
use tracing::{debug, error, info, instrument, warn};
use uuid::Uuid;
// use the same type alias as our contract without importing the whole thing just for this single line
pub type NodeId = u64;
#[instrument(skip(state), ret, err(Display))]
async fn make_deposit(
state: &ApiState,
pub_key: ed25519::PublicKey,
deposit_amount: &Coin,
) -> Result<DepositResponse, VpnApiError> {
let start = Instant::now();
let (on_done_tx, on_done_rx) = oneshot::channel();
let request = DepositRequest::new(pub_key, deposit_amount, on_done_tx);
state.request_deposit(request).await;
let time_taken = start.elapsed();
let formatted = humantime::format_duration(time_taken);
let Ok(deposit_response) = on_done_rx.await else {
error!("failed to receive deposit response: the corresponding sender channel got dropped by the DepositMaker!");
return Err(VpnApiError::DepositFailure);
};
if time_taken > Duration::from_secs(20) {
warn!("attempting to resolve deposit request took {formatted}. perhaps the buffer is too small or the process/chain is overloaded?")
} else {
debug!("attempting to resolve deposit request took {formatted}")
}
deposit_response.ok_or(VpnApiError::DepositFailure)
}
#[instrument(
skip(state, request_data, request, requested_on),
fields(
@@ -59,25 +87,12 @@ pub(crate) async fn try_obtain_wallet_shares(
.await?;
let ecash_api_clients = state.ecash_clients(epoch).await?.clone();
let chain_write_permit = state.start_chain_tx().await;
let DepositResponse {
deposit_id,
tx_hash,
} = make_deposit(state, *ed25519_keypair.public_key(), &deposit_amount).await?;
info!("starting the deposit!");
// TODO: batch those up
// TODO: batch those up
let deposit_res = chain_write_permit
.make_ticketbook_deposit(
ed25519_keypair.public_key().to_base58_string(),
deposit_amount.clone(),
None,
)
.await?;
// explicitly drop it here so other tasks could start using it
drop(chain_write_permit);
let deposit_id = deposit_res.parse_singleton_u32_contract_data()?;
let tx_hash = deposit_res.transaction_hash;
info!(deposit_id = %deposit_id, tx_hash = %tx_hash, "deposit finished");
info!(deposit_id = %deposit_id, "deposit finished");
// store the deposit information so if we fail, we could perhaps still reuse it for another issuance
state
@@ -342,6 +357,7 @@ pub(crate) async fn try_obtain_blinded_ticketbook_async(
params: TicketbookObtainQueryParams,
pending: BlindedShares,
) {
let skip_webhook = params.skip_webhook;
if let Err(err) = try_obtain_blinded_ticketbook_async_inner(
&state,
request,
@@ -352,6 +368,11 @@ pub(crate) async fn try_obtain_blinded_ticketbook_async(
)
.await
{
if skip_webhook {
info!(uuid = %request,"the webhook is not going to be called for this request");
return;
}
// post to the webhook to notify of errors on this side
if let Err(webhook_err) = try_trigger_webhook_request_for_error(
&state,
@@ -0,0 +1,205 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use crate::error::VpnApiError;
use crate::http::state::ChainClient;
use nym_crypto::asymmetric::ed25519;
use nym_ecash_contract_common::deposit::DepositId;
use nym_validator_client::nyxd::cosmwasm_client::ContractResponseData;
use nym_validator_client::nyxd::{Coin, Hash};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
#[derive(Debug)]
pub(crate) struct DepositResponse {
pub tx_hash: Hash,
pub deposit_id: DepositId,
}
pub(crate) struct DepositRequest {
pubkey: ed25519::PublicKey,
deposit_amount: Coin,
on_done: oneshot::Sender<Option<DepositResponse>>,
}
impl DepositRequest {
pub(crate) fn new(
pubkey: ed25519::PublicKey,
deposit_amount: &Coin,
on_done: oneshot::Sender<Option<DepositResponse>>,
) -> Self {
DepositRequest {
pubkey,
deposit_amount: deposit_amount.clone(),
on_done,
}
}
}
pub(crate) type DepositRequestReceiver = mpsc::Receiver<DepositRequest>;
pub(crate) fn new_control_channels(
max_concurrent_deposits: usize,
) -> (DepositRequestSender, DepositRequestReceiver) {
let (tx, rx) = mpsc::channel(max_concurrent_deposits);
(tx.into(), rx)
}
#[derive(Debug, Clone)]
pub struct DepositRequestSender(mpsc::Sender<DepositRequest>);
impl From<mpsc::Sender<DepositRequest>> for DepositRequestSender {
fn from(inner: mpsc::Sender<DepositRequest>) -> Self {
DepositRequestSender(inner)
}
}
impl DepositRequestSender {
pub(crate) async fn request_deposit(&self, request: DepositRequest) {
if self.0.send(request).await.is_err() {
error!("failed to request deposit: the DepositMaker must have died!")
}
}
}
pub(crate) struct DepositMaker {
client: ChainClient,
max_concurrent_deposits: usize,
deposit_request_sender: DepositRequestSender,
deposit_request_receiver: DepositRequestReceiver,
short_sha: &'static str,
cancellation_token: CancellationToken,
}
impl DepositMaker {
pub(crate) fn new(
short_sha: &'static str,
client: ChainClient,
max_concurrent_deposits: usize,
cancellation_token: CancellationToken,
) -> Self {
let (deposit_request_sender, deposit_request_receiver) =
new_control_channels(max_concurrent_deposits);
DepositMaker {
client,
max_concurrent_deposits,
deposit_request_sender,
deposit_request_receiver,
short_sha,
cancellation_token,
}
}
pub(crate) fn deposit_request_sender(&self) -> DepositRequestSender {
self.deposit_request_sender.clone()
}
pub(crate) async fn process_deposit_requests(
&mut self,
requests: Vec<DepositRequest>,
) -> Result<(), VpnApiError> {
let chain_write_permit = self.client.start_chain_tx().await;
info!("starting deposits");
let mut contents = Vec::new();
let mut replies = Vec::new();
for request in requests {
// check if the channel is still open in case the receiver client has cancelled the request
if request.on_done.is_closed() {
warn!(
"the request for deposit from {} got cancelled",
request.pubkey
);
continue;
}
contents.push((request.pubkey.to_base58_string(), request.deposit_amount));
replies.push(request.on_done);
}
let deposits_res = chain_write_permit
.make_deposits(self.short_sha, contents)
.await;
let execute_res = match deposits_res {
Ok(res) => res,
Err(err) => {
// we have to let requesters know the deposit(s) failed
for reply in replies {
if reply.send(None).is_err() {
warn!("one of the deposit requesters has been terminated")
}
}
return Err(err);
}
};
let tx_hash = execute_res.transaction_hash;
info!("{} deposits made in transaction: {tx_hash}", replies.len());
let contract_data = match execute_res.to_contract_data() {
Ok(contract_data) => contract_data,
Err(err) => {
// that one is tricky. deposits technically got made, but we somehow failed to parse response,
// in this case terminate the proxy with 0 exit code so it wouldn't get automatically restarted
// because it requires some serious MANUAL intervention
error!("CRITICAL FAILURE: failed to parse out deposit information from the contract transaction. either the chain got upgraded and the schema changed or the ecash contract got changed! terminating the process. it has to be inspected manually. error was: {err}");
self.cancellation_token.cancel();
return Err(VpnApiError::DepositFailure);
}
};
if contract_data.len() != replies.len() {
// another critical failure, that one should be quite impossible and thus has to be manually inspected
error!("CRITICAL FAILURE: failed to parse out all deposit information from the contract transaction. got {} responses while we sent {} deposits! either the chain got upgraded and the schema changed or the ecash contract got changed! terminating the process. it has to be inspected manually", contract_data.len(), replies.len());
self.cancellation_token.cancel();
return Err(VpnApiError::DepositFailure);
}
for (reply_channel, response) in replies.into_iter().zip(contract_data) {
let response_index = response.message_index;
let deposit_id = match response.parse_singleton_u32_contract_data() {
Ok(deposit_id) => deposit_id,
Err(err) => {
// another impossibility
error!("CRITICAL FAILURE: failed to parse out deposit id out of the response at index {response_index}: {err}. either the chain got upgraded and the schema changed or the ecash contract got changed! terminating the process. it has to be inspected manually");
self.cancellation_token.cancel();
return Err(VpnApiError::DepositFailure);
}
};
if reply_channel
.send(Some(DepositResponse {
deposit_id,
tx_hash,
}))
.is_err()
{
warn!("one of the deposit requesters has been terminated. deposit {deposit_id} will remain unclaimed!");
// this shouldn't happen as the requester task shouldn't be killed, but it's not a critical failure
// we just lost some tokens, but it's not an undefined on-chain behaviour
}
}
Ok(())
}
pub async fn run_forever(mut self) {
info!("starting the deposit maker task");
loop {
let mut receive_buffer = Vec::with_capacity(self.max_concurrent_deposits);
tokio::select! {
_ = self.cancellation_token.cancelled() => {
break
}
received = self.deposit_request_receiver.recv_many(&mut receive_buffer, self.max_concurrent_deposits) => {
debug!("received {received} deposit requests");
if let Err(err) = self.process_deposit_requests(receive_buffer).await {
error!("failed to process received deposit requests: {err}")
}
}
}
}
}
}
@@ -115,6 +115,9 @@ pub enum VpnApiError {
#[error("timed out while attempting to obtain partial wallet from {client_repr}")]
EcashApiRequestTimeout { client_repr: String },
#[error("failed to create deposit")]
DepositFailure,
}
impl VpnApiError {
@@ -1,64 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use axum::{
extract::{ConnectInfo, Request},
http::{
header::{HOST, USER_AGENT},
HeaderValue,
},
middleware::Next,
response::IntoResponse,
};
use colored::*;
use std::net::SocketAddr;
use tokio::time::Instant;
use tracing::info;
/// Simple logger for requests
pub async fn logger(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
req: Request,
next: Next,
) -> impl IntoResponse {
let method = req.method().to_string().green();
let uri = req.uri().to_string().blue();
let agent = header_map(
req.headers().get(USER_AGENT),
"Unknown User Agent".to_string(),
);
let host = header_map(req.headers().get(HOST), "Unknown Host".to_string());
let start = Instant::now();
let res = next.run(req).await;
let time_taken = start.elapsed();
let status = res.status();
let print_status = if status.is_client_error() || status.is_server_error() {
status.to_string().red()
} else if status.is_success() {
status.to_string().green()
} else {
status.to_string().yellow()
};
let taken = "time taken".bold();
let time_taken = match time_taken.as_millis() {
ms if ms > 500 => format!("{taken}: {}", format!("{ms}ms").red()),
ms if ms > 200 => format!("{taken}: {}", format!("{ms}ms").yellow()),
ms if ms > 50 => format!("{taken}: {}", format!("{ms}ms").bright_yellow()),
ms => format!("{taken}: {ms}ms"),
};
let agent_str = "agent".bold();
info!("[{addr} -> {host}] {method} '{uri}': {print_status} {time_taken} {agent_str}: {agent}");
res
}
fn header_map(header: Option<&HeaderValue>, msg: String) -> String {
header
.map(|x| x.to_str().unwrap_or(&msg).to_string())
.unwrap_or(msg)
}
@@ -1,5 +0,0 @@
// Copyright 2024 Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
pub mod auth;
pub mod logging;
@@ -10,7 +10,6 @@ use tokio_util::sync::CancellationToken;
use tracing::info;
pub mod helpers;
pub mod middleware;
pub mod router;
pub mod state;
pub mod types;
@@ -22,10 +21,15 @@ pub struct HttpServer {
}
impl HttpServer {
pub fn new(bind_address: SocketAddr, state: ApiState, auth_token: String) -> Self {
pub fn new(
bind_address: SocketAddr,
state: ApiState,
auth_token: String,
cancellation: CancellationToken,
) -> Self {
HttpServer {
bind_address,
cancellation: state.cancellation_token(),
cancellation,
router: build_router(state, auth_token),
}
}
@@ -4,8 +4,8 @@
use crate::http::state::ApiState;
use axum::Router;
use nym_credential_proxy_requests::routes;
use nym_http_api_common::middleware::bearer_auth::AuthLayer;
use crate::http::middleware::auth::AuthLayer;
pub(crate) use nym_http_api_common::{Output, OutputParams};
pub mod v1;
@@ -1,13 +1,11 @@
// Copyright 2024 Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use crate::http::middleware::auth::AuthLayer;
use crate::http::state::ApiState;
use axum::Router;
use nym_credential_proxy_requests::routes::api::v1;
use nym_http_api_common::middleware::bearer_auth::AuthLayer;
// pub mod bandwidth_voucher;
// pub mod freepass;
pub mod openapi;
pub mod ticketbook;
@@ -21,7 +21,7 @@ use nym_credential_proxy_requests::api::v1::ticketbook::models::{
use nym_credential_proxy_requests::routes::api::v1::ticketbook;
use nym_http_api_common::{FormattedResponse, OutputParams};
use time::OffsetDateTime;
use tracing::{error, info, span, warn, Level};
use tracing::{error, info, span, warn, Instrument, Level};
pub(crate) mod shares;
@@ -71,55 +71,58 @@ pub(crate) async fn obtain_ticketbook_shares(
let requested_on = OffsetDateTime::now_utc();
let span = span!(Level::INFO, "obtain ticketboook", uuid = %uuid);
let _entered = span.enter();
info!("");
async move {
info!("");
let output = params.output.unwrap_or_default();
let output = params.output.unwrap_or_default();
state.ensure_not_in_epoch_transition(Some(uuid)).await?;
let epoch_id = state
.current_epoch_id()
.await
.map_err(|err| RequestError::new_server_error(err, uuid))?;
state.ensure_not_in_epoch_transition(Some(uuid)).await?;
let epoch_id = state
.current_epoch_id()
.await
.map_err(|err| RequestError::new_server_error(err, uuid))?;
if let Err(err) = ensure_sane_expiration_date(payload.expiration_date) {
warn!("failure due to invalid expiration date");
return Err(RequestError::new_with_uuid(
err.to_string(),
uuid,
StatusCode::BAD_REQUEST,
));
}
if let Err(err) = ensure_sane_expiration_date(payload.expiration_date) {
warn!("failure due to invalid expiration date");
return Err(RequestError::new_with_uuid(
err.to_string(),
uuid,
StatusCode::BAD_REQUEST,
));
}
// if additional data was requested, grab them first in case there are any cache/network issues
let (
master_verification_key,
aggregated_expiration_date_signatures,
aggregated_coin_index_signatures,
) = state
.response_global_data(
params.include_master_verification_key,
params.include_expiration_date_signatures,
params.include_coin_index_signatures,
// if additional data was requested, grab them first in case there are any cache/network issues
let (
master_verification_key,
aggregated_expiration_date_signatures,
aggregated_coin_index_signatures,
) = state
.response_global_data(
params.include_master_verification_key,
params.include_expiration_date_signatures,
params.include_coin_index_signatures,
epoch_id,
payload.expiration_date,
uuid,
)
.await?;
let shares = try_obtain_wallet_shares(&state, uuid, requested_on, payload)
.await
.inspect_err(|err| warn!("request failure: {err}"))
.map_err(|err| RequestError::new(err.to_string(), StatusCode::INTERNAL_SERVER_ERROR))?;
info!("request was successful!");
Ok(output.to_response(TicketbookWalletSharesResponse {
epoch_id,
payload.expiration_date,
uuid,
)
.await?;
let shares = try_obtain_wallet_shares(&state, uuid, requested_on, payload)
.await
.inspect_err(|err| warn!("request failure: {err}"))
.map_err(|err| RequestError::new(err.to_string(), StatusCode::INTERNAL_SERVER_ERROR))?;
info!("request was successful!");
Ok(output.to_response(TicketbookWalletSharesResponse {
epoch_id,
shares,
master_verification_key,
aggregated_coin_index_signatures,
aggregated_expiration_date_signatures,
}))
shares,
master_verification_key,
aggregated_coin_index_signatures,
aggregated_expiration_date_signatures,
}))
}
.instrument(span)
.await
}
/// Attempt to obtain blinded shares of an ecash ticketbook wallet asynchronously
@@ -159,63 +162,69 @@ pub(crate) async fn obtain_ticketbook_shares_async(
let requested_on = OffsetDateTime::now_utc();
let span = span!(Level::INFO, "[async] obtain ticketboook", uuid = %uuid);
let _entered = span.enter();
info!("");
async move {
info!("");
let output = params.output.unwrap_or_default();
let output = params.output.unwrap_or_default();
// 1. perform basic validation
state.ensure_not_in_epoch_transition(Some(uuid)).await?;
// 1. perform basic validation
state.ensure_not_in_epoch_transition(Some(uuid)).await?;
if let Err(err) = ensure_sane_expiration_date(payload.inner.expiration_date) {
warn!("failure due to invalid expiration date");
return Err(RequestError::new_with_uuid(
err.to_string(),
uuid,
StatusCode::BAD_REQUEST,
));
}
// 2. store the request to retrieve the id
let pending = match state
.storage()
.insert_new_pending_async_shares_request(uuid, &payload.device_id, &payload.credential_id)
.await
{
Err(err) => {
error!("failed to insert new pending async shares: {err}");
if let Err(err) = ensure_sane_expiration_date(payload.inner.expiration_date) {
warn!("failure due to invalid expiration date");
return Err(RequestError::new_with_uuid(
err.to_string(),
uuid,
StatusCode::CONFLICT,
StatusCode::BAD_REQUEST,
));
}
Ok(pending) => pending,
};
let id = pending.id;
// 3. try to spawn a new task attempting to resolve the request
if state
.try_spawn(try_obtain_blinded_ticketbook_async(
state.clone(),
uuid,
requested_on,
payload,
params,
pending,
))
.is_none()
{
// we're going through the shutdown
return Err(RequestError::new_with_uuid(
"server shutdown in progress",
uuid,
StatusCode::INTERNAL_SERVER_ERROR,
));
// 2. store the request to retrieve the id
let pending = match state
.storage()
.insert_new_pending_async_shares_request(
uuid,
&payload.device_id,
&payload.credential_id,
)
.await
{
Err(err) => {
error!("failed to insert new pending async shares: {err}");
return Err(RequestError::new_with_uuid(
err.to_string(),
uuid,
StatusCode::CONFLICT,
));
}
Ok(pending) => pending,
};
let id = pending.id;
// 3. try to spawn a new task attempting to resolve the request
if state
.try_spawn(try_obtain_blinded_ticketbook_async(
state.clone(),
uuid,
requested_on,
payload,
params,
pending,
))
.is_none()
{
// we're going through the shutdown
return Err(RequestError::new_with_uuid(
"server shutdown in progress",
uuid,
StatusCode::INTERNAL_SERVER_ERROR,
));
}
// 4. in the meantime, return the id to the user
Ok(output.to_response(TicketbookWalletSharesAsyncResponse { id, uuid }))
}
// 4. in the meantime, return the id to the user
Ok(output.to_response(TicketbookWalletSharesAsyncResponse { id, uuid }))
.instrument(span)
.await
}
/// Obtain the current value of the bandwidth voucher deposit
@@ -17,7 +17,7 @@ use nym_credential_proxy_requests::api::v1::ticketbook::models::{
use nym_credential_proxy_requests::routes::api::v1::ticketbook::shares;
use nym_http_api_common::OutputParams;
use nym_validator_client::nym_api::EpochId;
use tracing::{debug, span, Level};
use tracing::{debug, span, Instrument, Level};
use uuid::Uuid;
async fn shares_to_response(
@@ -100,50 +100,51 @@ pub(crate) async fn query_for_shares_by_id(
let uuid = random_uuid();
let span = span!(Level::INFO, "query shares by id", uuid = %uuid, share_id = %share_id);
let _entered = span.enter();
debug!("");
async move {
debug!("");
// TODO: edge case: this will **NOT** work if shares got created in epoch X,
// but this query happened in epoch X+1
let shares = match state
.storage()
.load_wallet_shares_by_shares_id(share_id)
.await
{
Ok(shares) => {
if shares.is_empty() {
debug!("shares not found");
// TODO: edge case: this will **NOT** work if shares got created in epoch X,
// but this query happened in epoch X+1
let shares = match state
.storage()
.load_wallet_shares_by_shares_id(share_id)
.await
{
Ok(shares) => {
if shares.is_empty() {
debug!("shares not found");
// check for explicit error
match state
.storage()
.load_shares_error_by_shares_id(share_id)
.await
{
Ok(maybe_error_message) => {
if let Some(error_message) = maybe_error_message {
return Err(RequestError::new_with_uuid(
format!("failed to obtain wallet shares: {error_message} - share_id = {share_id}"),
uuid,
StatusCode::INTERNAL_SERVER_ERROR,
));
// check for explicit error
match state
.storage()
.load_shares_error_by_shares_id(share_id)
.await
{
Ok(maybe_error_message) => {
if let Some(error_message) = maybe_error_message {
return Err(RequestError::new_with_uuid(
format!("failed to obtain wallet shares: {error_message} - share_id = {share_id}"),
uuid,
StatusCode::INTERNAL_SERVER_ERROR,
));
}
}
Err(err) => return db_failure(err, uuid),
}
Err(err) => return db_failure(err, uuid),
return Err(RequestError::new_with_uuid(
format!("not found - share_id = {share_id}"),
uuid,
StatusCode::NOT_FOUND,
));
}
return Err(RequestError::new_with_uuid(
format!("not found - share_id = {share_id}"),
uuid,
StatusCode::NOT_FOUND,
));
shares
}
shares
}
Err(err) => return db_failure(err, uuid),
};
Err(err) => return db_failure(err, uuid),
};
shares_to_response(state, uuid, shares, params).await
shares_to_response(state, uuid, shares, params).await
}.instrument(span).await
}
/// Query by id for blinded wallet shares of a ticketbook
@@ -174,50 +175,51 @@ pub(crate) async fn query_for_shares_by_device_id_and_credential_id(
let uuid = random_uuid();
let span = span!(Level::INFO, "query shares by device and credential ids", uuid = %uuid, device_id = %device_id, credential_id = %credential_id);
let _entered = span.enter();
debug!("");
async move {
debug!("");
// TODO: edge case: this will **NOT** work if shares got created in epoch X,
// but this query happened in epoch X+1
let shares = match state
.storage()
.load_wallet_shares_by_device_and_credential_id(&device_id, &credential_id)
.await
{
Ok(shares) => {
if shares.is_empty() {
debug!("shares not found");
// TODO: edge case: this will **NOT** work if shares got created in epoch X,
// but this query happened in epoch X+1
let shares = match state
.storage()
.load_wallet_shares_by_device_and_credential_id(&device_id, &credential_id)
.await
{
Ok(shares) => {
if shares.is_empty() {
debug!("shares not found");
// check for explicit error
match state
.storage()
.load_shares_error_by_device_and_credential_id(&device_id, &credential_id)
.await
{
Ok(maybe_error_message) => {
if let Some(error_message) = maybe_error_message {
return Err(RequestError::new_with_uuid(
format!("failed to obtain wallet shares: {error_message} - device_id = {device_id}, credential_id = {credential_id}"),
uuid,
StatusCode::INTERNAL_SERVER_ERROR,
));
// check for explicit error
match state
.storage()
.load_shares_error_by_device_and_credential_id(&device_id, &credential_id)
.await
{
Ok(maybe_error_message) => {
if let Some(error_message) = maybe_error_message {
return Err(RequestError::new_with_uuid(
format!("failed to obtain wallet shares: {error_message} - device_id = {device_id}, credential_id = {credential_id}"),
uuid,
StatusCode::INTERNAL_SERVER_ERROR,
));
}
}
Err(err) => return db_failure(err, uuid),
}
Err(err) => return db_failure(err, uuid),
return Err(RequestError::new_with_uuid(
format!("not found - device_id = {device_id}, credential_id = {credential_id}"),
uuid,
StatusCode::NOT_FOUND,
));
}
return Err(RequestError::new_with_uuid(
format!("not found - device_id = {device_id}, credential_id = {credential_id}"),
uuid,
StatusCode::NOT_FOUND,
));
shares
}
shares
}
Err(err) => return db_failure(err, uuid),
};
Err(err) => return db_failure(err, uuid),
};
shares_to_response(state, uuid, shares, params).await
shares_to_response(state, uuid, shares, params).await
}.instrument(span).await
}
pub(crate) fn routes() -> Router<ApiState> {
@@ -1,13 +1,13 @@
// Copyright 2024 Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use crate::http::middleware::auth::AuthLayer;
use crate::http::middleware::logging;
use crate::http::state::ApiState;
use axum::response::Redirect;
use axum::routing::{get, MethodRouter};
use axum::Router;
use nym_credential_proxy_requests::routes;
use nym_http_api_common::middleware::bearer_auth::AuthLayer;
use nym_http_api_common::middleware::logging;
use std::sync::Arc;
use zeroize::Zeroizing;
@@ -1,6 +1,7 @@
// Copyright 2024 Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use crate::deposit_maker::{DepositRequest, DepositRequestSender};
use crate::error::VpnApiError;
use crate::helpers::LockTimer;
use crate::http::types::RequestError;
@@ -28,20 +29,24 @@ use nym_credentials::{
AggregatedCoinIndicesSignatures, AggregatedExpirationDateSignatures, EpochVerificationKey,
};
use nym_credentials_interface::VerificationKeyAuth;
use nym_ecash_contract_common::msg::ExecuteMsg;
use nym_validator_client::coconut::EcashApiError;
use nym_validator_client::nym_api::EpochId;
use nym_validator_client::nyxd::contract_traits::dkg_query_client::Epoch;
use nym_validator_client::nyxd::contract_traits::{
DkgQueryClient, EcashQueryClient, NymContractsProvider, PagedDkgQueryClient,
};
use nym_validator_client::nyxd::{Coin, NyxdClient};
use nym_validator_client::nyxd::cosmwasm_client::types::ExecuteResult;
use nym_validator_client::nyxd::{Coin, CosmWasmClient, NyxdClient};
use nym_validator_client::{nyxd, DirectSigningHttpRpcNyxdClient, EcashApiClient};
use std::future::Future;
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;
use time::{Date, OffsetDateTime};
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tokio::task::JoinHandle;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tracing::{debug, info, warn};
@@ -59,36 +64,19 @@ impl ApiState {
pub async fn new(
storage: VpnApiStorage,
zk_nym_web_hook_config: ZkNymWebHookConfig,
mnemonic: Mnemonic,
client: ChainClient,
deposit_requester: DepositRequestSender,
cancellation_token: CancellationToken,
) -> Result<Self, VpnApiError> {
let network_details = nym_network_defaults::NymNetworkDetails::new_from_env();
let client_config = nyxd::Config::try_from_nym_network_details(&network_details)?;
let nyxd_url = network_details
.endpoints
.first()
.ok_or_else(|| VpnApiError::NoNyxEndpointsAvailable)?
.nyxd_url
.as_str();
let client = NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic)?;
if client.ecash_contract_address().is_none() {
return Err(VpnApiError::UnavailableEcashContract);
}
if client.dkg_contract_address().is_none() {
return Err(VpnApiError::UnavailableDKGContract);
}
let state = ApiState {
inner: Arc::new(ApiStateInner {
storage,
client: RwLock::new(client),
client,
ecash_state: EcashState::default(),
zk_nym_web_hook_config,
task_tracker: TaskTracker::new(),
cancellation_token: CancellationToken::new(),
deposit_requester,
cancellation_token,
}),
};
@@ -136,10 +124,6 @@ impl ApiState {
self.inner.task_tracker.wait().await
}
pub(crate) fn cancellation_token(&self) -> CancellationToken {
self.inner.cancellation_token.clone()
}
pub(crate) fn zk_nym_web_hook(&self) -> &ZkNymWebHookConfig {
&self.inner.zk_nym_web_hook_config
}
@@ -220,16 +204,19 @@ impl ApiState {
}
pub(crate) async fn query_chain(&self) -> RwLockReadGuard<DirectSigningHttpRpcNyxdClient> {
let _acquire_timer = LockTimer::new("acquire chain query permit");
self.inner.client.read().await
self.inner.client.query_chain().await
}
pub(crate) async fn start_chain_tx(&self) -> ChainWritePermit {
let _acquire_timer = LockTimer::new("acquire exclusive chain write permit");
pub(crate) async fn request_deposit(&self, request: DepositRequest) {
let start = Instant::now();
self.inner.deposit_requester.request_deposit(request).await;
ChainWritePermit {
lock_timer: LockTimer::new("exclusive chain access permit"),
inner: self.inner.client.write().await,
let time_taken = start.elapsed();
let formatted = humantime::format_duration(time_taken);
if time_taken > Duration::from_secs(10) {
warn!("attempting to push new deposit request onto the queue took {formatted}. perhaps the buffer is too small or the process/chain is overloaded?")
} else {
debug!("attempting to push new deposit request onto the queue took {formatted}")
}
}
@@ -604,10 +591,57 @@ impl ApiState {
}
}
#[derive(Clone)]
pub struct ChainClient(Arc<RwLock<DirectSigningHttpRpcNyxdClient>>);
impl ChainClient {
pub fn new(mnemonic: Mnemonic) -> Result<Self, VpnApiError> {
let network_details = nym_network_defaults::NymNetworkDetails::new_from_env();
let client_config = nyxd::Config::try_from_nym_network_details(&network_details)?;
let nyxd_url = network_details
.endpoints
.first()
.ok_or_else(|| VpnApiError::NoNyxEndpointsAvailable)?
.nyxd_url
.as_str();
let client = NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic)?;
if client.ecash_contract_address().is_none() {
return Err(VpnApiError::UnavailableEcashContract);
}
if client.dkg_contract_address().is_none() {
return Err(VpnApiError::UnavailableDKGContract);
}
Ok(ChainClient(Arc::new(RwLock::new(client))))
}
pub(crate) async fn query_chain(&self) -> ChainReadPermit {
let _acquire_timer = LockTimer::new("acquire chain query permit");
self.0.read().await
}
pub(crate) async fn start_chain_tx(&self) -> ChainWritePermit {
let _acquire_timer = LockTimer::new("acquire exclusive chain write permit");
ChainWritePermit {
lock_timer: LockTimer::new("exclusive chain access permit"),
inner: self.0.write().await,
}
}
}
//
struct ApiStateInner {
storage: VpnApiStorage,
client: RwLock<DirectSigningHttpRpcNyxdClient>,
client: ChainClient,
deposit_requester: DepositRequestSender,
zk_nym_web_hook_config: ZkNymWebHookConfig,
@@ -666,6 +700,8 @@ pub(crate) struct EcashState {
CachedImmutableItems<Date, AggregatedExpirationDateSignatures>,
}
pub(crate) type ChainReadPermit<'a> = RwLockReadGuard<'a, DirectSigningHttpRpcNyxdClient>;
// explicitly wrap the WriteGuard for extra information regarding time taken
pub(crate) struct ChainWritePermit<'a> {
// it's not really dead, we only care about it being dropped
@@ -674,6 +710,55 @@ pub(crate) struct ChainWritePermit<'a> {
inner: RwLockWriteGuard<'a, DirectSigningHttpRpcNyxdClient>,
}
impl<'a> ChainWritePermit<'a> {
pub(crate) async fn make_deposits(
self,
short_sha: &'static str,
info: Vec<(String, Coin)>,
) -> Result<ExecuteResult, VpnApiError> {
let address = self.inner.address();
let starting_sequence = self.inner.get_sequence(&address).await?.sequence;
let deposits = info.len();
let ecash_contract = self
.inner
.ecash_contract_address()
.ok_or(VpnApiError::UnavailableEcashContract)?;
let deposit_messages = info
.into_iter()
.map(|(identity_key, amount)| {
(
ExecuteMsg::DepositTicketBookFunds { identity_key },
vec![amount],
)
})
.collect::<Vec<_>>();
let res = self
.inner
.execute_multiple(
ecash_contract,
deposit_messages,
None,
format!("cp-{short_sha}: performing {deposits} deposits"),
)
.await?;
loop {
let updated_sequence = self.inner.get_sequence(&address).await?.sequence;
if updated_sequence > starting_sequence {
break;
}
warn!("wrong sequence number... waiting before releasing chain lock");
tokio::time::sleep(Duration::from_millis(50)).await;
}
Ok(res)
}
}
impl Deref for ChainWritePermit<'_> {
type Target = DirectSigningHttpRpcNyxdClient;
@@ -7,19 +7,23 @@
#![warn(clippy::dbg_macro)]
use crate::cli::Cli;
use crate::deposit_maker::DepositMaker;
use crate::error::VpnApiError;
use crate::http::state::ApiState;
use crate::http::state::{ApiState, ChainClient};
use crate::http::HttpServer;
use crate::storage::VpnApiStorage;
use crate::tasks::StoragePruner;
use clap::Parser;
use nym_bin_common::logging::setup_tracing_logger;
use nym_bin_common::{bin_info, bin_info_owned};
use nym_network_defaults::setup_env;
use tracing::{info, trace};
use tokio_util::sync::CancellationToken;
use tracing::{error, info, trace};
pub mod cli;
pub mod config;
pub mod credentials;
mod deposit_maker;
pub mod error;
pub mod helpers;
pub mod http;
@@ -50,6 +54,20 @@ pub async fn wait_for_signal() {
}
}
fn build_sha_short() -> &'static str {
let bin_info = bin_info!();
if bin_info.commit_sha.len() < 7 {
panic!("unavailable build commit sha")
}
if bin_info.commit_sha == "VERGEN_IDEMPOTENT_OUTPUT" {
error!("the binary hasn't been built correctly. it doesn't have a commit sha information");
return "unknown";
}
&bin_info.commit_sha[..7]
}
async fn run_api(cli: Cli) -> Result<(), VpnApiError> {
// create the tasks
let bind_address = cli.bind_address();
@@ -58,14 +76,37 @@ async fn run_api(cli: Cli) -> Result<(), VpnApiError> {
let mnemonic = cli.mnemonic;
let auth_token = cli.http_auth_token;
let webhook_cfg = cli.webhook;
let api_state = ApiState::new(storage.clone(), webhook_cfg, mnemonic).await?;
let http_server = HttpServer::new(bind_address, api_state.clone(), auth_token);
let chain_client = ChainClient::new(mnemonic)?;
let cancellation_token = CancellationToken::new();
let storage_pruner = StoragePruner::new(api_state.cancellation_token(), storage);
let deposit_maker = DepositMaker::new(
build_sha_short(),
chain_client.clone(),
cli.max_concurrent_deposits,
cancellation_token.clone(),
);
let deposit_request_sender = deposit_maker.deposit_request_sender();
let api_state = ApiState::new(
storage.clone(),
webhook_cfg,
chain_client,
deposit_request_sender,
cancellation_token.clone(),
)
.await?;
let http_server = HttpServer::new(
bind_address,
api_state.clone(),
auth_token,
cancellation_token.clone(),
);
let storage_pruner = StoragePruner::new(cancellation_token, storage);
// spawn all the tasks
api_state.try_spawn(http_server.run_forever());
api_state.try_spawn(storage_pruner.run_forever());
api_state.try_spawn(deposit_maker.run_forever());
// wait for cancel signal (SIGINT, SIGTERM or SIGQUIT)
wait_for_signal().await;
@@ -78,10 +119,10 @@ async fn run_api(cli: Cli) -> Result<(), VpnApiError> {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
std::env::set_var(
"RUST_LOG",
"trace,handlebars=warn,tendermint_rpc=warn,h2=warn,hyper=warn,rustls=warn,reqwest=warn,tungstenite=warn,async_tungstenite=warn,tokio_util=warn,tokio_tungstenite=warn,tokio-util=warn,nym_validator_client=info",
);
// std::env::set_var(
// "RUST_LOG",
// "trace,handlebars=warn,tendermint_rpc=warn,h2=warn,hyper=warn,rustls=warn,reqwest=warn,tungstenite=warn,async_tungstenite=warn,tokio_util=warn,tokio_tungstenite=warn,tokio-util=warn,axum=warn,sqlx-core=warn,nym_validator_client=info",
// );
let cli = Cli::parse();
cli.webhook.ensure_valid_client_url()?;
@@ -90,6 +131,9 @@ async fn main() -> anyhow::Result<()> {
setup_env(cli.config_env_file.as_ref());
setup_tracing_logger();
let bin_info = bin_info_owned!();
info!("using the following version: {bin_info}");
run_api(cli).await?;
Ok(())
}
@@ -19,7 +19,9 @@ use nym_validator_client::nyxd::Coin;
use sqlx::ConnectOptions;
use std::fmt::Debug;
use std::path::Path;
use std::time::Duration;
use time::{Date, OffsetDateTime};
use tracing::log::LevelFilter;
use tracing::{debug, error, info, instrument};
use uuid::Uuid;
use zeroize::Zeroizing;
@@ -40,9 +42,15 @@ impl VpnApiStorage {
let opts = sqlx::sqlite::SqliteConnectOptions::new()
.filename(database_path)
.create_if_missing(true)
.disable_statement_logging();
.log_statements(LevelFilter::Trace)
.log_slow_statements(LevelFilter::Warn, Duration::from_millis(250));
let connection_pool = match sqlx::SqlitePool::connect_with(opts).await {
let pool_opts = sqlx::sqlite::SqlitePoolOptions::new()
.min_connections(5)
.max_connections(25)
.acquire_timeout(Duration::from_secs(60));
let connection_pool = match pool_opts.connect_with(opts).await {
Ok(db) => db,
Err(err) => {
error!("Failed to connect to SQLx database: {err}");
@@ -19,10 +19,11 @@ impl StoragePruner {
}
pub async fn run_forever(self) {
while !self.cancellation_token.is_cancelled() {
info!("starting the storage pruner task");
loop {
tokio::select! {
_ = self.cancellation_token.cancelled() => {
// The token was cancelled, task can shut down
break
}
_ = tokio::time::sleep(std::time::Duration::from_secs(60 * 60)) => {
match self.storage.prune_old_blinded_shares().await {
@@ -5,7 +5,7 @@ use crate::error::VpnApiError;
use clap::Args;
use reqwest::header::AUTHORIZATION;
use serde::Serialize;
use tracing::{debug, error, instrument, span, Level};
use tracing::{debug, error, instrument, span, Instrument, Level};
use url::Url;
use uuid::Uuid;
@@ -46,30 +46,33 @@ impl ZkNymWebHookConfig {
pub async fn try_trigger<T: Serialize + ?Sized>(&self, original_uuid: Uuid, payload: &T) {
let url = self.unchecked_client_url();
let span = span!(Level::DEBUG, "webhook", uuid = %original_uuid, url = %url);
let _entered = span.enter();
debug!("🕸️ about to trigger the webhook");
async move {
debug!("🕸️ about to trigger the webhook");
match reqwest::Client::new()
.post(url.clone())
.header(AUTHORIZATION, self.bearer_token())
.json(payload)
.send()
.await
{
Ok(res) => {
if !res.status().is_success() {
error!("❌🕸️ failed to call webhook: {res:?}");
} else {
debug!("✅🕸️ webhook triggered successfully: {res:?}");
if let Ok(body) = res.text().await {
debug!("body = {body}");
match reqwest::Client::new()
.post(url.clone())
.header(AUTHORIZATION, self.bearer_token())
.json(payload)
.send()
.await
{
Ok(res) => {
if !res.status().is_success() {
error!("❌🕸️ failed to call webhook: {res:?}");
} else {
debug!("✅🕸️ webhook triggered successfully: {res:?}");
if let Ok(body) = res.text().await {
debug!("body = {body}");
}
}
}
}
Err(err) => {
error!("failed to call webhook: {err}")
Err(err) => {
error!("failed to call webhook: {err}")
}
}
}
.instrument(span)
.await
}
}
+2
View File
@@ -0,0 +1,2 @@
nym-gateway-probe
keys/
@@ -1,6 +1,7 @@
# Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
# SPDX-License-Identifier: Apache-2.0
[package]
name = "nym-node-status-agent"
version = "1.0.0-rc.1"
@@ -15,14 +16,20 @@ readme.workspace = true
[dependencies]
anyhow = { workspace = true}
bincode = { workspace = true }
chrono = { workspace = true }
clap = { workspace = true, features = ["derive", "env"] }
nym-bin-common = { path = "../../common/bin-common", features = ["models"]}
nym-node-status-client = { path = "../nym-node-status-client" }
nym-crypto = { path = "../../common/crypto", features = ["asymmetric", "rand"] }
nym-bin-common = { path = "../common/bin-common", features = ["models"]}
nym-common-models = { path = "../common/models" }
nym-crypto = { path = "../common/crypto", features = ["asymmetric", "rand"] }
rand = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "process"] }
tokio-util = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
reqwest = { workspace = true, features = ["json"] }
serde = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
@@ -3,14 +3,14 @@
set -eu
export ENVIRONMENT=${ENVIRONMENT:-"sandbox"}
probe_git_ref="nym-vpn-core-v1.0.0-rc.14"
probe_git_ref="nym-vpn-core-v1.0.0-rc.6"
crate_root=$(dirname $(realpath "$0"))
monorepo_root=$(realpath "${crate_root}/../..")
monorepo_root=$(dirname "${crate_root}")
echo "Expecting nym-vpn-client repo at a sibling level of nym monorepo dir"
gateway_probe_src=$(dirname "${monorepo_root}")/nym-vpn-client/nym-vpn-core
echo "gateway_probe_src=$gateway_probe_src"
echo "crate_root=$crate_root"
set -a
source "${monorepo_root}/envs/${ENVIRONMENT}.env"
@@ -30,11 +30,9 @@ function copy_gw_probe() {
pushd $gateway_probe_src
git fetch -a
git checkout $probe_git_ref
cargo build --release --package nym-gateway-probe
cp target/release/nym-gateway-probe "$crate_root"
$crate_root/nym-gateway-probe --version
popd
}
@@ -46,7 +44,7 @@ function swarm() {
local workers=$1
for ((i = 1; i <= workers; i++)); do
${monorepo_root}/target/release/nym-node-status-agent run-probe &
../target/release/nym-node-status-agent run-probe &
done
wait
@@ -1,35 +1,62 @@
use crate::models::{get_testrun, submit_results, TestrunAssignment};
use anyhow::bail;
use api::ApiPaths;
use anyhow::{bail, Context};
use nym_common_models::ns_api::{get_testrun, submit_results, TestrunAssignment};
use nym_crypto::asymmetric::ed25519::{PrivateKey, Signature};
use std::fmt::Display;
use tracing::instrument;
mod api;
pub mod auth;
pub mod models;
use crate::cli::GwProbe;
pub struct NsApiClient {
api: ApiPaths,
const INTERNAL_TESTRUNS: &str = "internal/testruns";
pub(crate) async fn run_probe(
server_ip: &str,
server_port: u16,
ns_api_auth_key: &str,
probe_path: &str,
) -> anyhow::Result<()> {
let auth_key = PrivateKey::from_base58_string(ns_api_auth_key)
.context("Couldn't parse auth key, exiting")?;
let ns_api_client = Client::new(server_ip, server_port, auth_key);
let probe = GwProbe::new(probe_path.to_string());
let version = probe.version().await;
tracing::info!("Probe version:\n{}", version);
if let Some(testrun) = ns_api_client.request_testrun().await? {
let log = probe.run_and_get_log(&Some(testrun.gateway_identity_key));
ns_api_client
.submit_results(testrun.testrun_id, log, testrun.assigned_at_utc)
.await?;
} else {
tracing::info!("No testruns available, exiting")
}
Ok(())
}
struct Client {
server_address: String,
client: reqwest::Client,
auth_key: PrivateKey,
}
impl NsApiClient {
impl Client {
pub fn new(server_ip: &str, server_port: u16, auth_key: PrivateKey) -> Self {
let server_address = format!("{}:{}", server_ip, server_port);
let api = ApiPaths::new(server_address);
let client = reqwest::Client::new();
Self {
api,
server_address,
client,
auth_key,
}
}
#[instrument(level = "debug", skip_all)]
pub async fn request_testrun(&self) -> anyhow::Result<Option<TestrunAssignment>> {
let target_url = self.api.request_testrun();
pub(crate) async fn request_testrun(&self) -> anyhow::Result<Option<TestrunAssignment>> {
let target_url = self.api_with_subpath(None::<String>);
let payload = get_testrun::Payload {
agent_public_key: self.auth_key.public_key(),
@@ -66,13 +93,13 @@ impl NsApiClient {
}
#[instrument(level = "debug", skip(self, probe_result))]
pub async fn submit_results(
pub(crate) async fn submit_results(
&self,
testrun_id: i64,
probe_result: String,
assigned_at_utc: i64,
) -> anyhow::Result<()> {
let target_url = self.api.submit_results(testrun_id);
let target_url = self.api_with_subpath(Some(testrun_id));
let payload = submit_results::Payload {
probe_result,
@@ -102,4 +129,12 @@ impl NsApiClient {
let signed = self.auth_key.sign(&serialized);
Ok(signed)
}
fn api_with_subpath(&self, subpath: Option<impl Display>) -> String {
if let Some(subpath) = subpath {
format!("{}/{}/{}", self.server_address, INTERNAL_TESTRUNS, subpath)
} else {
format!("{}/{}", self.server_address, INTERNAL_TESTRUNS)
}
}
}
+1 -2
View File
@@ -1,7 +1,6 @@
nym-node-status-agent/nym-gateway-probe
nym-node-status-agent/keys/
data/
enter_db.sh
nym-gateway-probe
nym-node-status-api
*.sqlite
*.sqlite-journal

Some files were not shown because too many files have changed in this diff Show More