Compare commits

..

1 Commits

Author SHA1 Message Date
Bogdan-Ștefan Neacşu 79b8b4d324 Add query message wrapper 2024-11-15 16:31:51 +02:00
182 changed files with 922 additions and 6435 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ on:
jobs:
check-schema:
name: Generate and check schema
runs-on: ubuntu-20.04
runs-on: arc-ubuntu-20.04
env:
CARGO_TERM_COLOR: always
steps:
+1 -1
View File
@@ -13,7 +13,7 @@ on:
jobs:
matrix_prep:
runs-on: ubuntu-20.04
runs-on: arc-ubuntu-20.04
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -55,7 +55,6 @@ jobs:
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Build all binaries
uses: actions-rs/cargo@v1
+3 -4
View File
@@ -14,14 +14,13 @@ jobs:
- name: Install Rust stable
uses: actions-rs/toolchain@v1
with:
toolchain: 1.77
toolchain: stable
target: wasm32-unknown-unknown
override: true
components: rustfmt, clippy
- name: Install wasm-opt
uses: ./.github/actions/install-wasm-opt
with:
version: '114'
run: cargo install --version 0.114.0 wasm-opt
- name: Build release contracts
run: make contracts
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
git config --global user.name "Lawrence Stalder"
- name: Get version from cargo.toml
uses: mikefarah/yq@v4.44.5
uses: mikefarah/yq@v4.44.3
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/nym-credential-proxy/Cargo.toml
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
git config --global user.name "Lawrence Stalder"
- name: Get version from cargo.toml
uses: mikefarah/yq@v4.44.5
uses: mikefarah/yq@v4.44.3
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
+18 -14
View File
@@ -25,27 +25,31 @@ jobs:
git config --global user.email "lawrence@nymtech.net"
git config --global user.name "Lawrence Stalder"
- name: Get version from cargo.toml
uses: mikefarah/yq@v4.44.5
- name: Get version from package.json
uses: sergeysova/jq-action@v2
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/nym-network-monitor/Cargo.toml
cmd: jq -r '.version' ${{ env.WORKING_DIRECTORY }}/package.json
- name: Check if tag exists
run: |
if git rev-parse ${{ steps.get_version.outputs.value }} >/dev/null 2>&1; then
echo "Tag ${{ steps.get_version.outputs.value }} already exists"
fi
- name: Remove existing tag if exists
run: |
echo "Checking if tag ${{ env.CONTAINER_NAME }}-${{ steps.get_version.outputs.result }} exists..."
if git rev-parse ${{ env.CONTAINER_NAME }}-${{ steps.get_version.outputs.result }} >/dev/null 2>&1; then
echo "Tag ${{ env.CONTAINER_NAME }}-${{ steps.get_version.outputs.result }} already exists"
git push --delete origin ${{ env.CONTAINER_NAME }}-${{ steps.get_version.outputs.result }}
git tag -d ${{ env.CONTAINER_NAME }}-${{ steps.get_version.outputs.result }}
if git rev-parse ${{ steps.get_version.outputs.value }} >/dev/null 2>&1; then
git push --delete origin ${{ steps.get_version.outputs.value }}
git tag -d ${{ steps.get_version.outputs.value }}
fi
- name: Create tag
run: |
git tag -a ${{ env.CONTAINER_NAME }}-${{ steps.get_version.outputs.result }} -m "Version ${{ steps.get_version.outputs.result }}"
git push origin ${{ env.CONTAINER_NAME }}-${{ steps.get_version.outputs.result }}
git tag -a ${{ steps.get_version.outputs.value }} -m "Version ${{ steps.get_version.outputs.value }}"
git push origin ${{ steps.get_version.outputs.value }}
- name: BuildAndPushImageOnHarbor
run: |
docker build -f nym-network-monitor.dockerfile ${{ env.WORKING_DIRECTORY }} -t harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }}:${{ steps.get_version.outputs.result }} -t harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }}:latest
docker push harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }} --all-tags
docker build -f nym-network-monitor.dockerfile ${{ env.WORKING_DIRECTORY }} -t harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }}:${{ steps.get_version.outputs.value }} -t harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }}:latest
docker push harbor.nymte.ch/nym/${{ env.CONTAINER_NAME }} --all-tags
@@ -31,7 +31,7 @@ jobs:
git config --global user.name "Lawrence Stalder"
- name: Get version from cargo.toml
uses: mikefarah/yq@v4.44.5
uses: mikefarah/yq@v4.44.3
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
@@ -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
@@ -26,7 +26,7 @@ jobs:
git config --global user.name "Lawrence Stalder"
- name: Get version from cargo.toml
uses: mikefarah/yq@v4.44.5
uses: mikefarah/yq@v4.44.3
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
git config --global user.name "Lawrence Stalder"
- name: Get version from cargo.toml
uses: mikefarah/yq@v4.44.5
uses: mikefarah/yq@v4.44.3
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/Cargo.toml
@@ -26,7 +26,7 @@ jobs:
git config --global user.name "Lawrence Stalder"
- name: Get version from cargo.toml
uses: mikefarah/yq@v4.44.5
uses: mikefarah/yq@v4.44.3
id: get_version
with:
cmd: yq -oy '.package.version' ${{ env.WORKING_DIRECTORY }}/nym-credential-proxy/Cargo.toml
-192
View File
@@ -4,198 +4,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
## [Unreleased]
## [2024.13-magura] (2024-11-18)
- Limit race probability ([#5145])
- bugifx: assign 'node_id' when converting from 'GatewayDetails' to 'TestNode' ([#5143])
- bugfix: make sure to assign correct node_id and identity during 'gateway_details' table migration ([#5142])
- Respond to auth messages with same version ([#5140])
- Pain/polyfill deprecated endpoints ([#5131])
- change: dont select mixnodes bonded with vested tokens into the rewarded set ([#5129])
- nym-credential-proxy-requests: reqwest use rustls-tls ([#5116])
- bugfix: preserve as much as possible of the rewarded set during migration ([#5103])
- Feature/force refresh node ([#5101])
- Add NYM_VPN_API to env files ([#5099])
- bugfix: fixed historical uptimes for nodes ([#5097])
- Remove old use of 1GB constant ([#5096])
- Graceful agent 1.1.5 ([#5093])
- Add more translations from v2 to v3 authenticator ([#5091])
- Nym node - Fix claim delegator rewards ([#5090])
- Make 250 GB/30 days for free ride mode ([#5083])
- Don't increase bandwidth two times ([#5081])
- Fix expiration date as today + 7 days ([#5076])
- Fix gateway decreasing bandwidth ([#5075])
- Allow custom http port to be reset ([#5073])
- bugfix: additional checks inside credential proxy ([#5072])
- chore: deprecated old nym-api client methods and replaced them when possible ([#5069])
- NS API with directory v2 (#5058) ([#5068])
- bugfix: credential-proxy obtain-async ([#5067])
- Allow nym node config updates ([#5066])
- bugfix: use corrext axum extractors for ecash route arguments ([#5065])
- Merge2/release/2024.13 magura ([#5063])
- bugfix/feature: added NymApiClient method to get all skimmed nodes ([#5062])
- Merge1/release/2024.13 magura ([#5061])
- added hacky routes to return nymnodes alongside legacy nodes ([#5051])
- bugfix: mark migrated gateways as rewarded in the previous epoch in case theyre in the rewarded set ([#5049])
- bugfix: adjust runtime storage migration ([#5047])
- bugfix: supersede 'cb13be27f8f61d9ae74d924e85d2e6787895eb14' by using… ([#5046])
- bugfix: restore default http port for nym-api ([#5045])
- bugfix: fix ecash handlers routes ([#5043])
- bugfix: don't assign exit gateways to standby set ([#5041])
- bugfix: make sure nym-nodes are also tested by network monitor ([#5040])
- bugfix: use bonded nym-nodes for determining initial network monitor … ([#5039])
- bugfix: make gateways insert themselves into [local] topology ([#5038])
- Pass poisson flag ([#5037])
- bugfix: use human readable roles for annotations ([#5036])
- bugfix: use old name for 'epoch_role' in SkimmedNode ([#5034])
- bugfix: make sure to use correct highest node id when assigning role ([#5032])
- feature: use axum_client_ip for attempting to extract source ip ([#5031])
- bugfix: fixed backwards incompatibility for /gateways/described endpoint ([#5030])
- bugfix: verifying signed information of legacy nodes ([#5029])
- bugfix: introduce 'LegacyPendingMixNodeChanges' that does not contain 'cost_params_change' ([#5028])
- bugfix: missing #[serde(default)] for announce port ([#5024])
- bugfix: directory v2.1 `get_all_avg_gateway_reliability_in_interval` query ([#5023])
- added 'get_all_described_nodes' to NymApiClient and adjusted return t… ([#5016])
- Reapply fixes to new branch ([#5014])
- Consume only positive bandwidth ([#5013])
- feature: adjusted ticket sizes to the agreed amounts ([#5009])
- Push private ip before inserting ([#5008])
- chore: update itertools in compact ecash ([#4994])
- feature: make accepting t&c a hard requirement for rewarded set selection ([#4993])
- Fix rustfmt in nym-credential-proxy ([#4992])
- bugfix: client memory leak ([#4991])
- Eliminate 0 bandwidth race check ([#4988])
- [DOCs;/operators]: Release notes for v2024.12 aero ([#4984])
- Add topup req constructor ([#4983])
- Fix critical issues SI86 and SI87 from Cure53 ([#4982])
- Rename nym-vpn-api to nym-credential-proxy ([#4981])
- enable global ecash routes even if api is not a signer ([#4980])
- resolve beta clippy issues in contracts ([#4978])
- Re-enable vested delegation migration ([#4977])
- feature: require reporting using nym-node binary for rewarded set selection ([#4976])
- Top up bandwidth ([#4975])
- [Product Data] Add session type based on ecash ticket received ([#4974])
- Bugfix/additional directory fixes ([#4973])
- feat: add Dockerfile for nym node ([#4972])
- chore: remove unused rocket code ([#4968])
- Import nym-vpn-api crates ([#4967])
- feature: importer-cli to correctly handle mixnet/vesting import ([#4966])
- bugfix: fix expected return type on /v1/gateways endpoint ([#4965])
- [Product Data] First step in gateway usage data collection ([#4963])
- Bump sqlx to 0.7.4 ([#4959])
- Add env feature to clap and make clap parameters available as env variables ([#4957])
- Feature/contract state tools ([#4954])
- expose authenticator address along other address in node-details ([#4953])
- Extract packet processing from mixnode-common ([#4949])
- nym-api container ([#4948])
- Ticket type storage ([#4947])
- Add "utoipa" feature to nym-node ([#4945])
- build(deps): bump the patch-updates group across 1 directory with 9 updates ([#4944])
- V2 performance monitoring feature flag ([#4943])
- Bugfix/rewarder post pruning adjustments ([#4942])
- Switch over the last set of jobs to arc runners ([#4938])
- Fix broken build after merge ([#4937])
- bugfix: correctly paginate through 'search_tx' endpoint ([#4936])
- Add more conversions for responses of authenticator messages ([#4929])
- Directory Sevices v2.1 ([#4903])
- Migrate Legacy Node (Frontend) ([#4826])
- Fix critical issues SI84 and SI85 from Cure53 ([#4758])
[#5145]: https://github.com/nymtech/nym/pull/5145
[#5143]: https://github.com/nymtech/nym/pull/5143
[#5142]: https://github.com/nymtech/nym/pull/5142
[#5140]: https://github.com/nymtech/nym/pull/5140
[#5131]: https://github.com/nymtech/nym/pull/5131
[#5129]: https://github.com/nymtech/nym/pull/5129
[#5116]: https://github.com/nymtech/nym/pull/5116
[#5103]: https://github.com/nymtech/nym/pull/5103
[#5101]: https://github.com/nymtech/nym/pull/5101
[#5099]: https://github.com/nymtech/nym/pull/5099
[#5097]: https://github.com/nymtech/nym/pull/5097
[#5096]: https://github.com/nymtech/nym/pull/5096
[#5093]: https://github.com/nymtech/nym/pull/5093
[#5091]: https://github.com/nymtech/nym/pull/5091
[#5090]: https://github.com/nymtech/nym/pull/5090
[#5083]: https://github.com/nymtech/nym/pull/5083
[#5081]: https://github.com/nymtech/nym/pull/5081
[#5076]: https://github.com/nymtech/nym/pull/5076
[#5075]: https://github.com/nymtech/nym/pull/5075
[#5073]: https://github.com/nymtech/nym/pull/5073
[#5072]: https://github.com/nymtech/nym/pull/5072
[#5069]: https://github.com/nymtech/nym/pull/5069
[#5068]: https://github.com/nymtech/nym/pull/5068
[#5067]: https://github.com/nymtech/nym/pull/5067
[#5066]: https://github.com/nymtech/nym/pull/5066
[#5065]: https://github.com/nymtech/nym/pull/5065
[#5063]: https://github.com/nymtech/nym/pull/5063
[#5062]: https://github.com/nymtech/nym/pull/5062
[#5061]: https://github.com/nymtech/nym/pull/5061
[#5051]: https://github.com/nymtech/nym/pull/5051
[#5049]: https://github.com/nymtech/nym/pull/5049
[#5047]: https://github.com/nymtech/nym/pull/5047
[#5046]: https://github.com/nymtech/nym/pull/5046
[#5045]: https://github.com/nymtech/nym/pull/5045
[#5043]: https://github.com/nymtech/nym/pull/5043
[#5041]: https://github.com/nymtech/nym/pull/5041
[#5040]: https://github.com/nymtech/nym/pull/5040
[#5039]: https://github.com/nymtech/nym/pull/5039
[#5038]: https://github.com/nymtech/nym/pull/5038
[#5037]: https://github.com/nymtech/nym/pull/5037
[#5036]: https://github.com/nymtech/nym/pull/5036
[#5034]: https://github.com/nymtech/nym/pull/5034
[#5032]: https://github.com/nymtech/nym/pull/5032
[#5031]: https://github.com/nymtech/nym/pull/5031
[#5030]: https://github.com/nymtech/nym/pull/5030
[#5029]: https://github.com/nymtech/nym/pull/5029
[#5028]: https://github.com/nymtech/nym/pull/5028
[#5024]: https://github.com/nymtech/nym/pull/5024
[#5023]: https://github.com/nymtech/nym/pull/5023
[#5016]: https://github.com/nymtech/nym/pull/5016
[#5014]: https://github.com/nymtech/nym/pull/5014
[#5013]: https://github.com/nymtech/nym/pull/5013
[#5009]: https://github.com/nymtech/nym/pull/5009
[#5008]: https://github.com/nymtech/nym/pull/5008
[#4994]: https://github.com/nymtech/nym/pull/4994
[#4993]: https://github.com/nymtech/nym/pull/4993
[#4992]: https://github.com/nymtech/nym/pull/4992
[#4991]: https://github.com/nymtech/nym/pull/4991
[#4988]: https://github.com/nymtech/nym/pull/4988
[#4984]: https://github.com/nymtech/nym/pull/4984
[#4983]: https://github.com/nymtech/nym/pull/4983
[#4982]: https://github.com/nymtech/nym/pull/4982
[#4981]: https://github.com/nymtech/nym/pull/4981
[#4980]: https://github.com/nymtech/nym/pull/4980
[#4978]: https://github.com/nymtech/nym/pull/4978
[#4977]: https://github.com/nymtech/nym/pull/4977
[#4976]: https://github.com/nymtech/nym/pull/4976
[#4975]: https://github.com/nymtech/nym/pull/4975
[#4974]: https://github.com/nymtech/nym/pull/4974
[#4973]: https://github.com/nymtech/nym/pull/4973
[#4972]: https://github.com/nymtech/nym/pull/4972
[#4968]: https://github.com/nymtech/nym/pull/4968
[#4967]: https://github.com/nymtech/nym/pull/4967
[#4966]: https://github.com/nymtech/nym/pull/4966
[#4965]: https://github.com/nymtech/nym/pull/4965
[#4963]: https://github.com/nymtech/nym/pull/4963
[#4959]: https://github.com/nymtech/nym/pull/4959
[#4957]: https://github.com/nymtech/nym/pull/4957
[#4954]: https://github.com/nymtech/nym/pull/4954
[#4953]: https://github.com/nymtech/nym/pull/4953
[#4949]: https://github.com/nymtech/nym/pull/4949
[#4948]: https://github.com/nymtech/nym/pull/4948
[#4947]: https://github.com/nymtech/nym/pull/4947
[#4945]: https://github.com/nymtech/nym/pull/4945
[#4944]: https://github.com/nymtech/nym/pull/4944
[#4943]: https://github.com/nymtech/nym/pull/4943
[#4942]: https://github.com/nymtech/nym/pull/4942
[#4938]: https://github.com/nymtech/nym/pull/4938
[#4937]: https://github.com/nymtech/nym/pull/4937
[#4936]: https://github.com/nymtech/nym/pull/4936
[#4929]: https://github.com/nymtech/nym/pull/4929
[#4903]: https://github.com/nymtech/nym/pull/4903
[#4826]: https://github.com/nymtech/nym/pull/4826
[#4758]: https://github.com/nymtech/nym/pull/4758
## [2024.12-aero] (2024-10-17)
- nym-node: don't use bloomfilters for double spending checks ([#4960])
Generated
+127 -399
View File
File diff suppressed because it is too large Load Diff
+3 -12
View File
@@ -149,7 +149,7 @@ members = [
"tools/internal/contract-state-importer/importer-cli",
"tools/internal/contract-state-importer/importer-contract",
"tools/internal/testnet-manager",
"tools/internal/testnet-manager/dkg-bypass-contract", "common/nym-tui-common",
"tools/internal/testnet-manager/dkg-bypass-contract",
]
default-members = [
@@ -314,7 +314,7 @@ serde = "1.0.211"
serde_bytes = "0.11.15"
serde_derive = "1.0"
serde_json = "1.0.132"
serde_json_path = "0.7.1"
serde_json_path = "0.6.7"
serde_repr = "0.1"
serde_with = "3.9.0"
serde_yaml = "0.9.25"
@@ -329,7 +329,7 @@ syn = "1"
sysinfo = "0.30.13"
tap = "1.0.1"
tar = "0.4.42"
tempfile = "3.14"
tempfile = "3.5.0"
thiserror = "1.0.64"
time = "0.3.30"
tokio = "1.39"
@@ -412,15 +412,6 @@ wasm-bindgen-futures = "0.4.45"
wasmtimer = "0.2.0"
web-sys = "0.3.72"
# tui related
better-panic = "0.3.0"
color-eyre = "0.6.3"
crossterm = "0.28.1"
strip-ansi-escapes = "0.2.0"
ratatui = "0.29.0"
tui-logger = "0.14.0"
# Profile settings for individual crates
# Compile-time verified queries do quite a bit of work at compile time. Incremental
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.43"
version = "1.1.42"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.43"
version = "1.1.42"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address"
edition = "2021"
@@ -22,7 +22,4 @@ pub enum Error {
#[error("conversion: {0}")]
Conversion(String),
#[error("failed to serialize response packet: {source}")]
FailedToSerializeResponsePacket { source: Box<bincode::ErrorKind> },
}
-1
View File
@@ -1,7 +1,6 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod traits;
pub mod v1;
pub mod v2;
pub mod v3;
-343
View File
@@ -1,343 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use nym_credentials_interface::CredentialSpendingData;
use nym_crypto::asymmetric::x25519::PrivateKey;
use nym_service_provider_requests_common::{Protocol, ServiceProviderType};
use nym_sphinx::addressing::clients::Recipient;
use nym_wireguard_types::PeerPublicKey;
use crate::{
v1, v2, v3,
v4::{self, registration::IpPair},
Error,
};
#[derive(Copy, Clone, Debug)]
pub enum AuthenticatorVersion {
V1,
V2,
V3,
V4,
UNKNOWN,
}
impl From<Protocol> for AuthenticatorVersion {
fn from(value: Protocol) -> Self {
if value.service_provider_type != ServiceProviderType::Authenticator {
AuthenticatorVersion::UNKNOWN
} else if value.version == v1::VERSION {
AuthenticatorVersion::V1
} else if value.version == v2::VERSION {
AuthenticatorVersion::V2
} else if value.version == v3::VERSION {
AuthenticatorVersion::V3
} else if value.version == v4::VERSION {
AuthenticatorVersion::V4
} else {
AuthenticatorVersion::UNKNOWN
}
}
}
pub trait InitMessage {
fn pub_key(&self) -> PeerPublicKey;
}
impl InitMessage for v1::registration::InitMessage {
fn pub_key(&self) -> PeerPublicKey {
self.pub_key
}
}
impl InitMessage for v2::registration::InitMessage {
fn pub_key(&self) -> PeerPublicKey {
self.pub_key
}
}
impl InitMessage for v3::registration::InitMessage {
fn pub_key(&self) -> PeerPublicKey {
self.pub_key
}
}
impl InitMessage for v4::registration::InitMessage {
fn pub_key(&self) -> PeerPublicKey {
self.pub_key
}
}
pub trait FinalMessage {
fn pub_key(&self) -> PeerPublicKey;
fn verify(&self, private_key: &PrivateKey, nonce: u64) -> Result<(), Error>;
fn private_ips(&self) -> IpPair;
fn credential(&self) -> Option<CredentialSpendingData>;
}
impl FinalMessage for v1::GatewayClient {
fn pub_key(&self) -> PeerPublicKey {
self.pub_key
}
fn verify(&self, private_key: &PrivateKey, nonce: u64) -> Result<(), Error> {
self.verify(private_key, nonce)
}
fn private_ips(&self) -> IpPair {
self.private_ip.into()
}
fn credential(&self) -> Option<CredentialSpendingData> {
None
}
}
impl FinalMessage for v2::registration::FinalMessage {
fn pub_key(&self) -> PeerPublicKey {
self.gateway_client.pub_key
}
fn verify(&self, private_key: &PrivateKey, nonce: u64) -> Result<(), Error> {
self.gateway_client.verify(private_key, nonce)
}
fn private_ips(&self) -> IpPair {
self.gateway_client.private_ip.into()
}
fn credential(&self) -> Option<CredentialSpendingData> {
self.credential.clone()
}
}
impl FinalMessage for v3::registration::FinalMessage {
fn pub_key(&self) -> PeerPublicKey {
self.gateway_client.pub_key
}
fn verify(&self, private_key: &PrivateKey, nonce: u64) -> Result<(), Error> {
self.gateway_client.verify(private_key, nonce)
}
fn private_ips(&self) -> IpPair {
self.gateway_client.private_ip.into()
}
fn credential(&self) -> Option<CredentialSpendingData> {
self.credential.clone()
}
}
impl FinalMessage for v4::registration::FinalMessage {
fn pub_key(&self) -> PeerPublicKey {
self.gateway_client.pub_key
}
fn verify(&self, private_key: &PrivateKey, nonce: u64) -> Result<(), Error> {
self.gateway_client.verify(private_key, nonce)
}
fn private_ips(&self) -> IpPair {
self.gateway_client.private_ips
}
fn credential(&self) -> Option<CredentialSpendingData> {
self.credential.clone()
}
}
pub trait QueryBandwidthMessage {
fn pub_key(&self) -> PeerPublicKey;
}
impl QueryBandwidthMessage for PeerPublicKey {
fn pub_key(&self) -> PeerPublicKey {
*self
}
}
pub trait TopUpMessage {
fn pub_key(&self) -> PeerPublicKey;
fn credential(&self) -> CredentialSpendingData;
}
impl TopUpMessage for v3::topup::TopUpMessage {
fn pub_key(&self) -> PeerPublicKey {
self.pub_key
}
fn credential(&self) -> CredentialSpendingData {
self.credential.clone()
}
}
impl TopUpMessage for v4::topup::TopUpMessage {
fn pub_key(&self) -> PeerPublicKey {
self.pub_key
}
fn credential(&self) -> CredentialSpendingData {
self.credential.clone()
}
}
pub enum AuthenticatorRequest {
Initial {
msg: Box<dyn InitMessage + Send + Sync + 'static>,
protocol: Protocol,
reply_to: Recipient,
request_id: u64,
},
Final {
msg: Box<dyn FinalMessage + Send + Sync + 'static>,
protocol: Protocol,
reply_to: Recipient,
request_id: u64,
},
QueryBandwidth {
msg: Box<dyn QueryBandwidthMessage + Send + Sync + 'static>,
protocol: Protocol,
reply_to: Recipient,
request_id: u64,
},
TopUpBandwidth {
msg: Box<dyn TopUpMessage + Send + Sync + 'static>,
protocol: Protocol,
reply_to: Recipient,
request_id: u64,
},
}
impl From<v1::request::AuthenticatorRequest> for AuthenticatorRequest {
fn from(value: v1::request::AuthenticatorRequest) -> Self {
match value.data {
v1::request::AuthenticatorRequestData::Initial(init_message) => Self::Initial {
msg: Box::new(init_message),
protocol: Protocol {
version: value.version,
service_provider_type: ServiceProviderType::Authenticator,
},
reply_to: value.reply_to,
request_id: value.request_id,
},
v1::request::AuthenticatorRequestData::Final(gateway_client) => Self::Final {
msg: Box::new(gateway_client),
protocol: Protocol {
version: value.version,
service_provider_type: ServiceProviderType::Authenticator,
},
reply_to: value.reply_to,
request_id: value.request_id,
},
v1::request::AuthenticatorRequestData::QueryBandwidth(peer_public_key) => {
Self::QueryBandwidth {
msg: Box::new(peer_public_key),
protocol: Protocol {
version: value.version,
service_provider_type: ServiceProviderType::Authenticator,
},
reply_to: value.reply_to,
request_id: value.request_id,
}
}
}
}
}
impl From<v2::request::AuthenticatorRequest> for AuthenticatorRequest {
fn from(value: v2::request::AuthenticatorRequest) -> Self {
match value.data {
v2::request::AuthenticatorRequestData::Initial(init_message) => Self::Initial {
msg: Box::new(init_message),
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
},
v2::request::AuthenticatorRequestData::Final(final_message) => Self::Final {
msg: final_message,
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
},
v2::request::AuthenticatorRequestData::QueryBandwidth(peer_public_key) => {
Self::QueryBandwidth {
msg: Box::new(peer_public_key),
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
}
}
}
}
}
impl From<v3::request::AuthenticatorRequest> for AuthenticatorRequest {
fn from(value: v3::request::AuthenticatorRequest) -> Self {
match value.data {
v3::request::AuthenticatorRequestData::Initial(init_message) => Self::Initial {
msg: Box::new(init_message),
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
},
v3::request::AuthenticatorRequestData::Final(final_message) => Self::Final {
msg: final_message,
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
},
v3::request::AuthenticatorRequestData::QueryBandwidth(peer_public_key) => {
Self::QueryBandwidth {
msg: Box::new(peer_public_key),
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
}
}
v3::request::AuthenticatorRequestData::TopUpBandwidth(top_up_message) => {
Self::TopUpBandwidth {
msg: top_up_message,
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
}
}
}
}
}
impl From<v4::request::AuthenticatorRequest> for AuthenticatorRequest {
fn from(value: v4::request::AuthenticatorRequest) -> Self {
match value.data {
v4::request::AuthenticatorRequestData::Initial(init_message) => Self::Initial {
msg: Box::new(init_message),
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
},
v4::request::AuthenticatorRequestData::Final(final_message) => Self::Final {
msg: final_message,
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
},
v4::request::AuthenticatorRequestData::QueryBandwidth(peer_public_key) => {
Self::QueryBandwidth {
msg: Box::new(peer_public_key),
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
}
}
v4::request::AuthenticatorRequestData::TopUpBandwidth(top_up_message) => {
Self::TopUpBandwidth {
msg: top_up_message,
protocol: value.protocol,
reply_to: value.reply_to,
request_id: value.request_id,
}
}
}
}
}
@@ -17,6 +17,11 @@ fn generate_random() -> u64 {
rng.next_u64()
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct QueryMessage {
pub pub_key: PeerPublicKey,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthenticatorRequest {
pub protocol: Protocol,
@@ -65,7 +70,7 @@ impl AuthenticatorRequest {
)
}
pub fn new_query_request(peer_public_key: PeerPublicKey, reply_to: Recipient) -> (Self, u64) {
pub fn new_query_request(query_message: QueryMessage, reply_to: Recipient) -> (Self, u64) {
let request_id = generate_random();
(
Self {
@@ -73,7 +78,7 @@ impl AuthenticatorRequest {
service_provider_type: ServiceProviderType::Authenticator,
version: VERSION,
},
data: AuthenticatorRequestData::QueryBandwidth(peer_public_key),
data: AuthenticatorRequestData::QueryBandwidth(query_message.pub_key),
reply_to,
request_id,
},
@@ -98,16 +98,6 @@ impl TryFrom<v3::response::AuthenticatorResponse> for v2::response::Authenticato
}
}
impl From<v2::response::AuthenticatorResponse> for v3::response::AuthenticatorResponse {
fn from(value: v2::response::AuthenticatorResponse) -> Self {
Self {
protocol: value.protocol,
data: value.data.into(),
reply_to: value.reply_to,
}
}
}
impl TryFrom<v3::response::AuthenticatorResponseData> for v2::response::AuthenticatorResponseData {
type Error = crate::Error;
@@ -139,22 +129,6 @@ impl TryFrom<v3::response::AuthenticatorResponseData> for v2::response::Authenti
}
}
impl From<v2::response::AuthenticatorResponseData> for v3::response::AuthenticatorResponseData {
fn from(value: v2::response::AuthenticatorResponseData) -> Self {
match value {
v2::response::AuthenticatorResponseData::PendingRegistration(
pending_registration_response,
) => Self::PendingRegistration(pending_registration_response.into()),
v2::response::AuthenticatorResponseData::Registered(registered_response) => {
Self::Registered(registered_response.into())
}
v2::response::AuthenticatorResponseData::RemainingBandwidth(
remaining_bandwidth_response,
) => Self::RemainingBandwidth(remaining_bandwidth_response.into()),
}
}
}
impl From<v3::response::PendingRegistrationResponse> for v2::response::PendingRegistrationResponse {
fn from(value: v3::response::PendingRegistrationResponse) -> Self {
Self {
@@ -165,16 +139,6 @@ impl From<v3::response::PendingRegistrationResponse> for v2::response::PendingRe
}
}
impl From<v2::response::PendingRegistrationResponse> for v3::response::PendingRegistrationResponse {
fn from(value: v2::response::PendingRegistrationResponse) -> Self {
Self {
request_id: value.request_id,
reply_to: value.reply_to,
reply: value.reply.into(),
}
}
}
impl From<v3::response::RegisteredResponse> for v2::response::RegisteredResponse {
fn from(value: v3::response::RegisteredResponse) -> Self {
Self {
@@ -185,16 +149,6 @@ impl From<v3::response::RegisteredResponse> for v2::response::RegisteredResponse
}
}
impl From<v2::response::RegisteredResponse> for v3::response::RegisteredResponse {
fn from(value: v2::response::RegisteredResponse) -> Self {
Self {
request_id: value.request_id,
reply_to: value.reply_to,
reply: value.reply.into(),
}
}
}
impl From<v3::response::RemainingBandwidthResponse> for v2::response::RemainingBandwidthResponse {
fn from(value: v3::response::RemainingBandwidthResponse) -> Self {
Self {
@@ -205,16 +159,6 @@ impl From<v3::response::RemainingBandwidthResponse> for v2::response::RemainingB
}
}
impl From<v2::response::RemainingBandwidthResponse> for v3::response::RemainingBandwidthResponse {
fn from(value: v2::response::RemainingBandwidthResponse) -> Self {
Self {
request_id: value.request_id,
reply_to: value.reply_to,
reply: value.reply.map(Into::into),
}
}
}
impl From<v3::registration::RegistrationData> for v2::registration::RegistrationData {
fn from(value: v3::registration::RegistrationData) -> Self {
Self {
@@ -225,16 +169,6 @@ impl From<v3::registration::RegistrationData> for v2::registration::Registration
}
}
impl From<v2::registration::RegistrationData> for v3::registration::RegistrationData {
fn from(value: v2::registration::RegistrationData) -> Self {
Self {
nonce: value.nonce,
gateway_data: value.gateway_data.into(),
wg_port: value.wg_port,
}
}
}
impl From<v3::registration::RegistredData> for v2::registration::RegistredData {
fn from(value: v3::registration::RegistredData) -> Self {
Self {
@@ -245,16 +179,6 @@ impl From<v3::registration::RegistredData> for v2::registration::RegistredData {
}
}
impl From<v2::registration::RegistredData> for v3::registration::RegistredData {
fn from(value: v2::registration::RegistredData) -> Self {
Self {
pub_key: value.pub_key,
private_ip: value.private_ip,
wg_port: value.wg_port,
}
}
}
impl From<v3::registration::RemainingBandwidthData> for v2::registration::RemainingBandwidthData {
fn from(value: v3::registration::RemainingBandwidthData) -> Self {
Self {
@@ -262,11 +186,3 @@ impl From<v3::registration::RemainingBandwidthData> for v2::registration::Remain
}
}
}
impl From<v2::registration::RemainingBandwidthData> for v3::registration::RemainingBandwidthData {
fn from(value: v2::registration::RemainingBandwidthData) -> Self {
Self {
available_bandwidth: value.available_bandwidth,
}
}
}
@@ -27,7 +27,7 @@ pub type HmacSha256 = Hmac<Sha256>;
pub type Nonce = u64;
pub type Taken = Option<SystemTime>;
pub const BANDWIDTH_CAP_PER_DAY: u64 = 250 * 1024 * 1024 * 1024; // 250 GB
pub const BANDWIDTH_CAP_PER_DAY: u64 = 1024 * 1024 * 1024; // 1 GB
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct InitMessage {
@@ -20,6 +20,11 @@ fn generate_random() -> u64 {
rng.next_u64()
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct QueryMessage {
pub pub_key: PeerPublicKey,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthenticatorRequest {
pub protocol: Protocol,
@@ -68,7 +73,7 @@ impl AuthenticatorRequest {
)
}
pub fn new_query_request(peer_public_key: PeerPublicKey, reply_to: Recipient) -> (Self, u64) {
pub fn new_query_request(query_message: QueryMessage, reply_to: Recipient) -> (Self, u64) {
let request_id = generate_random();
(
Self {
@@ -76,7 +81,7 @@ impl AuthenticatorRequest {
service_provider_type: ServiceProviderType::Authenticator,
version: VERSION,
},
data: AuthenticatorRequestData::QueryBandwidth(peer_public_key),
data: AuthenticatorRequestData::QueryBandwidth(query_message.pub_key),
reply_to,
request_id,
},
@@ -3,7 +3,7 @@
use nym_service_provider_requests_common::{Protocol, ServiceProviderType};
use crate::{v2, v3, v4};
use crate::{v3, v4};
impl From<v3::request::AuthenticatorRequest> for v4::request::AuthenticatorRequest {
fn from(authenticator_request: v3::request::AuthenticatorRequest) -> Self {
@@ -64,16 +64,6 @@ impl From<Box<v3::topup::TopUpMessage>> for Box<v4::topup::TopUpMessage> {
}
}
impl From<v2::registration::GatewayClient> for v4::registration::GatewayClient {
fn from(gw_client: v2::registration::GatewayClient) -> Self {
Self {
pub_key: gw_client.pub_key,
private_ips: gw_client.private_ip.into(),
mac: gw_client.mac.into(),
}
}
}
impl From<v3::registration::GatewayClient> for v4::registration::GatewayClient {
fn from(gw_client: v3::registration::GatewayClient) -> Self {
Self {
@@ -94,22 +84,6 @@ impl From<v4::registration::GatewayClient> for v3::registration::GatewayClient {
}
}
impl From<v4::registration::GatewayClient> for v2::registration::GatewayClient {
fn from(gw_client: v4::registration::GatewayClient) -> Self {
Self {
pub_key: gw_client.pub_key,
private_ip: gw_client.private_ips.ipv4.into(),
mac: gw_client.mac.into(),
}
}
}
impl From<v2::registration::ClientMac> for v4::registration::ClientMac {
fn from(mac: v2::registration::ClientMac) -> Self {
Self::new(mac.to_vec())
}
}
impl From<v3::registration::ClientMac> for v4::registration::ClientMac {
fn from(mac: v3::registration::ClientMac) -> Self {
Self::new(mac.to_vec())
@@ -122,12 +96,6 @@ impl From<v4::registration::ClientMac> for v3::registration::ClientMac {
}
}
impl From<v4::registration::ClientMac> for v2::registration::ClientMac {
fn from(mac: v4::registration::ClientMac) -> Self {
Self::new(mac.to_vec())
}
}
impl TryFrom<v4::response::AuthenticatorResponse> for v3::response::AuthenticatorResponse {
type Error = crate::Error;
@@ -42,12 +42,6 @@ impl IpPair {
}
}
impl From<(Ipv4Addr, Ipv6Addr)> for IpPair {
fn from((ipv4, ipv6): (Ipv4Addr, Ipv6Addr)) -> Self {
IpPair { ipv4, ipv6 }
}
}
impl fmt::Display for IpPair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.ipv4, self.ipv6)
@@ -20,6 +20,11 @@ fn generate_random() -> u64 {
rng.next_u64()
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct QueryMessage {
pub pub_key: PeerPublicKey,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthenticatorRequest {
pub protocol: Protocol,
@@ -68,7 +73,7 @@ impl AuthenticatorRequest {
)
}
pub fn new_query_request(peer_public_key: PeerPublicKey, reply_to: Recipient) -> (Self, u64) {
pub fn new_query_request(query_message: QueryMessage, reply_to: Recipient) -> (Self, u64) {
let request_id = generate_random();
(
Self {
@@ -76,7 +81,7 @@ impl AuthenticatorRequest {
service_provider_type: ServiceProviderType::Authenticator,
version: VERSION,
},
data: AuthenticatorRequestData::QueryBandwidth(peer_public_key),
data: AuthenticatorRequestData::QueryBandwidth(query_message.pub_key),
reply_to,
request_id,
},
-1
View File
@@ -47,7 +47,6 @@ pub fn setup_logging() {
#[cfg(feature = "basic_tracing")]
pub fn setup_tracing_logger() {
let log_builder = tracing_subscriber::fmt()
.with_writer(std::io::stderr)
// Use a more compact, abbreviated log format
.compact()
// Display source code file paths
@@ -1,6 +1,7 @@
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nym_api::NymApiClientExt;
use crate::nyxd::{self, NyxdClient};
use crate::signing::direct_wallet::DirectSecp256k1HdWallet;
use crate::signing::signer::{NoSigner, OfflineSigner};
@@ -31,7 +32,6 @@ use nym_network_defaults::NymNetworkDetails;
use time::Date;
use url::Url;
pub use crate::nym_api::NymApiClientExt;
pub use nym_mixnet_contract_common::{
mixnode::MixNodeDetails, GatewayBond, IdentityKey, IdentityKeyRef, NodeId, NymNodeDetails,
};
@@ -332,10 +332,10 @@ impl NymApiClient {
NymApiClient { nym_api }
}
pub fn new_with_user_agent(api_url: Url, user_agent: impl Into<UserAgent>) -> Self {
pub fn new_with_user_agent(api_url: Url, user_agent: UserAgent) -> Self {
let nym_api = nym_api::Client::builder::<_, ValidatorClientError>(api_url)
.expect("invalid api url")
.with_user_agent(user_agent.into())
.with_user_agent(user_agent)
.build::<ValidatorClientError>()
.expect("failed to build nym api client");
@@ -13,7 +13,7 @@ use nym_api_requests::ecash::models::{
use nym_api_requests::ecash::VerificationKeyResponse;
use nym_api_requests::models::{
AnnotationResponse, ApiHealthResponse, LegacyDescribedMixNode, NodePerformanceResponse,
NodeRefreshBody, NymNodeDescription,
NymNodeDescription,
};
use nym_api_requests::nym_nodes::PaginatedCachedNodesResponse;
use nym_api_requests::pagination::PaginatedResponse;
@@ -695,32 +695,16 @@ pub trait NymApiClientExt: ApiClient {
&self,
node_id: NodeId,
) -> Result<NodePerformanceResponse, NymAPIError> {
self.get_json(
&[
routes::API_VERSION,
"nym-nodes",
"performance",
&node_id.to_string(),
],
NO_PARAMS,
)
.await
self.get_json_from(format!("/v1/nym-nodes/performance/{node_id}"))
.await
}
async fn get_node_annotation(
&self,
node_id: NodeId,
) -> Result<AnnotationResponse, NymAPIError> {
self.get_json(
&[
routes::API_VERSION,
"nym-nodes",
"annotation",
&node_id.to_string(),
],
NO_PARAMS,
)
.await
self.get_json_from(format!("/v1/nym-nodes/annotation/{node_id}"))
.await
}
#[deprecated]
@@ -933,18 +917,6 @@ pub trait NymApiClientExt: ApiClient {
.await
}
async fn force_refresh_describe_cache(
&self,
request: &NodeRefreshBody,
) -> Result<(), NymAPIError> {
self.post_json(
&[routes::API_VERSION, "nym-nodes", "refresh-described"],
NO_PARAMS,
request,
)
.await
}
async fn issued_ticketbooks_for(
&self,
expiration_date: Date,
@@ -10,10 +10,10 @@ use cosmrs::AccountId;
use nym_contracts_common::signing::Nonce;
use nym_mixnet_contract_common::gateway::{PreassignedGatewayIdsResponse, PreassignedId};
use nym_mixnet_contract_common::nym_node::{
EpochAssignmentResponse, NodeDetailsByIdentityResponse, NodeDetailsResponse,
NodeOwnershipResponse, NodeRewardingDetailsResponse, PagedNymNodeBondsResponse,
PagedNymNodeDetailsResponse, PagedUnbondedNymNodesResponse, Role, RolesMetadataResponse,
StakeSaturationResponse, UnbondedNodeResponse, UnbondedNymNode,
EpochAssignmentResponse, NodeDetailsByIdentityResponse, NodeOwnershipResponse,
NodeRewardingDetailsResponse, PagedNymNodeBondsResponse, PagedNymNodeDetailsResponse,
PagedUnbondedNymNodesResponse, Role, RolesMetadataResponse, StakeSaturationResponse,
UnbondedNodeResponse, UnbondedNymNode,
};
use nym_mixnet_contract_common::reward_params::WorkFactor;
use nym_mixnet_contract_common::{
@@ -311,7 +311,10 @@ pub trait MixnetQueryClient {
.await
}
async fn get_nymnode_details(&self, node_id: NodeId) -> Result<NodeDetailsResponse, NyxdError> {
async fn get_nymnode_details(
&self,
node_id: NodeId,
) -> Result<NodeOwnershipResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetNymNodeDetails { node_id })
.await
}
@@ -98,13 +98,6 @@ impl DirectSecp256k1HdWallet {
Ok((private_key, public_key))
}
pub fn derive_extended_private_key(
&self,
hd_path: &DerivationPath,
) -> Result<XPrv, DirectSecp256k1HdWalletError> {
Ok(XPrv::derive_from_path(self.seed, hd_path)?)
}
pub fn try_derive_accounts(&self) -> Result<Vec<AccountData>, DirectSecp256k1HdWalletError> {
let mut accounts = Vec::with_capacity(self.accounts.len());
for derivation_info in &self.accounts {
@@ -15,9 +15,7 @@ mixnet-contract-common = { path = "../mixnet-contract", package = "nym-mixnet-co
contracts-common = { path = "../contracts-common", package = "nym-contracts-common", version = "0.5.0" }
serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
# without this feature, cargo clippy emits a ton of incompatibility warnings
# https://docs.rs/ts-rs/latest/ts_rs/#serde-compatability
ts-rs = { workspace = true, optional = true, features = ["no-serde-warnings"] }
ts-rs = { workspace = true, optional = true}
[features]
schema = ["cw2"]
+1 -9
View File
@@ -221,15 +221,7 @@ impl From<PayInfo> for NymPayInfo {
}
#[derive(
Copy,
Clone,
Debug,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
strum::EnumIter,
Copy, Clone, Debug, PartialEq, Serialize, Deserialize, strum::Display, strum::EnumString,
)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
-127
View File
@@ -282,48 +282,6 @@ impl Client {
}
}
pub async fn create_delete_request<K, V>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> RequestBuilder
where
K: AsRef<str>,
V: AsRef<str>,
{
let url = sanitize_url(&self.base_url, path, params);
self.reqwest_client.delete(url)
}
pub async fn send_delete_request<K, V, E>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<Response, HttpClientError<E>>
where
K: AsRef<str>,
V: AsRef<str>,
E: Display,
{
tracing::trace!("Sending DELETE request");
let url = sanitize_url(&self.base_url, path, params);
#[cfg(target_arch = "wasm32")]
{
Ok(wasmtimer::tokio::timeout(
self.request_timeout,
self.reqwest_client.delete(url).send(),
)
.await
.map_err(|_timeout| HttpClientError::RequestTimeout)??)
}
#[cfg(not(target_arch = "wasm32"))]
{
Ok(self.reqwest_client.delete(url).send().await?)
}
}
#[instrument(level = "debug", skip_all)]
pub async fn get_json<T, K, V, E>(
&self,
@@ -357,22 +315,6 @@ impl Client {
parse_response(res, true).await
}
pub async fn delete_json<T, K, V, E>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
K: AsRef<str>,
V: AsRef<str>,
E: Display + DeserializeOwned,
{
let res = self.send_delete_request(path, params).await?;
parse_response(res, false).await
}
#[instrument(level = "debug", skip_all)]
pub async fn get_json_endpoint<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
@@ -437,35 +379,6 @@ impl Client {
parse_response(res, true).await
}
pub async fn delete_json_endpoint<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
E: Display + DeserializeOwned,
S: AsRef<str>,
{
#[cfg(target_arch = "wasm32")]
let res = {
wasmtimer::tokio::timeout(
self.request_timeout,
self.reqwest_client
.delete(self.base_url.join(endpoint.as_ref())?)
.send(),
)
.await
.map_err(|_timeout| HttpClientError::RequestTimeout)??
};
#[cfg(not(target_arch = "wasm32"))]
let res = {
self.reqwest_client
.delete(self.base_url.join(endpoint.as_ref())?)
.send()
.await?
};
parse_response(res, false).await
}
}
// define those methods on the trait for nicer extensions (and not having to type the thing twice)
@@ -498,17 +411,6 @@ pub trait ApiClient {
V: AsRef<str> + Sync,
E: Display + DeserializeOwned;
async fn delete_json<T, K, V, E>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
K: AsRef<str> + Sync,
V: AsRef<str> + Sync,
E: Display + DeserializeOwned;
/// `get` json data from the provided absolute endpoint, i.e. for example `"/api/v1/mixnodes?since=12345"`
async fn get_json_from<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
where
@@ -526,12 +428,6 @@ pub trait ApiClient {
for<'a> T: Deserialize<'a>,
E: Display + DeserializeOwned,
S: AsRef<str> + Sync + Send;
async fn delete_json_from<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
E: Display + DeserializeOwned,
S: AsRef<str> + Sync + Send;
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
@@ -567,20 +463,6 @@ impl ApiClient for Client {
self.post_json(path, params, json_body).await
}
async fn delete_json<T, K, V, E>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
K: AsRef<str> + Sync,
V: AsRef<str> + Sync,
E: Display + DeserializeOwned,
{
self.delete_json(path, params).await
}
async fn get_json_from<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
@@ -603,15 +485,6 @@ impl ApiClient for Client {
{
self.post_json_endpoint(endpoint, json_body).await
}
async fn delete_json_from<T, S, E>(&self, endpoint: S) -> Result<T, HttpClientError<E>>
where
for<'a> T: Deserialize<'a>,
E: Display + DeserializeOwned,
S: AsRef<str> + Sync + Send,
{
self.delete_json_endpoint(endpoint).await
}
}
// utility function that should solve the double slash problem in API urls forever.
-3
View File
@@ -11,7 +11,4 @@ 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"] }
-94
View File
@@ -1,101 +1,7 @@
use nym_crypto::asymmetric::ed25519::{PublicKey, Signature, SignatureError};
use serde::{Deserialize, Serialize};
pub mod get_testrun {
use super::*;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Payload {
pub agent_public_key: PublicKey,
pub timestamp: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GetTestrunRequest {
pub payload: Payload,
pub signature: Signature,
}
impl SignedRequest for GetTestrunRequest {
type Payload = Payload;
fn public_key(&self) -> &PublicKey {
&self.payload.agent_public_key
}
fn signature(&self) -> &Signature {
&self.signature
}
fn payload(&self) -> &Self::Payload {
&self.payload
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TestrunAssignment {
pub testrun_id: i64,
pub assigned_at_utc: i64,
pub gateway_identity_key: String,
}
pub mod submit_results {
use super::*;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Payload {
pub probe_result: String,
pub agent_public_key: PublicKey,
pub assigned_at_utc: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SubmitResults {
pub payload: Payload,
pub signature: Signature,
}
impl SignedRequest for SubmitResults {
type Payload = Payload;
fn public_key(&self) -> &PublicKey {
&self.payload.agent_public_key
}
fn signature(&self) -> &Signature {
&self.signature
}
fn payload(&self) -> &Self::Payload {
&self.payload
}
}
}
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;
}
-40
View File
@@ -157,46 +157,6 @@ impl NymNetworkDetails {
}
}
#[rustfmt::skip]
#[cfg(feature = "env")]
pub fn export_to_env(self) {
use crate::var_names;
use std::env::set_var;
fn set_optional_var(var_name: &str, value: Option<String>) {
if let Some(value) = value {
set_var(var_name, value);
}
}
set_var(var_names::NETWORK_NAME, self.network_name);
set_var(var_names::BECH32_PREFIX, self.chain_details.bech32_account_prefix);
set_var(var_names::MIX_DENOM, self.chain_details.mix_denom.base);
set_var(var_names::MIX_DENOM_DISPLAY, self.chain_details.mix_denom.display);
set_var(var_names::STAKE_DENOM, self.chain_details.stake_denom.base);
set_var(var_names::STAKE_DENOM_DISPLAY, self.chain_details.stake_denom.display);
set_var(var_names::DENOMS_EXPONENT, self.chain_details.mix_denom.display_exponent.to_string());
if let Some(e) = self.endpoints.first() {
set_var(var_names::NYXD, e.nyxd_url.clone());
set_optional_var(var_names::NYM_API, e.api_url.clone());
set_optional_var(var_names::NYXD_WEBSOCKET, e.websocket_url.clone());
}
set_optional_var(var_names::MIXNET_CONTRACT_ADDRESS, self.contracts.mixnet_contract_address);
set_optional_var(var_names::VESTING_CONTRACT_ADDRESS, self.contracts.vesting_contract_address);
set_optional_var(var_names::ECASH_CONTRACT_ADDRESS, self.contracts.ecash_contract_address);
set_optional_var(var_names::GROUP_CONTRACT_ADDRESS, self.contracts.group_contract_address);
set_optional_var(var_names::MULTISIG_CONTRACT_ADDRESS, self.contracts.multisig_contract_address);
set_optional_var(var_names::COCONUT_DKG_CONTRACT_ADDRESS, self.contracts.coconut_dkg_contract_address);
set_optional_var(var_names::EXPLORER_API, self.explorer_api);
set_optional_var(var_names::NYM_VPN_API, self.nym_vpn_api_url);
}
pub fn default_gas_price_amount(&self) -> f64 {
GAS_PRICE_AMOUNT
}
-45
View File
@@ -1,45 +0,0 @@
[package]
name = "nym-tui-common"
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]
async-trait = { workspace = true }
humantime-serde = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true, features = ["sync", "rt-multi-thread", "signal", "macros"] }
tokio-stream = { workspace = true }
tokio-util = { workspace = true, features = ["rt"] }
tracing = { workspace = true }
thiserror = { workspace = true }
# tui
crossterm = { workspace = true, features = ["event-stream"] }
ratatui = { workspace = true, features = ["serde", "macros", "crossterm"] }
tui-logger = { workspace = true, optional = true, features = ["tracing-support"], default-features = false }
# panic handlers
better-panic = { workspace = true }
color-eyre = { workspace = true }
strip-ansi-escapes = { workspace = true }
[dev-dependencies]
tracing-subscriber = { workspace = true, features = ["env-filter"] }
tracing = { workspace = true, features = ["log"] }
[[example]]
name = "hello_world"
required-features = ["logger"]
[features]
logger = ["tui-logger"]
@@ -1,175 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use async_trait::async_trait;
use color_eyre::eyre;
use crossterm::event::{KeyCode, KeyEvent};
use nym_tui_common::tui::config::keybindings::{KeyBinding, LoggerKeybindings};
use nym_tui_common::{
run_tui, Action, ActionDispatcher, ActionSender, AppAction, Component, DebugHistory, Logger,
LoggerProps, State,
};
use ratatui::layout::{Layout, Rect};
use ratatui::prelude::Constraint;
use ratatui::widgets::Paragraph;
use ratatui::Frame;
use tracing::log::LevelFilter;
use tracing_subscriber::EnvFilter;
// useful pattern for tabs, etc:
/*
fn get_active_page_component_mut(&mut self) -> &mut dyn Component {
match self.props.active_tab {
ActiveTab::Tab1 => &mut self.tab1,
ActiveTab::Tab2 => &mut self.tab2,
}
}
*/
struct Props {
custom_quit: KeyBinding,
}
impl From<&HelloStore> for Props {
fn from(store: &HelloStore) -> Self {
Props {
custom_quit: store.config.custom_quit,
}
}
}
pub struct HelloRootApp {
props: Props,
action_sender: ActionSender<HelloActions>,
logger: Logger<HelloStore, HelloActions>,
debug_history: DebugHistory<HelloStore, HelloActions>,
}
impl Component for HelloRootApp {
type State = HelloStore;
type Actions = HelloActions;
fn new(state: &HelloStore, action_sender: ActionSender<HelloActions>) -> Self
where
Self: Sized,
{
HelloRootApp {
props: Props::from(state),
action_sender: action_sender.clone(),
logger: Logger::new(state, action_sender.clone()),
debug_history: DebugHistory::new(state, action_sender),
}
}
fn update(self, state: &Self::State) -> Self
where
Self: Sized,
{
HelloRootApp {
logger: self.logger.update(state),
debug_history: self.debug_history.update(state),
..self
}
}
fn tick(&mut self) -> bool {
let logger_tick = self.logger.tick();
let debug_history_tick = self.debug_history.tick();
logger_tick || debug_history_tick
}
fn handle_key(&mut self, key: KeyEvent) -> eyre::Result<()> {
let maybe_binding = KeyBinding::from(key);
if maybe_binding == self.props.custom_quit {
self.action_sender.send(Action::Quit);
}
self.logger.handle_key(key)?;
self.debug_history.handle_key(key)?;
Ok(())
}
fn view(&mut self, frame: &mut Frame, rect: Rect) {
let [logs, hello_rect] =
Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)]).areas(rect);
self.logger.view(frame, logs);
frame.render_widget(Paragraph::new("Hello world!").centered(), hello_rect);
self.debug_history.view(frame, rect);
}
}
#[derive(Debug, Clone)]
pub enum HelloActions {}
impl AppAction for HelloActions {}
#[derive(Clone)]
pub struct HelloConfig {
pub custom_quit: KeyBinding,
pub logger_keybindings: LoggerKeybindings,
}
impl Default for HelloConfig {
fn default() -> Self {
HelloConfig {
custom_quit: KeyBinding::new(KeyCode::Char('x')),
logger_keybindings: Default::default(),
}
}
}
#[derive(Clone, Default)]
pub struct HelloStore {
config: HelloConfig,
}
impl<'a> From<&'a HelloStore> for LoggerProps {
fn from(store: &'a HelloStore) -> LoggerProps {
LoggerProps {
keybindings: store.config.logger_keybindings,
}
}
}
impl State for HelloStore {}
#[derive(Default)]
pub struct HelloDispatcher {}
#[async_trait]
impl ActionDispatcher for HelloDispatcher {
type Store = HelloStore;
type Actions = HelloActions;
async fn handle_app_action(
&mut self,
action: Self::Actions,
store: &mut Self::Store,
) -> eyre::Result<()> {
let _ = action;
let _ = store;
Ok(())
}
}
#[tokio::main]
async fn main() -> eyre::Result<()> {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::Layer;
let filter: EnvFilter = "trace,mio=warn".parse()?;
tracing_subscriber::registry()
.with(tui_logger::tracing_subscriber_layer().with_filter(filter))
.init();
tui_logger::init_logger(LevelFilter::Trace)?;
run_tui::<HelloRootApp, _>(Default::default(), HelloDispatcher {}, Default::default()).await
}
-24
View File
@@ -1,24 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::char::ParseCharError;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum NymTuiError {
#[error("failed to abort tui processing task within specified duration")]
TuiTaskAbortFailure,
#[error("{str} could not be parsed into a character: {source}")]
InvalidCharacter {
str: String,
#[source]
source: ParseCharError,
},
#[error("could not process an unknown keybinding: '{value}'")]
UnknownKeyBinding { value: String },
#[error("could not process an unknown key modifier: '{value}'")]
UnknownKeyModifier { value: String },
}
-46
View File
@@ -1,46 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#![warn(clippy::expect_used)]
#![warn(clippy::unwrap_used)]
#![warn(clippy::todo)]
#![warn(clippy::dbg_macro)]
#![warn(clippy::panic)]
use crate::tui::manager::TuiManager;
use color_eyre::eyre;
pub mod error;
pub mod tui;
pub use crate::tui::config::TuiConfig;
pub use tui::action::{Action, AppAction};
pub use tui::dispatcher::store::State;
pub use tui::dispatcher::{ActionDispatcher, ActionSender};
pub use tui::initialize_panic_handler;
pub use tui::ui::components::Component;
// components:
pub use tui::ui::components::common::DebugHistory;
#[cfg(feature = "logger")]
pub use tui::ui::components::common::{Logger, LoggerProps};
pub async fn run_tui<C, D>(
config: TuiConfig,
action_dispatcher: D,
initial_state: D::Store,
) -> eyre::Result<()>
where
C: Component + Send + Sync + 'static,
C::State: Send + Sync + 'static,
C::Actions: Send + Sync + Clone + 'static,
D: ActionDispatcher<Store = C::State, Actions = C::Actions> + Send + Sync + 'static,
{
initialize_panic_handler()?;
TuiManager::<C>::build_new(config, action_dispatcher, initial_state)?
.wait_for_exit_or_signal()
.await;
Ok(())
}
-13
View File
@@ -1,13 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use std::fmt::Debug;
#[derive(Debug)]
pub enum Action<T: AppAction> {
Quit,
AppDefined(T),
}
pub trait AppAction: Debug {}
@@ -1,271 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use std::sync::LazyLock;
use crate::error::NymTuiError;
#[cfg(feature = "logger")]
use tui_logger::TuiWidgetEvent;
static KEY_MODIFIERS: LazyLock<HashMap<&'static str, KeyModifiers>> = LazyLock::new(|| {
let mut m = HashMap::new();
m.insert("shift", KeyModifiers::SHIFT);
m.insert("ctrl", KeyModifiers::CONTROL);
m.insert("alt", KeyModifiers::ALT);
m.insert("super", KeyModifiers::SUPER);
m.insert("hyper", KeyModifiers::HYPER);
m.insert("meta", KeyModifiers::META);
m
});
static SPECIAL_KEYS: LazyLock<HashMap<&'static str, KeyCode>> = LazyLock::new(|| {
let mut m = HashMap::new();
m.insert("backspace", KeyCode::Backspace);
m.insert("enter", KeyCode::Enter);
m.insert("left", KeyCode::Left);
m.insert("right", KeyCode::Right);
m.insert("up", KeyCode::Up);
m.insert("down", KeyCode::Down);
m.insert("home", KeyCode::Home);
m.insert("end", KeyCode::End);
m.insert("pageup", KeyCode::PageUp);
m.insert("pagedown", KeyCode::PageDown);
m.insert("tab", KeyCode::Tab);
m.insert("backtab", KeyCode::BackTab);
m.insert("delete", KeyCode::Delete);
m.insert("insert", KeyCode::Insert);
m.insert("null", KeyCode::Null);
m.insert("esc", KeyCode::Esc);
m.insert("space", KeyCode::Char(' '));
m.insert("f1", KeyCode::F(1));
m.insert("f2", KeyCode::F(2));
m.insert("f3", KeyCode::F(3));
m.insert("f4", KeyCode::F(4));
m.insert("f5", KeyCode::F(5));
m.insert("f6", KeyCode::F(6));
m.insert("f7", KeyCode::F(7));
m.insert("f8", KeyCode::F(8));
m.insert("f9", KeyCode::F(9));
m.insert("f10", KeyCode::F(10));
m.insert("f11", KeyCode::F(11));
m.insert("f12", KeyCode::F(12));
m
});
#[cfg(feature = "logger")]
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct LoggerKeybindings {
// TODO: give them better names
tui_logger_space_key: KeyBinding,
tui_logger_up_key: KeyBinding,
tui_logger_down_key: KeyBinding,
tui_logger_left_key: KeyBinding,
tui_logger_right_key: KeyBinding,
tui_logger_plus_key: KeyBinding,
tui_logger_minus_key: KeyBinding,
tui_logger_hide_key: KeyBinding,
tui_logger_focus_key: KeyBinding,
tui_logger_prev_page_key: KeyBinding,
tui_logger_next_page_key: KeyBinding,
tui_logger_escape_key: KeyBinding,
}
#[cfg(feature = "logger")]
impl Default for LoggerKeybindings {
fn default() -> Self {
LoggerKeybindings {
tui_logger_space_key: KeyBinding::new(KeyCode::Char(' ')),
tui_logger_up_key: KeyBinding::new(KeyCode::Up),
tui_logger_down_key: KeyBinding::new(KeyCode::Down),
tui_logger_left_key: KeyBinding::new(KeyCode::Left),
tui_logger_right_key: KeyBinding::new(KeyCode::Right),
tui_logger_plus_key: KeyBinding::new(KeyCode::Char('+')),
tui_logger_minus_key: KeyBinding::new(KeyCode::Char('-')),
tui_logger_hide_key: KeyBinding::new(KeyCode::Char('h')),
tui_logger_focus_key: KeyBinding::new(KeyCode::Char('f')),
tui_logger_prev_page_key: KeyBinding::new(KeyCode::PageUp),
tui_logger_next_page_key: KeyBinding::new(KeyCode::PageDown),
tui_logger_escape_key: KeyBinding::new(KeyCode::Esc),
}
}
}
#[cfg(feature = "logger")]
impl LoggerKeybindings {
pub fn tui_logger_event(&self, key: KeyBinding) -> Option<TuiWidgetEvent> {
if key == self.tui_logger_space_key {
Some(TuiWidgetEvent::SpaceKey)
} else if key == self.tui_logger_up_key {
Some(TuiWidgetEvent::UpKey)
} else if key == self.tui_logger_down_key {
Some(TuiWidgetEvent::DownKey)
} else if key == self.tui_logger_left_key {
Some(TuiWidgetEvent::LeftKey)
} else if key == self.tui_logger_right_key {
Some(TuiWidgetEvent::RightKey)
} else if key == self.tui_logger_plus_key {
Some(TuiWidgetEvent::PlusKey)
} else if key == self.tui_logger_minus_key {
Some(TuiWidgetEvent::MinusKey)
} else if key == self.tui_logger_hide_key {
Some(TuiWidgetEvent::HideKey)
} else if key == self.tui_logger_focus_key {
Some(TuiWidgetEvent::FocusKey)
} else if key == self.tui_logger_prev_page_key {
Some(TuiWidgetEvent::PrevPageKey)
} else if key == self.tui_logger_next_page_key {
Some(TuiWidgetEvent::NextPageKey)
} else if key == self.tui_logger_escape_key {
Some(TuiWidgetEvent::EscapeKey)
} else {
None
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[serde(try_from = "String")]
#[serde(into = "String")]
pub struct KeyBinding {
pub code: KeyCode,
pub modifier: KeyModifiers,
}
impl KeyBinding {
pub fn new(code: KeyCode) -> Self {
KeyBinding {
code,
modifier: KeyModifiers::NONE,
}
}
pub fn new_with_modifier(code: KeyCode, modifier: KeyModifiers) -> Self {
KeyBinding { code, modifier }
}
}
impl From<KeyEvent> for KeyBinding {
fn from(value: KeyEvent) -> Self {
KeyBinding {
code: value.code,
modifier: value.modifiers,
}
}
}
impl Display for KeyBinding {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.modifier.contains(KeyModifiers::SHIFT) {
write!(f, "shift+")?;
}
if self.modifier.contains(KeyModifiers::CONTROL) {
write!(f, "ctrl+")?;
}
if self.modifier.contains(KeyModifiers::ALT) {
write!(f, "alt+")?;
}
if self.modifier.contains(KeyModifiers::SUPER) {
write!(f, "super+")?;
}
if self.modifier.contains(KeyModifiers::HYPER) {
write!(f, "hyper+")?;
}
if self.modifier.contains(KeyModifiers::META) {
write!(f, "meta+")?;
}
match self.code {
KeyCode::Backspace => write!(f, "backspace"),
KeyCode::Enter => write!(f, "enter"),
KeyCode::Left => write!(f, "left"),
KeyCode::Right => write!(f, "right"),
KeyCode::Up => write!(f, "up"),
KeyCode::Down => write!(f, "down"),
KeyCode::Home => write!(f, "home"),
KeyCode::End => write!(f, "end"),
KeyCode::PageUp => write!(f, "pageup"),
KeyCode::PageDown => write!(f, "pagedown"),
KeyCode::Tab => write!(f, "tab"),
KeyCode::BackTab => write!(f, "backtab"),
KeyCode::Delete => write!(f, "delete"),
KeyCode::Insert => write!(f, "insert"),
KeyCode::Char(c) => write!(f, "{c}"),
KeyCode::Null => write!(f, "null"),
KeyCode::Esc => write!(f, "esc"),
_ => write!(f, "unknown"),
}
}
}
impl From<KeyBinding> for String {
fn from(value: KeyBinding) -> Self {
value.to_string()
}
}
impl TryFrom<String> for KeyBinding {
type Error = NymTuiError;
fn try_from(value: String) -> Result<Self, Self::Error> {
value.parse()
}
}
impl FromStr for KeyBinding {
type Err = NymTuiError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.rsplit_once('+') {
Some((modifiers, value)) => Ok(Self {
code: parse_keycode(value)?,
modifier: parse_modifiers(modifiers)?,
}),
None => Ok(Self {
code: parse_keycode(s)?,
modifier: KeyModifiers::NONE,
}),
}
}
}
fn parse_keycode(value: &str) -> Result<KeyCode, NymTuiError> {
Ok(if value.len() == 1 {
KeyCode::Char(
char::from_str(value)
.map_err(|source| NymTuiError::InvalidCharacter {
str: value.to_string(),
source,
})?
.to_ascii_lowercase(),
)
} else {
SPECIAL_KEYS
.get(value)
.cloned()
.ok_or_else(|| NymTuiError::UnknownKeyBinding {
value: value.to_string(),
})?
})
}
fn parse_modifiers(modifiers: &str) -> Result<KeyModifiers, NymTuiError> {
modifiers
.split('+')
.try_fold(KeyModifiers::NONE, |modifiers, token| {
KEY_MODIFIERS
.get(token)
.map(|modifier| modifiers | *modifier)
.ok_or_else(|| NymTuiError::UnknownKeyModifier {
value: token.to_string(),
})
})
}
pub fn key_event_to_string(key_event: &KeyEvent) -> String {
KeyBinding::from(*key_event).to_string()
}
@@ -1,69 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use serde::{Deserialize, Serialize};
use std::time::Duration;
pub mod keybindings;
pub const DEFAULT_TICK_RATE: Duration = Duration::from_millis(200);
const DEFAULT_SHUTDOWN_GRACE: Duration = Duration::from_millis(500);
const DEFAULT_CANCEL_GRACE: Duration = Duration::from_millis(500);
const DEFAULT_ABORT_GRACE: Duration = Duration::from_millis(200);
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub struct TuiConfig {
pub tui: Tui,
// #[serde(default)]
// pub key_bindings: KeyBindings,
#[serde(default)]
pub debug: Debug,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub struct Debug {
pub debug_mode_enabled: bool,
#[serde(with = "humantime_serde")]
pub shutdown_grace: Duration,
#[serde(with = "humantime_serde")]
pub cancel_grace: Duration,
#[serde(with = "humantime_serde")]
pub abort_grace: Duration,
}
impl Default for Debug {
fn default() -> Self {
Debug {
debug_mode_enabled: true,
shutdown_grace: DEFAULT_SHUTDOWN_GRACE,
cancel_grace: DEFAULT_CANCEL_GRACE,
abort_grace: DEFAULT_ABORT_GRACE,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, Clone, Copy)]
pub struct Tui {
#[serde(default, flatten)]
pub debug: TuiDebug,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub struct TuiDebug {
#[serde(with = "humantime_serde")]
pub tick_rate: Duration,
}
impl Default for TuiDebug {
fn default() -> Self {
TuiDebug {
tick_rate: DEFAULT_TICK_RATE,
// frame_rate: DEFAULT_FRAME_RATE,
}
}
}
@@ -1,139 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::tui::action::Action;
use crate::tui::dispatcher::store::State;
use crate::AppAction;
use async_trait::async_trait;
use color_eyre::eyre;
use tokio::sync::mpsc::UnboundedSender;
use tokio_stream::wrappers::UnboundedReceiverStream;
use tokio_stream::StreamExt;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
pub mod store;
#[derive(Clone)]
pub struct ActionSender<T: AppAction>(UnboundedSender<Action<T>>);
impl<T> From<UnboundedSender<Action<T>>> for ActionSender<T>
where
T: AppAction,
{
fn from(value: UnboundedSender<Action<T>>) -> Self {
ActionSender(value)
}
}
impl<T> ActionSender<T>
where
T: AppAction,
{
pub fn send(&self, action: impl Into<Action<T>>) {
if let Err(unsent) = self.0.send(action.into()) {
error!("failed to send {:?} action to the dispatcher", unsent.0)
}
}
}
pub type ActionReceiver<T> = UnboundedReceiverStream<Action<T>>;
pub type StateUpdateSender<S> = UnboundedSender<S>;
pub type StateUpdateReceiver<S> = UnboundedReceiverStream<S>;
#[async_trait]
pub trait ActionDispatcher {
type Store: State;
type Actions: AppAction;
async fn handle_app_action(
&mut self,
action: Self::Actions,
store: &mut Self::Store,
) -> eyre::Result<()>;
}
pub struct DispatcherLoop<D: ActionDispatcher> {
dispatcher: D,
store: D::Store,
// to be used with async actions
#[allow(dead_code)]
action_sender: ActionSender<D::Actions>,
action_receiver: ActionReceiver<D::Actions>,
state_update_sender: StateUpdateSender<D::Store>,
cancellation_token: CancellationToken,
}
impl<D> DispatcherLoop<D>
where
D: ActionDispatcher + Send + Sync + 'static,
D::Store: Send + Sync + 'static,
{
pub(crate) fn new(
dispatcher: D,
store: D::Store,
action_sender: impl Into<ActionSender<D::Actions>>,
action_receiver: impl Into<ActionReceiver<D::Actions>>,
state_update_sender: StateUpdateSender<D::Store>,
cancellation_token: CancellationToken,
) -> DispatcherLoop<D> {
DispatcherLoop {
dispatcher,
store,
action_sender: action_sender.into(),
action_receiver: action_receiver.into(),
state_update_sender,
cancellation_token,
}
}
async fn handle_action(&mut self, action: Option<Action<D::Actions>>) -> eyre::Result<()> {
let Some(action) = action else {
warn!("the dispatcher channel has closed! we're probably already in shutdown!");
// but if we're not, make sure to kick it off...
self.cancellation_token.cancel();
return Ok(());
};
match action {
Action::Quit => {
debug!("attempting to handle the QUIT action");
self.cancellation_token.cancel();
// no need to send any state updates here
return Ok(());
}
Action::AppDefined(action) => {
debug!("attempting to handle the following action: {:?}", action);
self.dispatcher
.handle_app_action(action, &mut self.store)
.await?;
}
}
self.state_update_sender.send(self.store.clone())?;
Ok(())
}
pub async fn run(&mut self) -> eyre::Result<()> {
info!("starting the dispatcher loop");
// issue initial state
self.state_update_sender.send(self.store.clone())?;
loop {
tokio::select! {
biased;
_ = self.cancellation_token.cancelled() => {
info!("received cancellation token");
break;
}
maybe_action = self.action_receiver.next() => {
self.handle_action(maybe_action).await?
}
}
}
Ok(())
}
}
@@ -1,6 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub trait State: Clone {
//
}
-80
View File
@@ -1,80 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use color_eyre::eyre;
use crossterm::event::EventStream;
use ratatui::backend::CrosstermBackend as Backend;
use ratatui::crossterm::{
self, cursor,
terminal::{EnterAlternateScreen, LeaveAlternateScreen},
};
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio_stream::Stream;
pub struct TuiHandle {
pub terminal: ratatui::Terminal<Backend<std::io::Stderr>>,
pub crossterm_events: EventStream,
}
impl TuiHandle {
pub fn new() -> Result<TuiHandle, eyre::Error> {
let terminal = ratatui::Terminal::new(Backend::new(std::io::stderr()))?;
let crossterm_events = EventStream::new();
Ok(TuiHandle {
terminal,
crossterm_events,
})
}
pub fn enter(&self) -> Result<(), eyre::Error> {
crossterm::terminal::enable_raw_mode()?;
crossterm::execute!(std::io::stderr(), EnterAlternateScreen, cursor::Hide)?;
Ok(())
}
pub fn exit(&mut self) -> eyre::Result<()> {
if crossterm::terminal::is_raw_mode_enabled()? {
self.terminal.flush()?;
crossterm::execute!(std::io::stderr(), LeaveAlternateScreen, cursor::Show)?;
crossterm::terminal::disable_raw_mode()?;
}
Ok(())
}
}
impl Stream for TuiHandle {
type Item = <EventStream as Stream>::Item;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.crossterm_events).poll_next(cx)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.crossterm_events.size_hint()
}
}
impl Deref for TuiHandle {
type Target = ratatui::Terminal<Backend<std::io::Stderr>>;
fn deref(&self) -> &Self::Target {
&self.terminal
}
}
impl DerefMut for TuiHandle {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.terminal
}
}
impl Drop for TuiHandle {
fn drop(&mut self) {
// well. at this point we can't do much, we'll just go straight into the panic handler
#[allow(clippy::expect_used)]
self.exit().expect("failed to teardown the terminal")
}
}
-158
View File
@@ -1,158 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::tui::action::Action;
use crate::tui::config::TuiConfig;
use crate::tui::dispatcher::{ActionDispatcher, ActionSender, DispatcherLoop};
use crate::tui::ui::UiEventLoop;
use crate::Component;
use color_eyre::eyre;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tracing::{error, info};
pub struct TuiManager<C: Component> {
shutdown_grace: Duration,
cancel_grace: Duration,
abort_grace: Duration,
task_tracker: TaskTracker,
cancellation_token: CancellationToken,
dispatcher_handle: JoinHandle<eyre::Result<()>>,
ui_event_loop_handle: JoinHandle<eyre::Result<()>>,
action_sender: ActionSender<C::Actions>,
}
impl<C> TuiManager<C>
where
C: Component + Send + Sync + 'static,
C::State: Send + Sync + 'static,
C::Actions: Send + Sync + Clone + 'static,
{
pub(crate) fn build_new<D>(
config: TuiConfig,
action_dispatcher: D,
initial_state: D::Store,
) -> eyre::Result<TuiManager<C>>
where
D: ActionDispatcher<Store = C::State, Actions = C::Actions> + Send + Sync + 'static,
{
let task_tracker = TaskTracker::new();
let cancellation_token = CancellationToken::new();
let (action_tx, action_rx) = mpsc::unbounded_channel();
let (state_tx, state_rx) = mpsc::unbounded_channel();
let mut dispatcher_loop = DispatcherLoop::new(
action_dispatcher,
initial_state,
action_tx.clone(),
action_rx,
state_tx,
cancellation_token.clone(),
);
let mut ui_event_loop = UiEventLoop::<C>::new(
config.tui.debug.tick_rate,
cancellation_token.clone(),
state_rx,
action_tx.clone(),
)?;
let dispatcher_handle = task_tracker.spawn(async move { dispatcher_loop.run().await });
let ui_event_loop_handle = task_tracker.spawn(async move { ui_event_loop.run().await });
task_tracker.close();
Ok(TuiManager {
shutdown_grace: config.debug.shutdown_grace,
cancel_grace: config.debug.cancel_grace,
abort_grace: config.debug.abort_grace,
task_tracker,
cancellation_token,
dispatcher_handle,
ui_event_loop_handle,
action_sender: action_tx.into(),
})
}
async fn graceful_shutdown(&self) {
// 1. try to send quit action to handle it the most gracefully
self.action_sender.send(Action::Quit);
if timeout(self.shutdown_grace, self.task_tracker.wait())
.await
.is_ok()
{
return;
}
error!("timed out while waiting for graceful shutdown");
// 2. if that doesn't work, issue cancellation token
self.cancellation_token.cancel();
if timeout(self.cancel_grace, self.task_tracker.wait())
.await
.is_ok()
{
return;
}
error!("timed out while attempting to resolve cancellation token shutdown");
// 3. finally go with nuclear option and just abort the tasks
self.dispatcher_handle.abort();
self.ui_event_loop_handle.abort();
if timeout(self.abort_grace, self.task_tracker.wait())
.await
.is_ok()
{
return;
}
error!("somehow we still failed to shutdown our tasks! we might end up in a dirty state... oh well")
}
pub(crate) async fn wait_for_exit_or_signal(&self) {
tokio::select! {
_ = self.task_tracker.wait() => {
// user decided to quit with 'normal' action
}
_ = wait_for_signal() => {
self.graceful_shutdown().await
}
}
}
}
#[cfg(unix)]
#[allow(clippy::expect_used)]
pub async fn wait_for_signal() {
use tokio::signal::unix::{signal, SignalKind};
let mut sigterm = signal(SignalKind::terminate()).expect("failed to setup SIGTERM channel");
let mut sigquit = signal(SignalKind::quit()).expect("failed to setup SIGQUIT channel");
tokio::select! {
_ = tokio::signal::ctrl_c() => {
info!("Received SIGINT");
},
_ = sigterm.recv() => {
info!("Received SIGTERM");
}
_ = sigquit.recv() => {
info!("Received SIGQUIT");
}
}
}
#[cfg(not(unix))]
pub async fn wait_for_signal() {
tokio::select! {
_ = tokio::signal::ctrl_c() => {
info!("Received SIGINT");
},
}
}
-46
View File
@@ -1,46 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::tui::handle::TuiHandle;
use color_eyre::eyre;
use tracing::error;
pub mod action;
pub mod config;
pub(crate) mod dispatcher;
pub mod handle;
pub(crate) mod manager;
pub(crate) mod ui;
pub fn initialize_panic_handler() -> eyre::Result<()> {
let (panic_hook, eyre_hook) = color_eyre::config::HookBuilder::default()
.display_location_section(true)
.display_env_section(true)
.into_hooks();
eyre_hook.install()?;
std::panic::set_hook(Box::new(move |panic_info| {
if let Err(r) = TuiHandle::new().and_then(|mut h| h.exit()) {
error!("Unable to exit Terminal: {:?}", r);
}
let msg = format!("{}", panic_hook.panic_report(panic_info));
#[cfg(not(debug_assertions))]
{
eprintln!("{}", msg); // prints color-eyre stack trace to stderr
}
error!("error: {}", strip_ansi_escapes::strip_str(msg));
#[cfg(debug_assertions)]
{
// Better Panic stacktrace that is only enabled when debugging.
better_panic::Settings::auto()
.most_recent_first(false)
.lineno_suffix(true)
.verbosity(better_panic::Verbosity::Full)
.create_panic_handler()(panic_info);
}
std::process::exit(1);
}));
Ok(())
}
@@ -1,70 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::tui::config::keybindings::key_event_to_string;
use crate::tui::dispatcher::ActionSender;
use crate::{AppAction, Component, State};
use crossterm::event::KeyEvent;
use ratatui::layout::{Alignment, Rect};
use ratatui::prelude::{Line, Style, Stylize};
use ratatui::widgets::Block;
use ratatui::Frame;
use std::marker::PhantomData;
pub struct DebugHistory<S, A> {
last_tick_key_events: Vec<KeyEvent>,
phantom_state: PhantomData<S>,
phantom_action: PhantomData<A>,
}
impl<S, A> Component for DebugHistory<S, A>
where
S: State,
A: AppAction,
{
type State = S;
type Actions = A;
fn new(_state: &Self::State, _action_sender: ActionSender<Self::Actions>) -> Self
where
Self: Sized,
{
DebugHistory {
last_tick_key_events: vec![],
phantom_state: PhantomData,
phantom_action: PhantomData,
}
}
fn tick(&mut self) -> bool {
let was_empty = self.last_tick_key_events.is_empty();
self.last_tick_key_events.drain(..);
!was_empty
}
fn handle_key(&mut self, key: KeyEvent) -> color_eyre::Result<()> {
self.last_tick_key_events.push(key);
Ok(())
}
fn view(&mut self, frame: &mut Frame, rect: Rect) {
frame.render_widget(
Block::default()
.title_top(
Line::from(format!(
"{:?}",
&self
.last_tick_key_events
.iter()
.map(key_event_to_string)
.collect::<Vec<_>>()
))
.alignment(Alignment::Right),
)
.title_style(Style::default().bold()),
rect,
);
}
}
@@ -1,81 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::tui::config::keybindings::LoggerKeybindings;
use crate::tui::dispatcher::store::State;
use crate::tui::dispatcher::ActionSender;
use crate::tui::ui::components::Component;
use crate::AppAction;
use crossterm::event::KeyEvent;
use ratatui::layout::Rect;
use ratatui::prelude::*;
use ratatui::widgets::Block;
use ratatui::Frame;
use std::marker::PhantomData;
use tui_logger::{TuiLoggerLevelOutput, TuiLoggerSmartWidget, TuiWidgetState};
pub struct Props {
pub keybindings: LoggerKeybindings,
}
pub struct Logger<S, A> {
props: Props,
widget_state: TuiWidgetState,
phantom_state: PhantomData<S>,
phantom_action: PhantomData<A>,
}
impl<S, A> Component for Logger<S, A>
where
S: State,
for<'a> Props: From<&'a S>,
A: AppAction,
{
type State = S;
type Actions = A;
fn new(state: &Self::State, _action_sender: ActionSender<Self::Actions>) -> Self
where
Self: Sized,
{
Logger {
props: Props::from(state),
widget_state: TuiWidgetState::new(),
phantom_state: PhantomData,
phantom_action: PhantomData,
}
}
fn tick(&mut self) -> bool {
true
}
fn handle_key(&mut self, key: KeyEvent) -> color_eyre::Result<()> {
if let Some(tui_event) = self.props.keybindings.tui_logger_event(key.into()) {
self.widget_state.transition(tui_event)
}
Ok(())
}
fn view(&mut self, frame: &mut Frame, rect: Rect) {
let border = Block::bordered();
let inner_area = border.inner(rect);
frame.render_widget(border, rect);
let tui_sm = TuiLoggerSmartWidget::default()
.style_error(Style::default().fg(Color::Red))
.style_warn(Style::default().fg(Color::Yellow))
.style_info(Style::default().fg(Color::Green))
.style_debug(Style::default().fg(Color::Cyan))
.style_trace(Style::default().fg(Color::Magenta))
.output_separator(':')
.output_timestamp(Some("%F %H:%M:%S%.3f".to_string()))
.output_level(Some(TuiLoggerLevelOutput::Long))
.output_target(true)
.output_file(true)
.output_line(true)
.state(&self.widget_state);
frame.render_widget(tui_sm, inner_area);
}
}
@@ -1,12 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod debug_history;
#[cfg(feature = "logger")]
pub mod logger;
pub use debug_history::DebugHistory;
#[cfg(feature = "logger")]
pub use logger::{Logger, Props as LoggerProps};
@@ -1,45 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::tui::dispatcher::ActionSender;
use crate::{AppAction, State};
use color_eyre::eyre;
use crossterm::event::KeyEvent;
use ratatui::prelude::Rect;
use ratatui::Frame;
pub mod common;
// pub trait Props<'a>: From<&'a Self::State> {
// type State: State;
// }
pub trait Component {
type State: State;
type Actions: AppAction;
fn new(state: &Self::State, action_sender: ActionSender<Self::Actions>) -> Self
where
Self: Sized;
fn update(self, state: &Self::State) -> Self
where
Self: Sized,
{
let _ = state;
self
}
// returns boolean indicating whether a rerender is needed
// fn tick(&mut self) -> bool;
fn tick(&mut self) -> bool {
false
}
fn handle_key(&mut self, key: KeyEvent) -> eyre::Result<()> {
let _ = key;
Ok(())
}
fn view(&mut self, frame: &mut Frame, rect: Rect);
}
-154
View File
@@ -1,154 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::tui::dispatcher::{ActionSender, StateUpdateReceiver};
use crate::tui::handle::TuiHandle;
use crate::tui::ui::components::Component;
use color_eyre::eyre;
use color_eyre::eyre::eyre;
use crossterm::event::Event;
use humantime_serde::re::humantime;
use std::io;
use std::marker::PhantomData;
use std::time::Duration;
use tokio::time::{timeout, Instant};
use tokio_stream::StreamExt;
use tokio_util::sync::CancellationToken;
use tracing::{info, trace, warn};
pub mod components;
pub struct UiEventLoop<C: Component> {
tick_rate: Duration,
cancellation_token: CancellationToken,
state_receiver: StateUpdateReceiver<C::State>,
// only to be used to construct root 'App' instance
action_sender: ActionSender<C::Actions>,
tui_handle: TuiHandle,
root_component: PhantomData<C>,
}
impl<C> UiEventLoop<C>
where
C: Component,
{
pub fn new(
tick_rate: Duration,
cancellation_token: CancellationToken,
state_receiver: impl Into<StateUpdateReceiver<C::State>>,
action_sender: impl Into<ActionSender<C::Actions>>,
) -> eyre::Result<Self> {
Ok(UiEventLoop {
tick_rate,
cancellation_token,
state_receiver: state_receiver.into(),
action_sender: action_sender.into(),
tui_handle: TuiHandle::new()?,
root_component: PhantomData,
})
}
async fn handle_ui_event(
&mut self,
event: Option<io::Result<Event>>,
root_app: &mut C,
) -> eyre::Result<()> {
let Some(event) = event else {
warn!("the crossterm event channel has closed! we're probably already in shutdown!");
// but if we're not, make sure to kick it off...
self.cancellation_token.cancel();
return Ok(());
};
match event? {
Event::FocusGained => {}
Event::FocusLost => {}
Event::Key(key_event) => root_app.handle_key(key_event)?,
Event::Mouse(_) => {}
Event::Paste(_) => {}
Event::Resize(_, _) => {}
}
Ok(())
}
async fn handle_updated_state(&mut self, state: Option<C::State>, root_app: C) -> C
where
C: Component,
{
let Some(updated_state) = state else {
warn!("the state update channel has closed! we're probably already in shutdown!");
// but if we're not, make sure to kick it off...
self.cancellation_token.cancel();
return root_app;
};
root_app.update(&updated_state)
}
pub async fn run(&mut self) -> eyre::Result<()>
where
// this clone shouldn't really be needed...
C::Actions: Clone,
{
info!("starting the ui loop");
// wait for initial state...
let initial_state = timeout(Duration::from_secs(1), self.state_receiver.next())
.await?
.ok_or_else(|| eyre!("did not receive initial state!"))?;
let mut root_app = C::new(&initial_state, self.action_sender.clone());
let mut tick_rate = self.tick_rate;
let mut tick_interval = tokio::time::interval(tick_rate);
self.tui_handle.enter()?;
let mut draw = true;
loop {
if draw {
let draw_start = Instant::now();
trace!("redrawing the UI");
self.tui_handle
.draw(|frame| root_app.view(frame, frame.area()))?;
let taken = humantime::format_duration(draw_start.elapsed()).to_string();
trace!(time_taken = taken, "UI drawing");
}
tokio::select! {
biased;
_ = self.cancellation_token.cancelled() => {
info!("received cancellation token");
break;
}
maybe_ui_event = self.tui_handle.next() => {
self.handle_ui_event(maybe_ui_event, &mut root_app).await?;
draw = true;
}
state_update = self.state_receiver.next() => {
root_app = self.handle_updated_state(state_update, root_app).await;
// the tick rate has changed
if self.tick_rate != tick_rate {
tick_rate = self.tick_rate;
tick_interval = tokio::time::interval(tick_rate);
}
draw = true;
}
_ = tick_interval.tick() => {
let tick_start = Instant::now();
draw = root_app.tick();
let taken = humantime::format_duration(tick_start.elapsed()).to_string();
trace!(time_taken = taken, will_redraw = draw, "app tick");
},
}
}
Ok(())
}
}
@@ -3,7 +3,7 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[repr(u8)]
pub enum ServiceProviderType {
NetworkRequester = 0,
-1
View File
@@ -95,7 +95,6 @@ impl ClientStatsController {
gateway_conn_stats: self.gateway_conn_stats.report(),
nym_api_stats: self.nym_api_stats.report(),
connection_stats: self.connection_stats.report(),
..Default::default()
}
}
-22
View File
@@ -12,14 +12,9 @@ use serde::{Deserialize, Serialize};
use sysinfo::System;
use time::OffsetDateTime;
const KIND: &str = "client_stats_report";
const VERSION: &str = "v1";
/// Report object containing both data to be reported and client / device context. We take extra care not to overcapture context information.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientStatsReport {
pub(crate) kind: String,
pub(crate) api_version: String,
pub(crate) last_update_time: OffsetDateTime,
pub(crate) client_id: String,
pub(crate) client_type: String,
@@ -46,23 +41,6 @@ impl TryFrom<&[u8]> for ClientStatsReport {
}
}
impl Default for ClientStatsReport {
fn default() -> Self {
ClientStatsReport {
kind: KIND.to_string(),
api_version: VERSION.to_string(),
last_update_time: OffsetDateTime::now_utc(),
client_id: Default::default(),
client_type: Default::default(),
os_information: Default::default(),
packet_stats: Default::default(),
gateway_conn_stats: Default::default(),
nym_api_stats: Default::default(),
connection_stats: Default::default(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OsInformation {
pub(crate) os_type: String,
+1 -9
View File
@@ -3,7 +3,7 @@ use crate::deprecated::DelegationEvent;
use crate::error::TypesError;
use crate::mixnode::NodeCostParams;
use cosmwasm_std::Decimal;
use nym_mixnet_contract_common::{Delegation as MixnetContractDelegation, NodeId, NodeRewarding};
use nym_mixnet_contract_common::{Delegation as MixnetContractDelegation, NodeId};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -70,14 +70,6 @@ pub struct DelegationWithEverything {
pub mixnode_is_unbonding: Option<bool>,
}
pub struct NodeInformation {
pub owner: String,
pub mix_id: NodeId,
pub node_identity: String,
pub rewarding_details: NodeRewarding,
pub is_unbonding: bool,
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
+3 -7
View File
@@ -7,8 +7,8 @@ use defguard_wireguard_rs::{
WireguardInterfaceApi,
};
use futures::channel::oneshot;
use nym_authenticator_requests::latest::registration::{
RemainingBandwidthData, BANDWIDTH_CAP_PER_DAY,
use nym_authenticator_requests::{
latest::registration::RemainingBandwidthData, v1::registration::BANDWIDTH_CAP_PER_DAY,
};
use nym_credential_verification::{
bandwidth_storage_manager::BandwidthStorageManager, BandwidthFlushingBehaviourConfig,
@@ -194,10 +194,6 @@ impl<St: Storage + Clone + 'static> PeerController<St> {
);
self.bw_storage_managers
.insert(peer.public_key.clone(), bandwidth_storage_manager);
// try to immediately update the host information, to eliminate races
if let Ok(host_information) = self.wg_api.inner.read_interface_data() {
*self.host_information.write().await = host_information;
}
tokio::spawn(async move {
if let Err(e) = handle.run().await {
log::error!("Peer handle shut down ungracefully - {e}");
@@ -234,7 +230,7 @@ impl<St: Storage + Clone + 'static> PeerController<St> {
// host information not updated yet
return Ok(None);
};
BANDWIDTH_CAP_PER_DAY.saturating_sub(peer.rx_bytes + peer.tx_bytes) as i64
BANDWIDTH_CAP_PER_DAY.saturating_sub((peer.rx_bytes + peer.tx_bytes) as i64)
};
Ok(Some(RemainingBandwidthData {
+3 -3
View File
@@ -6,7 +6,7 @@ use crate::peer_controller::PeerControlRequest;
use defguard_wireguard_rs::host::Peer;
use defguard_wireguard_rs::{host::Host, key::Key};
use futures::channel::oneshot;
use nym_authenticator_requests::latest::registration::BANDWIDTH_CAP_PER_DAY;
use nym_authenticator_requests::v2::registration::BANDWIDTH_CAP_PER_DAY;
use nym_credential_verification::bandwidth_storage_manager::BandwidthStorageManager;
use nym_gateway_storage::models::WireguardPeer;
use nym_gateway_storage::Storage;
@@ -18,7 +18,7 @@ use tokio::sync::{mpsc, RwLock};
use tokio_stream::{wrappers::IntervalStream, StreamExt};
pub(crate) type SharedBandwidthStorageManager<St> = Arc<RwLock<BandwidthStorageManager<St>>>;
const AUTO_REMOVE_AFTER: Duration = Duration::from_secs(60 * 60 * 24 * 30); // 30 days
const AUTO_REMOVE_AFTER: Duration = Duration::from_secs(60 * 60 * 24); // 24 hours
pub struct PeerHandle<St> {
storage: St,
@@ -98,7 +98,7 @@ impl<St: Storage + Clone + 'static> PeerHandle<St> {
} else {
if SystemTime::now().duration_since(self.startup_timestamp)? >= AUTO_REMOVE_AFTER {
log::debug!(
"Peer {} has been present for 30 days, removing it",
"Peer {} has been present for 24 hours, removing it",
self.public_key.to_string()
);
let success = self.remove_peer().await?;
+17 -8
View File
@@ -104,10 +104,7 @@ pub(crate) fn next_nymnode_id_counter(store: &mut dyn Storage) -> StdResult<Node
}
pub(crate) fn initialise_storage(storage: &mut dyn Storage) -> Result<(), MixnetContractError> {
let active_bucket = RoleStorageBucket::default();
let inactive_bucket = active_bucket.other();
ACTIVE_ROLES_BUCKET.save(storage, &active_bucket)?;
ACTIVE_ROLES_BUCKET.save(storage, &RoleStorageBucket::default())?;
let roles = vec![
Role::Layer1,
Role::Layer2,
@@ -117,12 +114,24 @@ pub(crate) fn initialise_storage(storage: &mut dyn Storage) -> Result<(), Mixnet
Role::Standby,
];
for role in roles {
ROLES.save(storage, (active_bucket as u8, role), &vec![])?;
ROLES.save(storage, (inactive_bucket as u8, role), &vec![])?
ROLES.save(storage, (RoleStorageBucket::default() as u8, role), &vec![])?;
ROLES.save(
storage,
(RoleStorageBucket::default().other() as u8, role),
&vec![],
)?
}
ROLES_METADATA.save(storage, active_bucket as u8, &Default::default())?;
ROLES_METADATA.save(storage, inactive_bucket as u8, &Default::default())?;
ROLES_METADATA.save(
storage,
RoleStorageBucket::default() as u8,
&Default::default(),
)?;
ROLES_METADATA.save(
storage,
RoleStorageBucket::default().other() as u8,
&Default::default(),
)?;
Ok(())
}
@@ -1,36 +0,0 @@
export const Clt = ({ children, backgroundColor = 'white', borderColor = 'black', pointPosition = 'left', pointOffset = '2rem', pointAlignment = 'end', pointTranslate, pointLength = '2rem', cornerRadius = '0.5rem', borderWidth = '0.2rem', pointWidthMultiplier = 0.5, pointLengthMultiplier = 1, style = {} }) => {
const center = pointAlignment === 'center'
const offset = center ? '50%' : pointOffset
const translate = center ? (pointPosition === 'left' || pointPosition === 'right') ? 'translateY(-50%)' : 'translateX(-50%)' : pointTranslate
const wMult = Math.min(pointWidthMultiplier, 0.99)
const lMult = Math.max(pointLengthMultiplier, 1)
const props = {
'--pointLength': pointLength,
'--positionOffset': offset,
'--bkg-color': backgroundColor,
'--bdr-color': borderColor,
'--corner-radius': cornerRadius,
'--border-width': borderWidth,
'--pointWidthMultiplier': wMult,
'--pointLengthMultiplier': lMult,
...style
}
return (
<div className={`clt ${pointPosition}`} style={props}>
<div className={`clt__bubble ${pointPosition}`}>
<div className="clt__content">
{children}
</div>
</div>
<div className={`clt__point-wrapper ${pointPosition} ${pointAlignment}`} style={{ ...(translate && { transform: translate }) }}>
<div className={`clt__point ${pointPosition}`} />
</div>
</div>
)
}
@@ -1,7 +0,0 @@
| **Item** | **Description** | **Amount in NYM** |
|:-------------------|:------------------------------------------------------|--------------------:|
| Total Supply | Maximum amount of NYM token in existence | 1_000_000_000 |
| Mixmining Reserve | Tokens releasing for operators rewards | 196_896_265 |
| Vesting Tokens | Tokens locked outside of cicrulation for future claim | 500 |
| Circulating Supply | Amount of unlocked tokens | 803_103_234 |
| Stake Saturation | Optimal size of node self-bond + delegation | 1_016_987 |
@@ -1 +1 @@
Wednesday, November 20th 2024, 15:53:00 UTC
Tuesday, October 29th 2024, 09:51:52 UTC
@@ -1,5 +1,5 @@
```sh
2024-11-20T15:53:01.702819Z  INFO nym-api/src/main.rs:40: Starting nym api...
2024-10-29T09:51:53.363364Z  INFO nym-api/src/main.rs:41: Starting nym api...
Usage: nym-api [OPTIONS] <COMMAND>
Commands:
@@ -54,6 +54,8 @@ 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>
@@ -1 +0,0 @@
803_103_234
@@ -1,7 +0,0 @@
| **Item** | **Description** | **Amount in NYM** |
|:-------------------|:------------------------------------------------------|--------------------:|
| Total Supply | Maximum amount of NYM token in existence | 1_000_000_000 |
| Mixmining Reserve | Tokens releasing for operators rewards | 196_896_265 |
| Vesting Tokens | Tokens locked outside of cicrulation for future claim | 500 |
| Circulating Supply | Amount of unlocked tokens | 803_103_234 |
| Stake Saturation | Optimal size of node self-bond + delegation | 1_016_987 |
+1 -1
View File
@@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.
// see https://nextjs.org/docs/basic-features/typescript for more information.
-12
View File
@@ -772,18 +772,6 @@ const config = {
permanent: true,
basePath: false,
},
{
source: "/operators/troubleshooting/nodes.html",
destination: "/docs/operators/troubleshooting/nodes",
permanent: true,
basePath: false,
},
{
source: "/operators/nodes/manual-upgrade.html",
destination: "/docs/operators/nodes/maintenance/manual-upgrade",
permanent: true,
basePath: false,
},
{
source: "/developers/faq/general-faq.html",
destination: "/docs/operators/faq/general-faq",
@@ -14,4 +14,4 @@ MultiSURBs were implemented in `v1.1.4`. Clients, when sending a message to anot
If a reply is too large still (i.e. it would use more space than the available combined payload of the SURBs sent with the original message), the receiver will use a SURB to ask the sender for more SURBs.
You can read more about SURBs in §4.5 of the [Nym Whitepaper](https://nymtech.net/nym-whitepaper.pdf) as well as the [SURB traffic page](../traffic/anonymous-replies) to learn more about how SURBs are used in the Mixnet, known attacks relying on SURBs, etc.
You can read more about SURBs in §4.5 of the [Nym Whitepaper](https://nymtech.net/nym-whitepaper.pdf) as well as the [SURB format page](../traffic/anonymous-replies).
@@ -0,0 +1,13 @@
# Anonymous Replies with SURBs
> SURBs are the Sphinx equivalent of "onion addresses" in Tor, with the caveat that a SURB can only
be used once (to prevent replay attacks) and within its epoch of validity (the mix node public keys used to
prepare the SURB are only valid for a limited period).
> ...
> A SURB effectively contains: (1) the encrypted headers of a Sphinx message that, if sent to the mixnet, will be routed back to the original sender; (2) the address of the first-layer mix node where the message should be sent; and (3) a cryptographic key to encrypt the reply payload.
>
> [Nym Whitepaper](https://nymtech.net/nym-whitepaper.pdf) §4.6
As outlined in the [concepts](../concepts/anonymous-replies) section, SURBs are layer encrypted sets of Sphinx headers detailing a reply path ending in the sending client's [Nym address](../traffic/addressing-system). Clients receiving messages with SURBs attached are able to write a payload to the provided headers without ever learning about anything other than the first hop back into the Mixnet - the Gateway they are currently connected to.
There is a balance to be struck between the amount of SURBs to compute to send along with messages (which takes computation resources) and not sending enough SURBs initially, thus having to wait for a SURB to be sent from the receiver to the sender, requesting more SURBs be sent.
@@ -1,78 +0,0 @@
import { Callout } from 'nextra/components'
# Anonymous Replies with SURBs
> SURBs are pre-computed Sphinx packet headers encoding a mixnet route that ends in the participant that created the SURB. A sender can generate one or more SURBs and include them in their Sphinx message to a recipient. The recipient can use the SURBs as Sphinx headers to send back replies or acknowledgements that anonymously reach back the original sender after going through the mixnet.
>
> SURBs are the Sphinx equivalent of "onion addresses" in Tor, with the caveat that a SURB can only be used once (to prevent replay attacks) and within its epoch of validity (the mix node public keys used to prepare the SURB are only valid for a limited period). SURB headers are encrypted by the sender, so the recipient sending it back cannot infer from it any information about the message route, the per-hop latency, or the senders address, which is encoded in the innermost (last) routing layer of the SURB. SURBs ('Single Use Reply Blocks') allow clients to reply to incoming messages anonymously.
>
> ...
>
> A SURB effectively contains: (1) the encrypted headers of a Sphinx message that, if sent to the mixnet, will be routed back to the original sender; (2) the address of the first-layer mix node where the message should be sent; and (3) a cryptographic key to encrypt the reply payload.
> [Nym Whitepaper](https://nymtech.net/nym-whitepaper.pdf) §4.5
As outlined in the [concepts](../concepts/anonymous-replies) section, SURBs are layer encrypted sets of Sphinx headers detailing a reply path ending in the sending client's [Nym address](../traffic/addressing-system). Clients receiving messages with SURBs attached are able to write a payload to the provided headers without ever learning about anything other than the first hop back into the Mixnet - the Gateway they (the sender of the reply) are currently registered with.
Put simply, client A sends client B a request of some kind. Before sending the request through the Mixnet, it creates a number of SURBs and sends those along with the request. Client B writes the response to the request to the payload of the SURBs, and then sends these through the Mixnet. Since Sphinx packets are multiply route-encrypted, the first destination of the packet is the `nym-node` running as an Entry Gateway that client B has registered with already, so no information regarding either the path through the Mixnet or the destination of the SURBs (aka the Nym address of client A) is revealed to client B.
## Anatomy of a SURB
Diagramatic representation coming soon™️.
## Sender Tags
For a session between two clients, the sending client generates a random alphanumeric string, referred to as a `sender tag` which is sent along with the SURBs to the receiver of its message(s). The `sender tag` is generated randomly, and does not refer in any way to any identifiers of the sending client.
This is done so that receiving clients have some way of differentiating incoming SURBs from multiple clients and can split them into different 'buckets' in order to facilitate concurrent anonymous replies.
## Replenishing SURBs
Since each SURB is just a pre-computed Sphinx packet header, and Sphinx packets only have a finite payload size, then the size of a possible reply for the amount of SURBs sent with a request is `# SURBs * payload size in bytes`. However it is often the case that replies may be variable in size and larger than the alloted payload size, and/or the sending client did not want to compute many Sphinx headers to send with its initial request.
As such, when a client is running out of SURBs to use for replying, it will use a SURB to send a request to the initial sending client. This request is a request for more SURBs to be sent to it.
```mermaid
---
config:
theme: neo-dark
layout: elk
---
sequenceDiagram
participant Nym Client (Sender)
participant Mixnet Nodes
participant Nym Client (Receiver)
Nym Client (Sender) ->> Nym Client (Sender): Create Sphinx packets with request payload & Sphinx packets with N SURBs
Nym Client (Sender) ->> Mixnet Nodes: Sphinx packets (with payload + with SURBs)
Mixnet Nodes ->> Nym Client (Receiver): Sphinx packets (with payload + with SURBs)
Nym Client (Receiver) ->> Nym Client (Receiver): Decrypt packets
Nym Client (Receiver) ->> Nym Client (Receiver): Perform computation
Nym Client (Receiver) ->> Nym Client (Receiver): Prepare response - problem! Response requires > N * SURB payloads
Nym Client (Receiver) ->> Mixnet Nodes: Sphinx packets (SURB request)
Mixnet Nodes ->> Nym Client (Sender): Sphinx packets (SURB request)
Nym Client (Sender) ->> Nym Client (Sender): Create more SURBs
Nym Client (Sender) ->> Mixnet Nodes: Sphinx packets (SURBs)
Mixnet Nodes ->> Nym Client (Receiver): Sphinx packets (SURBs)
Nym Client (Receiver) ->> Nym Client (Receiver): Write response to SURB payloads
Nym Client (Receiver) ->> Mixnet Nodes: SURBs with payload
Mixnet Nodes ->> Nym Client (Sender): SURBs with payload
Nym Client (Sender) ->> Nym Client (Sender): Decrypt - anonymous response received
```
There is a balance to be struck between the amount of SURBs to compute to send along with messages (aka the sending client A spending computation resources) and not sending enough SURBs initially, thus having to wait for a SURB to be sent from the receiving client B to client A requesting more SURBs be sent, which themselves have to be then sent through the Mixnet to client B to be written to and sent back through the Mixnet again.
If you are able to spend the extra resources upfront and send a lot of SURBs, fewer trips through the Mixnet are required for traffic to go back and forth. However, bear in mind that SURBs in the future will have a finite lifespan (see the section below) so precomputing a very large number to send with the initial message (assuming you are expecting a large reponse, or several messages back and forth) will not work. Furthermore, sending huge amounts of SURBs might open your app up to [possible attacks](#anatomy-of-a-surb).
## SURB Lifetimes
<Callout type="warning">
At the time of writing, SURBs themselves are valid indefinitely, but clients purge their local DB of SURBs that are older than a day on restart. SURBs are valid between topology changes over epochs as `nym-nodes` have a single static publick key, so unless a node goes offline, SURBs will still work even after a topology change.
We still have a few features to add to the Mixnet to add some extra security which will dramatically limit the amount of time SURBs are valid for, but will increase the overall security of the network, so do **not** build with the current status in mind. Instead, check out the information below, and build with this in mind.
</Callout>
Once node key rotation (part of the larger [forward secrecy](https://en.wikipedia.org/wiki/Forward_secrecy) work) and [replay protection](https://www.kaspersky.com/resource-center/definitions/replay-attack) is implemented, SURBs will only be valid for the length of the key epoch (aka for the length of time a `nym-node` retains a particular public key between rotations). The length of the key epoch is still to be decided.
Although this means that there will probably be more back-and-forth between clients sending large volumes of traffic, this will make the network more secure overall.
## Known Attacks Using SURBs
There is a known attack in which a malicious service provider / client continually requests that a sending client sends more and more SURBs to them, accruing a large number of them. The attacker then sends all SURBs back to the sending clients at once in order to try and see permutations in the traffic exiting the Mixnet to the sending client, in order to work out which Gateway they are using as their Entry Gateway.
This attack however relies upon the attacker already being able to actively scan all `nym-node`s running as Gateways and capture that traffic, as well as (once the [zk-nym scheme]() is enabled, spend money to send that traffic through the Mixnet. Furthermore, this is an _active attack_ and requires a client to be either be running a malicious service, or be in a position to request multiple bundles of SURBs from clients via some service.
@@ -3,8 +3,6 @@ import { Tabs } from 'nextra/components';
import { RunTabs } from 'components/operators/nodes/node-run-command-tabs';
import { VarInfo } from 'components/variable-info.tsx';
import { AccordionTemplate } from 'components/accordion-template.tsx';
import { Steps } from 'nextra/components';
export const TestingSteps = () => (
@@ -33,523 +31,6 @@ This page displays a full list of all the changes during our release cycle from
<VarInfo />
## `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.
- [Release binaries](https://github.com/nymtech/nym/releases/tag/nym-binaries-v2024.13-magura)
- [Release CHANGELOG.md](https://github.com/nymtech/nym/blob/nym-binaries-v2024.13-magura/CHANGELOG.md)
- [`nym-node`](nodes/nym-node.mdx) version `1.1.10`
```sh
nym-node
Binary Name: nym-node
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.82.0
rustc Channel: stable
cargo Profile: release
```
- [New smart contracts](https://github.com/nymtech/nym/releases/tag/nym-contracts-magura)
- **[New wallet version 1.2.15](https://github.com/nymtech/nym/releases/tag/nym-wallet-v1.2.15) is out!** - allowing operators to migrate to `nym-node` in Mixnet smart contract.
- [New wallet changelog](https://github.com/nymtech/nym/blob/nym-wallet-v1.2.15/nym-wallet/CHANGELOG.md)
- [New directory services v2.1: API & Mixnet contract changes](#directory-services-v21-api--mixnet-contract-changes)
### Features
- [Migrate Legacy Node (Frontend) ](https://github.com/nymtech/nym/pull/4826)
- [Directory Sevices v2.1](https://github.com/nymtech/nym/pull/4903): Read section [Directory Services v2.1: API & Mixnet Contract Changes ](#directory-services-v21-api--mixnet-contract-changes) below with detailed explanation or the [PR notes](https://github.com/nymtech/nym/pull/4903)
- [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/>}>
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
- [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)
- [`nym-api` container](https://github.com/nymtech/nym/pull/4948)
- [Extract packet processing from mixnode-common](https://github.com/nymtech/nym/pull/4949): First step on a journey of making a strong interface around packet processing, and packet processing portability. This one only moves stuff around, so it should be safe to just blindly merge.
- [expose authenticator address along other address in node-details](https://github.com/nymtech/nym/pull/4953): Expose authenticator address along ip packet router and network requester for easier parsing
- [Feature/contract state tools](https://github.com/nymtech/nym/pull/4954): Introduced/reimplemented old tools for importing cosmwasm contract states given a kv dump file. This makes it significantly easier to plan and test complex state migrations on actual chains where we risk timing out on expensive operations.
- [Add env feature to clap and make clap parameters available as env variables](https://github.com/nymtech/nym/pull/4957)
- [Bump sqlx to 0.7.4](https://github.com/nymtech/nym/pull/4959)
- [`Product Data` First step in gateway usage data collection](https://github.com/nymtech/nym/pull/4963): This PR is the first step towards collecting data on gateway usage. It builds up on an old code for what was then nym-connect. It exposes unique users count and connection time histogram on the `metrics/sessions` endpoint of the self-described API on entry-gateways. For the time being, data is collected by probing the `ActiveClientStore` every minute and extracting data from this. Data is stored internally and exposed on the next day, i.e. UTC day $d$ exposes data from day $d-1$. The [`statistics`](https://github.com/nymtech/nym/tree/simon/product_data/gateway/src/node/statistics) module will evolve as we add collection for product data and censorship resistance study. The collection will also eventually switch from probing to event-based for more accurate data.
- [`importer-cli` to correctly handle mixnet/vesting import](https://github.com/nymtech/nym/pull/4966)
- [Import `nym-vpn-api` crates](https://github.com/nymtech/nym/pull/4967): Keep these crates in a separate workspace for now. The idea is to add them to the main workspace in time, but this appears to might require some changes to how sqlite is used. Alternatively these issues might go away once we upgrade sqlite in the main workspace. Also we intend to rename some of these to something like `nym-credential-facade`, and the wasm lib should be incorporated in one of the existing crates in `common`.
- [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.
- [Top up bandwidth](https://github.com/nymtech/nym/pull/4975)
- [feature: require reporting using nym-node binary for rewarded set selection](https://github.com/nymtech/nym/pull/4976)
- [Re-enable vested delegation migration](https://github.com/nymtech/nym/pull/4977): supersedes [\#4956](https://github.com/nymtech/nym/pull/4956) by removing the contract migration code as it's already been run on mainnet.
- [Resolve beta clippy issues in contracts](https://github.com/nymtech/nym/pull/4978)
- [Enable global ecash routes even if api is not a signer](https://github.com/nymtech/nym/pull/4980)
- [Rename `nym-vpn-api` to `nym-credential-proxy`](https://github.com/nymtech/nym/pull/4981)
- [Add topup req constructor](https://github.com/nymtech/nym/pull/4983)
- [Eliminate 0 bandwidth race check](https://github.com/nymtech/nym/pull/4988)
- [Make accepting t&c a hard requirement for rewarded set selection](https://github.com/nymtech/nym/pull/4993)
- [chore: update itertools in compact ecash](https://github.com/nymtech/nym/pull/4994): supersedes [\#4916](https://github.com/nymtech/nym/pull/4916)
- [Push private ip before inserting](https://github.com/nymtech/nym/pull/5008)
- [Adjusted ticket sizes to the agreed amounts](https://github.com/nymtech/nym/pull/5009)
- [Consume only positive bandwidth](https://github.com/nymtech/nym/pull/5013)
- [Reapply fixes to new branch](https://github.com/nymtech/nym/pull/5014)
- [Added `get_all_described_nodes` to NymApiClient and adjusted return](https://github.com/nymtech/nym/pull/5016)
- [feature: use axum_client_ip for attempting to extract source ip](https://github.com/nymtech/nym/pull/5031): improves source ip logging by extracting relevant header when nym-api is run behind a proxy
- [Pass poisson flag ](https://github.com/nymtech/nym/pull/5037)
- [Added hacky routes to return nymnodes alongside legacy nodes](https://github.com/nymtech/nym/pull/5051)
- [Use unstable explorer client](https://github.com/nymtech/nym/pull/5058): Clean up stale testruns & better logging:
- use new `/unstable` endpoints on explorer for backwards compatibility
- log gw identity key
- better agent testrun logging
- log responses on server side
- change response code for agents
- update sqlx data
- fix agent - probe gw bug
- [Merge1/release/2024.13 magura](https://github.com/nymtech/nym/pull/5061)
- [Merge2/release/2024.13 magura](https://github.com/nymtech/nym/pull/5063)
- [Feature/wallet bonding fixes](https://github.com/nymtech/nym/pull/5064)
- [Allow nym node config updates](https://github.com/nymtech/nym/pull/5066)
- [NS API with directory v2 (#5058)](https://github.com/nymtech/nym/pull/5068)
- [chore: deprecated old nym-api client methods and replaced them when possible](https://github.com/nymtech/nym/pull/5069): this is to that the next time those methods are used outside the monorepo, the relevant calls flag up the CI via clippy
- [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 expiration date as today + 7 days](https://github.com/nymtech/nym/pull/5076)
- [Don't increase bandwidth two times](https://github.com/nymtech/nym/pull/5081)
- [Make 250 GB/30 days for free ride mode](https://github.com/nymtech/nym/pull/5083)
- [Nym node - Fix claim delegator rewards](https://github.com/nymtech/nym/pull/5090)
- [Add more translations from v2 to v3 authenticator](https://github.com/nymtech/nym/pull/5091)
- [Graceful agent 1.1.5](https://github.com/nymtech/nym/pull/5093): API improvements:
- agent exits gracefully when no testrun available
- agent reads content of server's error message in case of 503
- API doesn't log every error (to avoid log spam)
- update network probe within NS agent image: [CI rebuild](https://github.com/nymtech/nym/blob/release/2024.13-magura/nym-node-status-agent/Dockerfile#L9) of NS agent will pick up updated network probe
- [Remove old use of 1GB constant](https://github.com/nymtech/nym/pull/5096)
- [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
- [`nym-credential-proxy-requests`: reqwest use rustls-tls](https://github.com/nymtech/nym/pull/5116)
- [change: dont select mixnodes bonded with vested tokens into the rewarded set](https://github.com/nymtech/nym/pull/5129)
- [Pain/polyfill deprecated endpoints](https://github.com/nymtech/nym/pull/5131)
- [Respond to auth messages with same version](https://github.com/nymtech/nym/pull/5140)
- [Limit race probability](https://github.com/nymtech/nym/pull/5145)
### Bugfix
- [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)
- [Bugfix/rewarder post pruning adjustments](https://github.com/nymtech/nym/pull/4942): this PR introduces/fixes the following:
- 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
- [bugfix: fix expected return type on /v1/gateways endpoint](https://github.com/nymtech/nym/pull/4965)
- [Bugfix/additional directory fixes](https://github.com/nymtech/nym/pull/4973): This branch introduces additional fixes to the new directory services
- [Fix critical issues SI86 and SI87 from Cure53](https://github.com/nymtech/nym/pull/4982): This pull request fixes the following issues:
- 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
- [Fix rustfmt in nym-credential-proxy](https://github.com/nymtech/nym/pull/4992)
- [bugfix: directory v2.1 `get_all_avg_gateway_reliability_in_interval` query](https://github.com/nymtech/nym/pull/5023): fixes query for avg gateway performance (no idea why it makes a difference, but it does...)
- [bugfix: missing #[serde(default)] for announce port](https://github.com/nymtech/nym/pull/5024)
- [bugfix: introduce 'LegacyPendingMixNodeChanges' that does not contain 'cost_params_change'](https://github.com/nymtech/nym/pull/5028)
- [bugfix: verifying signed information of legacy nodes](https://github.com/nymtech/nym/pull/5029)
- [bugfix: fixed backwards incompatibility for /gateways/described endpoint](https://github.com/nymtech/nym/pull/5030)
- [bugfix: make sure to use correct highest node id when assigning role](https://github.com/nymtech/nym/pull/5032)
- [bugfix: use old name for 'epoch_role' in SkimmedNode](https://github.com/nymtech/nym/pull/5034)
- [bugfix: use human readable roles for annotations](https://github.com/nymtech/nym/pull/5036)
- [bugfix: make gateways insert themselves into [local] topology](https://github.com/nymtech/nym/pull/5038)
- [bugfix: use bonded nym-nodes for determining initial network monitor …](https://github.com/nymtech/nym/pull/5039)
- [bugfix: make sure nym-nodes are also tested by network monitor](https://github.com/nymtech/nym/pull/5040)
- [bugfix: don't assign exit gateways to standby set](https://github.com/nymtech/nym/pull/5041)
- [bugfix: fix ecash handlers routes](https://github.com/nymtech/nym/pull/5043)
- [bugfix: restore default http port for nym-api](https://github.com/nymtech/nym/pull/5045): when it was run under 'rocket' server the port used was 8000. let's restore that value
- [bugfix: supersede 'cb13be27f8f61d9ae74d924e85d2e6787895eb14' by using…](https://github.com/nymtech/nym/pull/5046)
- [bugfix: adjust runtime storage migration](https://github.com/nymtech/nym/pull/5047): remove the panic during migration as the gateway count can actually be different if some of them have already migrated to nym-nodes before the code has been run
- [bugfix: mark migrated gateways as rewarded in the previous epoch in case theyre in the rewarded set](https://github.com/nymtech/nym/pull/5049)
- [bugfix/feature: added NymApiClient method to get all skimmed nodes](https://github.com/nymtech/nym/pull/5062)
- [bugfix: use corrext axum extractors for ecash route arguments](https://github.com/nymtech/nym/pull/5065)
- [bugfix: credential-proxy obtain-async](https://github.com/nymtech/nym/pull/5067)
- [bugfix: wallet backend fixes](https://github.com/nymtech/nym/pull/5070)
- [bugfix: additional checks inside credential proxy](https://github.com/nymtech/nym/pull/5072)
- [bugfix: [wallet] displaying delegations for native nymnodes](https://github.com/nymtech/nym/pull/5087)
- [bugfix: preserve as much as possible of the rewarded set during migration](https://github.com/nymtech/nym/pull/5103)
- [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="⚠️">
**Every operator has to make sure that their nodes [self-described endpoint works](nodes/performance-and-testing/node-api-check#basic-api-usage), otherwise the node will be un-routable and thus won't get any rewards!**
</Callout>
- **New technical documentation:** All Nym documentation starts from a new entry page [nymtech.net/docs](https://nymtech.net/docs/operators/introduction). To run locally or propose collaboration, start in our [repository](https://github.com/nymtech/nym/tree/develop/documentation)
- **New [Tokenomics chapter](tokenomics.mdx) with [Mixnet Rewards page](tokenomics/mixnet-rewards.mdx)**
- **[Operators release & rewards roadmap](tokenomics/mixnet-rewards.mdx#roadmap)**
- **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.
- Simplified [bonding](nodes/nym-node/bonding.mdx) and [Mixnet smart contract migration](nodes/nym-node/bonding.mdx#migrate-to-nym-node-in-mixnet-smart-contract)
- Nodes bonded with vesting tokens are [not allowed to join rewarded set](https://github.com/nymtech/nym/pull/5129) - read more on [Nym operators forum](https://forum.nymtech.net/t/vesting-accounts-are-no-longer-supported/827)
#### Wallet changes
**[New wallet version 1.2.15](https://github.com/nymtech/nym/releases/tag/nym-wallet-v1.2.15) is out!**
- [New wallet changelog](https://github.com/nymtech/nym/blob/nym-wallet-v1.2.15/nym-wallet/CHANGELOG.md)
- This version of wallet allows and prompts operators to migrate their gateway or mixnode to a `nym-node` in the Mixnet smart contract - an important step in [project smoosh](archive/faq/smoosh-faq.mdx). To do so follow these steps:
<br />
<AccordionTemplate name="Steps to use wallet for node migration">
<Steps>
###### 1. Download the wallet from [the release page](https://github.com/nymtech/nym/releases/tag/nym-wallet-v1.2.15)
###### 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)
- 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
###### 3. Open the wallet and sign in
###### 4. Migrate!
- Go to Bonding and you will be prompted with such message:
![](/images/operators/wallet-screenshots/migrate_nym-node.png)
- In case you for some reason didn't see the prompt or you closed it - you can click in the upper right corner of the same window on this button:
![](/images/operators/wallet-screenshots/migrate_nym-node2.png)
- Confirm the transaction
###### 5. Welcome to new episode of `nym-node`!
</ Steps>
</AccordionTemplate>
- **Older versions will not allow bonding new nodes!**
#### Selection & Rewarding
- **Config score is introduced:** In the current version the nodes selection to the active set has a new parameter (which multiplies the existing formula) - `config_score`. Config score looks if the node binary is `nym-node` (not legacy `nym-mixnode` or `nym-gateway`) **AND** if [Terms & Conditions](nodes/nym-node/setup.mdx#terms--conditions) are accepted. Config score has binary values of either 0 or 1, with a following logic:
| **Run `nym-node` binary** | **T&C's accepted** | **`config_score`** |
| :-- | :-- | ---: |
| True | False | 0 |
| False | True | 0 |
| False | False | 0 |
| True | True | 1 |
- The active set selection formula is then:
> CONFIG_SCORE \* STAKE_SATURATION \* PERFORMANCE ^ 20
- 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
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).
##### API High Level Changes
###### New/Added
- All new routes that return multiple nodes/entries/etc now wrap their responses to expect pagination. Currently, however, full data is returned for each of the endpoints since the pagination hasn't been implemented yet. But once we add it, it won't be a breaking API change.
###### Removed
- `rocket` support has been completely removed. All routes are now always served via `axum`
###### Changed
- Getting anything to do with all nodes (including gateways) requires knowing their `node_id`. For legacy gateway endpoints, we have a helper method that translates identity key to the `node_id`
- Rewarded set is no longer populated with just mixnodes. Instead `nym-node`s are assigned to eligible roles (based on stake and performance) in the following order:
- entry gateways
- exit gateways
- mixnodes
- standby
- A lot of legacy routes got deprecated. while technically they still "work" and return data, they only return data for legacy `nym-mixnode` and `nym-gateway`. What it means is that as operators are migrating their nodes (in the smart contract), those endpoints will start running dry.
- Since layers are only assigned during rewarded set assignment, for the purposes of network monitor (v1) and legacy mixnode routes, layerless nodes are put on random layers during annotation
- All legacy gateway queries now also include additional field in their respones: `node_id` that indicate the id pre-assigned during contract migration
- Nym Node performance is a bit odd. When network monitors (v1 and v2) were made, there was no concept of a Nym Node. The solution taken is checking whther there is any mixnode performance for node with a given id, if so - return it. Otherwise we grab the equivalent gateway performance. In the future it should probably be averaged or maybe split into explicit mixing or gateway routing performance metrics.
##### `nym-api` Changes
- Root route `/` now redirects to `/swagger`
###### `nym-node` Routes
<br />
<AccordionTemplate name="Nym Node API routes">
- `/v1/nym-nodes/annotation/<NODE_ID>` - get annotation about particular `nym-node`, as gathered by this `nym-api`. Currently this just includes last 24h performance metric and the current node role
- `/v1/nym-nodes/bonded` - get bond information about Nym Nodes, as present in the mixnet contract
- `/v1/nym-nodes/described` - get described information about Nym Nodes, as present on their self-described API
- `/v1/nym-nodes/historical-performance/<NODE_ID>` - return historical performance of this `nym-node` on the provided date
- `/v1/nym-nodes/performance-history/<NODE_ID>` - return performance history of this `nym-node` (as a 0 - 1 float)
- `/v1/nym-nodes/uptime-history/<NODE_ID>` - return current uptime of this `nym-node` (as a 0 - 100 u8); added for compatibility with existing APIs using that data format
- `/v1/nym-nodes/performance/<NODE_ID>` - return current performance of this `nym-node`
</ AccordionTemplate>
<br />
<AccordionTemplate name="Unstable API routes">
- `/v1/unstable/nym-nodes/noise` - returns basic information needed for the noise protocol between nodes
- `/v1/unstable/nym-nodes/skimmed/active` - returns all: Nym Nodes and legacy mixnodes and legacy gateways, that are currently in the active set, unless `no-legacy` parameter is used
- `/v1/unstable/nym-nodes/skimmed/mixnodes/active` - returns all: Nym Nodes and legacy mixnodes, that are currently in the active set, unless `no-legacy` parameter is used
- `/v1/unstable/nym-nodes/skimmed/mixnodes/all` - returns all: Nym Nodes and legacy mixnodes, that are currently bonded and support mixing role, unless `no-legacy` parameter is used
- `/v1/unstable/nym-nodes/skimmed/entry-gateways/active` - returns all: Nym Nodes and legacy gateways, that are currently in the active set and are assigned the entry role, unless `no-legacy` parameter is used
- `/v1/unstable/nym-nodes/skimmed/exit-gateways/active` - returns all: Nym Nodes and legacy gateways, that are currently in the active set and are assigned the exit role, unless `no-legacy` parameter is used
- `/v1/unstable/nym-nodes/skimmed/entry-gateways/all` - returns all: Nym Nodes and legacy gateways, that are currently bonded and support entry gateway role, unless `no-legacy` parameter is used
- `/v1/unstable/nym-nodes/skimmed/exit-gateways/all` - returns all: Nym Nodes and legacy gateways, that are currently bonded and support exit gateway role, unless `no-legacy` parameter is used
</ AccordionTemplate>
###### Deprecated (will be removed eventually, so please migrate away from their usage)
Some endpoints got purposely deprecated without any equivalent reimplemented since they do not belong on `nym-api`. This includes for example `/stake-saturation` (which can be obtained directly from the contract instead) or `/inclusion-probability` (for this run your own Monte Carlo simulation).
<br />
<AccordionTemplate name="Deprecated API routes">
- `contract-cache` routes - all of the below got deprecated as they will only return **legacy** `nym-mixnode` and `nym-gateway` data:
- `/v1/gateways`
- `/v1/gateways/blacklisted`
- `/v1/mixnodes`
- `/v1/mixnodes/active` - just to restate the obvious, it will only return a small **SUBSET** of the active set that since it will ignore active Nym Nodes
- `/v1/mixnodes/active/detailed`
- `/v1/mixnodes/blacklisted`
- `/v1/mixnodes/detailed`
- `/v1/mixnodes/rewarded`
- `/v1/mixnodes/rewarded/detailed`
- `status` routes - all of the below got deprecated as they will only return **legacy** `nym-mixnode` and `nym-gateway` data:
- `/v1/status/gateway/<ID_KEY>/report`
- `/v1/status/gateway/<ID_KEY>/history`
- `/v1/status/gateway/<ID_KEY>/core-status-count`
- `/v1/status/gateway/<ID_KEY>/avg_uptime`
- `/v1/status/gateways/detailed`
- `/v1/status/gateways/detailed-unfiltered`
- `/v1/status/mixnode/<MIX_ID>/report`
- `/v1/status/mixnode/<MIX_ID>/history`
- `/v1/status/mixnode/<MIX_ID>/core-status-count`
- `/v1/status/mixnode/<MIX_ID>/avg_uptime`
- `/v1/status/mixnodes/detailed`
- `/v1/status/mixnodes/detailed-unfiltered`
- `/v1/status/mixnode/<MIX_ID>/status`
- `/v1/status/mixnode/<MIX_ID>/reward-estimation`
- `/v1/status/mixnode/<MIX_ID>/compute-reward-estimation`
- `/v1/status/mixnode/<MIX_ID>/stake-saturation`
- `/v1/status/mixnode/<MIX_ID>/inclusion-probability`
- `/v1/status/mixnodes/inclusion_probability`
- `/v1/status/mixnodes/rewarded/detailed`
- `/v1/status/mixnodes/active/detailed`
- `nym-node` routes - all of the below got deprecated as they will only return **legacy** `nym-mixnode` and `nym-gateway` data:
- `/v1/gateways/described`
- `/v1/mixnodes/described`
- `Unstable Nym Nodes Routes`:
- `/v1/unstable/nym-nodes/mixnodes/skimmed` - due to inconsistency in behaviour (i.e. active vs all) it is now redirected to `/v1/unstable/nym-nodes/mixnodes/skimmed/active` and unwraps the pagination
- `/v1/unstable/nym-nodes/gateways/skimmed` - due to inconsistency in behaviour (i.e. active vs all) it is now redirected to `/v1/unstable/nym-nodes/entry-gateways/skimmed/all` and unwraps the pagination
</ AccordionTemplate>
<br />
<AccordionTemplate name="Changed API routes">
- `Unstable Nym Nodes Routes`:
- `/v1/unstable/nym-nodes/skimmed` - now works with `exit` parameter
- `/v1/unstable/nym-nodes/skimmed` - introduced `no-legacy` flag to ignore legacy `nym-mixnode` and `nym-gateway` (where applicable)
- `/v1/unstable/nym-nodes/skimmed` - will now return all nodes if no query parameter is provided
</ AccordionTemplate>
##### Mixnet Contract
<Callout type="warning" emoji="">
**Every operator has to make sure that their nodes [self-described endpoint works](nodes/performance-and-testing/node-api-check#basic-api-usage), otherwise the node will be un-routable and thus won't get any rewards!**
</Callout>
###### High Level Changes
**New/Added**
- All new nodes are now bonded as Nym Nodes, even when using old `BondMixnode` or `BondGateway` messages (messages are getting translated)
- Operators only announce nodes identity key (`<ID_KEY>`), host and port to the directory. Everything else is discovered via self-described endpoint
- All Nym Nodes in the rewarded set are eligible for rewards and staking. Even if they serve one of the gateway roles. Legacy gateways can't be staked on nor get rewards.
- All nodes, including legacy mixnodes and legacy gateways, are now uniquely identified by a monotonically increasing `node_id`
- All legacy gateways are preassigned `node_id` during the contract migration
**Removed**
> 🔥 all concepts of node families got purged, removed, deleted, thrown into the abyss. they simply no longer exist and the world is all better for it.
**Changed**
- Bunch of types got changed/renamed with some fields being added/removed/deprecated. It's be quite a lot of work to list them all here, but whenever possible and feasible, they should be cross-compatible (but not always).
- Rewarded set is no longer just a "number". Instead it has an explicit number of all `nym-node` modes: mixnodes, entry and exit gateways as well as standby nodes
- Rewarding is now based on two parameters: performance and work factor as opposed to performance and "is active" flag. However, in practice, during this transitional period, it is assumed that the work factor will be equivalent to what would have been calculated using the old "is active" flag
###### Transaction Messages Changes
<br />
<AccordionTemplate name="Added transaction messages">
- `BondNymNode` - self-explanatory
- `UnbondNymNode` - self-explanatory
- `UpdateNodeConfig` - works as `UpdateMixnodeConfig`; it lets you change your announced host or http api port
- `MigrateMixnode` - migrate your existing legacy mixnode into a Nym Node
- `MigrateGateway` - migrate your exsting legacy gasteway into a Nym Node. enables staking and rewarding
- `AssignRoles` - an additional step for epoch transition transactions. think of it as a replacement for `AdvanceCurrentEpoch`. it assigns nodes to particular roles for the given epoch
</AccordionTemplate>
<br />
<AccordionTemplate name="Removed transaction messages">
- As mentioned, all family-related things got killed off, so the following no longer exist: `CreateFamily`, `JoinFamily`, `LeaveFamily`, `KickFamilyMember`, `CreateFamilyOnBehalf`, `JoinFamilyOnBehalf`, `LeaveFamilyOnBehalf`, `KickFamilyMemberOnBehalf`
- `UpdateActiveSetSize` - the rewarded/active set are now based on the role distribution
- `AssignNodeLayer` - we're no longer explicitly assigning roles to all mixnodes, instead they get assigned mixing roles
- `AdvanceCurrentEpoch` - the logic for advancing the epoch/assigning active set has changed so this message was removed
</AccordionTemplate>
## `v2024.12.1-aero` - patch
- [Release binaries](https://github.com/nymtech/nym/releases/tag/nym-binaries-v2024.12.1-aero)
- `nym-node` patch only, no other binaries
```sh
nym-node
Binary Name: nym-node
Build Timestamp: 2024-11-07T08:45:13.162565620Z
Build Version: 1.1.9-1
Commit SHA: ccdee808303ffcfa8ed77176d3f629512045febb
Commit Date: 2024-11-06T16:31:30.000000000+01:00
Commit Branch: HEAD
rustc Version: 1.82.0
rustc Channel: stable
cargo Profile: release
```
### Changes
- Fixed timeout connectivity issues with authenticator
- Amended network allowance cap
## `v2024.12-aero`
- [Release binaries](https://github.com/nymtech/nym/releases/tag/nym-binaries-v2024.12-aero)
@@ -1309,7 +790,7 @@ Every `nym-node` should be upgraded to the latest version! Operators can test us
**`nym-node`**
- Make sure to fill in basic description info, into the file located at `.nym/nym-nodes/<ID>/data/description.toml` (all nodes)
- Configure wireguard routing with new [`network_tunnel_manager.sh`](https://github.com/nymtech/nym/blob/develop/scripts/network_tunnel_manager.sh) following [these steps](nodes/configuration.md#routing-configuration) (Gateways only for the time being)
- Configure wireguard routing with new [`network_tunnel_manager.sh`](https://gist.github.com/tommyv1987/ccf6ca00ffb3d7e13192edda61bb2a77) following [these steps](nodes/configuration.md#routing-configuration) (Gateways only for the time being)
- Enable Wireguard with `--wireguard-enabled true` flag included in your run command (Gateways only for the time being)
- Note: On some VPS this setup may not be enough to get the correct results as some ISPs have their own security groups setup below the individual VPS. In that case a ticket to ISP will have to be issued to open the needed settings. We are working on a template for such ticket.
- Setup [reverse proxy and WSS](nodes/proxy-configuration.md) on `nym-node` (Gateways only for the time being)
@@ -1551,9 +1032,9 @@ ufw status
**Step 2: Download and Prepare the Network Tunnel Manager Script**
1. Download the [`network_tunnel_manager.sh`](https://github.com/nymtech/nym/blob/develop/scripts/network_tunnel_manager.sh) script:
1. Download the [`network_tunnel_manager.sh`](https://gist.github.com/tommyv1987/ccf6ca00ffb3d7e13192edda61bb2a77) script:
```bash
curl -L -o network_tunnel_manager.sh https://github.com/nymtech/nym/blob/develop/scripts/network_tunnel_manager.sh
curl -L -o network_tunnel_manager.sh https://gist.githubusercontent.com/tommyv1987/ccf6ca00ffb3d7e13192edda61bb2a77/raw/3c0a38c1416f8fdf22906c013299dd08d1497183/network_tunnel_manager.sh
```
2. Make the script executable:
@@ -6,9 +6,10 @@ import { MyTab } from 'components/generic-tabs.tsx';
# Community Counsel: Running Exit Gateway
This page is a part of Nym Community Counsel (before Legal Forum) and its content is composed by shared advices in [Node Operators Legal Forum](https://matrix.to/#/!YfoUFsJjsXbWmijbPG:nymtech.chat?via=nymtech.chat&via=matrix.org) (Matrix chat) as well as though pull requests done by the node operators directly to our [repository](https://github.com/nymtech/nym/tree/develop/documentation/docs/pages/operators), reviewed by Nym DevRels.
This document presents an initiative to further support Nyms mission of allowing privacy for everyone everywhere. This would be achieved with the support of Nym node operators operating Gateways and opening these to any online service. Such setup needs a **clear policy**, one which will remain the **same for all operators** running Nym nodes. [**Nym exit policy**](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) was inspired by (nowadays deprecated) Tor Null deny list and Tor reduced policy and created to meet the changes decided by Nym operators community through the governance (like in this [vote](https://forum.nymtech.net/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464)). This policy aims to find a healthy compromise between protecting the operators and NymVPN users against attacks while allowing for as wide experience when accessing the internet through Nym Network.
This document presents an initiative to further support Nyms mission of allowing privacy for everyone everywhere. This would be achieved with the support of Nym node operators operating Gateways and opening these to any online service. Such setup needs a **clear policy**, one which will remain the **same for all operators** running Nym nodes. [**Nym exit policy**](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) is a combination of safeguards like (nowadays deprecated) `Tor Null deny list` and `Tor reduced policy` together with changes decided by Nym operators community through the governance (like in this [vote](https://forum.nymtech.net/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464)). This policy aims to find a healthy compromise between protecting the operators and NymVPN users against attacks while allowing for as wide experience when accessing the internet through Nym Network.
<Callout type="warning" emoji="⚠️">
@@ -18,17 +19,13 @@ The following part is for informational purposes only. Nym core team cannot prov
## Summary
**Nym supports privacy for everyone, everywhere.**
To offer a better and more private everyday experience for its users, Nym would like them to use any online services they please, without limiting its access to a few messaging apps or crypto wallets.
To achieve this, operators running Exit Gateways would have to “open” their nodes to a wider range of online services, in a similar fashion to Tor exit relays following [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt).
* This document outlines a plan to change Nym Gateways from operating with an allow to a deny list to enable broader uptake and usage of the Nym Mixnet. It provides operators with an overview of the plan, pros and cons, legal as well as technical advice.
* Nym is committed to ensuring privacy for all users, regardless of their location and for the broadest possible range of online services. In order to achieve this aim, the Nym Mixnet needs to increase its usability across a broad range of apps and services.
* To decentralise and enable privacy for a broader range of services, Nym transitioned from allow list to a deny list - creating a new [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt).
* Currently, Nym Gateway nodes only enable access to apps and services that are on an allow list that is maintained by the core team.
* Future changes of the exit policy is done via an off-chain governance, like in this [vote](https://forum.nymtech.net/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464).
* To decentralise and enable privacy for a broader range of services, this initiative will have to transition from the current allow list to a deny list - [exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt). In accordance with the (nowadays deprecated) `Tor Null deny list` and `Tor reduced policy` together with changes decided by Nym operators community through the governance (like in this [vote](https://forum.nymtech.net/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464))
* This will enhance the usage and appeal of Nym products for end users. As a result, increased usage will ultimately lead to higher revenues for Nym operators.
@@ -39,6 +36,35 @@ To achieve this, operators running Exit Gateways would have to “open” their
* This document serves as the basis for a consultation with Nym node operators on any concerns or additional support and information you need for this change to be successful and ensure maximum availability, usability and adoption.
## Goal of the initiative
**Nym supports privacy for everyone, everywhere.**
To offer a better and more private everyday experience for its users, Nym would like them to use any online services they please, without limiting its access to a few messaging apps or crypto wallets.
To achieve this, operators running Exit Gateways would have to “open” their nodes to a wider range of online services, in a similar fashion to Tor exit relays following this [exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt).
## Pros and cons of the initiative
Previous setup: Running nodes supporting strict SOCKS5 app-based traffic
| **Dimension** | **Pros** | **Cons** |
| :--- | :--- | :--- |
| Aspirational | | - Very limited use cases, not supportive of the “Privacy for everyone everywhere” aspiration - Limited appeal to users, low competitiveness in the market, thus low usage |
| Technical | - No changes required in technical setup | |
| Operational | - No impact on operators operations (e.g., relationships with VPS providers) - Low overhead - Can be run as an individual | |
| Legal | - Limited legal risks for operators | |
| Financial | | - Low revenues for operators due to limited product traction |
The new setup: Running nodes supporting traffic of any online service (with safeguards in the form of a denylist)
| **Dimension** | **Pros** | **Cons** |
| :--- | :--- | :--- |
| Aspirational | - Higher market appeal of a fully-fledged product able to answer all users use cases - Relevance in the market, driving higher usage | |
| Technical | - Very limited changes required in the technical setup (changes in the allow -> denylist) | - Increased monitoring required to detect and prevent abuse (e.g. spam) |
| Operational | | - Higher operational overhead, such as dealing with DMCA / abuse complaints, managing the VPS provider questions, or helping the community to maintain the denylist - Administrative overhead if running nodes as a company or an entity |
| Legal | | - Ideally requires to check legal environment with local privacy association or lawyer | Financial | - Higher revenue potential for operators due to the increase in network usage | - If not running VPS with an unlimited bandwidth plan, higher costs due to higher network usage |
## Exit Gateways: New setup
@@ -48,22 +74,20 @@ This restricts the hosts that the NymConnect app can connect to and has the effe
The principal change in the new configuration is to make this short allow list more permissive. Nym's [exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) will restrict the hosts to which Nym Mixnet and Nym VPN users are permitted to connect. This will be done in an effort to protect the operators, as Gateways will act both as SOCKS5 Network Requesters, and exit nodes for IP traffic from Nym Mixnet VPN and VPN clients (both wrapped in the same app).
As of now the Gateways will be defaulted to a policy decided by Nym operators community through the governance (like in this [vote](https://forum.nymtech.net/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464)). This policy will remain the same for all the nodes, without any option to modify it by Nym node operators individually, to secure stable and reliable service for the end users.
As of now we the Gateways will be defaulted to a combination of (nowadays deprecated) `Tor Null deny list` (note: Tornull is not affiliated with Tor Project) - reproduction permitted under Creative Commons Attribution 3.0 United States License which is IP-based, e.g., `ExitPolicy reject 5.188.10.0/23:*` and `Tor reduced policy` together with changes decided by Nym operators community through the governance (like in this [vote](https://forum.nymtech.net/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464)). This policy will remain the same for all the nodes, without any option to modify it by Nym node operators individually, to secure stable and reliable service for the end users.
The Exit Gateways will exhibit an HTML page (on port `80` and `443`) resembling the one proposed documented [here](landing-pages.mdx
). By doing so, the operator will be able to disclose details regarding their Gateway, including the currently configured exit policy, all without the need for direct correspondence with regulatory or law enforcement agencies. It also makes the behavior of Exit Gateways transparent and even computable (a possible feature would be to offer a machine readable form of the notice in JSON or YAML).
For exit relays on ports 80 and 443, the Gateways will exhibit an HTML page resembling the one proposed by [Tor](https://gitlab.torproject.org/tpo/core/tor/-/raw/HEAD/contrib/operator-tools/tor-exit-notice.html). By doing so, the operator will be able to disclose details regarding their Gateway, including the currently configured exit policy, all without the need for direct correspondence with regulatory or law enforcement agencies. It also makes the behavior of Exit Gateways transparent and even computable (a possible feature would be to offer a machine readable form of the notice in JSON or YAML).
We also recommend operators to check the technical advice from [Tor](https://community.torproject.org/relay/setup/exit/).
## Community Counsel & Legal environment of Nym Exit Gateway
The Node Operators Community Counsel pages are divided according [jurisdictions](jurisdictions.mdx). Nym Node operators are invited to add their legal findings or helpful suggestions directly through [pull requests](add-content.mdx). This can be done as a new legal information (or entire new country) to the list of [jurisdictions](jurisdictions.mdx) or in a form of an advice to [Community counsel pages](../community-counsel.mdx), like sharing examples of Exit Gateway [landing pages](landing-pages.mdx), templates etcetra.
The Node Operators Community Counsel pages are divided according [jurisdictions](jurisdictions.mdx). Nym Node operators are invited to add their legal findings or helpful suggestions directly through [pull requests](add-content.mdx). This can be done as a new legal information (or entire new country) to the list of [jurisdictions](jurisdictions.mdx) or in a form of an advice to [Community counsel pages](../community-counsel.mdx), like sharing examples of Exit Gateway [landing pages](landing-pages.md), templates etcetra.
## How to add content
Our aim is to establish a strong community network, sharing legal findings and other suggestions with each other. We would like to encourage all of the current and future operators to do research about the situation in the jurisdiction they operate in as well as solutions to any challenges when running an Exit Gateway and add those through a pull request (PR). Please check out the [steps to make a pull request](add-content.mdx).
## Tor legal advice
Giving the legal similarity between Nym Exit Gateways and Tor Exit Relays, it is helpful to have a look in [Tor community Exit Guidelines](https://community.torproject.org/relay/community-resources/tor-exit-guidelines/). This chapter is an exert of tor page.
@@ -33,11 +33,6 @@ If you want to dive deeper into Nym's architecture, clients, nodes, and SDK exam
* [Validators](nodes/validator-setup.mdx)
* [Nym API Setup](nodes/validator-setup/nym-api.mdx)
**Tokenomics, rewards and roadmap**
* [General tokenomics page](tokenomics.mdx)
* [Nym Node rewards page](tokenomics/mixnet-rewards.mdx)
* [Nym operators roadmap](tokenomics/mixnet-rewards.mdx#roadmap)
**Maintenance, troubleshooting and FAQ**
* [FAQ](faq/nym-nodes-faq.mdx)
@@ -25,20 +25,15 @@ You are asked to `sign` a transaction and bond your node to Nyx blockchain so th
Do not bond your node to the API if the previous steps weren't finished. Bad connectivity, closed ports, or other poor setup will result in your node getting blacklisted.
</Callout>
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.
**Every operator has to make sure that their nodes [self-described endpoint works](nodes/performance-and-testing/node-api-check#basic-api-usage), otherwise the node will be un-routable and thus won't get any rewards!**
## Bond via the Desktop wallet (recommended)
You can bond your `nym-node` via the Desktop wallet.
<Steps>
###### 1. Insert bonding information
###### 1. Insert bonding information
- Open your wallet, and head to the `Bonding` page and click on `Bond` Button, and input your node details. Press `Next`.
- Open your wallet, and head to the `Bond` page, then select the node type `Mixnode` and input your node details. Press `Next`.
- To find out your `nym-node` details, run this command in your VPS:
```sh
./nym-node bonding-information --id <ID>
@@ -48,9 +43,9 @@ You can bond your `nym-node` via the Desktop wallet.
echo "$(curl -4 https://ifconfig.me)"
```
###### 2. Bond to correct HTTP port
###### 2. Bond to correct ports
- In your wallet: Open the box called `Show advanced options` and make sure that your `Custom HTTP port` is set correctly like in your `config.toml`. **We strongly recommend to keep it on default `8080`.** For reference these are the ports used by `nym-node`:
- In your wallet: Open the box called `Show advanced options` and make sure all your ports are set correctly, like the values in this table:
| Node type | Port name | Correct port value |
| :-- | :-- | :-- |
@@ -60,15 +55,16 @@ echo "$(curl -4 https://ifconfig.me)"
| Gateway (entry & exit) | Mix port | `1789` |
| Gateway (entry & exit) | Client WS API port | `9000` |
- Use own `ID_KEY`, and `Host`, which can be either your IPv4 address or hostname:
- If you bonding `nym-node --mode mixnode` through *Bond mixnode* desktop wallet menu, change manually *HTTP api port* value from deprecated `8000` to `8080` - a generic `nym-node` HTTP port (for all modes).
![](/images/operators/wallet-screenshots/bonding_nym-node.png)
![](/images/operators/wallet-screenshots/new_http_port.png)
###### 3. Enter your values and sign with your node
- Enter the `Amount`, `Operating cost` and `Profit margin` and press `Next`
<Callout type="warning" emoji="⚠️">
If you are part of [Nym Delegation Program](https://delegations.explorenym.net) or Service Grants Program, make sure your values are within the [rules](https://forum.nymtech.net/t/nym-delegations-program-update/466) of the programs. Operators setting up larger OP or PM than defined in the rules will be excluded from the program without prior warning!
</Callout>
@@ -97,56 +93,8 @@ Your node will now be bonded and ready to receive traffic, latest at the beginni
If everything worked, you'll see your node running on the either the [Sandbox testnet network explorer](https://sandbox-explorer.nymtech.net) or the [mainnet network explorer](https://explorer.nymtech.net), depending on which environment you're running.
<Callout type="warning" emoji="">
**After migration to `nym-node` in Mixnet smart contract, many explorers, includyng Nym explorers will not pick up value correctly. While we are working on Nym Explorer v2, we would like to invite operators to use [Nym Harbourmaster](https://harbourmaster.nymtech.net) to track their nodes.**
</Callout>
## Change Settings via Desktop Wallet
In case you decide to change any settings like `custom HTTP port` or your `host` from an IP address to a hostname, don't forget to announce it to the API via changing these values in the desktop wallet.
- Go back to `Bonding` page, click on `Nym Node Settings` and change the values like in this example:
![](/images/operators/wallet-screenshots/settings_nym-node.png)
## Migrate to `nym-node` in Mixnet Smart Contract
From `nym-wallet` version `1.2.15` onward the application allows and prompts operators to migrate their gateway or mixnode to a `nym-node` in the Mixnet smart contract - an important step in [project smoosh](../../archive/faq/smoosh-faq.mdx). To do so follow these steps:
<Steps>
###### 1. Download the latest wallet from [the release page](https://github.com/nymtech/nym/releases)
###### 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
- 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
###### 3. Open the wallet and sign in
###### 4. Migrate!
- Go to Bonding and you will be prompted with such message:
![](/images/operators/wallet-screenshots/migrate_nym-node.png)
- In case you for some reason didn't see the prompt or you closed it - you can click in the upper right corner of the same window on this button:
![](/images/operators/wallet-screenshots/migrate_nym-node2.png)
- Confirm the transaction
###### 5. Welcome to new episode of `nym-node`!
</ Steps>
<Callout type="warning" emoji="⚠️">
Versions older than `nym-wallet v 1.2.15` will not allow bonding new nodes.
</Callout>
## Bond via the CLI (power users)
If you want to bond your Mix Node via the CLI, then check out the [relevant section in the Nym CLI](https://nymtech.net/docs/tools/nym-cli.html#bond-a-mix-node) docs.
@@ -268,7 +268,7 @@ Make sure to keep your IPv4 address enabled while setting up IPv6, as the majori
### Routing Configuration
While we're working on Rust implementation to have these settings as a part of the binary build, to solve these connectivity requirements in the meantime we wrote a script [`network_tunnel_manager.sh`](https://github.com/nymtech/nym/blob/develop/scripts/network_tunnel_manager.sh) to support operators to configure their servers and address all the connectivity requirements.
While we're working on Rust implementation to have these settings as a part of the binary build, to solve these connectivity requirements in the meantime we wrote a script [`network_tunnel_manager.sh`](https://gist.github.com/tommyv1987/ccf6ca00ffb3d7e13192edda61bb2a77) to support operators to configure their servers and address all the connectivity requirements.
Networking configuration across different ISPs and various operation systems does not have a generic solution. If the provided configuration setup doesn't solve your problem check out [IPv6 troubleshooting](../../troubleshooting/vps-isp.mdx#ipv6-troubleshooting) page. Be aware that you may have to do more research, customised adjustments or contact your ISP to change settings for your VPS.
@@ -285,7 +285,7 @@ The script should be used in a context where `nym-node` is running to fully util
###### 1. Download `network_tunnel_manager.sh`, make executable and run:
```sh
curl -L https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/network_tunnel_manager.sh -o network_tunnel_manager.sh && \
curl -L https://gist.githubusercontent.com/tommyv1987/ccf6ca00ffb3d7e13192edda61bb2a77/raw/74241cc06492b955e582052939090f57a285a65e/network_tunnel_manager.sh -o network_tunnel_manager.sh && \
chmod +x network_tunnel_manager.sh && \
./network_tunnel_manager.sh
```
@@ -14,21 +14,7 @@ This documentation page provides a guide on how to set up and run a [NYM NODE](.
## Current version
```sh
nym-node
Binary Name: nym-node
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.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 />
*/}
## Summary
@@ -1,193 +0,0 @@
import { Callout } from 'nextra/components';
import { Tabs } from 'nextra/components';
import { MyTab } from 'components/generic-tabs.tsx';
import { RunTabs } from 'components/operators/nodes/node-run-command-tabs';
import { VarInfo } from 'components/variable-info.tsx';
import { MigrateTabs } from 'components/operators/nodes/node-migrate-command-tabs';
import NyxPercentStake from 'components/outputs/api-scraping-outputs/nyx-outputs/nyx-percent-stake.md';
import NyxTotalStake from 'components/outputs/api-scraping-outputs/nyx-outputs/nyx-total-stake.md';
import CirculatingSupply from 'components/outputs/api-scraping-outputs/nyx-outputs/circulating-supply.md';
import TokenTable from 'components/outputs/api-scraping-outputs/nyx-outputs/token-table.md';
import StakingTarget from 'components/outputs/api-scraping-outputs/nyx-outputs/staking-target.md';
import StakingScaleFactor from 'components/outputs/api-scraping-outputs/nyx-outputs/staking-scale-factor.md';
import StakeSaturation from 'components/outputs/api-scraping-outputs/nyx-outputs/stake-saturation.md';
import { TimeNow } from 'components/time-now.tsx';
import { AccordionTemplate } from 'components/accordion-template.tsx';
# Nym Tokenomics
<TimeNow />
Nym Network is composed of two main elements, the Mixnet represented by [Nym Nodes](nodes/nym-node/nym-node.mdx) routing and mixing the data packets, and Nyx blockchain distributted accros [validator set](tokenomics/validator-rewards.mdx), using smart contracts (based on [cosmwasm](https://cosmwasm.com/)) to monitor and reward Nym Nodes by querying API endpoints and distributing NYM token to operators according to work done by their nodes. All Nym nodes and validators are run by decentralised community of operators.
* Nym tokenomics are based on the research paper [*Reward Sharing for Mixnets*](https://nymtech.net/nym-cryptoecon-paper.pdf)
* For a more comprehensive overview, token live data and supply graphs, visit [*nymtech.net/about/token*](https://nymtech.net/about/token)
* To read about rewards calculation, visit [Nym Node rewards page](tokenomics/mixnet-rewards.mdx)
* To understand the implementation and release plan, see [Nym operators roadmap](tokenomics/mixnet-rewards.mdx#roadmap)
{/*
**Formulas and Examples Annotation**
To make it easier for the reader, we use a highlighting line on the left side, with a specific color:
<Callout borderColor="#008080" backgroundColor="#20b2aa" emoji="📌">
> **Turquoise with red pin for formulas.**
</Callout>
<Callout borderColor="#966fd6" backgroundColor="#b19cd9" emoji="">
<AccordionTemplate name="Example">
> Purple collapsible for examples.
</AccordionTemplate>
</Callout>
*/}
## NYM Token: Incentivise Stability & Secure Reputation
Besides the Mixnet itself, Nym Network is secured by its own blockchain Nyx (IBC on Cosmos) with a native token NYM.
**NYM token key features**
* **Incentives:** Distribute rewards to decentralised nodes based on mixing and routing (work). This dynamic ensures that the network is as robust as possible - the nodes are chosen every hour according to their performance.
* **Network take over defense:** Another decisive factor for a node to be chosen to the network active set is reputation. Reputation is a size of stake (delegation) where delegators earn proportional percentage of nodes rewards. Nodes without reputation are not chosen to take part in the network active set.
* **Centralisation defense:** Any node can only have a certain stake (called stake saturation) to earn maximum rewards, increasing stake level per node leads to decreasing rewards for the operator and all delegators. This feature makes it more difficult for whales to over-stake their nodes or to attract more delegators (stakers) as they would become dis-advantaged.
To learn more about rewards calculation and distribution, read the next page [*Nym Mixnet Rewards*](tokenomics/mixnet-rewards.mdx).
### Utility
*NYM token is a first and foremost a utility to secure Nym Network.*
![](/images/operators/tokenomics/nym_token_flow.png)
Nyx blockchain's validators run API to monitor the network and node performance. Based on the live input the operators and stakers of the working nodes get rewarded. The network is adjusted and re-randomized in the beginning of each epoch (60 min) composing the best performing nodes with the highest reputation.
This creates an incentive for people to operate Nym nodes as quality and reliable service. The reputation system also works as a network defense against a large adversary take over or sybil attacks.
Node reputation is calculated by delegation. Delegation is a stake done by NYM token holders on top of nodes they want to support to join the network as it compensate the stakers with APR. Therefore there is an incentive for NYM holders to stake their token on top of nodes which they believe will perform well.
To prevent a whale takeover and centralisation, the revenue grows alongside nodes stake size only until a certain point, after which the rewards per staker start to decrease. We call this mark *node stake saturation*.
Thanks to Nyx blockchain API monitoring, the flow is dynamic and constantly optimized based on live metrics. Below is a detailed explanation and reckoning of Nym tokenomics logic.
## Tokenomics
### Summary in Numbers
Below is a table with token supply distribution.
<TokenTable />
To get live data, visit [Nym token page](https://nymtech.net/about/token) or see how to [query API endpoints](#query-tokenomics-api).
### Calculation & Explanation
To get a full comprehension of [node operators rewards](tokenomics/mixnet-rewards.mdx) calculation and [delegators APR height](https://nymtech.net/about/token), we need to understand some basic logic behind the numbers presented. This chapter covers some of the most essential variables in Nym tokenomics flow.
```ascii
┌───────────┐ staking ┌───────────┐ sum of ┌───────────┐
│ │ supply │ │ nym nodes │ │
│circulating│ scale │ staking │ in rewarded │ stake │
│ supply │ factor │ target │ set │saturation │
│ ├────────────►│ ├──────────────►│ │
└───────────┘ └───────────┘ └───────────┘
```
#### Supply
<br />
<b>Circulating supply is <span style={{display: 'inline-block'}}><CirculatingSupply /></span> NYM.</b>
NYM token is capped at 1b. Visit [Nym token page](https://nymtech.net/about/token) to see live data and graphs.
#### Staking target
A number of aimed NYM tokens to be staked in the network. The staking target a is multiplier of staking supply scale factor and circulating supply.
<Callout type="info" borderColor="#008080" backgroundColor="#20b2aa" emoji="📌">
> **staking_target = staking_supply_scale_factor \* circulating_supply**
</Callout>
Staking supply scale factor is currently it's set to be <span style={{display: 'inline-block'}}><StakingScaleFactor /></span>.
The value of this variable can be changed to optimize the metrics of the network. With a current circulating supply of <span style={{display: 'inline-block'}}><CirculatingSupply /></span> NYM and staking supply scale factor <span style={{display: 'inline-block'}}><StakingScaleFactor /></span>, <b>the staking target is <span style={{display: 'inline-block'}}><StakingTarget /></span> NYM.</b>
#### Stake saturation
Node reputation in a form of self bond or stakers delegation. Stake saturation is calculated as:
<Callout type="info" borderColor="#008080" backgroundColor="#20b2aa" emoji="📌">
> **stake_saturation = staking_target / rewarded_set_size**
>
> **rewarded_set_size = active_set_size + standby_set_size**
</Callout>
With current circulating supply of <span style={{display: 'inline-block'}}><CirculatingSupply /></span> NYM, staking target of <span style={{display: 'inline-block'}}><StakingTarget /></span> NYM, divided by the sum of nodes in the [rewarded set](https://validator.nymtech.net/api/v1/epoch/reward_params), <b>the stake saturation level is <span style={{display: 'inline-block'}}><StakeSaturation /></span> NYM per node.</b>
#### Active set
Nym Network needs an optimised number of nodes to route and mix the packets. This healthy balance lies in between being too congested - which would detriment speed and user experience - on one side, and having too little traffic per node - which would could weaken anonymity - on the other.
The way how we approach this challenge is different for Mixnet (5-hop) and dVPN (2-hop) mode.
<div>
<Tabs items={[
<strong>Mixnet mode</strong>,
<strong>dVPN mode</strong>,
]} defaultIndex="0">
<MyTab>
Nym Mixnet is using an active set of chosen nodes. Currently <b>the [active set size](https://validator.nymtech.net/api/v1/epoch/reward_params) is 240 nodes</b>, 120 with Gateway functionality: 50 entry (1st layer) and 70 exit (5th layer) and 120 as Mixnode (2nd, 3rd and 4th mixing layer). The active set is chosen in the beginning of each epoch (60min). The best performing and reputated (optimal stake saturation) nodes are chosen. Performance is much more ample as you can see in the formula below:
<Callout type ="info" borderColor="#008080" backgroundColor="#20b2aa" emoji="📌">
> **active_set_selection_probability = ( node_performance ^ 20 ) * stake_saturation**
</Callout>
</MyTab>
<MyTab>
In dVPN (2-hop) mode every node which meets the performance criteria, including wireguard and IPv6 routing tests, becomes eligible to take part in the network. Whether the node is working on not then depends on the end users choise of the location or exact nodes selection.
</MyTab>
</Tabs>
</div>
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*](mixnet-rewards.md).
## Query Validator API
We have available API endpoints which can be accessed via [Swagger UI page](https://validator.nymtech.net/api/swagger/index.html). Or by querying the endpoints directly:
```sh
curl -X 'GET' \
'https://validator.nymtech.net/api/v1/circulating-supply' \
-H 'accept: application/json'sh
curl -X 'GET' \
'https://validator.nymtech.net/api/v1/circulating-supply/total-supply-value' \
-H 'accept: application/json'sh
curl -X 'GET' \
'https://validator.nymtech.net/api/v1/circulating-supply-value' \
-H 'accept: application/json'sh
curl -X 'GET' \
'https://validator.nymtech.net/api/v1/epoch/reward_params' \
-H 'accept: application/json'sh
```
> The unit of value is measured in `uNYM`.
<Callout type="info" borderColor="#008080" backgroundColor="#20b2aa" emoji="📌">
> **1 NYM = 1_000_000 uNYM**
</Callout>
@@ -1,3 +1,6 @@
{ "mixnet-rewards": "Nym Mixnet Rewards",
"validator-rewards": "Nyx Validator Rewards"
{
"validator-rewards": "Nyx Validator Rewards",
"mixnet-rewards": {
"display": "hidden"
}
}
@@ -0,0 +1,46 @@
<!-- THIS PAGE IS ALL COMMENTED FROM SUMMARY - NO NEED TO REVIEW YET!!! -->
<!-- DROPPING THIS FROM THE MAINTENANCE -->
### Mix Node Reward Estimation API endpoint
The Reward Estimation API endpoint allows Mix Node operators to estimate the rewards they could earn for running a Nym Mix Node with a specific `MIX_ID`.
> The `<MIX_ID>` can be found in the "Mix ID" column of the [Network Explorer](https://explorer.nymtech.net/network-components/mixnodes/active).
The endpoint is a particularly common for Mix Node operators as it can provide an estimate of potential earnings based on factors such as the amount of traffic routed through the Mix Node, the quality of the Mix Node's performance, and the overall demand for Mix Nodes in the network. This information can be useful for Mix Node operators in deciding whether or not to run a Mix Node and in optimizing its operations for maximum profitability.
Using this API endpoint returns information about the Reward Estimation:
```sh
/status/mixnode/<MIX_ID>/reward-estimation
```
Query Response:
```sh
"estimation": {
"total_node_reward": "942035.916721770541325331",
"operator": "161666.263307386408152071",
"delegates": "780369.65341438413317326",
"operating_cost": "54444.444444444444444443"
},
```
> The unit of value is measured in `uNYM`.
- `estimated_total_node_reward` - An estimate of the total amount of rewards that a particular Mix Node can expect to receive during the current epoch. This value is calculated by the Nym Validator based on a number of factors, including the current state of the network, the number of Mix Nodes currently active in the network, and the amount of network traffic being processed by the Mix Node.
- `estimated_operator_reward` - An estimate of the amount of rewards that a particular Mix Node operator can expect to receive. This value is calculated by the Nym Validator based on a number of factors, including the amount of traffic being processed by the Mix Node, the quality of service provided by the Mix Node, and the operator's stake in the network.
- `estimated_delegators_reward` - An estimate of the amount of rewards that Mix Node delegators can expect to receive individually. This value is calculated by the Nym Validator based on a number of factors, including the amount of traffic being processed by the Mix Node, the quality of service provided by the Mix Node, and the delegator's stake in the network.
- `estimated_node_profit` - An estimate of the profit that a particular Mix node operator can expect to earn. This value is calculated by subtracting the Mix Node operator's `operating_costs` from their `estimated_operator_reward` for the current epoch.
- `estimated_operator_cost` - An estimate of the total cost that a particular Mix Node operator can expect to incur for their participation. This value is calculated by the Nym Validator based on a number of factors, including the cost of running a Mix Node, such as server hosting fees, and other expenses associated with operating the Mix Node.
### Validator: Installing and configuring nginx for HTTPS
#### Setup
[Nginx](https://www.nginx.com/resources/glossary/nginx) is an open source software used for operating high-performance web servers. It allows us to set up reverse proxying on our validator server to improve performance and security.
Install `nginx` and allow the 'Nginx Full' rule in your firewall:
@@ -1,332 +0,0 @@
import { Callout } from 'nextra/components';
import { Tabs } from 'nextra/components';
import { MyTab } from 'components/generic-tabs.tsx';
import { RunTabs } from 'components/operators/nodes/node-run-command-tabs';
import { VarInfo } from 'components/variable-info.tsx';
import { MigrateTabs } from 'components/operators/nodes/node-migrate-command-tabs';
import NyxPercentStake from 'components/outputs/nyx-outputs/nyx-percent-stake.md';
import NyxTotalStake from 'components/outputs/nyx-outputs/nyx-total-stake.md';
import { TimeNow } from 'components/time-now.tsx';
import { AccordionTemplate } from 'components/accordion-template.tsx';
import { Clt } from 'components/callout-custom/CalloutCustom.jsx';
# Nym Operators Rewards
<TimeNow />
* Nym tokenomics are based on the research paper [*Reward Sharing for Mixnets*](https://nymtech.net/nym-cryptoecon-paper.pdf)
* For a more comprehensive overview, live data and supply graphs, visit [*nymtech.net/about/token*](https://nymtech.net/about/token)
We are working on the final architecture of [*Fair Mixnet*](#fair-mixnet) tokenomics implementation and its detailed documentation. **The current design is called [*Naive rewarding*](#naive-rewarding).** It is an intermediate step, allowing operators to migrate to `nym-node` in Mixnet smart contract and for the first time recieve delegations and earn rewards for any `nym-node` functionality, in opposite to the past system, where only Mixnodes were able to recieve delegations and rewards.
**Please read the [roadmap section below](#roadmap) to see the planned development.**
{/*
**Formulas and Examples Annotation**
To make it easier for the reader, we use a highlighting line on the left side, with a specific color:
<Clt borderColor='#008080' backgroundColor='#20b2aa' pointPosition='right' pointOffset='3rem' pointAlignment='center'>
> **Turquoise with red pin for formulas.**
</Clt>
<Callout borderColor="#966fd6" backgroundColor="#b19cd9" emoji="">
<AccordionTemplate name="Example">
> Purple collapsible for examples.
</AccordionTemplate>
</Callout>
*/}
<Callout type="info" emoji="️">
Nodes bonded with vesting tokens are [not allowed to join rewarded set](https://github.com/nymtech/nym/pull/5129) - read more on [Nym operators forum](https://forum.nymtech.net/t/vesting-accounts-are-no-longer-supported/827).
</Callout>
## Overview
This is a quick summary, to understand the full picture, please see detailed [*Rewards Logic & Calculation*](#rewards-logic--calculation) chapter below.
* The operators of `nym-node` get rewarded from Mixmining pool, which emits around 6000 NYM per hour.
* A [rewarded set](../tokenomics.mdx#active-set) of `nym-nodes` selected for Nym network routing and mixing can be is currently 240 nodes in total and it's selected for each new epoch (60 min). The number can be adjusted - look here for the current value: [validator.nymtech.net/api/v1/epoch/reward_params](https://validator.nymtech.net/api/v1/epoch/reward_params)
* `nym-nodes` can run in mode `entry-gateway`, `exit-gateway` and `mixnode`, which are positioned into layers
* NymVPN users can chose to route through Nym Network in two ways:
- Mixnet: 5 layers routing and mixing - full privacy
- Wireguard: 2 layers routing, skipping 3 mixing layers - fast mode
* **The current reward system is *Native rewarding* - an intermediate step - where each layer get's rewarded the same**
* In the final model, nodes will get rewarded based on their layer position and the work they do (collected user tickets), where and the reward distribution per layer will be according to a [decision made by the operators](https://forum.nymtech.net/t/poll-what-should-be-the-split-of-mixmining-rewards-among-the-layers-of-the-nym-mixnet/407) as follows:
- 5-hop: 16%-16%-16%-16%-36%
- 2-hop: 33%-67%
* Currently Gateways earn rewards only from taking a part in the rewarded set. The operators can sign up to a grant program as a substitution for 2-hop routing.
* To read more about the final design and future implementation, see [*Roadmap*](#roadmap) chapter for more details.
## Rewards Logic & Calculation
**Note that in the current intermediate model we use one active set to reward all nodes and they are asign same (naive) work factor of 1 / 240, whether they work as Mixnode or Gateway of any kind, in both 2-hop and 5-hop mode. In reality it means that all nodes are rewarded within 5-hop reward scheme only.**
**However NymVPN client can chose any `nym-node --mode entry-gateway` and `--mode exit-gateway` in the network to route through the mixnet and as well as any of those which passed [wireguard probing test](https://harbourmaster.nymtech.net) to route as dVPN nodes.**
### Nym Network rewarded set distribution
<div>
<Tabs items={[
<strong>Mixnet mode (5-hop)</strong>,
<strong>dVPN mode (2-hop)</strong>,
]} defaultIndex="0">
<MyTab>
```ascii
Network
layer: 1. 2. 3. 4. 5.
--------
┌► mixnode ─┐ mixnode mixnode
│ │
Node entry │ │ exit
type: gateway ──┘ mixnode │ mixnode ┌─► mixnode ───► gateway
│ │
│ │
mixnode └─► mixnode ─┘ mixnode
```
| **Network layer** | **1** | **2** | **3** | **4** | **5** |
| :-- | :---: | :---: | :---: | :---: | :---: |
| Node functionality in layer | Entry Gateway | Mixnode | Mixnode | Mixnode | Exit Gateway |
| Nodes in [active set](tokenomics.mdx#active-set) | 50 | 40 | 40 | 40 | 70 |
| Naive rewarding: Rewards distribution per node | 1 / 240 | 1 / 240 | 1 / 240 | 1 / 240 | 1 / 240 |
| Final model: Rewards distribution per node | 0.16 / 240 | 0.16 / 240 | 0.16 / 240 | 0.16 / 240 | 0.36 / 240 |
</MyTab>
<MyTab>
```ascii
Network
layer: 1. 2.
--------
Node entry exit
type: gateway ──────────────────────────────────────────► gateway
```
| **Network layer** | **1** | **2** |
| :-- | :---: | :---: |
| Node functionality in layer | Entry Gateway | Exit Gateway |
| Naive rewarding: Nodes in [active set](tokenomics.mdx#active-set) | 50 | 70 |
| Naive rewarding: Rewards distribution per node | 1 / 240 | 1 / 240 | 1 / 240 | 1 / 240 | 1 / 240 |
| Final model: Active nodes | All following criteria for eligibility | All following criteria for eligibility |
| Final model: Rewards distribution per node | 0.33 \* collected_user_tickets | 0.67 \* collected_user_tickets |
</MyTab>
</Tabs>
</div>
### Active Set Selection
*Performance matters!*
For a node to be rewarded, the node must be part of a [Rewarded set](https://validator.nymtech.net/api/v1/epoch/reward_params) (which currently = active set) in the first place. The active set is selected in the beginning of each epoch (every 60min) where total of 240 Nym nodes - represented by 120 mixnodes and 120 gateways, are randomly allocated across the layers.
The algorithm choosing nodes into the active set takes into account node's performance and [stake saturation](../tolkenomics.mdx#stake-saturation), both values being between 0 and 1 and config score which is either 0 or 1.
**Config score is introduced:** The nodes selection to the active set has a new parameter - `config_score`. Config score currently looks if the node binary is `nym-node` (not legacy `nym-mixnode` or `nym-gateway`) **AND** if [Terms & Conditions](nodes/nym-node/setup.mdx#terms--conditions) are accepted. Config score has binary values of either 0 or 1, with a following logic:
| **Run `nym-node` binary** | **T&C's accepted** | **`config_score`** |
| :-- | :-- | ---: |
| True | False | 0 |
| False | True | 0 |
| False | False | 0 |
| True | True | 1 |
The entire active set selection probablity:
<Callout type="info" emoji="📌">
> **active_set_selection_probability = config_score \* stake_saturation \* node_performance ^ 20**
</Callout>
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">
> 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 />
> node_4 = 0.95 ^ 20 \* 1.0 = 0.358 <br />
> node_5 = 0.90 ^ 20 \* 1.0 = 0.122 <br />
</AccordionTemplate>
As you can see the performance (also known as *Routing score*) is much more important during the active set selection. A node with 100% performance but only 50% stake saturation has much bigger chance to be chosen than a node with 95% performance but full stake saturation and incomparably bigger chance than 90% performing node with 100% stake saturation.
### Layer Distribution
Once the rewarded set (currently 120 Mixnodes and 120 Gateways) is selected, the nodes can start to route and mix packets in the Nym Network. Each hour a total of 6000 NYM is distributed between the layers from Mixmining pool. Currently in our *Naive rewarding* intermediate design, all layers get a same portion, therefore each node is *naively* assigned same working factor and therefore earns 1/240 of the rewards per epoch.
We are working on the final design with the ratio implementing a [decision made by the operators](https://forum.nymtech.net/t/poll-what-should-be-the-split-of-mixmining-rewards-among-the-layers-of-the-nym-mixnet/407) as follows:
<Callout type="info" borderColor="#008080" backgroundColor="#20b2aa" emoji="📌">
>5-hop mixnet mode: <br />
> 16%; 16%; 16%; 16%; 36% <br/>
> <br/>
> 2-hop dVPN mode: <br />
> 33%; 67%
</Callout>
{/*
In real numbers: If hourly revenue to all 240 nodes is 6000 NYM, the layer compartmentalisation is 960 NYM for Entry Gateway layer and each Mixnode layer and 2160 NYM for Exit Gateway layer. The calculation is in the example below:
<Callout borderColor="#966fd6" backgroundColor="#b19cd9" emoji="">
<AccordionTemplate name="Example">
> Purple collapsible for examples.
5-hop mixnet mode:
$0.16 * 6000 = 960; 0.16 * 6000 = 960; 0.16 * 6000 = 960; 0.16 * 6000 = 960; 0.36 * 6000 2160$
2-hop wireguard mode:
$33\% - 67\%$
</AccordionTemplate>
</Callout>
### Node Rewards within Same Layer
### Operation Cost, Profit Margin & Delegation
### APR Calculation
*/}
## Roadmap
We are working on the final architecture of [*Fair Mixnet*](#fair-mixnet) tokenomics implementation. The current design is called [*Naive rewarding*](#naive-rewarding). This is an intermediate step, allowing operators to migrate to `nym-node` in Mixnet smart contract and for the first time recieve delegations and earn rewards for any `nym-node` functionality, in opposite to the past system, where only Mixnodes were able to recieve delegations and rewards.
On November 5th, we presented a release roadmap in live [Operators Townhall](https://www.youtube.com/watch?v=3G1pJqvO2VM) where we explained in detail the steps of Nym node and tokenomics development and the effect it will have on node operators and put it into a rough timeline.
![](/images/operators/tokenomics/roadmap_24-q4.png)
### Naive Rewarding
***Naive rewarding* is the current tokenomics design.** The table below lists features and logic of this design.
![](/images/operators/tokenomics/roadmap_naive.png)
### Fair Mixnet
***Fair Mixnet* is the final architecture model that we work towards.** The table below lists features and logic of the design once implemented.
![](/images/operators/tokenomics/roadmap_fair.png)
{/*
## Stats
NYM token is capped at 1b. Below is a table with actual\* token supply distribution.
mdrun cd ../../../scripts/cdmrun && ./api_targets.py s --api mainnet --endpoint circulating-supply --format
ADD MIXNET STATS GRAPHS
DROPPING THIS FROM THE MAINTENANCE PAGE - NEEDS REWORK
## Mix Node Reward Estimation API endpoint
THIS NEEDS REDO
The Reward Estimation API endpoint allows Mix Node operators to estimate the rewards they could earn for running a Nym Mix Node with a specific `MIX_ID`.
> The `<MIX_ID>` can be found in the "Mix ID" column of the [Harbourmaster](https://harbourmaster/nymtech.net).
The endpoint is a particularly common for Mix Node operators as it can provide an estimate of potential earnings based on factors such as the amount of traffic routed through the Mix Node, the quality of the Mix Node's performance, and the overall demand for Mix Nodes in the network. This information can be useful for Mix Node operators in deciding whether or not to run a Mix Node and in optimizing its operations for maximum profitability.
We have available API endpoints which can be accessed via [Swagger UI page](https://validator.nymtech.net/api/swagger/index.html). Or by querying the endpoints directly:
```sh
curl -X 'GET' \
'https://validator.nymtech.net/api/v1/status/mixnode/<MIX_ID>/reward-estimation' \
-H 'accept: application/json'sh
```
Query response will look like this:
```sh
"estimation": {
"total_node_reward": "942035.916721770541325331",
"operator": "161666.263307386408152071",
"delegates": "780369.65341438413317326",
"operating_cost": "54444.444444444444444443"
},
```
> The unit of value is measured in `uNYM`.
<Callout borderColor="#008080" backgroundColor="#20b2aa" emoji="📌">
$1 \ NYM = 1 \_ 000 \_ 000 \ uNYM$
</Callout>
- `estimated_total_node_reward` - An estimate of the total amount of rewards that a particular Mix Node can expect to receive during the current epoch. This value is calculated by the Nym Validator based on a number of factors, including the current state of the network, the number of Mix Nodes currently active in the network, and the amount of network traffic being processed by the Mix Node.
- `estimated_operator_reward` - An estimate of the amount of rewards that a particular Mix Node operator can expect to receive. This value is calculated by the Nym Validator based on a number of factors, including the amount of traffic being processed by the Mix Node, the quality of service provided by the Mix Node, and the operator's stake in the network.
- `estimated_delegators_reward` - An estimate of the amount of rewards that Mix Node delegators can expect to receive individually. This value is calculated by the Nym Validator based on a number of factors, including the amount of traffic being processed by the Mix Node, the quality of service provided by the Mix Node, and the delegator's stake in the network.
- `estimated_node_profit` - An estimate of the profit that a particular Mix node operator can expect to earn. This value is calculated by subtracting the Mix Node operator's `operating_costs` from their `estimated_operator_reward` for the current epoch.
- `estimated_operator_cost` - An estimate of the total cost that a particular Mix Node operator can expect to incur for their participation. This value is calculated by the Nym Validator based on a number of factors, including the cost of running a Mix Node, such as server hosting fees, and other expenses associated with operating the Mix Node.
*/}
{/*
?DROPPING THIS FROM THE OLD MAINTENANCE PAGE
### Mix Node Reward Estimation API endpoint
The Reward Estimation API endpoint allows Mix Node operators to estimate the rewards they could earn for running a Nym Mix Node with a specific `MIX_ID`.
> The `<MIX_ID>` can be found in the "Mix ID" column of the [Network Explorer](https://explorer.nymtech.net/network-components/mixnodes/active).
The endpoint is a particularly common for Mix Node operators as it can provide an estimate of potential earnings based on factors such as the amount of traffic routed through the Mix Node, the quality of the Mix Node's performance, and the overall demand for Mix Nodes in the network. This information can be useful for Mix Node operators in deciding whether or not to run a Mix Node and in optimizing its operations for maximum profitability.
Using this API endpoint returns information about the Reward Estimation:
```sh
/status/mixnode/<MIX_ID>/reward-estimation
```
Query Response:
```sh
"estimation": {
"total_node_reward": "942035.916721770541325331",
"operator": "161666.263307386408152071",
"delegates": "780369.65341438413317326",
"operating_cost": "54444.444444444444444443"
},
```
> The unit of value is measured in `uNYM`.
- `estimated_total_node_reward` - An estimate of the total amount of rewards that a particular Mix Node can expect to receive during the current epoch. This value is calculated by the Nym Validator based on a number of factors, including the current state of the network, the number of Mix Nodes currently active in the network, and the amount of network traffic being processed by the Mix Node.
- `estimated_operator_reward` - An estimate of the amount of rewards that a particular Mix Node operator can expect to receive. This value is calculated by the Nym Validator based on a number of factors, including the amount of traffic being processed by the Mix Node, the quality of service provided by the Mix Node, and the operator's stake in the network.
- `estimated_delegators_reward` - An estimate of the amount of rewards that Mix Node delegators can expect to receive individually. This value is calculated by the Nym Validator based on a number of factors, including the amount of traffic being processed by the Mix Node, the quality of service provided by the Mix Node, and the delegator's stake in the network.
- `estimated_node_profit` - An estimate of the profit that a particular Mix node operator can expect to earn. This value is calculated by subtracting the Mix Node operator's `operating_costs` from their `estimated_operator_reward` for the current epoch.
- `estimated_operator_cost` - An estimate of the total cost that a particular Mix Node operator can expect to incur for their participation. This value is calculated by the Nym Validator based on a number of factors, including the cost of running a Mix Node, such as server hosting fees, and other expenses associated with operating the Mix Node.
### Validator: Installing and configuring nginx for HTTPS
#### Setup
[Nginx](https://www.nginx.com/resources/glossary/nginx) is an open source software used for operating high-performance web servers. It allows us to set up reverse proxying on our validator server to improve performance and security.
Install `nginx` and allow the 'Nginx Full' rule in your firewall:
*/}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 396 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 479 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 357 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

View File
@@ -7,46 +7,28 @@ set -o pipefail
cd ../scripts &&
python csv2md.py -s 1 ../docs/data/csv/variables.csv > ../docs/components/outputs/csv2md-outputs/variables.md &&
python csv2md.py -s 0 ../docs/data/csv/isp-sheet.csv > ../docs/components/outputs/csv2md-outputs/isp-sheet.md &&
cd cmdrun &&
./nyx-percent-stake.sh > ../../docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-percent-stake.md &&
./nyx-total-stake.sh > ../../docs/components/outputs/api-scraping-outputs/nyx-outputs/nyx-total-stake.md &&
./nyx-percent-stake.sh > ../../docs/components/outputs/nyx-outputs/nyx-percent-stake.md &&
./nyx-total-stake.sh > ../../docs/components/outputs/nyx-outputs/nyx-total-stake.md &&
cd ../api-scraping &&
python api_targets.py v --api mainnet --endpoint circulating-supply --value circulating_supply amount --separator _ > ../../docs/components/outputs/api-scraping-outputs/nyx-outputs/circulating-supply.md &&
python api_targets.py v --api mainnet --endpoint circulating-supply --format markdown --separator _ > ../../docs/components/outputs/api-scraping-outputs/nyx-outputs/token-table.md &&
python api_targets.py v --api mainnet --endpoint epoch/reward_params --value interval staking_supply_scale_factor --format percent > ../../docs/components/outputs/api-scraping-outputs/nyx-outputs/staking-scale-factor.md &&
python api_targets.py v --api mainnet --endpoint epoch/reward_params --value interval stake_saturation_point --separator _ > ../../docs/components/outputs/api-scraping-outputs/nyx-outputs/stake-saturation.md &&
python api_targets.py time_now > ../../docs/components/outputs/api-scraping-outputs/time-now.md &&
python api_targets.py c --staking_target --separator _ > ../../docs/components/outputs/api-scraping-outputs/nyx-outputs/staking-target.md &&
cd ../../../scripts &&
echo '```python' > ../documentation/docs/components/outputs/command-outputs/node-api-check-query-help.md &&
python node_api_check.py query_stats --help >> ../documentation/docs/components/outputs/command-outputs/node-api-check-query-help.md &&
echo '```' >> ../documentation/docs/components/outputs/command-outputs/node-api-check-query-help.md &&
echo '```python' > ../documentation/docs/components/outputs/command-outputs/node-api-check-help.md &&
python node_api_check.py --help >> ../documentation/docs/components/outputs/command-outputs/node-api-check-help.md &&
echo '```' >> ../documentation/docs/components/outputs/command-outputs/node-api-check-help.md &&
cd ../target/release/ &&
echo '```sh' > ../../documentation/docs/components/outputs/command-outputs/nym-node-help.md &&
./nym-node --help >> ../../documentation/docs/components/outputs/command-outputs/nym-node-help.md &&
echo '```' >> ../../documentation/docs/components/outputs/command-outputs/nym-node-help.md &&
echo '```sh' > ../../documentation/docs/components/outputs/command-outputs/nym-node-run-help.md &&
./nym-node run --help >> ../../documentation/docs/components/outputs/command-outputs/nym-node-run-help.md &&
echo '```' >> ../../documentation/docs/components/outputs/command-outputs/nym-node-run-help.md &&
echo '```sh' > ../../documentation/docs/components/outputs/command-outputs/nymvisor-help.md &&
./nymvisor --help >> ../../documentation/docs/components/outputs/command-outputs/nymvisor-help.md &&
echo '```' >> ../../documentation/docs/components/outputs/command-outputs/nymvisor-help.md &&
echo '```sh' > ../../documentation/docs/components/outputs/command-outputs/nym-api-help.md &&
./nym-api --help >> ../../documentation/docs/components/outputs/command-outputs/nym-api-help.md &&
echo '```' >> ../../documentation/docs/components/outputs/command-outputs/nym-api-help.md &&
+2 -3
View File
@@ -18,7 +18,6 @@ GROUP_CONTRACT_ADDRESS=n1qg5ega6dykkxc307y25pecuufrjkxkaggkkxh7nad0vhyhtuhw3sa07
MULTISIG_CONTRACT_ADDRESS=n1zwv6feuzhy6a9wekh96cd57lsarmqlwxdypdsplw6zhfncqw6ftqx5a364
COCONUT_DKG_CONTRACT_ADDRESS=n1aakfpghcanxtc45gpqlx8j3rq0zcpyf49qmhm9mdjrfx036h4z5sy2vfh9
EXPLORER_API=https://canary-explorer.performance.nymte.ch/api/
EXPLORER_API=https://canary-explorer.performance.nymte.ch/api
NYXD=https://canary-validator.performance.nymte.ch
NYM_API=https://canary-api.performance.nymte.ch/api/
NYM_VPN_API=https://nym-vpn-api-git-deploy-canary-nyx-network-staging.vercel.app/api/
NYM_API=https://canary-api.performance.nymte.ch/api

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