Compare commits

..

5 Commits

Author SHA1 Message Date
Jędrzej Stuczyński d916854ba3 Revert "Ability to update mixnode config in maintenance mode"
This reverts commit dbd0e6b4fa.
2022-11-15 16:17:50 +00:00
Jędrzej Stuczyński dbd0e6b4fa Ability to update mixnode config in maintenance mode 2022-11-14 14:24:03 +00:00
Jędrzej Stuczyński abf7b57ccb Bugfix/correct staking supply accounting (#1706)
* Added staking_supply_scale_factor field on RewardingParams

* Scaling the amount of tokens released to the circulating/staking supplies
2022-10-27 11:05:55 +01:00
Jędrzej Stuczyński ec1988b745 Added code for gateway migration 2022-10-24 09:51:14 +01:00
Jędrzej Stuczyński 08bb9c0fbc Saving received messages from v1 contract into new storage 2022-10-24 09:51:13 +01:00
200 changed files with 1345 additions and 3532 deletions
-18
View File
@@ -3,21 +3,3 @@
RUST_LOG=info
RUST_BACKTRACE=1
#########################################
# geoipupdate (needed for explorer-api) #
#########################################
# MaxMind account ID (change it to a valid account ID)
GEOIPUPDATE_ACCOUNT_ID=xxx
# MaxMind license key (change it to a valid license key)
GEOIPUPDATE_LICENSE_KEY=xxx
# List of space-separated database edition IDs. Edition IDs may
# consist of letters, digits, and dashes. For example, GeoIP2-City
# would download the GeoIP2 City database (GeoIP2-City).
GEOIPUPDATE_EDITION_IDS=GeoLite2-Country
# The number of hours between geoipupdate runs. If this is not set
# or is set to 0, geoipupdate will run once and exit.
GEOIPUPDATE_FREQUENCY=72
# The path to the directory where geoipupdate will download the
# database.
GEOIP_DB_DIRECTORY=./explorer-api/geo_ip
@@ -1,56 +0,0 @@
name: CI for Network Explorer API
on:
workflow_dispatch:
release:
types: [created]
env:
NETWORK: mainnet
jobs:
publish-nym:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get -y install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
- name: Check the release tag starts with `nym-explorer-api-`
if: startsWith(github.ref, 'refs/tags/nym-explorer-api-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Release tag did not start with nym-explorer-api-...')
- name: Install Rust stable
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Build all explorer-api
uses: actions-rs/cargo@v1
with:
command: build
args: --manifest-path explorer-api/Cargo.toml --workspace --release
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: my-artifact
path: |
target/release/explorer-api
retention-days: 30
- name: Upload to release based on tag name
uses: softprops/action-gh-release@v1
if: github.event_name == 'release'
with:
files: |
target/release/explorer-api
@@ -25,9 +25,6 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get -y install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
- name: Check the release tag starts with `nym-binaries-`
if: startsWith(github.ref, 'refs/tags/nym-binaries-') == false && github.event_name != 'workflow_dispatch'
uses: actions/github-script@v3
+11 -27
View File
@@ -2,40 +2,31 @@
Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.1.0](https://github.com/nymtech/nym/tree/v1.1.0) (2022-11-09)
## Unreleased
### Added
- clients: add testing-only support for two more extended packet sizes (8kb and 16kb).
- common/ledger: new library for communicating with a Ledger device ([#1640])
- native-client/socks5-client/wasm-client: `disable_loop_cover_traffic_stream` Debug config option to disable the separate loop cover traffic stream ([#1666])
- native-client/socks5-client/wasm-client: `disable_main_poisson_packet_distribution` Debug config option to make the client ignore poisson distribution in the main packet stream and ONLY send real message (and as fast as they come) ([#1664])
- native-client/socks5-client/wasm-client: `use_extended_packet_size` Debug config option to make the client use 'ExtendedPacketSize' for its traffic (32kB as opposed to 2kB in 1.0.2) ([#1671])
- network-requester: added additional Blockstream Green wallet endpoint to `example.allowed.list` ([#1611])
- validator-api: add `interval_operating_cost` and `profit_margin_percent` to compute reward estimation endpoint
- nym-cli: added CLI tool for interacting with the Nyx blockchain and Nym mixnet smart contracts ([#1577])
- validator-client: added `query_contract_smart` and `query_contract_raw` on `NymdClient` ([#1558])
- network-requester: added additional Blockstream Green wallet endpoint to `example.allowed.list` ([#1611](https://github.com/nymtech/nym/pull/1611))
- common/ledger: new library for communicating with a Ledger device ([#1640])
- native-client/socks5-client: `disable_loop_cover_traffic_stream` Debug config option to disable the separate loop cover traffic stream ([#1666])
- native-client/socks5-client: `disable_main_poisson_packet_distribution` Debug config option to make the client ignore poisson distribution in the main packet stream and ONLY send real message (and as fast as they come) ([#1664])
- native-client/socks5-client: `use_extended_packet_size` Debug config option to make the client use 'ExtendedPacketSize' for its traffic (32kB as opposed to 2kB in 1.0.2) ([#1671])
- wasm-client: uses updated wasm-compatible `client-core` so that it's now capable of packet retransmission, cover traffic and poisson delay (among other things!) ([#1673])
- validator-api: add `interval_operating_cost` and `profit_margin_percent` to cmpute reward estimation endpoint
### Fixed
- socks5-client: fix bug where in some cases packet reordering could trigger a connection being closed too early ([#1702],[#1724])
- validator-api: mixnode, gateway should now prefer values in config.toml over mainnet defaults ([#1645])
- validator-api: should now correctly update historical uptimes for all mixnodes and gateways every 24h ([#1721])
- validator-api, mixnode, gateway should now prefer values in config.toml over mainnet defaults ([#1645])
### Changed
- clients: bound the sphinx packet channel and reduce sending rate if gateway can't keep up ([#1703],[#1725])
- gateway-client: will attempt to read now as many as 8 websocket messages at once, assuming they're already available on the socket ([#1669])
- moved `Percent` struct to `contracts-common`, change affects explorer-api
- socks5 client: graceful shutdown should fix error on disconnect in nym-connect ([#1591])
- validator-api: changed error serialization on `inclusion_probability`, `stake-saturation` and `reward-estimation` endpoints to provide more accurate information ([#1681])
- validator-client: made `fee` argument optional for `execute` and `execute_multiple` ([#1541])
- socks5 client: graceful shutdown should fix error on disconnect in nym-connect ([#1591])
- wasm-client: fixed build errors on MacOS and changed example JS code to use mainnet ([#1585])
- validator-api: changes to internal SQL schema due to the mixnet contract revamp ([#1472])
- validator-api: changes to internal data structures due to the mixnet contract revamp ([#1472])
- validator-api: split epoch-operations into multiple separate transactions ([#1472])
- gateway-client: will attempt to read now as many as 8 websocket messages at once, assuming they're already available on the socket ([#1669])
[#1472]: https://github.com/nymtech/nym/pull/1472
[#1541]: https://github.com/nymtech/nym/pull/1541
[#1558]: https://github.com/nymtech/nym/pull/1558
[#1577]: https://github.com/nymtech/nym/pull/1577
@@ -43,18 +34,11 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
[#1591]: https://github.com/nymtech/nym/pull/1591
[#1640]: https://github.com/nymtech/nym/pull/1640
[#1645]: https://github.com/nymtech/nym/pull/1645
[#1611]: https://github.com/nymtech/nym/pull/1611
[#1664]: https://github.com/nymtech/nym/pull/1664
[#1666]: https://github.com/nymtech/nym/pull/1645
[#1669]: https://github.com/nymtech/nym/pull/1669
[#1671]: https://github.com/nymtech/nym/pull/1671
[#1673]: https://github.com/nymtech/nym/pull/1673
[#1681]: https://github.com/nymtech/nym/pull/1681
[#1702]: https://github.com/nymtech/nym/pull/1702
[#1703]: https://github.com/nymtech/nym/pull/1703
[#1721]: https://github.com/nymtech/nym/pull/1721
[#1724]: https://github.com/nymtech/nym/pull/1724
[#1725]: https://github.com/nymtech/nym/pull/1725
## [nym-binaries-1.0.2](https://github.com/nymtech/nym/tree/nym-binaries-1.0.2)
Generated
+9 -34
View File
@@ -578,7 +578,7 @@ dependencies = [
[[package]]
name = "client-core"
version = "1.1.0"
version = "1.0.1"
dependencies = [
"config",
"crypto",
@@ -739,7 +739,6 @@ dependencies = [
"cosmwasm-std",
"schemars",
"serde",
"serde_json",
"thiserror",
]
@@ -1582,17 +1581,14 @@ dependencies = [
[[package]]
name = "explorer-api"
version = "1.1.0"
version = "1.0.1"
dependencies = [
"chrono",
"clap 3.2.8",
"contracts-common",
"dotenv",
"humantime-serde",
"isocountry",
"itertools",
"log",
"logging",
"maxminddb",
"mixnet-contract-common",
"network-defaults",
@@ -2731,14 +2727,6 @@ dependencies = [
"cfg-if 1.0.0",
]
[[package]]
name = "logging"
version = "0.1.0"
dependencies = [
"log",
"pretty_env_logger",
]
[[package]]
name = "loom"
version = "0.5.4"
@@ -3070,7 +3058,7 @@ dependencies = [
[[package]]
name = "nym-cli"
version = "1.1.0"
version = "1.0.0"
dependencies = [
"anyhow",
"base64",
@@ -3081,7 +3069,6 @@ dependencies = [
"clap_complete_fig",
"dotenv",
"log",
"logging",
"network-defaults",
"nym-cli-commands",
"pretty_env_logger",
@@ -3122,7 +3109,7 @@ dependencies = [
[[package]]
name = "nym-client"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"clap 3.2.8",
"client-core",
@@ -3137,7 +3124,6 @@ dependencies = [
"gateway-client",
"gateway-requests",
"log",
"logging",
"network-defaults",
"nymsphinx",
"pemstore",
@@ -3159,7 +3145,7 @@ dependencies = [
[[package]]
name = "nym-gateway"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"anyhow",
"async-trait",
@@ -3179,7 +3165,6 @@ dependencies = [
"gateway-requests",
"humantime-serde",
"log",
"logging",
"mixnet-client",
"mixnode-common",
"network-defaults",
@@ -3206,7 +3191,7 @@ dependencies = [
[[package]]
name = "nym-mixnode"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"anyhow",
"bs58",
@@ -3222,7 +3207,6 @@ dependencies = [
"humantime-serde",
"lazy_static",
"log",
"logging",
"mixnet-client",
"mixnode-common",
"nonexhaustive-delayqueue",
@@ -3248,7 +3232,7 @@ dependencies = [
[[package]]
name = "nym-network-requester"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"async-trait",
"clap 3.2.8",
@@ -3257,7 +3241,6 @@ dependencies = [
"futures",
"ipnetwork 0.20.0",
"log",
"logging",
"network-defaults",
"nymsphinx",
"ordered-buffer",
@@ -3283,7 +3266,6 @@ version = "1.0.2"
dependencies = [
"dirs",
"log",
"logging",
"pretty_env_logger",
"rocket",
"serde",
@@ -3295,7 +3277,7 @@ dependencies = [
[[package]]
name = "nym-socks5-client"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"clap 3.2.8",
"client-core",
@@ -3310,7 +3292,6 @@ dependencies = [
"gateway-client",
"gateway-requests",
"log",
"logging",
"network-defaults",
"nymsphinx",
"ordered-buffer",
@@ -3359,7 +3340,7 @@ dependencies = [
[[package]]
name = "nym-validator-api"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"anyhow",
"async-trait",
@@ -3369,7 +3350,6 @@ dependencies = [
"coconut-interface",
"config",
"console-subscriber",
"contracts-common",
"cosmwasm-std",
"credential-storage",
"credentials",
@@ -3384,7 +3364,6 @@ dependencies = [
"humantime-serde",
"inclusion-probability",
"log",
"logging",
"mixnet-contract-common",
"multisig-contract-common",
"nymcoconut",
@@ -6408,7 +6387,6 @@ dependencies = [
"coconut-interface",
"colored",
"config",
"contracts-common",
"cosmrs",
"cosmwasm-std",
"cw3",
@@ -6497,14 +6475,12 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
name = "vesting-contract"
version = "1.1.0"
dependencies = [
"contracts-common",
"cosmwasm-std",
"cw-storage-plus",
"mixnet-contract-common",
"schemars",
"serde",
"thiserror",
"vergen 5.1.17",
"vesting-contract-common",
]
@@ -6512,7 +6488,6 @@ dependencies = [
name = "vesting-contract-common"
version = "0.1.0"
dependencies = [
"contracts-common",
"cosmwasm-std",
"mixnet-contract-common",
"schemars",
-1
View File
@@ -41,7 +41,6 @@ members = [
"common/execute",
"common/inclusion-probability",
"common/ledger",
"common/logging",
"common/mixnode-common",
"common/network-defaults",
"common/nonexhaustive-delayqueue",
-3
View File
@@ -92,9 +92,6 @@ build-wallet:
build-connect:
cargo build --manifest-path nym-connect/Cargo.toml --workspace
build-explorer-api:
cargo build --manifest-path explorer-api/Cargo.toml --workspace
build-wasm-client:
cargo build --manifest-path clients/webassembly/Cargo.toml --workspace --target wasm32-unknown-unknown
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "client-core"
version = "1.1.0"
version = "1.0.1"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
edition = "2021"
@@ -16,7 +16,6 @@ use rand::{rngs::OsRng, CryptoRng, Rng};
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc::error::TrySendError;
#[cfg(not(target_arch = "wasm32"))]
use tokio::time;
@@ -172,18 +171,11 @@ impl LoopCoverTrafficStream<OsRng> {
)
.expect("Somehow failed to generate a loop cover message with a valid topology");
if let Err(err) = self.mix_tx.try_send(vec![cover_message]) {
match err {
TrySendError::Full(_) => {
// This isn't a problem, if the channel is full means we're already sending the
// max amount of messages downstream can handle.
log::debug!("Failed to send cover message - channel full");
}
TrySendError::Closed(_) => {
log::warn!("Failed to send cover message - channel closed");
}
}
}
// if this one fails, there's no retrying because it means that either:
// - we run out of memory
// - the receiver channel is closed
// in either case there's no recovery and we can only panic
self.mix_tx.unbounded_send(vec![cover_message]).unwrap();
// TODO: I'm not entirely sure whether this is really required, because I'm not 100%
// sure how `yield_now()` works - whether it just notifies the scheduler or whether it
+15 -17
View File
@@ -2,15 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
use crate::spawn_future;
use futures::channel::mpsc;
use futures::StreamExt;
use gateway_client::GatewayClient;
use log::*;
use nymsphinx::forwarding::packet::MixPacket;
pub type BatchMixMessageSender = tokio::sync::mpsc::Sender<Vec<MixPacket>>;
pub type BatchMixMessageReceiver = tokio::sync::mpsc::Receiver<Vec<MixPacket>>;
pub type BatchMixMessageSender = mpsc::UnboundedSender<Vec<MixPacket>>;
pub type BatchMixMessageReceiver = mpsc::UnboundedReceiver<Vec<MixPacket>>;
// We remind ourselves that 32 x 32kb = 1024kb, a reasonable size for a network buffer.
pub const MIX_MESSAGE_RECEIVER_BUFFER_SIZE: usize = 32;
const MAX_FAILURE_COUNT: usize = 100;
pub struct MixTrafficController {
@@ -25,17 +25,15 @@ pub struct MixTrafficController {
}
impl MixTrafficController {
pub fn new(gateway_client: GatewayClient) -> (MixTrafficController, BatchMixMessageSender) {
let (sphinx_message_sender, sphinx_message_receiver) =
tokio::sync::mpsc::channel(MIX_MESSAGE_RECEIVER_BUFFER_SIZE);
(
MixTrafficController {
gateway_client,
mix_rx: sphinx_message_receiver,
consecutive_gateway_failure_count: 0,
},
sphinx_message_sender,
)
pub fn new(
mix_rx: BatchMixMessageReceiver,
gateway_client: GatewayClient,
) -> MixTrafficController {
MixTrafficController {
gateway_client,
mix_rx,
consecutive_gateway_failure_count: 0,
}
}
async fn on_messages(&mut self, mut mix_packets: Vec<MixPacket>) {
@@ -74,7 +72,7 @@ impl MixTrafficController {
while !shutdown.is_shutdown() {
tokio::select! {
mix_packets = self.mix_rx.recv() => match mix_packets {
mix_packets = self.mix_rx.next() => match mix_packets {
Some(mix_packets) => {
self.on_messages(mix_packets).await;
},
@@ -98,7 +96,7 @@ impl MixTrafficController {
spawn_future(async move {
debug!("Started MixTrafficController without graceful shutdown support");
while let Some(mix_packets) = self.mix_rx.recv().await {
while let Some(mix_packets) = self.mix_rx.next().await {
self.on_messages(mix_packets).await;
}
})
@@ -27,23 +27,6 @@ use tokio::time;
#[cfg(target_arch = "wasm32")]
use wasm_timer;
// The minimum time between increasing the average delay between packets. If we hit the ceiling in
// the available buffer space we want to take somewhat swift action, but we still need to give a
// short time to give the channel a chance reduce pressure.
const INCREASE_DELAY_MIN_CHANGE_INTERVAL_SECS: u64 = 1;
// The minimum time between decreasing the average delay between packets. We don't want to change
// to quickly to keep things somewhat stable. Also there are buffers downstreams meaning we need to
// wait a little to see the effect before we decrease further.
const DECREASE_DELAY_MIN_CHANGE_INTERVAL_SECS: u64 = 30;
// If we enough time passes without any sign of backpressure in the channel, we can consider
// lowering the average delay. The goal is to keep somewhat stable, rather than maxing out
// bandwidth at all times.
const ACCEPTABLE_TIME_WITHOUT_BACKPRESSURE_SECS: u64 = 30;
// The maximum multiplier we apply to the base average Poisson delay.
const MAX_DELAY_MULTIPLIER: u32 = 6;
// The minium multiplier we apply to the base average Poisson delay.
const MIN_DELAY_MULTIPLIER: u32 = 1;
/// Configurable parameters of the `OutQueueControl`
pub(crate) struct Config {
/// Average delay an acknowledgement packet is going to get delay at a single mixnode.
@@ -85,101 +68,6 @@ impl Config {
}
}
struct SendingDelayController {
/// Multiply the average sending delay.
/// This is normally set to unity, but if we detect backpressure we increase this
/// multiplier. We use discrete steps.
current_multiplier: u32,
/// Maximum delay multiplier
upper_bound: u32,
/// Minimum delay multiplier
lower_bound: u32,
/// To make sure we don't change the multiplier to fast, we limit a change to some duration
#[cfg(not(target_arch = "wasm32"))]
time_when_changed: time::Instant,
#[cfg(target_arch = "wasm32")]
time_when_changed: wasm_timer::Instant,
/// If we have a long enough time without any backpressure detected we try reducing the sending
/// delay multiplier
#[cfg(not(target_arch = "wasm32"))]
time_when_backpressure_detected: time::Instant,
#[cfg(target_arch = "wasm32")]
time_when_backpressure_detected: wasm_timer::Instant,
}
#[cfg(not(target_arch = "wasm32"))]
fn get_time_now() -> time::Instant {
time::Instant::now()
}
#[cfg(target_arch = "wasm32")]
fn get_time_now() -> wasm_timer::Instant {
wasm_timer::Instant::now()
}
impl SendingDelayController {
fn new(lower_bound: u32, upper_bound: u32) -> Self {
assert!(lower_bound <= upper_bound);
let now = get_time_now();
SendingDelayController {
current_multiplier: MIN_DELAY_MULTIPLIER,
upper_bound,
lower_bound,
time_when_changed: now,
time_when_backpressure_detected: now,
}
}
fn current_multiplier(&self) -> u32 {
self.current_multiplier
}
fn increase_delay_multiplier(&mut self) {
self.current_multiplier =
(self.current_multiplier + 1).clamp(self.lower_bound, self.upper_bound);
self.time_when_changed = get_time_now();
log::debug!(
"Increasing sending delay multiplier to: {}",
self.current_multiplier
);
}
fn decrease_delay_multiplier(&mut self) {
self.current_multiplier =
(self.current_multiplier - 1).clamp(self.lower_bound, self.upper_bound);
self.time_when_changed = get_time_now();
log::debug!(
"Decreasing sending delay multiplier to: {}",
self.current_multiplier
);
}
fn record_backpressure_detected(&mut self) {
self.time_when_backpressure_detected = get_time_now();
}
fn not_increased_delay_recently(&self) -> bool {
get_time_now()
> self.time_when_changed + Duration::from_secs(INCREASE_DELAY_MIN_CHANGE_INTERVAL_SECS)
}
fn is_sending_reliable(&self) -> bool {
let now = get_time_now();
let delay_change_interval = Duration::from_secs(DECREASE_DELAY_MIN_CHANGE_INTERVAL_SECS);
let acceptable_time_without_backpressure =
Duration::from_secs(ACCEPTABLE_TIME_WITHOUT_BACKPRESSURE_SECS);
now > self.time_when_backpressure_detected + acceptable_time_without_backpressure
&& now > self.time_when_changed + delay_change_interval
}
}
pub(crate) struct OutQueueControl<R>
where
R: CryptoRng + Rng,
@@ -201,10 +89,6 @@ where
#[cfg(target_arch = "wasm32")]
next_delay: Option<Pin<Box<wasm_timer::Delay>>>,
// To make sure we don't overload the mix_tx channel, we limit the rate we are pushing
// messages.
sending_rate_controller: SendingDelayController,
/// Channel used for sending prepared sphinx packets to `MixTrafficController` that sends them
/// out to the network without any further delays.
mix_tx: BatchMixMessageSender,
@@ -272,10 +156,6 @@ where
ack_key,
sent_notifier,
next_delay: None,
sending_rate_controller: SendingDelayController::new(
MIN_DELAY_MULTIPLIER,
MAX_DELAY_MULTIPLIER,
),
mix_tx,
real_receiver,
our_full_destination,
@@ -332,8 +212,15 @@ where
}
};
if let Err(err) = self.mix_tx.send(vec![next_message]).await {
log::error!("Failed to send - channel closed: {}", err);
// if this one fails, there's no retrying because it means that either:
// - we run out of memory
// - the receiver channel is closed
// in either case there's no recovery and we can only panic
if let Err(err) = self.mix_tx.unbounded_send(vec![next_message]) {
log::warn!(
"Failed to send {} packets (possible process shutdown?)",
err.into_inner().len()
);
}
// JS: Not entirely sure why or how it fixes stuff, but without the yield call,
@@ -347,44 +234,7 @@ where
tokio::task::yield_now().await;
}
fn current_average_message_sending_delay(&self) -> Duration {
self.config.average_message_sending_delay
* self.sending_rate_controller.current_multiplier()
}
fn adjust_current_average_message_sending_delay(&mut self) {
let used_slots = self.mix_tx.max_capacity() - self.mix_tx.capacity();
log::trace!(
"used_slots: {used_slots}, current_multiplier: {}",
self.sending_rate_controller.current_multiplier()
);
// Even just a single used slot is enough to signal backpressure
if used_slots > 0 {
log::trace!("Backpressure detected");
self.sending_rate_controller.record_backpressure_detected();
}
// If the buffer is running out, slow down the sending rate
if self.mix_tx.capacity() == 0
&& self.sending_rate_controller.not_increased_delay_recently()
{
self.sending_rate_controller.increase_delay_multiplier();
}
// Very carefully step up the sending rate in case it seems like we can solidly handle the
// current rate.
if self.sending_rate_controller.is_sending_reliable() {
self.sending_rate_controller.decrease_delay_multiplier();
}
}
fn poll_poisson(&mut self, cx: &mut Context<'_>) -> Poll<Option<StreamMessage>> {
// The average delay could change depending on if backpressure in the downstream channel
// (mix_tx) was detected.
self.adjust_current_average_message_sending_delay();
let avg_delay = self.current_average_message_sending_delay();
if let Some(ref mut next_delay) = &mut self.next_delay {
// it is not yet time to return a message
if next_delay.as_mut().poll(cx).is_pending() {
@@ -393,6 +243,7 @@ where
// we know it's time to send a message, so let's prepare delay for the next one
// Get the `now` by looking at the current `delay` deadline
let avg_delay = self.config.average_message_sending_delay;
let next_poisson_delay = sample_poisson_duration(&mut self.rng, avg_delay);
// The next interval value is `next_poisson_delay` after the one that just
+5 -24
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
use config::NymConfig;
use nymsphinx::params::PacketSize;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use std::path::PathBuf;
@@ -248,8 +247,8 @@ impl<T: NymConfig> Config<T> {
self.debug.disable_main_poisson_packet_distribution
}
pub fn get_use_extended_packet_size(&self) -> Option<ExtendedPacketSize> {
self.debug.use_extended_packet_size.clone()
pub fn get_use_extended_packet_size(&self) -> bool {
self.debug.use_extended_packet_size
}
pub fn get_version(&self) -> &str {
@@ -471,16 +470,8 @@ pub struct Debug {
/// poisson distribution.
pub disable_main_poisson_packet_distribution: bool,
/// Controls whether the sent sphinx packet use a NON-DEFAULT bigger size.
pub use_extended_packet_size: Option<ExtendedPacketSize>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ExtendedPacketSize {
Extended8,
Extended16,
Extended32,
/// Controls whether the sent sphinx packet use the NON-DEFAULT bigger size.
pub use_extended_packet_size: bool,
}
impl Default for Debug {
@@ -497,17 +488,7 @@ impl Default for Debug {
topology_resolution_timeout: DEFAULT_TOPOLOGY_RESOLUTION_TIMEOUT,
disable_loop_cover_traffic_stream: false,
disable_main_poisson_packet_distribution: false,
use_extended_packet_size: None,
}
}
}
impl From<ExtendedPacketSize> for PacketSize {
fn from(size: ExtendedPacketSize) -> PacketSize {
match size {
ExtendedPacketSize::Extended8 => PacketSize::ExtendedPacket8,
ExtendedPacketSize::Extended16 => PacketSize::ExtendedPacket16,
ExtendedPacketSize::Extended32 => PacketSize::ExtendedPacket32,
use_extended_packet_size: false,
}
}
}
+1 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.0"
version = "1.0.2"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
@@ -38,7 +38,6 @@ completions = { path = "../../common/completions" }
credential-storage = { path = "../../common/credential-storage" }
credentials = { path = "../../common/credentials", optional = true }
crypto = { path = "../../common/crypto" }
logging = { path = "../../common/logging"}
gateway-client = { path = "../../common/client-libs/gateway-client" }
gateway-requests = { path = "../../gateway/gateway-requests" }
network-defaults = { path = "../../common/network-defaults" }
+22 -18
View File
@@ -6,7 +6,9 @@ use client_core::client::inbound_messages::{
InputMessage, InputMessageReceiver, InputMessageSender,
};
use client_core::client::key_manager::KeyManager;
use client_core::client::mix_traffic::{BatchMixMessageSender, MixTrafficController};
use client_core::client::mix_traffic::{
BatchMixMessageReceiver, BatchMixMessageSender, MixTrafficController,
};
use client_core::client::real_messages_control;
use client_core::client::real_messages_control::RealMessagesController;
use client_core::client::received_buffer::{
@@ -29,6 +31,7 @@ use log::*;
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::addressing::nodes::NodeIdentity;
use nymsphinx::anonymous_replies::ReplySurb;
use nymsphinx::params::PacketSize;
use nymsphinx::receiver::ReconstructedMessage;
use task::{wait_for_signal, ShutdownListener, ShutdownNotifier};
@@ -100,9 +103,8 @@ impl NymClient {
topology_accessor,
);
if let Some(size) = self.config.get_base().get_use_extended_packet_size() {
log::debug!("Setting extended packet size: {:?}", size);
stream.set_custom_packet_size(size.into());
if self.config.get_base().get_use_extended_packet_size() {
stream.set_custom_packet_size(PacketSize::ExtendedPacket)
}
stream.start_with_shutdown(shutdown);
@@ -130,9 +132,8 @@ impl NymClient {
self.as_mix_recipient(),
);
if let Some(size) = self.config.get_base().get_use_extended_packet_size() {
log::debug!("Setting extended packet size: {:?}", size);
controller_config.set_custom_packet_size(size.into());
if self.config.get_base().get_use_extended_packet_size() {
controller_config.set_custom_packet_size(PacketSize::ExtendedPacket)
}
info!("Starting real traffic stream...");
@@ -262,13 +263,13 @@ impl NymClient {
// over it. Perhaps GatewayClient needs to be thread-shareable or have some channel for
// requests?
fn start_mix_traffic_controller(
&mut self,
mix_rx: BatchMixMessageReceiver,
gateway_client: GatewayClient,
shutdown: ShutdownListener,
) -> BatchMixMessageSender {
) {
info!("Starting mix traffic controller...");
let (mix_traffic_controller, mix_tx) = MixTrafficController::new(gateway_client);
mix_traffic_controller.start_with_shutdown(shutdown);
mix_tx
MixTrafficController::new(mix_rx, gateway_client).start_with_shutdown(shutdown);
}
fn start_websocket_listener(
@@ -355,6 +356,11 @@ impl NymClient {
// rather than creating them here, so say for example the buffer controller would create the request channels
// and would allow anyone to clone the sender channel
// sphinx_message_sender is the transmitter for any component generating sphinx packets that are to be sent to the mixnet
// they are used by cover traffic stream and real traffic stream
// sphinx_message_receiver is the receiver used by MixTrafficController that sends the actual traffic
let (sphinx_message_sender, sphinx_message_receiver) = mpsc::unbounded();
// unwrapped_sphinx_sender is the transmitter of mixnet messages received from the gateway
// unwrapped_sphinx_receiver is the receiver for said messages - used by ReceivedMessagesBuffer
let (mixnet_messages_sender, mixnet_messages_receiver) = mpsc::unbounded();
@@ -391,13 +397,11 @@ impl NymClient {
.start_gateway_client(mixnet_messages_sender, ack_sender, shutdown.subscribe())
.await;
// The sphinx_message_sender is the transmitter for any component generating sphinx packets
// that are to be sent to the mixnet. They are used by cover traffic stream and real
// traffic stream.
// The MixTrafficController then sends the actual traffic
let sphinx_message_sender =
Self::start_mix_traffic_controller(gateway_client, shutdown.subscribe());
self.start_mix_traffic_controller(
sphinx_message_receiver,
gateway_client,
shutdown.subscribe(),
);
self.start_real_traffic_controller(
shared_topology_accessor.clone(),
reply_key_storage,
+22 -1
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
use clap::{crate_version, Parser};
use logging::setup_logging;
use network_defaults::setup_env;
pub mod client;
@@ -35,3 +34,25 @@ fn banner() -> String {
crate_version!()
)
}
fn setup_logging() {
let mut log_builder = pretty_env_logger::formatted_timed_builder();
if let Ok(s) = ::std::env::var("RUST_LOG") {
log_builder.parse_filters(&s);
} else {
// default to 'Info'
log_builder.filter(None, log::LevelFilter::Info);
}
log_builder
.filter_module("hyper", log::LevelFilter::Warn)
.filter_module("tokio_reactor", log::LevelFilter::Warn)
.filter_module("reqwest", log::LevelFilter::Warn)
.filter_module("mio", log::LevelFilter::Warn)
.filter_module("want", log::LevelFilter::Warn)
.filter_module("tungstenite", log::LevelFilter::Warn)
.filter_module("tokio_tungstenite", log::LevelFilter::Warn)
.filter_module("handlebars", log::LevelFilter::Warn)
.filter_module("sled", log::LevelFilter::Warn)
.init();
}
+1 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.0"
version = "1.0.2"
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"
@@ -31,7 +31,6 @@ completions = { path = "../../common/completions" }
credential-storage = { path = "../../common/credential-storage" }
credentials = { path = "../../common/credentials", optional = true }
crypto = { path = "../../common/crypto" }
logging = { path = "../../common/logging"}
gateway-client = { path = "../../common/client-libs/gateway-client" }
gateway-requests = { path = "../../gateway/gateway-requests" }
network-defaults = { path = "../../common/network-defaults" }
+22 -18
View File
@@ -13,7 +13,9 @@ use client_core::client::inbound_messages::{
InputMessage, InputMessageReceiver, InputMessageSender,
};
use client_core::client::key_manager::KeyManager;
use client_core::client::mix_traffic::{BatchMixMessageSender, MixTrafficController};
use client_core::client::mix_traffic::{
BatchMixMessageReceiver, BatchMixMessageSender, MixTrafficController,
};
use client_core::client::real_messages_control::RealMessagesController;
use client_core::client::received_buffer::{
ReceivedBufferRequestReceiver, ReceivedBufferRequestSender, ReceivedMessagesBufferController,
@@ -34,6 +36,7 @@ use gateway_client::{
use log::*;
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::addressing::nodes::NodeIdentity;
use nymsphinx::params::PacketSize;
use task::{wait_for_signal, ShutdownListener, ShutdownNotifier};
pub mod config;
@@ -100,9 +103,8 @@ impl NymClient {
topology_accessor,
);
if let Some(size) = self.config.get_base().get_use_extended_packet_size() {
log::debug!("Setting extended packet size: {:?}", size);
stream.set_custom_packet_size(size.into());
if self.config.get_base().get_use_extended_packet_size() {
stream.set_custom_packet_size(PacketSize::ExtendedPacket)
}
stream.start_with_shutdown(shutdown);
@@ -130,9 +132,8 @@ impl NymClient {
self.as_mix_recipient(),
);
if let Some(size) = self.config.get_base().get_use_extended_packet_size() {
log::debug!("Setting extended packet size: {:?}", size);
controller_config.set_custom_packet_size(size.into());
if self.config.get_base().get_use_extended_packet_size() {
controller_config.set_custom_packet_size(PacketSize::ExtendedPacket)
}
info!("Starting real traffic stream...");
@@ -262,13 +263,13 @@ impl NymClient {
// over it. Perhaps GatewayClient needs to be thread-shareable or have some channel for
// requests?
fn start_mix_traffic_controller(
&mut self,
mix_rx: BatchMixMessageReceiver,
gateway_client: GatewayClient,
shutdown: ShutdownListener,
) -> BatchMixMessageSender {
) {
info!("Starting mix traffic controller...");
let (mix_traffic_controller, mix_tx) = MixTrafficController::new(gateway_client);
mix_traffic_controller.start_with_shutdown(shutdown);
mix_tx
MixTrafficController::new(mix_rx, gateway_client).start_with_shutdown(shutdown);
}
fn start_socks5_listener(
@@ -344,6 +345,11 @@ impl NymClient {
// rather than creating them here, so say for example the buffer controller would create the request channels
// and would allow anyone to clone the sender channel
// sphinx_message_sender is the transmitter for any component generating sphinx packets that are to be sent to the mixnet
// they are used by cover traffic stream and real traffic stream
// sphinx_message_receiver is the receiver used by MixTrafficController that sends the actual traffic
let (sphinx_message_sender, sphinx_message_receiver) = mpsc::unbounded();
// unwrapped_sphinx_sender is the transmitter of mixnet messages received from the gateway
// unwrapped_sphinx_receiver is the receiver for said messages - used by ReceivedMessagesBuffer
let (mixnet_messages_sender, mixnet_messages_receiver) = mpsc::unbounded();
@@ -380,13 +386,11 @@ impl NymClient {
.start_gateway_client(mixnet_messages_sender, ack_sender, shutdown.subscribe())
.await;
// The sphinx_message_sender is the transmitter for any component generating sphinx packets
// that are to be sent to the mixnet. They are used by cover traffic stream and real
// traffic stream.
// The MixTrafficController then sends the actual traffic
let sphinx_message_sender =
Self::start_mix_traffic_controller(gateway_client, shutdown.subscribe());
self.start_mix_traffic_controller(
sphinx_message_receiver,
gateway_client,
shutdown.subscribe(),
);
self.start_real_traffic_controller(
shared_topology_accessor.clone(),
reply_key_storage,
+20 -1
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
use clap::{crate_version, Parser};
use logging::setup_logging;
use network_defaults::setup_env;
pub mod client;
@@ -35,3 +34,23 @@ fn banner() -> String {
crate_version!()
)
}
fn setup_logging() {
let mut log_builder = pretty_env_logger::formatted_timed_builder();
if let Ok(s) = ::std::env::var("RUST_LOG") {
log_builder.parse_filters(&s);
} else {
// default to 'Info'
log_builder.filter(None, log::LevelFilter::Info);
}
log_builder
.filter_module("hyper", log::LevelFilter::Warn)
.filter_module("tokio_reactor", log::LevelFilter::Warn)
.filter_module("reqwest", log::LevelFilter::Warn)
.filter_module("mio", log::LevelFilter::Warn)
.filter_module("want", log::LevelFilter::Warn)
.filter_module("tungstenite", log::LevelFilter::Warn)
.filter_module("tokio_tungstenite", log::LevelFilter::Warn)
.init();
}
+3 -8
View File
@@ -4,7 +4,7 @@
// due to expansion of #[wasm_bindgen] macro on `Debug` Config struct
#![allow(clippy::drop_non_drop)]
use client_core::config::{Debug as ConfigDebug, ExtendedPacketSize, GatewayEndpoint};
use client_core::config::{Debug as ConfigDebug, GatewayEndpoint};
use std::time::Duration;
use url::Url;
use wasm_bindgen::prelude::*;
@@ -107,11 +107,6 @@ pub struct Debug {
impl From<Debug> for ConfigDebug {
fn from(debug: Debug) -> Self {
// For now we just always use the (older) 32kb extended size
let use_extended_packet_size = debug
.use_extended_packet_size
.then(|| ExtendedPacketSize::Extended32);
ConfigDebug {
average_packet_delay: Duration::from_millis(debug.average_packet_delay_ms),
average_ack_delay: Duration::from_millis(debug.average_ack_delay_ms),
@@ -131,7 +126,7 @@ impl From<Debug> for ConfigDebug {
disable_loop_cover_traffic_stream: debug.disable_loop_cover_traffic_stream,
disable_main_poisson_packet_distribution: debug
.disable_main_poisson_packet_distribution,
use_extended_packet_size,
use_extended_packet_size: debug.use_extended_packet_size,
}
}
}
@@ -153,7 +148,7 @@ impl From<ConfigDebug> for Debug {
disable_loop_cover_traffic_stream: debug.disable_loop_cover_traffic_stream,
disable_main_poisson_packet_distribution: debug
.disable_main_poisson_packet_distribution,
use_extended_packet_size: debug.use_extended_packet_size.is_some(),
use_extended_packet_size: debug.use_extended_packet_size,
}
}
}
+18 -15
View File
@@ -6,7 +6,7 @@ use client_core::client::{
cover_traffic_stream::LoopCoverTrafficStream,
inbound_messages::{InputMessage, InputMessageReceiver, InputMessageSender},
key_manager::KeyManager,
mix_traffic::{BatchMixMessageSender, MixTrafficController},
mix_traffic::{BatchMixMessageReceiver, BatchMixMessageSender, MixTrafficController},
real_messages_control::{self, RealMessagesController},
received_buffer::{
ReceivedBufferMessage, ReceivedBufferRequestReceiver, ReceivedBufferRequestSender,
@@ -22,6 +22,7 @@ use gateway_client::{
MixnetMessageSender,
};
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::params::PacketSize;
use rand::rngs::OsRng;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::spawn_local;
@@ -109,8 +110,8 @@ impl NymClient {
topology_accessor,
);
if let Some(size) = &self.config.debug.use_extended_packet_size {
stream.set_custom_packet_size(size.clone().into());
if self.config.debug.use_extended_packet_size {
stream.set_custom_packet_size(PacketSize::ExtendedPacket)
}
stream.start();
@@ -134,8 +135,8 @@ impl NymClient {
self.as_mix_recipient(),
);
if let Some(size) = &self.config.debug.use_extended_packet_size {
controller_config.set_custom_packet_size(size.clone().into());
if self.config.debug.use_extended_packet_size {
controller_config.set_custom_packet_size(PacketSize::ExtendedPacket)
}
console_log!("Starting real traffic stream...");
@@ -252,11 +253,13 @@ impl NymClient {
// TODO: if we want to send control messages to gateway_client, this CAN'T take the ownership
// over it. Perhaps GatewayClient needs to be thread-shareable or have some channel for
// requests?
fn start_mix_traffic_controller(gateway_client: GatewayClient) -> BatchMixMessageSender {
fn start_mix_traffic_controller(
&mut self,
mix_rx: BatchMixMessageReceiver,
gateway_client: GatewayClient,
) {
console_log!("Starting mix traffic controller...");
let (mix_traffic_controller, mix_tx) = MixTrafficController::new(gateway_client);
mix_traffic_controller.start();
mix_tx
MixTrafficController::new(mix_rx, gateway_client).start();
}
// TODO: this procedure is extremely overcomplicated, because it's based off native client's behaviour
@@ -304,6 +307,11 @@ impl NymClient {
// rather than creating them here, so say for example the buffer controller would create the request channels
// and would allow anyone to clone the sender channel
// sphinx_message_sender is the transmitter for any component generating sphinx packets that are to be sent to the mixnet
// they are used by cover traffic stream and real traffic stream
// sphinx_message_receiver is the receiver used by MixTrafficController that sends the actual traffic
let (sphinx_message_sender, sphinx_message_receiver) = mpsc::unbounded();
// unwrapped_sphinx_sender is the transmitter of mixnet messages received from the gateway
// unwrapped_sphinx_receiver is the receiver for said messages - used by ReceivedMessagesBuffer
let (mixnet_messages_sender, mixnet_messages_receiver) = mpsc::unbounded();
@@ -331,12 +339,7 @@ impl NymClient {
.start_gateway_client(mixnet_messages_sender, ack_sender)
.await;
// The sphinx_message_sender is the transmitter for any component generating sphinx packets
// that are to be sent to the mixnet. They are used by cover traffic stream and real
// traffic stream.
// The MixTrafficController then sends the actual traffic
let sphinx_message_sender = Self::start_mix_traffic_controller(gateway_client);
self.start_mix_traffic_controller(sphinx_message_receiver, gateway_client);
self.start_real_traffic_controller(
shared_topology_accessor.clone(),
ack_receiver,
@@ -62,19 +62,9 @@ impl PacketRouter {
trace!("routing regular packet");
received_messages.push(received_packet);
} else if received_packet.len()
== PacketSize::ExtendedPacket8.plaintext_size() - ack_overhead
== PacketSize::ExtendedPacket.plaintext_size() - ack_overhead
{
trace!("routing extended8 packet");
received_messages.push(received_packet);
} else if received_packet.len()
== PacketSize::ExtendedPacket16.plaintext_size() - ack_overhead
{
trace!("routing extended16 packet");
received_messages.push(received_packet);
} else if received_packet.len()
== PacketSize::ExtendedPacket32.plaintext_size() - ack_overhead
{
trace!("routing extended32 packet");
trace!("routing extended packet");
received_messages.push(received_packet);
} else {
// this can happen if other clients are not padding their messages
@@ -23,7 +23,6 @@ pub struct Config {
maximum_reconnection_backoff: Duration,
initial_connection_timeout: Duration,
maximum_connection_buffer_size: usize,
use_legacy_version: bool,
}
impl Config {
@@ -32,14 +31,12 @@ impl Config {
maximum_reconnection_backoff: Duration,
initial_connection_timeout: Duration,
maximum_connection_buffer_size: usize,
use_legacy_version: bool,
) -> Self {
Config {
initial_reconnection_backoff,
maximum_reconnection_backoff,
initial_connection_timeout,
maximum_connection_buffer_size,
use_legacy_version,
}
}
}
@@ -204,8 +201,7 @@ impl SendWithoutResponse for Client {
packet_mode: PacketMode,
) -> io::Result<()> {
trace!("Sending packet to {:?}", address);
let framed_packet =
FramedSphinxPacket::new(packet, packet_mode, self.config.use_legacy_version);
let framed_packet = FramedSphinxPacket::new(packet, packet_mode);
if let Some(sender) = self.conn_new.get_mut(&address) {
if let Err(err) = sender.channel.try_send(framed_packet) {
@@ -263,7 +259,6 @@ mod tests {
maximum_reconnection_backoff: Duration::from_millis(300_000),
initial_connection_timeout: Duration::from_millis(1_500),
maximum_connection_buffer_size: 128,
use_legacy_version: false,
})
}
@@ -24,14 +24,12 @@ impl PacketForwarder {
maximum_reconnection_backoff: Duration,
initial_connection_timeout: Duration,
maximum_connection_buffer_size: usize,
use_legacy_version: bool,
) -> (PacketForwarder, MixForwardingSender) {
let client_config = Config::new(
initial_reconnection_backoff,
maximum_reconnection_backoff,
initial_connection_timeout,
maximum_connection_buffer_size,
use_legacy_version,
);
let (packet_sender, packet_receiver) = mpsc::unbounded();
@@ -13,7 +13,6 @@ colored = "2.0"
cw3 = "0.13.1"
mixnet-contract-common = { path= "../../cosmwasm-smart-contracts/mixnet-contract" }
vesting-contract-common = { path= "../../cosmwasm-smart-contracts/vesting-contract" }
contracts-common = { path = "../../cosmwasm-smart-contracts/contracts-common" }
coconut-bandwidth-contract-common = { path= "../../cosmwasm-smart-contracts/coconut-bandwidth-contract" }
multisig-contract-common = { path = "../../cosmwasm-smart-contracts/multisig-contract" }
vesting-contract = { path = "../../../contracts/vesting" }
@@ -15,12 +15,14 @@ use cosmrs::rpc::query::Query;
use cosmrs::rpc::Error as TendermintRpcError;
use cosmrs::rpc::HttpClientUrl;
use cosmrs::tx::Msg;
use cosmwasm_std::Uint128;
use execute::execute;
use network_defaults::{ChainDetails, NymNetworkDetails};
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::time::SystemTime;
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
use vesting_contract_common::QueryMsg as VestingQueryMsg;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
@@ -45,7 +47,6 @@ pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
use mixnet_contract_common::MixId;
pub use signing_client::Client as SigningNymdClient;
pub use traits::{VestingQueryClient, VestingSigningClient};
use vesting_contract_common::PledgeCap;
pub mod coin;
pub mod cosmwasm_client;
@@ -481,6 +482,16 @@ impl<C> NymdClient<C> {
self.client.get_total_supply().await
}
pub async fn vesting_get_locked_pledge_cap(&self) -> Result<Uint128, NymdError>
where
C: CosmWasmClient + Sync,
{
let request = VestingQueryMsg::GetLockedPledgeCap {};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NymdError>
where
C: SigningCosmWasmClient + Sync,
@@ -726,16 +737,12 @@ impl<C> NymdClient<C> {
#[execute("vesting")]
fn _vesting_update_locked_pledge_cap(
&self,
address: String,
cap: PledgeCap,
amount: Uint128,
fee: Option<Fee>,
) -> (VestingExecuteMsg, Option<Fee>)
where
C: SigningCosmWasmClient + Sync,
{
(
VestingExecuteMsg::UpdateLockedPledgeCap { address, cap },
fee,
)
(VestingExecuteMsg::UpdateLockedPledgeCap { amount }, fee)
}
}
@@ -6,10 +6,8 @@ pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::error::NymdError;
use crate::nymd::NymdClient;
use async_trait::async_trait;
use contracts_common::ContractBuildInformation;
use cosmwasm_std::{Coin as CosmWasmCoin, Timestamp};
use mixnet_contract_common::MixId;
use serde::Deserialize;
use vesting_contract::vesting::Account;
use vesting_contract_common::{
messages::QueryMsg as VestingQueryMsg, AllDelegationsResponse, DelegationTimesResponse,
@@ -18,15 +16,6 @@ use vesting_contract_common::{
#[async_trait]
pub trait VestingQueryClient {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError>
where
for<'a> T: Deserialize<'a>;
async fn get_vesting_contract_version(&self) -> Result<ContractBuildInformation, NymdError> {
self.query_vesting_contract(VestingQueryMsg::GetContractVersion {})
.await
}
async fn locked_coins(
&self,
address: &str,
@@ -118,15 +107,6 @@ pub trait VestingQueryClient {
#[async_trait]
impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError>
where
for<'a> T: Deserialize<'a>,
{
self.client
.query_contract_smart(self.vesting_contract_address(), &query)
.await
}
async fn locked_coins(
&self,
vesting_account_address: &str,
@@ -9,7 +9,6 @@ use async_trait::async_trait;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use mixnet_contract_common::{Gateway, MixId, MixNode};
use vesting_contract_common::messages::{ExecuteMsg as VestingExecuteMsg, VestingSpecification};
use vesting_contract_common::PledgeCap;
#[async_trait]
pub trait VestingSigningClient {
@@ -106,7 +105,6 @@ pub trait VestingSigningClient {
staking_address: Option<String>,
vesting_spec: Option<VestingSpecification>,
amount: Coin,
cap: Option<PledgeCap>,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
}
@@ -384,7 +382,6 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
staking_address: Option<String>,
vesting_spec: Option<VestingSpecification>,
amount: Coin,
cap: Option<PledgeCap>,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
@@ -392,7 +389,6 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner_address: owner_address.to_string(),
staking_address,
vesting_spec,
cap,
};
self.client
.execute(
@@ -1,5 +1,4 @@
use thiserror::Error;
use validator_api_requests::models::RequestError;
#[derive(Error, Debug)]
pub enum ValidatorAPIError {
@@ -11,7 +10,4 @@ pub enum ValidatorAPIError {
#[error("Request failed with error message - {0}")]
GenericRequestFailure(String),
#[error("The validator API has failed to resolve our request. It returned status code {status} and additional error message: {}", error.message())]
ApiRequestFailure { status: u16, error: RequestError },
}
@@ -5,7 +5,6 @@ use crate::validator_api::error::ValidatorAPIError;
use crate::validator_api::routes::{CORE_STATUS_COUNT, SINCE_ARG};
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::{GatewayBond, IdentityKeyRef, MixId};
use reqwest::Response;
use serde::{Deserialize, Serialize};
use url::Url;
use validator_api_requests::coconut::{
@@ -13,10 +12,9 @@ use validator_api_requests::coconut::{
VerifyCredentialBody, VerifyCredentialResponse,
};
use validator_api_requests::models::{
GatewayCoreStatusResponse, GatewayStatusReportResponse, GatewayUptimeHistoryResponse,
InclusionProbabilityResponse, MixNodeBondAnnotated, MixnodeCoreStatusResponse,
MixnodeStatusReportResponse, MixnodeStatusResponse, MixnodeUptimeHistoryResponse, RequestError,
RewardEstimationResponse, StakeSaturationResponse, UptimeResponse,
GatewayCoreStatusResponse, InclusionProbabilityResponse, MixNodeBondAnnotated,
MixnodeCoreStatusResponse, MixnodeStatusResponse, RewardEstimationResponse,
StakeSaturationResponse, UptimeResponse,
};
pub mod error;
@@ -49,19 +47,6 @@ impl Client {
&self.url
}
async fn send_get_request<K, V>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<Response, ValidatorAPIError>
where
K: AsRef<str>,
V: AsRef<str>,
{
let url = create_api_url(&self.url, path, params);
Ok(self.reqwest_client.get(url).send().await?)
}
async fn query_validator_api<T, K, V>(
&self,
path: PathSegments<'_>,
@@ -72,36 +57,8 @@ impl Client {
K: AsRef<str>,
V: AsRef<str>,
{
let res = self.send_get_request(path, params).await?;
if res.status().is_success() {
Ok(res.json().await?)
} else {
Err(ValidatorAPIError::GenericRequestFailure(res.text().await?))
}
}
// This works for endpoints returning Result<Json<T>, ErrorResponse>
async fn query_validator_api_fallible<T, K, V>(
&self,
path: PathSegments<'_>,
params: Params<'_, K, V>,
) -> Result<T, ValidatorAPIError>
where
for<'a> T: Deserialize<'a>,
K: AsRef<str>,
V: AsRef<str>,
{
let res = self.send_get_request(path, params).await?;
let status = res.status();
if res.status().is_success() {
Ok(res.json().await?)
} else {
let request_error: RequestError = res.json().await?;
Err(ValidatorAPIError::ApiRequestFailure {
status: status.as_u16(),
error: request_error,
})
}
let url = create_api_url(&self.url, path, params);
Ok(self.reqwest_client.get(url).send().await?.json().await?)
}
async fn post_validator_api<B, T, K, V>(
@@ -178,74 +135,6 @@ impl Client {
.await
}
pub async fn get_mixnode_report(
&self,
mix_id: MixId,
) -> Result<MixnodeStatusReportResponse, ValidatorAPIError> {
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS,
routes::MIXNODE,
&mix_id.to_string(),
routes::REPORT,
],
NO_PARAMS,
)
.await
}
pub async fn get_gateway_report(
&self,
identity: IdentityKeyRef<'_>,
) -> Result<GatewayStatusReportResponse, ValidatorAPIError> {
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS,
routes::GATEWAY,
identity,
routes::REPORT,
],
NO_PARAMS,
)
.await
}
pub async fn get_mixnode_history(
&self,
mix_id: MixId,
) -> Result<MixnodeUptimeHistoryResponse, ValidatorAPIError> {
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS,
routes::MIXNODE,
&mix_id.to_string(),
routes::HISTORY,
],
NO_PARAMS,
)
.await
}
pub async fn get_gateway_history(
&self,
identity: IdentityKeyRef<'_>,
) -> Result<GatewayUptimeHistoryResponse, ValidatorAPIError> {
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS,
routes::GATEWAY,
identity,
routes::HISTORY,
],
NO_PARAMS,
)
.await
}
pub async fn get_rewarded_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeBondAnnotated>, ValidatorAPIError> {
@@ -345,7 +234,7 @@ impl Client {
&self,
mix_id: MixId,
) -> Result<RewardEstimationResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -362,7 +251,7 @@ impl Client {
&self,
mix_id: MixId,
) -> Result<StakeSaturationResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -379,7 +268,7 @@ impl Client {
&self,
mix_id: MixId,
) -> Result<InclusionProbabilityResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -396,7 +285,7 @@ impl Client {
&self,
mix_id: MixId,
) -> Result<UptimeResponse, ValidatorAPIError> {
self.query_validator_api_fallible(
self.query_validator_api(
&[
routes::API_VERSION,
routes::STATUS_ROUTES,
@@ -10,6 +10,7 @@ pub const GATEWAYS: &str = "gateways";
pub const DETAILED: &str = "detailed";
pub const ACTIVE: &str = "active";
pub const REWARDED: &str = "rewarded";
pub const COCONUT_ROUTES: &str = "coconut";
pub const BANDWIDTH: &str = "bandwidth";
@@ -27,8 +28,6 @@ pub const CORE_STATUS_COUNT: &str = "core-status-count";
pub const SINCE_ARG: &str = "since";
pub const STATUS: &str = "status";
pub const REPORT: &str = "report";
pub const HISTORY: &str = "history";
pub const REWARD_ESTIMATION: &str = "reward-estimation";
pub const AVG_UPTIME: &str = "avg_uptime";
pub const STAKE_SATURATION: &str = "stake-saturation";
@@ -12,7 +12,6 @@ use validator_client::nymd::AccountId;
use validator_client::nymd::VestingSigningClient;
use validator_client::nymd::{CosmosCoin, Denom};
use vesting_contract_common::messages::VestingSpecification;
use vesting_contract_common::PledgeCap;
use crate::context::SigningClient;
@@ -35,12 +34,6 @@ pub struct Args {
#[clap(long)]
pub staking_address: Option<String>,
#[clap(
long,
help = "Pledge cap as either absolute uNYM value or percentage, floats need to be in the 0.0 to 1.0 range and will be parsed as percentages, integers will be parsed as uNYM"
)]
pub pledge_cap: Option<PledgeCap>,
}
pub async fn create(args: Args, client: SigningClient, network_details: &NymNetworkDetails) {
@@ -62,7 +55,6 @@ pub async fn create(args: Args, client: SigningClient, network_details: &NymNetw
args.staking_address,
Some(vesting),
coin.into(),
args.pledge_cap,
None,
)
.await
@@ -10,7 +10,4 @@ edition = "2021"
cosmwasm-std = "1.0.0"
serde = { version = "1.0", features = ["derive"] }
schemars = "0.8"
thiserror = "1"
[dev-dependencies]
serde_json = "1.0.0"
thiserror = "1"
@@ -152,47 +152,3 @@ pub struct ContractBuildInformation {
/// Provides the rustc version that was used for the build, for example `1.52.0-nightly`.
pub rustc_version: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn percent_serde() {
let valid_value = Percent::from_percentage_value(80).unwrap();
let serialized = serde_json::to_string(&valid_value).unwrap();
let deserialized: Percent = serde_json::from_str(&serialized).unwrap();
assert_eq!(valid_value, deserialized);
let invalid_values = vec!["\"42\"", "\"1.1\"", "\"1.00000001\"", "\"foomp\"", "\"1a\""];
for invalid_value in invalid_values {
assert!(serde_json::from_str::<'_, Percent>(invalid_value).is_err())
}
assert_eq!(
serde_json::from_str::<'_, Percent>("\"0.95\"").unwrap(),
Percent::from_percentage_value(95).unwrap()
)
}
#[test]
fn percent_to_absolute_integer() {
let p = serde_json::from_str::<'_, Percent>("\"0.0001\"").unwrap();
assert_eq!(p.round_to_integer(), 0);
let p = serde_json::from_str::<'_, Percent>("\"0.0099\"").unwrap();
assert_eq!(p.round_to_integer(), 0);
let p = serde_json::from_str::<'_, Percent>("\"0.0199\"").unwrap();
assert_eq!(p.round_to_integer(), 1);
let p = serde_json::from_str::<'_, Percent>("\"0.45123\"").unwrap();
assert_eq!(p.round_to_integer(), 45);
let p = serde_json::from_str::<'_, Percent>("\"0.999999999\"").unwrap();
assert_eq!(p.round_to_integer(), 99);
let p = serde_json::from_str::<'_, Percent>("\"1.00\"").unwrap();
assert_eq!(p.round_to_integer(), 100);
}
}
@@ -13,6 +13,9 @@ pub enum MixnetContractError {
source: cosmwasm_std::StdError,
},
#[error("Provided percent value is greater than 100%")]
InvalidPercent,
#[error("Attempted to subtract decimals with overflow ({minuend}.sub({subtrahend}))")]
OverflowDecimalSubtraction {
minuend: Decimal,
@@ -133,4 +136,7 @@ pub enum MixnetContractError {
#[error("Mixnode {mix_id} appears multiple times in the provided rewarded set update!")]
DuplicateRewardedSetNode { mix_id: MixId },
#[error("Migration from the old contract is currently in progress. The transaction is temporarily disabled until that is finished")]
MigrationInProgress,
}
@@ -73,9 +73,6 @@ pub struct Interval {
// TODO add a better TS type generation
#[cfg_attr(feature = "generate-ts", ts(type = "string"))]
#[serde(with = "string_rfc3339_offset_date_time")]
// note: the `ts-rs failed to parse this attribute. It will be ignored.` warning emitted during
// compilation is fine (I guess). `ts-rs` can't handle `with` serde attribute, but that's okay
// since we explicitly specified this field should correspond to typescript's string
current_epoch_start: OffsetDateTime,
current_epoch_id: EpochId,
#[cfg_attr(feature = "generate-ts", ts(type = "{ secs: number; nanos: number; }"))]
@@ -8,7 +8,7 @@ use crate::reward_params::{
};
use crate::{delegation, ContractStateParams, MixId, Percent};
use crate::{Gateway, IdentityKey, MixNode};
use cosmwasm_std::Decimal;
use cosmwasm_std::{Addr, Coin, Decimal};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::time::Duration;
@@ -18,6 +18,7 @@ use std::time::Duration;
pub struct InstantiateMsg {
pub rewarding_validator_address: String,
pub vesting_contract_address: String,
pub v1_mixnet_contract_address: String,
pub rewarding_denom: String,
pub epochs_in_interval: u32,
@@ -68,6 +69,80 @@ impl InitialRewardingParams {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
// special, first-time migration:
#[serde(rename = "m1")]
SaveOperator {
#[serde(rename = "a1")]
host: String,
#[serde(rename = "a2")]
mix_port: u16,
#[serde(rename = "a3")]
verloc_port: u16,
#[serde(rename = "a4")]
http_api_port: u16,
#[serde(rename = "a5")]
sphinx_key: String,
#[serde(rename = "a6")]
identity_key: IdentityKey,
#[serde(rename = "a7")]
version: String,
#[serde(rename = "a8")]
pledge_amount: Coin,
#[serde(rename = "a9")]
owner: Addr,
#[serde(rename = "a10")]
block_height: u64,
#[serde(rename = "a11")]
profit_margin_percent: u8,
#[serde(rename = "a12")]
proxy: Option<Addr>,
},
#[serde(rename = "m2")]
SaveDelegation {
#[serde(rename = "a1")]
owner: Addr,
#[serde(rename = "a2")]
mix_id: u32,
#[serde(rename = "a3")]
amount: Coin,
#[serde(rename = "a4")]
block_height: u64,
#[serde(rename = "a5")]
proxy: Option<Addr>,
},
#[serde(rename = "m3")]
SaveGateway {
#[serde(rename = "a1")]
pledge_amount: Coin,
#[serde(rename = "a2")]
owner: Addr,
#[serde(rename = "a3")]
block_height: u64,
#[serde(rename = "a4")]
gateway: Gateway,
#[serde(rename = "a5")]
proxy: Option<Addr>,
},
// state/sys-params-related
UpdateRewardingValidatorAddress {
address: String,
@@ -268,6 +343,7 @@ impl ExecuteMsg {
ExecuteMsg::TestingResolveAllPendingEvents { .. } => {
"resolving all pending events".into()
}
_ => unimplemented!("migration-specific messages are not supported by this"),
}
}
}
@@ -169,10 +169,6 @@ impl RewardingParams {
self.interval.staking_supply = staking_supply;
}
if let Some(staking_supply_scale_factor) = updates.staking_supply_scale_factor {
self.interval.staking_supply_scale_factor = staking_supply_scale_factor
}
if let Some(sybil_resistance_percent) = updates.sybil_resistance_percent {
self.interval.sybil_resistance = sybil_resistance_percent;
}
@@ -244,9 +240,6 @@ pub struct IntervalRewardingParamsUpdate {
#[cfg_attr(feature = "generate-ts", ts(type = "string | null"))]
pub staking_supply: Option<Decimal>,
#[cfg_attr(feature = "generate-ts", ts(type = "string | null"))]
pub staking_supply_scale_factor: Option<Percent>,
#[cfg_attr(feature = "generate-ts", ts(type = "string | null"))]
pub sybil_resistance_percent: Option<Percent>,
@@ -264,7 +257,6 @@ impl IntervalRewardingParamsUpdate {
// essentially at least a single field has to be a `Some`
self.reward_pool.is_some()
|| self.staking_supply.is_some()
|| self.staking_supply_scale_factor.is_some()
|| self.sybil_resistance_percent.is_some()
|| self.active_set_work_factor.is_some()
|| self.interval_pool_emission.is_some()
@@ -1,7 +1,6 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use contracts_common::truncate_decimal;
use cosmwasm_std::{Coin, Decimal, Uint128};
/// Truncates all decimal points so that the reward would fit in a `Coin` and so that we would
@@ -18,3 +17,7 @@ pub fn truncate_reward(reward: Decimal, denom: impl Into<String>) -> Coin {
pub fn truncate_reward_amount(reward: Decimal) -> Uint128 {
truncate_decimal(reward)
}
pub fn truncate_decimal(amount: Decimal) -> Uint128 {
amount * Uint128::new(1)
}
@@ -2,12 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
use crate::error::MixnetContractError;
use crate::rewarding::helpers::truncate_decimal;
use crate::{Layer, RewardedSetNodeStatus};
use cosmwasm_std::Addr;
use cosmwasm_std::Coin;
use cosmwasm_std::{Addr, Uint128};
use cosmwasm_std::{Coin, Decimal};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::ops::Index;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize};
use std::fmt::{self, Display, Formatter};
use std::ops::{Index, Mul};
// type aliases for better reasoning about available data
pub type IdentityKey = String;
@@ -122,3 +125,48 @@ pub struct PagedRewardedSetResponse {
pub nodes: Vec<(MixId, RewardedSetNodeStatus)>,
pub start_next_after: Option<MixId>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn percent_serde() {
let valid_value = Percent::from_percentage_value(80).unwrap();
let serialized = serde_json::to_string(&valid_value).unwrap();
println!("{}", serialized);
let deserialized: Percent = serde_json::from_str(&serialized).unwrap();
assert_eq!(valid_value, deserialized);
let invalid_values = vec!["\"42\"", "\"1.1\"", "\"1.00000001\"", "\"foomp\"", "\"1a\""];
for invalid_value in invalid_values {
assert!(serde_json::from_str::<'_, Percent>(invalid_value).is_err())
}
assert_eq!(
serde_json::from_str::<'_, Percent>("\"0.95\"").unwrap(),
Percent::from_percentage_value(95).unwrap()
)
}
#[test]
fn percent_to_absolute_integer() {
let p = serde_json::from_str::<'_, Percent>("\"0.0001\"").unwrap();
assert_eq!(p.round_to_integer(), 0);
let p = serde_json::from_str::<'_, Percent>("\"0.0099\"").unwrap();
assert_eq!(p.round_to_integer(), 0);
let p = serde_json::from_str::<'_, Percent>("\"0.0199\"").unwrap();
assert_eq!(p.round_to_integer(), 1);
let p = serde_json::from_str::<'_, Percent>("\"0.45123\"").unwrap();
assert_eq!(p.round_to_integer(), 45);
let p = serde_json::from_str::<'_, Percent>("\"0.999999999\"").unwrap();
assert_eq!(p.round_to_integer(), 99);
let p = serde_json::from_str::<'_, Percent>("\"1.00\"").unwrap();
assert_eq!(p.round_to_integer(), 100);
}
}
@@ -6,7 +6,6 @@ edition = "2021"
[dependencies]
cosmwasm-std = "1.0.0"
mixnet-contract-common = { path = "../mixnet-contract" }
contracts-common = { path = "../contracts-common" }
serde = { version = "1.0", features = ["derive"] }
schemars = "0.8"
ts-rs = {version = "6.1.2", optional = true}
@@ -1,8 +1,5 @@
use std::str::FromStr;
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use contracts_common::Percent;
use cosmwasm_std::{Addr, Coin, Timestamp, Uint128};
use mixnet_contract_common::MixId;
use schemars::JsonSchema;
@@ -45,34 +42,6 @@ impl PledgeData {
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub enum PledgeCap {
Percent(Percent),
Absolute(Uint128), // This has to be in unym
}
impl FromStr for PledgeCap {
type Err = String;
fn from_str(cap: &str) -> Result<Self, Self::Err> {
let cap = cap.replace('_', "").replace(',', ".");
match Percent::from_str(&cap) {
Ok(p) => Ok(PledgeCap::Percent(p)),
Err(_) => match cap.parse::<u128>() {
Ok(i) => Ok(PledgeCap::Absolute(Uint128::from(i))),
Err(_e) => Err(format!("Could not parse {} as Percent or Uint128", cap)),
},
}
}
}
impl Default for PledgeCap {
fn default() -> Self {
PledgeCap::Percent(Percent::from_percentage_value(10).expect("This can never fail!"))
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct OriginalVestingResponse {
pub amount: Coin,
@@ -129,32 +98,3 @@ pub struct AllDelegationsResponse {
pub delegations: Vec<VestingDelegation>,
pub start_next_after: Option<(u32, MixId, u64)>,
}
#[cfg(test)]
mod test {
use contracts_common::Percent;
use cosmwasm_std::Uint128;
use std::str::FromStr;
use crate::PledgeCap;
#[test]
fn test_pledge_cap_from_str() {
assert_eq!(
PledgeCap::from_str("0.1").unwrap(),
PledgeCap::Percent(Percent::from_percentage_value(10).unwrap())
);
assert_eq!(
PledgeCap::from_str("0,1").unwrap(),
PledgeCap::Percent(Percent::from_percentage_value(10).unwrap())
);
assert_eq!(
PledgeCap::from_str("100_000_000_000").unwrap(),
PledgeCap::Absolute(Uint128::new(100_000_000_000))
);
assert_eq!(
PledgeCap::from_str("100000000000").unwrap(),
PledgeCap::Absolute(Uint128::new(100_000_000_000))
);
}
}
@@ -1,4 +1,4 @@
use cosmwasm_std::{Coin, Timestamp};
use cosmwasm_std::{Coin, Timestamp, Uint128};
use mixnet_contract_common::{
mixnode::{MixNodeConfigUpdate, MixNodeCostParams},
Gateway, MixId, MixNode,
@@ -6,8 +6,6 @@ use mixnet_contract_common::{
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::PledgeCap;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct InitMsg {
@@ -85,7 +83,6 @@ pub enum ExecuteMsg {
owner_address: String,
staking_address: Option<String>,
vesting_spec: Option<VestingSpecification>,
cap: Option<PledgeCap>,
},
WithdrawVestedCoins {
amount: Coin,
@@ -123,8 +120,7 @@ pub enum ExecuteMsg {
to_address: Option<String>,
},
UpdateLockedPledgeCap {
address: String,
cap: PledgeCap,
amount: Uint128,
},
}
@@ -160,7 +156,6 @@ impl ExecuteMsg {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
GetContractVersion {},
LockedCoins {
vesting_account_address: String,
block_time: Option<Timestamp>,
@@ -206,6 +201,7 @@ pub enum QueryMsg {
GetCurrentVestingPeriod {
address: String,
},
GetLockedPledgeCap {},
GetDelegationTimes {
address: String,
mix_id: MixId,
-10
View File
@@ -1,10 +0,0 @@
[package]
name = "logging"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.0"
pretty_env_logger = "0.4.0"
-25
View File
@@ -1,25 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
// I'd argue we should start transitioning from `log` to `tracing`
pub fn setup_logging() {
let mut log_builder = pretty_env_logger::formatted_timed_builder();
if let Ok(s) = ::std::env::var("RUST_LOG") {
log_builder.parse_filters(&s);
} else {
// default to 'Info'
log_builder.filter(None, log::LevelFilter::Info);
}
log_builder
.filter_module("hyper", log::LevelFilter::Warn)
.filter_module("tokio_reactor", log::LevelFilter::Warn)
.filter_module("reqwest", log::LevelFilter::Warn)
.filter_module("mio", log::LevelFilter::Warn)
.filter_module("want", log::LevelFilter::Warn)
.filter_module("tungstenite", log::LevelFilter::Warn)
.filter_module("tokio_tungstenite", log::LevelFilter::Warn)
.filter_module("handlebars", log::LevelFilter::Warn)
.filter_module("sled", log::LevelFilter::Warn)
.init();
}
@@ -116,10 +116,7 @@ impl SphinxPacketProcessor {
trace!("received an ack packet!");
Ok((None, data))
}
PacketSize::RegularPacket
| PacketSize::ExtendedPacket8
| PacketSize::ExtendedPacket16
| PacketSize::ExtendedPacket32 => {
PacketSize::RegularPacket | PacketSize::ExtendedPacket => {
trace!("received a normal packet!");
let (ack_data, message) = self.split_hop_data_into_ack_and_message(data)?;
let (ack_first_hop, ack_packet) = SurbAck::try_recover_first_hop_packet(&ack_data)?;
+1 -1
View File
@@ -10,7 +10,7 @@ pub const MIX_DENOM: DenomDetails = DenomDetails::new("unym", "nym", 6);
pub const STAKE_DENOM: DenomDetails = DenomDetails::new("unyx", "nyx", 6);
pub(crate) const MIXNET_CONTRACT_ADDRESS: &str =
"n17srjznxl9dvzdkpwpw24gg668wc73val88a6m5ajg6ankwvz9wtst0cznr";
"n14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9sjyvg3g";
pub(crate) const VESTING_CONTRACT_ADDRESS: &str =
"n1nc5tatafv6eyq7llkr2gv50ff9e22mnf70qgjlv737ktmt4eswrq73f2nw";
pub(crate) const BANDWIDTH_CLAIM_CONTRACT_ADDRESS: &str =
-1
View File
@@ -1 +0,0 @@
This project was partially funded through the NGI0 PET Fund, a fund established by NL.net with financial support from the European Commission's NGI programme, under the aegis of DG Communications Networks, Content and Technology under grant agreement No 825310.
+2 -4
View File
@@ -25,10 +25,8 @@ impl Display for MixPacketFormattingError {
InvalidPacketSize(actual) =>
write!(
f,
"received request had invalid size. (actual: {}, but expected one of: {} (ACK), {} (REGULAR), {}, {}, {} (EXTENDED))",
actual, PacketSize::AckPacket.size(), PacketSize::RegularPacket.size(),
PacketSize::ExtendedPacket8.size(), PacketSize::ExtendedPacket16.size(),
PacketSize::ExtendedPacket32.size()
"received request had invalid size. (actual: {}, but expected one of: {} (ACK), {} (REGULAR), {} (EXTENDED))",
actual, PacketSize::AckPacket.size(), PacketSize::RegularPacket.size(), PacketSize::ExtendedPacket.size()
),
MalformedSphinxPacket => write!(f, "received sphinx packet was malformed"),
InvalidPacketMode => write!(f, "provided packet mode is invalid")
+21 -114
View File
@@ -6,6 +6,7 @@ use bytes::{Buf, BufMut, BytesMut};
use nymsphinx_params::packet_modes::InvalidPacketMode;
use nymsphinx_params::packet_sizes::{InvalidPacketSize, PacketSize};
use nymsphinx_types::SphinxPacket;
use std::convert::TryFrom;
use std::io;
use tokio_util::codec::{Decoder, Encoder};
@@ -74,7 +75,7 @@ impl Decoder for SphinxCodec {
if src.is_empty() {
// can't do anything if we have no bytes, but let's reserve enough for the most
// conservative case, i.e. receiving an ack packet
src.reserve(Header::LEGACY_SIZE + PacketSize::AckPacket.size());
src.reserve(Header::SIZE + PacketSize::AckPacket.size());
return Ok(None);
}
@@ -86,7 +87,7 @@ impl Decoder for SphinxCodec {
};
let sphinx_packet_size = header.packet_size.size();
let frame_len = header.size() + sphinx_packet_size;
let frame_len = Header::SIZE + sphinx_packet_size;
if src.len() < frame_len {
// we don't have enough bytes to read the rest of frame
@@ -95,7 +96,7 @@ impl Decoder for SphinxCodec {
}
// advance buffer past the header - at this point we have enough bytes
src.advance(header.size());
src.advance(Header::SIZE);
let sphinx_packet_bytes = src.split_to(sphinx_packet_size);
let sphinx_packet = match SphinxPacket::from_bytes(&sphinx_packet_bytes) {
Ok(sphinx_packet) => sphinx_packet,
@@ -114,27 +115,21 @@ impl Decoder for SphinxCodec {
// has appropriate capacity in anticipation of future calls to decode.
// Failing to do so leads to inefficiency.
// if we have enough bytes to decode the header of the next packet, we can reserve enough bytes for
// if we have at least one more byte available, we can reserve enough bytes for
// the entire next frame, if not, we assume the next frame is an ack packet and
// reserve for that.
// we also assume the next packet coming from the same client will use exactly the same versioning
// as the current packet
let mut allocate_for_next_packet = header.size() + PacketSize::AckPacket.size();
if !src.is_empty() {
match Header::decode(src) {
Ok(Some(next_header)) => {
allocate_for_next_packet = next_header.size() + next_header.packet_size.size();
}
Ok(None) => {
// we don't have enough information to know how much to reserve, fallback to the ack case
}
let next_packet_len = match PacketSize::try_from(src[0]) {
Ok(next_packet_len) => next_packet_len,
// the next frame will be malformed but let's leave handling the error to the next
// call to 'decode', as presumably, the current sphinx packet is still valid
Err(_) => return Ok(Some(nymsphinx_packet)),
};
let next_frame_len = next_packet_len.size() + Header::SIZE;
src.reserve(next_frame_len - 1);
} else {
src.reserve(Header::SIZE + PacketSize::AckPacket.size());
}
src.reserve(allocate_for_next_packet);
Ok(Some(nymsphinx_packet))
}
@@ -204,8 +199,6 @@ mod packet_encoding {
#[cfg(test)]
mod decode_will_allocate_enough_bytes_for_next_call {
use super::*;
use nymsphinx_params::packet_version::PacketVersion;
use nymsphinx_params::PacketMode;
#[test]
fn for_empty_bytes() {
@@ -214,23 +207,20 @@ mod packet_encoding {
assert!(SphinxCodec.decode(&mut empty_bytes).unwrap().is_none());
assert_eq!(
empty_bytes.capacity(),
Header::LEGACY_SIZE + PacketSize::AckPacket.size()
Header::SIZE + PacketSize::AckPacket.size()
);
}
#[test]
fn for_bytes_with_legacy_header() {
fn for_bytes_with_header() {
// if header gets decoded there should be enough bytes for the entire frame
let packet_sizes = vec![
PacketSize::AckPacket,
PacketSize::RegularPacket,
PacketSize::ExtendedPacket8,
PacketSize::ExtendedPacket16,
PacketSize::ExtendedPacket32,
PacketSize::ExtendedPacket,
];
for packet_size in packet_sizes {
let header = Header {
packet_version: PacketVersion::Legacy,
packet_size,
packet_mode: Default::default(),
};
@@ -238,60 +228,12 @@ mod packet_encoding {
header.encode(&mut bytes);
assert!(SphinxCodec.decode(&mut bytes).unwrap().is_none());
assert_eq!(bytes.capacity(), Header::LEGACY_SIZE + packet_size.size())
assert_eq!(bytes.capacity(), Header::SIZE + packet_size.size())
}
}
#[test]
fn for_bytes_with_versioned_header() {
// if header gets decoded there should be enough bytes for the entire frame
let packet_sizes = vec![
PacketSize::AckPacket,
PacketSize::RegularPacket,
PacketSize::ExtendedPacket8,
PacketSize::ExtendedPacket16,
PacketSize::ExtendedPacket32,
];
for packet_size in packet_sizes {
let header = Header {
packet_version: PacketVersion::Versioned(123),
packet_size,
packet_mode: Default::default(),
};
let mut bytes = BytesMut::new();
header.encode(&mut bytes);
assert!(SphinxCodec.decode(&mut bytes).unwrap().is_none());
assert_eq!(
bytes.capacity(),
Header::VERSIONED_SIZE + packet_size.size()
)
}
}
#[test]
fn for_full_frame_with_legacy_header() {
// if full frame is used exactly, there should be enough space for header + ack packet
let packet = FramedSphinxPacket {
header: Header {
packet_version: PacketVersion::Legacy,
packet_size: Default::default(),
packet_mode: Default::default(),
},
packet: make_valid_sphinx_packet(Default::default()),
};
let mut bytes = BytesMut::new();
SphinxCodec.encode(packet, &mut bytes).unwrap();
assert!(SphinxCodec.decode(&mut bytes).unwrap().is_some());
assert_eq!(
bytes.capacity(),
Header::LEGACY_SIZE + PacketSize::AckPacket.size()
);
}
#[test]
fn for_full_frame_with_versioned_header() {
fn for_full_frame() {
// if full frame is used exactly, there should be enough space for header + ack packet
let packet = FramedSphinxPacket {
header: Header::default(),
@@ -303,50 +245,17 @@ mod packet_encoding {
assert!(SphinxCodec.decode(&mut bytes).unwrap().is_some());
assert_eq!(
bytes.capacity(),
Header::VERSIONED_SIZE + PacketSize::AckPacket.size()
Header::SIZE + PacketSize::AckPacket.size()
);
}
#[test]
fn for_full_frame_with_extra_bytes_with_legacy_header() {
// if there was at least 2 byte left, there should be enough space for entire next frame
fn for_full_frame_with_extra_byte() {
// if there was at least 1 byte left, there should be enough space for entire next frame
let packet_sizes = vec![
PacketSize::AckPacket,
PacketSize::RegularPacket,
PacketSize::ExtendedPacket8,
PacketSize::ExtendedPacket16,
PacketSize::ExtendedPacket32,
];
for packet_size in packet_sizes {
let first_packet = FramedSphinxPacket {
header: Header {
packet_version: PacketVersion::Legacy,
packet_size: Default::default(),
packet_mode: Default::default(),
},
packet: make_valid_sphinx_packet(Default::default()),
};
let mut bytes = BytesMut::new();
SphinxCodec.encode(first_packet, &mut bytes).unwrap();
bytes.put_u8(packet_size as u8);
bytes.put_u8(PacketMode::default() as u8);
assert!(SphinxCodec.decode(&mut bytes).unwrap().is_some());
assert!(bytes.capacity() >= Header::LEGACY_SIZE + packet_size.size())
}
}
#[test]
fn for_full_frame_with_extra_bytes_with_versioned_header() {
// if there was at least 3 byte left, there should be enough space for entire next frame
let packet_sizes = vec![
PacketSize::AckPacket,
PacketSize::RegularPacket,
PacketSize::ExtendedPacket8,
PacketSize::ExtendedPacket16,
PacketSize::ExtendedPacket32,
PacketSize::ExtendedPacket,
];
for packet_size in packet_sizes {
@@ -357,12 +266,10 @@ mod packet_encoding {
let mut bytes = BytesMut::new();
SphinxCodec.encode(first_packet, &mut bytes).unwrap();
bytes.put_u8(PacketVersion::new_versioned(123).as_u8().unwrap());
bytes.put_u8(packet_size as u8);
bytes.put_u8(PacketMode::default() as u8);
assert!(SphinxCodec.decode(&mut bytes).unwrap().is_some());
assert!(bytes.capacity() >= Header::VERSIONED_SIZE + packet_size.size())
assert!(bytes.capacity() >= Header::SIZE + packet_size.size())
}
}
}
+14 -81
View File
@@ -4,7 +4,6 @@
use crate::codec::SphinxCodecError;
use bytes::{BufMut, BytesMut};
use nymsphinx_params::packet_sizes::PacketSize;
use nymsphinx_params::packet_version::PacketVersion;
use nymsphinx_params::PacketMode;
use nymsphinx_types::SphinxPacket;
use std::convert::TryFrom;
@@ -18,14 +17,12 @@ pub struct FramedSphinxPacket {
}
impl FramedSphinxPacket {
pub fn new(packet: SphinxPacket, packet_mode: PacketMode, use_legacy_version: bool) -> Self {
pub fn new(packet: SphinxPacket, packet_mode: PacketMode) -> Self {
// If this fails somebody is using the library in a super incorrect way, because they
// already managed to somehow create a sphinx packet
let packet_size = PacketSize::get_type(packet.len()).unwrap();
FramedSphinxPacket {
header: Header {
packet_version: PacketVersion::new(use_legacy_version),
packet_size,
packet_mode,
},
@@ -51,9 +48,6 @@ impl FramedSphinxPacket {
// but would that really be worth it?
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
pub struct Header {
/// Represents the wire format version used to construct this packet.
pub(crate) packet_version: PacketVersion,
/// Represents type and consequently size of the included SphinxPacket.
pub(crate) packet_size: PacketSize,
@@ -70,25 +64,11 @@ pub struct Header {
}
impl Header {
pub(crate) const LEGACY_SIZE: usize = 2;
pub(crate) const VERSIONED_SIZE: usize = 3;
pub(crate) fn size(&self) -> usize {
if self.packet_version.is_legacy() {
Self::LEGACY_SIZE
} else {
Self::VERSIONED_SIZE
}
}
pub(crate) const SIZE: usize = 2;
pub(crate) fn encode(&self, dst: &mut BytesMut) {
// we reserve one byte for `packet_size` and the other for `mode`
dst.reserve(Self::LEGACY_SIZE);
if let Some(version) = self.packet_version.as_u8() {
dst.reserve(Self::VERSIONED_SIZE);
dst.put_u8(version)
}
dst.reserve(Self::SIZE);
dst.put_u8(self.packet_size as u8);
dst.put_u8(self.packet_mode as u8);
// reserve bytes for the actual packet
@@ -96,30 +76,16 @@ impl Header {
}
pub(crate) fn decode(src: &mut BytesMut) -> Result<Option<Self>, SphinxCodecError> {
if src.len() < Self::LEGACY_SIZE {
if src.len() < Self::SIZE {
// can't do anything if we don't have enough bytes - but reserve enough for the next call
src.reserve(Self::LEGACY_SIZE);
src.reserve(Self::SIZE);
return Ok(None);
}
let packet_version = PacketVersion::from(src[0]);
if packet_version.is_legacy() {
Ok(Some(Header {
packet_version,
packet_size: PacketSize::try_from(src[0])?,
packet_mode: PacketMode::try_from(src[1])?,
}))
} else if src.len() < Self::VERSIONED_SIZE {
// we're missing that 1 byte to read the full header...
src.reserve(Self::VERSIONED_SIZE);
Ok(None)
} else {
Ok(Some(Header {
packet_version,
packet_size: PacketSize::try_from(src[1])?,
packet_mode: PacketMode::try_from(src[2])?,
}))
}
Ok(Some(Header {
packet_size: PacketSize::try_from(src[0])?,
packet_mode: PacketMode::try_from(src[1])?,
}))
}
}
@@ -142,16 +108,7 @@ mod header_encoding {
// make sure this is still 'unknown' for if we make changes in the future
assert!(PacketSize::try_from(unknown_packet_size).is_err());
// unfortunately this will only work for the 'versioned' variant
// due to the hack used to get legacy mode compatibility
let mut bytes = BytesMut::from(
[
PacketVersion::new_versioned(123).as_u8().unwrap(),
unknown_packet_size,
PacketMode::default() as u8,
]
.as_ref(),
);
let mut bytes = BytesMut::from([unknown_packet_size, PacketMode::default() as u8].as_ref());
assert!(Header::decode(&mut bytes).is_err())
}
@@ -170,47 +127,23 @@ mod header_encoding {
let mut empty_bytes = BytesMut::new();
let decode_attempt_1 = Header::decode(&mut empty_bytes).unwrap();
assert!(decode_attempt_1.is_none());
assert!(empty_bytes.capacity() > Header::LEGACY_SIZE);
assert!(empty_bytes.capacity() > Header::SIZE);
let mut empty_bytes = BytesMut::with_capacity(1);
let decode_attempt_2 = Header::decode(&mut empty_bytes).unwrap();
assert!(decode_attempt_2.is_none());
assert!(empty_bytes.capacity() > Header::LEGACY_SIZE);
assert!(empty_bytes.capacity() > Header::SIZE);
}
#[test]
fn header_encoding_reserves_enough_bytes_for_full_sphinx_packet_in_legacy_mode() {
fn header_encoding_reserves_enough_bytes_for_full_sphinx_packet() {
let packet_sizes = vec![
PacketSize::AckPacket,
PacketSize::RegularPacket,
PacketSize::ExtendedPacket8,
PacketSize::ExtendedPacket16,
PacketSize::ExtendedPacket32,
PacketSize::ExtendedPacket,
];
for packet_size in packet_sizes {
let header = Header {
packet_version: PacketVersion::Legacy,
packet_size,
packet_mode: Default::default(),
};
let mut bytes = BytesMut::new();
header.encode(&mut bytes);
assert_eq!(bytes.capacity(), bytes.len() + packet_size.size())
}
}
#[test]
fn header_encoding_reserves_enough_bytes_for_full_sphinx_packet_in_versioned_mode() {
let packet_sizes = vec![
PacketSize::AckPacket,
PacketSize::RegularPacket,
PacketSize::ExtendedPacket8,
PacketSize::ExtendedPacket16,
PacketSize::ExtendedPacket32,
];
for packet_size in packet_sizes {
let header = Header {
packet_version: PacketVersion::Versioned(123),
packet_size,
packet_mode: Default::default(),
};
-12
View File
@@ -13,7 +13,6 @@ pub use packet_sizes::PacketSize;
pub mod packet_modes;
pub mod packet_sizes;
pub mod packet_version;
// If somebody can provide an argument why it might be reasonable to have more than 255 mix hops,
// I will change this to [`usize`]
@@ -25,17 +24,6 @@ pub const DEFAULT_NUM_MIX_HOPS: u8 = 3;
pub const FRAG_ID_LEN: usize = 5;
pub type SerializedFragmentIdentifier = [u8; FRAG_ID_LEN];
// wait, wait, but why are we starting with version 7?
// when packet header gets serialized, the following bytes (in that order) are put onto the wire:
// - packet_version (starting with v1.1.0)
// - packet_size indicator
// - packet_mode
// it also just so happens that the only valid values for packet_size indicator include values 1-6
// therefore if we receive byte `7` (or larger than that) we'll know we received a versioned packet,
// otherwise we should treat it as legacy
/// Increment it whenever we perform any breaking change in the wire format!
const CURRENT_PACKET_VERSION_NUMBER: u8 = 7;
// TODO: ask @AP about the choice of below algorithms
/// Hashing algorithm used during hkdf for ephemeral shared key generation per sphinx packet payload.
+6 -58
View File
@@ -5,7 +5,6 @@ use crate::FRAG_ID_LEN;
use nymsphinx_types::header::HEADER_SIZE;
use nymsphinx_types::PAYLOAD_OVERHEAD_SIZE;
use std::convert::TryFrom;
use std::str::FromStr;
// it's up to the smart people to figure those values out : )
const REGULAR_PACKET_SIZE: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + 2 * 1024;
@@ -16,16 +15,11 @@ const REGULAR_PACKET_SIZE: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + 2 * 102
const ACK_IV_SIZE: usize = 16;
const ACK_PACKET_SIZE: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + ACK_IV_SIZE + FRAG_ID_LEN;
const EXTENDED_PACKET_SIZE_8: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + 8 * 1024;
const EXTENDED_PACKET_SIZE_16: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + 16 * 1024;
const EXTENDED_PACKET_SIZE_32: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + 32 * 1024;
const EXTENDED_PACKET_SIZE: usize = HEADER_SIZE + PAYLOAD_OVERHEAD_SIZE + 32 * 1024;
#[derive(Debug)]
pub struct InvalidPacketSize;
#[derive(Debug)]
pub struct InvalidExtendedPacketSize;
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PacketSize {
@@ -36,28 +30,7 @@ pub enum PacketSize {
AckPacket = 2,
// for example for streaming fast and furious in uncompressed 10bit 4K HDR quality
ExtendedPacket32 = 3,
// for example for streaming fast and furious in heavily compressed lossy RealPlayer quality
ExtendedPacket8 = 4,
// for example for streaming fast and furious in compressed XviD quality
ExtendedPacket16 = 5,
}
impl FromStr for PacketSize {
type Err = InvalidPacketSize;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"regular" => Ok(Self::RegularPacket),
"ack" => Ok(Self::AckPacket),
"extended8" => Ok(Self::ExtendedPacket8),
"extended16" => Ok(Self::ExtendedPacket16),
"extended32" => Ok(Self::ExtendedPacket32),
_ => Err(InvalidPacketSize),
}
}
ExtendedPacket = 3,
}
impl TryFrom<u8> for PacketSize {
@@ -67,9 +40,7 @@ impl TryFrom<u8> for PacketSize {
match value {
_ if value == (PacketSize::RegularPacket as u8) => Ok(Self::RegularPacket),
_ if value == (PacketSize::AckPacket as u8) => Ok(Self::AckPacket),
_ if value == (PacketSize::ExtendedPacket8 as u8) => Ok(Self::ExtendedPacket8),
_ if value == (PacketSize::ExtendedPacket16 as u8) => Ok(Self::ExtendedPacket16),
_ if value == (PacketSize::ExtendedPacket32 as u8) => Ok(Self::ExtendedPacket32),
_ if value == (PacketSize::ExtendedPacket as u8) => Ok(Self::ExtendedPacket),
_ => Err(InvalidPacketSize),
}
}
@@ -80,9 +51,7 @@ impl PacketSize {
match self {
PacketSize::RegularPacket => REGULAR_PACKET_SIZE,
PacketSize::AckPacket => ACK_PACKET_SIZE,
PacketSize::ExtendedPacket8 => EXTENDED_PACKET_SIZE_8,
PacketSize::ExtendedPacket16 => EXTENDED_PACKET_SIZE_16,
PacketSize::ExtendedPacket32 => EXTENDED_PACKET_SIZE_32,
PacketSize::ExtendedPacket => EXTENDED_PACKET_SIZE,
}
}
@@ -99,33 +68,12 @@ impl PacketSize {
Ok(PacketSize::RegularPacket)
} else if PacketSize::AckPacket.size() == size {
Ok(PacketSize::AckPacket)
} else if PacketSize::ExtendedPacket8.size() == size {
Ok(PacketSize::ExtendedPacket8)
} else if PacketSize::ExtendedPacket16.size() == size {
Ok(PacketSize::ExtendedPacket16)
} else if PacketSize::ExtendedPacket32.size() == size {
Ok(PacketSize::ExtendedPacket32)
} else if PacketSize::ExtendedPacket.size() == size {
Ok(PacketSize::ExtendedPacket)
} else {
Err(InvalidPacketSize)
}
}
pub fn is_extended_size(&self) -> bool {
match self {
PacketSize::RegularPacket | PacketSize::AckPacket => false,
PacketSize::ExtendedPacket8
| PacketSize::ExtendedPacket16
| PacketSize::ExtendedPacket32 => true,
}
}
pub fn as_extended_size(self) -> Option<Self> {
if self.is_extended_size() {
Some(self)
} else {
None
}
}
}
impl Default for PacketSize {
@@ -1,59 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{PacketSize, CURRENT_PACKET_VERSION_NUMBER};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PacketVersion {
// this will allow updated mixnodes to still understand packets from before the update
Legacy,
Versioned(u8),
}
impl PacketVersion {
pub fn new(use_legacy: bool) -> Self {
if use_legacy {
Self::new_legacy()
} else {
Self::new_versioned(CURRENT_PACKET_VERSION_NUMBER)
}
}
pub fn new_legacy() -> Self {
PacketVersion::Legacy
}
pub fn new_versioned(version: u8) -> Self {
PacketVersion::Versioned(version)
}
pub fn is_legacy(&self) -> bool {
matches!(self, PacketVersion::Legacy)
}
pub fn as_u8(&self) -> Option<u8> {
match self {
PacketVersion::Legacy => None,
PacketVersion::Versioned(version) => Some(*version),
}
}
}
impl From<u8> for PacketVersion {
fn from(v: u8) -> Self {
match v {
n if n == PacketSize::RegularPacket as u8 => PacketVersion::Legacy,
n if n == PacketSize::AckPacket as u8 => PacketVersion::Legacy,
n if n == PacketSize::ExtendedPacket8 as u8 => PacketVersion::Legacy,
n if n == PacketSize::ExtendedPacket16 as u8 => PacketVersion::Legacy,
n if n == PacketSize::ExtendedPacket32 as u8 => PacketVersion::Legacy,
n => PacketVersion::Versioned(n),
}
}
}
impl Default for PacketVersion {
fn default() -> Self {
PacketVersion::Versioned(CURRENT_PACKET_VERSION_NUMBER)
}
}
+10 -23
View File
@@ -13,13 +13,6 @@ pub struct OrderedMessageBuffer {
messages: HashMap<u64, OrderedMessage>,
}
/// Data returned from `OrderedMessageBuffer` on a successful read of gapless ordered data.
#[derive(Debug, PartialEq, Eq)]
pub struct ReadContiguousData {
pub data: Vec<u8>,
pub last_index: u64,
}
impl OrderedMessageBuffer {
pub fn new() -> OrderedMessageBuffer {
OrderedMessageBuffer {
@@ -49,7 +42,7 @@ impl OrderedMessageBuffer {
/// a read will return the bytes of messages 0, 1, 2. Subsequent reads will
/// return `None` until message 3 comes in, at which point 3, 4, and any
/// further contiguous messages which have arrived will be returned.
pub fn read(&mut self) -> Option<ReadContiguousData> {
pub fn read(&mut self) -> Option<Vec<u8>> {
if !self.messages.contains_key(&self.next_index) {
return None;
}
@@ -73,10 +66,7 @@ impl OrderedMessageBuffer {
.collect();
trace!("Returning {} bytes from ordered message buffer", data.len());
Some(ReadContiguousData {
data,
last_index: index,
})
Some(data)
}
}
@@ -112,11 +102,11 @@ mod test_chunking_and_reassembling {
};
buffer.write(first_message);
let first_read = buffer.read().unwrap().data;
let first_read = buffer.read().unwrap();
assert_eq!(vec![1, 2, 3, 4], first_read);
buffer.write(second_message);
let second_read = buffer.read().unwrap().data;
let second_read = buffer.read().unwrap();
assert_eq!(vec![5, 6, 7, 8], second_read);
assert_eq!(None, buffer.read()); // second read on fully ordered result set is empty
@@ -138,7 +128,7 @@ mod test_chunking_and_reassembling {
buffer.write(first_message);
buffer.write(second_message);
let second_read = buffer.read();
assert_eq!(vec![1, 2, 3, 4, 5, 6, 7, 8], second_read.unwrap().data);
assert_eq!(vec![1, 2, 3, 4, 5, 6, 7, 8], second_read.unwrap());
assert_eq!(None, buffer.read()); // second read on fully ordered result set is empty
}
@@ -157,8 +147,8 @@ mod test_chunking_and_reassembling {
buffer.write(second_message);
buffer.write(first_message);
let read = buffer.read().unwrap().data;
assert_eq!(vec![1, 2, 3, 4, 5, 6, 7, 8], read);
let read = buffer.read();
assert_eq!(vec![1, 2, 3, 4, 5, 6, 7, 8], read.unwrap());
assert_eq!(None, buffer.read()); // second read on fully ordered result set is empty
}
}
@@ -192,7 +182,7 @@ mod test_chunking_and_reassembling {
#[test]
fn everything_up_to_the_indexing_gap_is_returned() {
let mut buffer = setup();
let ordered_bytes = buffer.read().unwrap().data;
let ordered_bytes = buffer.read().unwrap();
assert_eq!([0, 0, 0, 0, 1, 1, 1, 1].to_vec(), ordered_bytes);
// we shouldn't get any more from a second attempt if nothing is added
@@ -218,7 +208,7 @@ mod test_chunking_and_reassembling {
};
buffer.write(two_message);
let more_ordered_bytes = buffer.read().unwrap().data;
let more_ordered_bytes = buffer.read().unwrap();
assert_eq!([2, 2, 2, 2, 3, 3, 3, 3].to_vec(), more_ordered_bytes);
// let's add another message
@@ -237,10 +227,7 @@ mod test_chunking_and_reassembling {
};
buffer.write(four_message);
assert_eq!(
[4, 4, 4, 4, 5, 5, 5, 5].to_vec(),
buffer.read().unwrap().data
);
assert_eq!([4, 4, 4, 4, 5, 5, 5, 5].to_vec(), buffer.read().unwrap());
// at this point we should again get back nothing if we try a read
assert_eq!(None, buffer.read());
+1 -1
View File
@@ -2,7 +2,7 @@ mod buffer;
mod message;
mod sender;
pub use buffer::{OrderedMessageBuffer, ReadContiguousData};
pub use buffer::OrderedMessageBuffer;
pub use message::MessageError;
pub use message::OrderedMessage;
pub use sender::OrderedMessageSender;
@@ -4,7 +4,7 @@
use futures::channel::mpsc;
use futures::StreamExt;
use log::*;
use ordered_buffer::{OrderedMessage, OrderedMessageBuffer, ReadContiguousData};
use ordered_buffer::{OrderedMessage, OrderedMessageBuffer};
use socks5_requests::ConnectionId;
use std::collections::{HashMap, HashSet};
use task::ShutdownListener;
@@ -38,13 +38,12 @@ pub enum ControllerCommand {
struct ActiveConnection {
is_closed: bool,
closed_at_index: Option<u64>,
connection_sender: Option<ConnectionSender>,
ordered_buffer: OrderedMessageBuffer,
}
impl ActiveConnection {
fn write_to_buf(&mut self, payload: Vec<u8>, is_closed: bool) {
fn write_to_buf(&mut self, payload: Vec<u8>) {
let ordered_message = match OrderedMessage::try_from_bytes(payload) {
Ok(msg) => msg,
Err(err) => {
@@ -52,13 +51,10 @@ impl ActiveConnection {
return;
}
};
if is_closed {
self.closed_at_index = Some(ordered_message.index);
}
self.ordered_buffer.write(ordered_message);
}
fn read_from_buf(&mut self) -> Option<ReadContiguousData> {
fn read_from_buf(&mut self) -> Option<Vec<u8>> {
self.ordered_buffer.read()
}
}
@@ -103,7 +99,6 @@ impl Controller {
is_closed: false,
connection_sender: Some(connection_sender),
ordered_buffer: OrderedMessageBuffer::new(),
closed_at_index: None,
};
if let Some(_active_conn) = self.active_connections.insert(conn_id, active_connection) {
error!("Received a duplicate 'Connect'!")
@@ -132,23 +127,21 @@ impl Controller {
fn send_to_connection(&mut self, conn_id: ConnectionId, payload: Vec<u8>, is_closed: bool) {
if let Some(active_connection) = self.active_connections.get_mut(&conn_id) {
if !payload.is_empty() {
active_connection.write_to_buf(payload, is_closed);
active_connection.write_to_buf(payload);
} else if !is_closed {
error!("Tried to write an empty message to a not-closing connection. Please let us know if you see this message");
}
// if messages get unordered, make sure we don't lose information about
// remote socket getting closed!
active_connection.is_closed |= is_closed;
if let Some(payload) = active_connection.read_from_buf() {
if let Some(closed_at_index) = active_connection.closed_at_index {
if payload.last_index > closed_at_index {
active_connection.is_closed = true;
}
}
if let Err(err) = active_connection
.connection_sender
.as_mut()
.unwrap()
.unbounded_send(ConnectionMessage {
payload: payload.data,
payload,
socket_closed: active_connection.is_closed,
})
{
-1
View File
@@ -62,7 +62,6 @@ pub struct DelegationWithEverything {
// DEPRECATED, IF POSSIBLE TRY TO DISCONTINUE USE OF IT!
pub pending_events: Vec<DelegationEvent>,
pub mixnode_is_unbonding: Option<bool>,
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
+4 -35
View File
@@ -1,46 +1,14 @@
## [nym-contracts-v1.1.0](https://github.com/nymtech/nym/tree/nym-contracts-v1.1.0) (2022-11-09)
### Changed
- mixnet-contract: rework of rewarding ([#1472]), which includes, but is not limited to:
- internal reward accounting was modified to be similar to the ideas presented in Cosmos' F1 paper, which results in throughput gains and no storage or gas cost bloat over time,
- introduced internal queues for pending epoch and interval events that only get resolved once relevant epoch/interval rolls over
- the contract no longer stores any historical information regarding past epochs/parameters/stake state for the purposes of rewarding
- a lot of queries got renamed to keep naming more consistent,
- introduced new utility-based queries such as a query for reward estimation for the current epoch,
- mixnodes are now identified by a monotonously increasing `mix_id`
- bonding now results in getting fresh `mix_id` and thus if given node decides to unbond and rebond, it will lose all its delegations,
- mixnode operators are now allowed to set their operating costs as opposed to having fixed value of 40nym/interval
- rewarding parameters are now correctly updated at an **interval** end
- rewarding parameters now include a staking supply scale factor attribute (beta in the tokenomics paper)
- node performance can now be more granular with internal `Decimal` representation as opposed to an `u8`
- node profit margin can now be more granular with internal `Decimal` representation as opposed to an `u8`
- mixnode operators are now allowed to change their configuration options, such as port information, without having to unbond
- mixnode unbonding is no longer instantaneous, instead it happens once an epoch rolls over
- it is now possible to query for operator and node history to see how often (and with what parameters) they rebonded
- other minor bugfixes and changes
- ...
- new exciting bugs to find and squash
- vesting-contract: optional locked token pledge cap per account ([#1687]), defaults to 10%
- vesting-contract: updated internal delegation storage due to mixnet contract revamp ([#1472])
### Added
- vesting-contract: added query for obtaining contract build information ([#1726])
[#1472]: https://github.com/nymtech/nym/pull/1472
[#1687]: https://github.com/nymtech/nym/pull/1687
[#1726]: https://github.com/nymtech/nym/pull/1726
## [nym-contracts-v1.0.2](https://github.com/nymtech/nym/tree/nym-contracts-v1.0.2) (2022-09-13)
### Added
- vesting-contract: added queries for delegation timestamps and paged query for all vesting delegations in the contract ([#1569])
- all binaries: added shell completion and [Fig](fig.io) spec generation ([#1638])
### Changed
- mixnet-contract: compounding delegator rewards now happens instantaneously as opposed to having to wait for the current epoch to finish ([#1571])
- network-requester: updated CLI to use `clap` macros ([#1638])
### Fixed
@@ -50,8 +18,9 @@
[#1544]: https://github.com/nymtech/nym/pull/1544
[#1569]: https://github.com/nymtech/nym/pull/1569
[#1571]: https://github.com/nymtech/nym/pull/1571
[#1569]: https://github.com/nymtech/nym/pull/1571
[#1613]: https://github.com/nymtech/nym/pull/1613
[#1638]: https://github.com/nymtech/nym/pull/1638
## [nym-contracts-v1.0.1](https://github.com/nymtech/nym/tree/nym-contracts-v1.0.1) (2022-06-22)
+1 -4
View File
@@ -930,7 +930,7 @@ checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f"
[[package]]
name = "mixnet-contract"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"bs58",
"cosmwasm-schema",
@@ -1608,14 +1608,12 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
name = "vesting-contract"
version = "1.1.0"
dependencies = [
"contracts-common",
"cosmwasm-std",
"cw-storage-plus",
"mixnet-contract-common",
"schemars",
"serde",
"thiserror",
"vergen",
"vesting-contract-common",
]
@@ -1623,7 +1621,6 @@ dependencies = [
name = "vesting-contract-common"
version = "0.1.0"
dependencies = [
"contracts-common",
"cosmwasm-std",
"mixnet-contract-common",
"schemars",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "mixnet-contract"
version = "1.1.0"
version = "1.0.2"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
edition = "2021"
+101 -180
View File
@@ -2,18 +2,28 @@
// SPDX-License-Identifier: Apache-2.0
use crate::constants::{INITIAL_GATEWAY_PLEDGE_AMOUNT, INITIAL_MIXNODE_PLEDGE_AMOUNT};
use crate::delegations;
use crate::gateways::storage as gateways_storage;
use crate::interval::storage as interval_storage;
use crate::mixnet_contract_settings::storage as mixnet_params_storage;
use crate::mixnodes::storage as mixnode_storage;
use crate::mixnodes::storage::{assign_layer, next_mixnode_id_counter};
use crate::rewards::storage as rewards_storage;
use cosmwasm_std::{
entry_point, to_binary, Addr, Coin, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response,
coin, entry_point, to_binary, Addr, Coin, Deps, DepsMut, Env, MessageInfo, QueryResponse,
Response,
};
use cw_storage_plus::Item;
use mixnet_contract_common::error::MixnetContractError;
use mixnet_contract_common::{
ContractState, ContractStateParams, ExecuteMsg, InstantiateMsg, Interval, MigrateMsg, QueryMsg,
ContractState, ContractStateParams, Delegation, ExecuteMsg, GatewayBond, InstantiateMsg,
Interval, MigrateMsg, MixNode, MixNodeBond, MixNodeCostParams, MixNodeRewarding, Percent,
QueryMsg,
};
// To be removed once entire contract is unlocked
const V1_MIXNET_CONTRACT: Item<'_, String> = Item::new("v1_mixnet_contract");
fn default_initial_state(
owner: Addr,
rewarding_validator_address: Addr,
@@ -70,6 +80,8 @@ pub fn instantiate(
mixnode_storage::initialise_storage(deps.storage)?;
rewards_storage::initialise_storage(deps.storage, reward_params)?;
V1_MIXNET_CONTRACT.save(deps.storage, &msg.v1_mixnet_contract_address)?;
Ok(Response::default())
}
@@ -81,194 +93,102 @@ pub fn execute(
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, MixnetContractError> {
// only the old mixnet contract is allowed to request migration-specific commands here
if info.sender != V1_MIXNET_CONTRACT.load(deps.storage)? {
return Err(MixnetContractError::Unauthorized);
}
match msg {
// state/sys-params-related
ExecuteMsg::UpdateRewardingValidatorAddress { address } => {
crate::mixnet_contract_settings::transactions::try_update_rewarding_validator_address(
deps, info, address,
)
}
ExecuteMsg::UpdateContractStateParams { updated_parameters } => {
crate::mixnet_contract_settings::transactions::try_update_contract_settings(
deps,
info,
updated_parameters,
)
}
ExecuteMsg::UpdateActiveSetSize {
active_set_size,
force_immediately,
} => crate::rewards::transactions::try_update_active_set_size(
deps,
env,
info,
active_set_size,
force_immediately,
),
ExecuteMsg::UpdateRewardingParams {
updated_params,
force_immediately,
} => crate::rewards::transactions::try_update_rewarding_params(
deps,
env,
info,
updated_params,
force_immediately,
),
ExecuteMsg::UpdateIntervalConfig {
epochs_in_interval,
epoch_duration_secs,
force_immediately,
} => crate::interval::transactions::try_update_interval_config(
deps,
env,
info,
epochs_in_interval,
epoch_duration_secs,
force_immediately,
),
ExecuteMsg::AdvanceCurrentEpoch {
new_rewarded_set,
expected_active_set_size,
} => crate::interval::transactions::try_advance_epoch(
deps,
env,
info,
new_rewarded_set,
expected_active_set_size,
),
ExecuteMsg::ReconcileEpochEvents { limit } => {
crate::interval::transactions::try_reconcile_epoch_events(deps, env, info, limit)
}
// mixnode-related:
ExecuteMsg::BondMixnode {
mix_node,
cost_params,
owner_signature,
} => crate::mixnodes::transactions::try_add_mixnode(
deps,
env,
info,
mix_node,
cost_params,
owner_signature,
),
ExecuteMsg::BondMixnodeOnBehalf {
mix_node,
cost_params,
ExecuteMsg::SaveOperator {
host,
mix_port,
verloc_port,
http_api_port,
sphinx_key,
identity_key,
version,
pledge_amount,
owner,
owner_signature,
} => crate::mixnodes::transactions::try_add_mixnode_on_behalf(
deps,
env,
info,
mix_node,
cost_params,
owner,
owner_signature,
),
ExecuteMsg::UnbondMixnode {} => {
crate::mixnodes::transactions::try_remove_mixnode(deps, env, info)
}
ExecuteMsg::UnbondMixnodeOnBehalf { owner } => {
crate::mixnodes::transactions::try_remove_mixnode_on_behalf(deps, env, info, owner)
}
ExecuteMsg::UpdateMixnodeCostParams { new_costs } => {
crate::mixnodes::transactions::try_update_mixnode_cost_params(
deps, env, info, new_costs,
)
}
ExecuteMsg::UpdateMixnodeCostParamsOnBehalf { new_costs, owner } => {
crate::mixnodes::transactions::try_update_mixnode_cost_params_on_behalf(
deps, env, info, new_costs, owner,
)
}
ExecuteMsg::UpdateMixnodeConfig { new_config } => {
crate::mixnodes::transactions::try_update_mixnode_config(deps, info, new_config)
}
ExecuteMsg::UpdateMixnodeConfigOnBehalf { new_config, owner } => {
crate::mixnodes::transactions::try_update_mixnode_config_on_behalf(
deps, info, new_config, owner,
)
}
block_height,
profit_margin_percent,
proxy,
} => {
let mixnode = MixNode {
host,
mix_port,
verloc_port,
http_api_port,
sphinx_key,
identity_key,
version,
};
let layer = assign_layer(deps.storage)?;
// gateway-related:
ExecuteMsg::BondGateway {
gateway,
owner_signature,
} => crate::gateways::transactions::try_add_gateway(
deps,
env,
info,
gateway,
owner_signature,
),
ExecuteMsg::BondGatewayOnBehalf {
gateway,
owner,
owner_signature,
} => crate::gateways::transactions::try_add_gateway_on_behalf(
deps,
env,
info,
gateway,
owner,
owner_signature,
),
ExecuteMsg::UnbondGateway {} => {
crate::gateways::transactions::try_remove_gateway(deps, info)
}
ExecuteMsg::UnbondGatewayOnBehalf { owner } => {
crate::gateways::transactions::try_remove_gateway_on_behalf(deps, info, owner)
}
let cost_params = MixNodeCostParams {
// this value must be valid since we got it from the v1 contract which we trust
profit_margin_percent: Percent::from_percentage_value(profit_margin_percent as u64)
.unwrap(),
interval_operating_cost: coin(40_000_000, &pledge_amount.denom),
};
let node_id = next_mixnode_id_counter(deps.storage)?;
let current_epoch =
interval_storage::current_interval(deps.storage)?.current_epoch_absolute_id();
let mixnode_rewarding =
MixNodeRewarding::initialise_new(cost_params, &pledge_amount, current_epoch);
let mixnode_bond = MixNodeBond::new(
node_id,
owner,
pledge_amount,
layer,
mixnode,
proxy,
block_height,
);
// delegation-related:
ExecuteMsg::DelegateToMixnode { mix_id } => {
crate::delegations::transactions::try_delegate_to_mixnode(deps, env, info, mix_id)
}
ExecuteMsg::DelegateToMixnodeOnBehalf { mix_id, delegate } => {
crate::delegations::transactions::try_delegate_to_mixnode_on_behalf(
deps, env, info, mix_id, delegate,
)
}
ExecuteMsg::UndelegateFromMixnode { mix_id } => {
crate::delegations::transactions::try_remove_delegation_from_mixnode(
deps, env, info, mix_id,
)
}
ExecuteMsg::UndelegateFromMixnodeOnBehalf { mix_id, delegate } => {
crate::delegations::transactions::try_remove_delegation_from_mixnode_on_behalf(
deps, env, info, mix_id, delegate,
)
}
mixnode_storage::mixnode_bonds().save(deps.storage, node_id, &mixnode_bond)?;
rewards_storage::MIXNODE_REWARDING.save(deps.storage, node_id, &mixnode_rewarding)?;
// reward-related
ExecuteMsg::RewardMixnode {
Ok(Response::new())
}
ExecuteMsg::SaveDelegation {
owner,
mix_id,
performance,
} => crate::rewards::transactions::try_reward_mixnode(deps, env, info, mix_id, performance),
amount,
block_height,
proxy,
} => {
let mut mix_rewarding =
rewards_storage::MIXNODE_REWARDING.load(deps.storage, mix_id)?;
mix_rewarding.add_base_delegation(amount.amount);
rewards_storage::MIXNODE_REWARDING.save(deps.storage, mix_id, &mix_rewarding)?;
ExecuteMsg::WithdrawOperatorReward {} => {
crate::rewards::transactions::try_withdraw_operator_reward(deps, info)
let delegation = Delegation::new(
owner,
mix_id,
mix_rewarding.total_unit_reward,
amount,
block_height,
proxy,
);
let storage_key = delegation.storage_key();
delegations::storage::delegations().save(deps.storage, storage_key, &delegation)?;
Ok(Response::new())
}
ExecuteMsg::WithdrawOperatorRewardOnBehalf { owner } => {
crate::rewards::transactions::try_withdraw_operator_reward_on_behalf(deps, info, owner)
}
ExecuteMsg::WithdrawDelegatorReward { mix_id } => {
crate::rewards::transactions::try_withdraw_delegator_reward(deps, info, mix_id)
}
ExecuteMsg::WithdrawDelegatorRewardOnBehalf { mix_id, owner } => {
crate::rewards::transactions::try_withdraw_delegator_reward_on_behalf(
deps, info, mix_id, owner,
)
ExecuteMsg::SaveGateway {
pledge_amount,
owner,
block_height,
gateway,
proxy,
} => {
let bond = GatewayBond::new(pledge_amount, owner, block_height, gateway, proxy);
gateways_storage::gateways().save(deps.storage, bond.identity(), &bond)?;
Ok(Response::new())
}
// testing-only
#[cfg(feature = "contract-testing")]
ExecuteMsg::TestingResolveAllPendingEvents { limit } => {
crate::testing::transactions::try_resolve_all_pending_events(deps, env, limit)
}
_ => Err(MixnetContractError::MigrationInProgress),
}
}
@@ -491,6 +411,7 @@ mod tests {
let init_msg = InstantiateMsg {
rewarding_validator_address: "foomp123".to_string(),
vesting_contract_address: "bar456".to_string(),
v1_mixnet_contract_address: "whatever".to_string(),
rewarding_denom: "uatom".to_string(),
epochs_in_interval: 1234,
epoch_duration: Duration::from_secs(4321),
@@ -1220,7 +1220,6 @@ mod tests {
let update = IntervalRewardingParamsUpdate {
reward_pool: Some(before.interval.reward_pool / two),
staking_supply: Some(before.interval.staking_supply * four),
staking_supply_scale_factor: None,
sybil_resistance_percent: Some(Percent::from_percentage_value(42).unwrap()),
active_set_work_factor: None,
interval_pool_emission: None,
@@ -1710,7 +1710,6 @@ pub mod tests {
let update = IntervalRewardingParamsUpdate {
reward_pool: None,
staking_supply: None,
staking_supply_scale_factor: None,
sybil_resistance_percent: None,
active_set_work_factor: None,
interval_pool_emission: None,
@@ -1743,7 +1742,6 @@ pub mod tests {
let empty_update = IntervalRewardingParamsUpdate {
reward_pool: None,
staking_supply: None,
staking_supply_scale_factor: None,
sybil_resistance_percent: None,
active_set_work_factor: None,
interval_pool_emission: None,
@@ -1763,7 +1761,6 @@ pub mod tests {
let update = IntervalRewardingParamsUpdate {
reward_pool: None,
staking_supply: None,
staking_supply_scale_factor: None,
sybil_resistance_percent: None,
active_set_work_factor: None,
interval_pool_emission: None,
@@ -1798,7 +1795,6 @@ pub mod tests {
let update = IntervalRewardingParamsUpdate {
reward_pool: None,
staking_supply: None,
staking_supply_scale_factor: None,
sybil_resistance_percent: None,
active_set_work_factor: None,
interval_pool_emission: None,
@@ -1823,7 +1819,6 @@ pub mod tests {
let update = IntervalRewardingParamsUpdate {
reward_pool: None,
staking_supply: None,
staking_supply_scale_factor: None,
sybil_resistance_percent: None,
active_set_work_factor: None,
interval_pool_emission: None,
@@ -1864,7 +1859,6 @@ pub mod tests {
let update = IntervalRewardingParamsUpdate {
reward_pool: Some(old.interval.reward_pool / two),
staking_supply: Some(old.interval.staking_supply * four),
staking_supply_scale_factor: None,
sybil_resistance_percent: None,
active_set_work_factor: None,
interval_pool_emission: None,
+1 -5
View File
@@ -15,7 +15,6 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
mixnet-contract-common = { path = "../../common/cosmwasm-smart-contracts/mixnet-contract" }
contracts-common = { path = "../../common/cosmwasm-smart-contracts/contracts-common" }
vesting-contract-common = { path = "../../common/cosmwasm-smart-contracts/vesting-contract" }
cosmwasm-std = { version = "1.0.0 "}
@@ -23,7 +22,4 @@ cw-storage-plus = { version = "0.13.4", features = ["iterator"] }
schemars = "0.8"
serde = { version = "1.0", default-features = false, features = ["derive"] }
thiserror = { version = "1.0" }
[build-dependencies]
vergen = { version = "5", default-features = false, features = ["build", "git", "rustc"] }
thiserror = { version = "1.0" }
-8
View File
@@ -1,8 +0,0 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use vergen::{vergen, Config};
fn main() {
vergen(Config::default()).expect("failed to extract build metadata")
}
+14 -39
View File
@@ -1,14 +1,13 @@
use crate::errors::ContractError;
use crate::queued_migrations::migrate_to_v2_mixnet_contract;
use crate::storage::{
account_from_address, save_account, BlockTimestampSecs, ADMIN, DELEGATIONS,
MIXNET_CONTRACT_ADDRESS, MIX_DENOM,
account_from_address, locked_pledge_cap, update_locked_pledge_cap, BlockTimestampSecs, ADMIN,
DELEGATIONS, MIXNET_CONTRACT_ADDRESS, MIX_DENOM,
};
use crate::traits::{
DelegatingAccount, GatewayBondingAccount, MixnodeBondingAccount, VestingAccount,
};
use crate::vesting::{populate_vesting_periods, Account};
use contracts_common::ContractBuildInformation;
use cosmwasm_std::{
coin, entry_point, to_binary, BankMsg, Coin, Deps, DepsMut, Env, MessageInfo, Order,
QueryResponse, Response, StdResult, Timestamp, Uint128,
@@ -26,8 +25,8 @@ use vesting_contract_common::messages::{
ExecuteMsg, InitMsg, MigrateMsg, QueryMsg, VestingSpecification,
};
use vesting_contract_common::{
AllDelegationsResponse, DelegationTimesResponse, OriginalVestingResponse, Period, PledgeCap,
PledgeData, VestingDelegation,
AllDelegationsResponse, DelegationTimesResponse, OriginalVestingResponse, Period, PledgeData,
VestingDelegation,
};
pub const INITIAL_LOCKED_PLEDGE_CAP: Uint128 = Uint128::new(100_000_000_000);
@@ -60,8 +59,8 @@ pub fn execute(
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::UpdateLockedPledgeCap { address, cap } => {
try_update_locked_pledge_cap(address, cap, info, deps)
ExecuteMsg::UpdateLockedPledgeCap { amount } => {
try_update_locked_pledge_cap(amount, info, deps)
}
ExecuteMsg::TrackReward { amount, address } => {
try_track_reward(deps, info, amount, &address)
@@ -89,12 +88,10 @@ pub fn execute(
owner_address,
staking_address,
vesting_spec,
cap,
} => try_create_periodic_vesting_account(
&owner_address,
staking_address,
vesting_spec,
cap,
info,
env,
deps,
@@ -147,18 +144,14 @@ pub fn execute(
///
/// Callable by ADMIN only, see [instantiate].
pub fn try_update_locked_pledge_cap(
address: String,
cap: PledgeCap,
amount: Uint128,
info: MessageInfo,
deps: DepsMut,
) -> Result<Response, ContractError> {
if info.sender != ADMIN.load(deps.storage)? {
return Err(ContractError::NotAdmin(info.sender.as_str().to_string()));
}
let mut account = account_from_address(&address, deps.storage, deps.api)?;
account.pledge_cap = Some(cap);
save_account(&account, deps.storage)?;
update_locked_pledge_cap(amount, deps.storage)?;
Ok(Response::default())
}
@@ -437,7 +430,6 @@ fn try_create_periodic_vesting_account(
owner_address: &str,
staking_address: Option<String>,
vesting_spec: Option<VestingSpecification>,
cap: Option<PledgeCap>,
info: MessageInfo,
env: Env,
deps: DepsMut<'_>,
@@ -445,7 +437,6 @@ fn try_create_periodic_vesting_account(
if info.sender != ADMIN.load(deps.storage)? {
return Err(ContractError::NotAdmin(info.sender.as_str().to_string()));
}
let mix_denom = MIX_DENOM.load(deps.storage)?;
let account_exists = account_from_address(owner_address, deps.storage, deps.api).is_ok();
@@ -461,11 +452,6 @@ fn try_create_periodic_vesting_account(
let owner_address = deps.api.addr_validate(owner_address)?;
let staking_address = if let Some(staking_address) = staking_address {
let staking_account_exists =
account_from_address(&staking_address, deps.storage, deps.api).is_ok();
if staking_account_exists {
return Err(ContractError::StakingAccountAlreadyExists(staking_address));
}
Some(deps.api.addr_validate(&staking_address)?)
} else {
None
@@ -486,7 +472,6 @@ fn try_create_periodic_vesting_account(
coin.clone(),
start_time,
periods,
cap,
deps.storage,
)?;
@@ -501,7 +486,7 @@ fn try_create_periodic_vesting_account(
#[entry_point]
pub fn query(deps: Deps<'_>, env: Env, msg: QueryMsg) -> Result<QueryResponse, ContractError> {
let query_res = match msg {
QueryMsg::GetContractVersion {} => to_binary(&get_contract_version()),
QueryMsg::GetLockedPledgeCap {} => to_binary(&get_locked_pledge_cap(deps)),
QueryMsg::LockedCoins {
vesting_account_address,
block_time,
@@ -582,6 +567,11 @@ pub fn query(deps: Deps<'_>, env: Env, msg: QueryMsg) -> Result<QueryResponse, C
Ok(query_res?)
}
/// Get locked_pledge_cap, the hard cap for staking/bonding with unvested tokens.
pub fn get_locked_pledge_cap(deps: Deps<'_>) -> Uint128 {
locked_pledge_cap(deps.storage)
}
/// Get current vesting period for a given [crate::vesting::Account].
pub fn try_get_current_vesting_period(
address: &str,
@@ -608,21 +598,6 @@ pub fn try_get_account(address: &str, deps: Deps<'_>) -> Result<Account, Contrac
account_from_address(address, deps.storage, deps.api)
}
/// Gets build information of this contract.
pub fn get_contract_version() -> ContractBuildInformation {
// as per docs
// env! macro will expand to the value of the named environment variable at
// compile time, yielding an expression of type `&'static str`
ContractBuildInformation {
build_timestamp: env!("VERGEN_BUILD_TIMESTAMP").to_string(),
build_version: env!("VERGEN_BUILD_SEMVER").to_string(),
commit_sha: env!("VERGEN_GIT_SHA").to_string(),
commit_timestamp: env!("VERGEN_GIT_COMMIT_TIMESTAMP").to_string(),
commit_branch: env!("VERGEN_GIT_BRANCH").to_string(),
rustc_version: env!("VERGEN_RUSTC_SEMVER").to_string(),
}
}
/// Gets currently locked coins, see [crate::traits::VestingAccount::locked_coins]
pub fn try_get_locked_coins(
vesting_account_address: &str,
-2
View File
@@ -44,8 +44,6 @@ pub enum ContractError {
InvalidAddress(String),
#[error("VESTING ({}): Account already exists: {0}", line!())]
AccountAlreadyExists(String),
#[error("VESTING ({}): Staking account already exists: {0}", line!())]
StakingAccountAlreadyExists(String),
#[error("VESTING ({}): Too few coins sent for vesting account creation, sent {sent}, need at least {need}", line!())]
MinVestingFunds { sent: u128, need: u128 },
#[error("VESTING ({}): Maximum amount of locked coins has already been pledged: {current}, cap is {cap}", line!())]
+16 -1
View File
@@ -1,5 +1,5 @@
use crate::errors::ContractError;
use crate::vesting::Account;
use crate::{contract::INITIAL_LOCKED_PLEDGE_CAP, errors::ContractError};
use cosmwasm_std::{Addr, Api, Storage, Uint128};
use cw_storage_plus::{Item, Map};
use mixnet_contract_common::{IdentityKey, MixId};
@@ -20,6 +20,21 @@ pub const DELEGATIONS: Map<'_, (u32, MixId, BlockTimestampSecs), Uint128> = Map:
pub const ADMIN: Item<'_, String> = Item::new("adm");
pub const MIXNET_CONTRACT_ADDRESS: Item<'_, String> = Item::new("mix");
pub const MIX_DENOM: Item<'_, String> = Item::new("den");
pub const LOCKED_PLEDGE_CAP: Item<'_, Uint128> = Item::new("lck");
pub fn locked_pledge_cap(storage: &dyn Storage) -> Uint128 {
LOCKED_PLEDGE_CAP
.load(storage)
.unwrap_or(INITIAL_LOCKED_PLEDGE_CAP)
}
pub fn update_locked_pledge_cap(
amount: Uint128,
storage: &mut dyn Storage,
) -> Result<(), ContractError> {
LOCKED_PLEDGE_CAP.save(storage, &amount)?;
Ok(())
}
pub fn save_delegation(
key: (u32, MixId, BlockTimestampSecs),
-27
View File
@@ -2,12 +2,9 @@
pub mod helpers {
use crate::contract::instantiate;
use crate::vesting::{populate_vesting_periods, Account};
use contracts_common::Percent;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info, MockApi, MockQuerier};
use cosmwasm_std::{Addr, Coin, Empty, Env, MemoryStorage, OwnedDeps, Storage, Uint128};
use std::str::FromStr;
use vesting_contract_common::messages::{InitMsg, VestingSpecification};
use vesting_contract_common::PledgeCap;
pub const TEST_COIN_DENOM: &str = "unym";
@@ -40,7 +37,6 @@ pub mod helpers {
},
start_time_ts,
periods,
None,
storage,
)
.unwrap()
@@ -60,29 +56,6 @@ pub mod helpers {
},
start_time,
periods,
Some(PledgeCap::from_str("0.1").unwrap()),
storage,
)
.unwrap()
}
pub fn vesting_account_percent_fixture(storage: &mut dyn Storage, env: &Env) -> Account {
let start_time = env.block.time;
let periods =
populate_vesting_periods(start_time.seconds(), VestingSpecification::default());
Account::new(
Addr::unchecked("owner"),
Some(Addr::unchecked("staking")),
Coin {
amount: Uint128::new(1_000_000_000_000),
denom: TEST_COIN_DENOM.to_string(),
},
start_time,
periods,
Some(PledgeCap::Percent(
Percent::from_percentage_value(10).unwrap(),
)),
storage,
)
.unwrap()
@@ -1,4 +1,5 @@
use crate::errors::ContractError;
use crate::storage::locked_pledge_cap;
use crate::storage::save_delegation;
use crate::storage::MIXNET_CONTRACT_ADDRESS;
use crate::traits::DelegatingAccount;
@@ -37,9 +38,8 @@ impl DelegatingAccount for Account {
storage: &mut dyn Storage,
) -> Result<Response, ContractError> {
let current_balance = self.load_balance(storage)?;
let total_pledged_locked = self.total_pledged_locked(storage, env)?;
let total_pledged_after = total_pledged_locked + coin.amount;
let locked_pledge_cap = self.absolute_pledge_cap()?;
let total_pledged_after = self.total_pledged_locked(storage, env)? + coin.amount;
let locked_pledge_cap = locked_pledge_cap(storage);
if locked_pledge_cap < total_pledged_after {
return Err(ContractError::LockedPledgeCapReached {
@@ -1,5 +1,6 @@
use super::PledgeData;
use crate::errors::ContractError;
use crate::storage::locked_pledge_cap;
use crate::storage::MIXNET_CONTRACT_ADDRESS;
use crate::traits::GatewayBondingAccount;
use crate::traits::VestingAccount;
@@ -21,9 +22,8 @@ impl GatewayBondingAccount for Account {
storage: &mut dyn Storage,
) -> Result<Response, ContractError> {
let current_balance = self.load_balance(storage)?;
let total_pledged_locked = self.total_pledged_locked(storage, env)?;
let total_pledged_after = total_pledged_locked + pledge.amount;
let locked_pledge_cap = self.absolute_pledge_cap()?;
let total_pledged_after = self.total_pledged_locked(storage, env)? + pledge.amount;
let locked_pledge_cap = locked_pledge_cap(storage);
if locked_pledge_cap < total_pledged_after {
return Err(ContractError::LockedPledgeCapReached {
@@ -3,6 +3,7 @@
use super::Account;
use crate::errors::ContractError;
use crate::storage::locked_pledge_cap;
use crate::storage::MIXNET_CONTRACT_ADDRESS;
use crate::traits::MixnodeBondingAccount;
use crate::traits::VestingAccount;
@@ -38,9 +39,8 @@ impl MixnodeBondingAccount for Account {
storage: &mut dyn Storage,
) -> Result<Response, ContractError> {
let current_balance = self.load_balance(storage)?;
let total_pledged_locked = self.total_pledged_locked(storage, env)?;
let total_pledged_after = total_pledged_locked + pledge.amount;
let locked_pledge_cap = self.absolute_pledge_cap()?;
let total_pledged_after = self.total_pledged_locked(storage, env)? + pledge.amount;
let locked_pledge_cap = locked_pledge_cap(storage);
if locked_pledge_cap < total_pledged_after {
return Err(ContractError::LockedPledgeCapReached {
+2 -17
View File
@@ -5,13 +5,12 @@ use crate::storage::{
remove_delegation, remove_gateway_pledge, save_account, save_balance, save_bond_pledge,
save_gateway_pledge, save_withdrawn, BlockTimestampSecs, DELEGATIONS, KEY,
};
use crate::traits::VestingAccount;
use cosmwasm_std::{Addr, Coin, Order, Storage, Timestamp, Uint128};
use cw_storage_plus::Bound;
use mixnet_contract_common::MixId;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use vesting_contract_common::{Period, PledgeCap, PledgeData};
use vesting_contract_common::{Period, PledgeData};
mod delegating_account;
mod gateway_bonding_account;
@@ -24,6 +23,7 @@ fn generate_storage_key(storage: &mut dyn Storage) -> Result<u32, ContractError>
Ok(key)
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Account {
pub owner_address: Addr,
@@ -32,8 +32,6 @@ pub struct Account {
pub periods: Vec<VestingPeriod>,
pub coin: Coin,
storage_key: u32,
#[serde(default)]
pub pledge_cap: Option<PledgeCap>,
}
impl Account {
@@ -43,7 +41,6 @@ impl Account {
coin: Coin,
start_time: Timestamp,
periods: Vec<VestingPeriod>,
pledge_cap: Option<PledgeCap>,
storage: &mut dyn Storage,
) -> Result<Self, ContractError> {
let storage_key = generate_storage_key(storage)?;
@@ -55,24 +52,12 @@ impl Account {
periods,
coin,
storage_key,
pledge_cap,
};
save_account(&account, storage)?;
account.save_balance(amount, storage)?;
Ok(account)
}
pub fn pledge_cap(&self) -> PledgeCap {
self.pledge_cap.clone().unwrap_or_default()
}
pub fn absolute_pledge_cap(&self) -> Result<Uint128, ContractError> {
match self.pledge_cap() {
PledgeCap::Absolute(cap) => Ok(cap),
PledgeCap::Percent(p) => Ok(p * self.get_original_vesting().amount.amount),
}
}
pub fn coin(&self) -> Coin {
self.coin.clone()
}
@@ -105,7 +105,7 @@ impl VestingAccount for Account {
}
fn get_end_time(&self) -> Timestamp {
self.periods[(self.num_vesting_periods() - 1)].end_time()
self.periods[(self.num_vesting_periods() - 1) as usize].end_time()
}
fn get_original_vesting(&self) -> OriginalVestingResponse {
@@ -123,17 +123,16 @@ impl VestingAccount for Account {
storage: &dyn Storage,
) -> Result<Coin, ContractError> {
let block_time = block_time.unwrap_or(env.block.time);
let period = self.get_current_vesting_period(block_time);
let withdrawn = self.load_withdrawn(storage)?;
let max_available = self
.get_vested_coins(Some(block_time), env, storage)?
.amount
.saturating_sub(withdrawn);
let period = self.get_current_vesting_period(block_time);
let start_time = match period {
Period::Before => 0,
Period::After => u64::MAX,
Period::In(idx) => self.periods[idx].start_time,
Period::In(idx) => self.periods[idx as usize].start_time,
};
let coin = self.total_delegations_at_timestamp(storage, start_time)?;
@@ -156,8 +155,15 @@ impl VestingAccount for Account {
let block_time = block_time.unwrap_or(env.block.time);
let delegated_free = self.get_delegated_free(Some(block_time), env, storage)?;
let period = self.get_current_vesting_period(block_time);
let start_time = match period {
Period::Before => 0,
Period::After => u64::MAX,
Period::In(idx) => self.periods[idx as usize].start_time,
};
let delegations_before_start_time =
self.total_delegations_at_timestamp(storage, block_time.seconds())?;
self.total_delegations_at_timestamp(storage, start_time)?;
let amount = delegations_before_start_time - delegated_free.amount;
@@ -179,7 +185,7 @@ impl VestingAccount for Account {
let start_time = match period {
Period::Before => 0,
Period::After => u64::MAX,
Period::In(idx) => self.periods[idx].start_time,
Period::In(idx) => self.periods[idx as usize].start_time,
};
let amount = if let Some(bond) = self
+4 -38
View File
@@ -15,7 +15,7 @@ pub struct VestingPeriod {
impl VestingPeriod {
pub fn end_time(&self) -> Timestamp {
Timestamp::from_seconds(self.start_time + self.period_seconds)
Timestamp::from_seconds(self.start_time + self.period_seconds as u64)
}
}
@@ -26,7 +26,7 @@ pub fn populate_vesting_periods(
let mut periods = Vec::with_capacity(vesting_spec.num_periods() as usize);
for i in 0..vesting_spec.num_periods() {
let period = VestingPeriod {
start_time: start_time + i * vesting_spec.period_seconds(),
start_time: start_time + i as u64 * vesting_spec.period_seconds(),
period_seconds: vesting_spec.period_seconds(),
};
periods.push(period);
@@ -38,7 +38,6 @@ pub fn populate_vesting_periods(
mod tests {
use crate::contract::*;
use crate::storage::*;
use crate::support::tests::helpers::vesting_account_percent_fixture;
use crate::support::tests::helpers::{
init_contract, vesting_account_mid_fixture, vesting_account_new_fixture, TEST_COIN_DENOM,
};
@@ -52,7 +51,6 @@ mod tests {
use mixnet_contract_common::{Gateway, MixNode, Percent};
use vesting_contract_common::messages::{ExecuteMsg, VestingSpecification};
use vesting_contract_common::Period;
use vesting_contract_common::PledgeCap;
#[test]
fn test_account_creation() {
@@ -63,7 +61,6 @@ mod tests {
owner_address: "owner".to_string(),
staking_address: Some("staking".to_string()),
vesting_spec: None,
cap: Some(PledgeCap::Absolute(Uint128::from(100_000_000_000u128))),
};
// Try creating an account when not admin
let response = execute(deps.as_mut(), env.clone(), info.clone(), msg.clone());
@@ -392,38 +389,12 @@ mod tests {
assert_eq!(locked_coins.amount, Uint128::new(660_000_000_000));
}
#[test]
fn test_percent_cap() {
let mut deps = init_contract();
let env = mock_env();
let account = vesting_account_percent_fixture(&mut deps.storage, &env);
assert_eq!(
account.absolute_pledge_cap().unwrap(),
Uint128::new(100_000_000_000)
)
}
#[test]
fn test_delegations() {
let mut deps = init_contract();
let env = mock_env();
// let account = vesting_account_new_fixture(&mut deps.storage, &env);
let msg = ExecuteMsg::CreateAccount {
owner_address: "owner".to_string(),
staking_address: Some("staking".to_string()),
vesting_spec: None,
cap: Some(PledgeCap::Absolute(Uint128::from(100_000_000_000u128))),
};
let info = mock_info("admin", &coins(1_000_000_000_000, TEST_COIN_DENOM));
let _response = execute(deps.as_mut(), env.clone(), info.clone(), msg.clone());
let account = load_account(&Addr::unchecked("owner"), &deps.storage)
.unwrap()
.unwrap();
let account = vesting_account_new_fixture(&mut deps.storage, &env);
// Try delegating too much
let err = account.try_delegate_to_mixnode(
@@ -463,7 +434,7 @@ mod tests {
let balance = account.load_balance(&deps.storage).unwrap();
assert_eq!(balance, Uint128::new(910000000000));
// Try delegating too much againcalca
// Try delegating too much again
let err = account.try_delegate_to_mixnode(
1,
Coin {
@@ -478,10 +449,6 @@ mod tests {
let total_delegations = account.total_delegations_for_mix(1, &deps.storage).unwrap();
assert_eq!(Uint128::new(90_000_000_000), total_delegations);
let account = load_account(&Addr::unchecked("owner"), &deps.storage)
.unwrap()
.unwrap();
// Current period -> block_time: None
let delegated_free = account
.get_delegated_free(None, &env, &deps.storage)
@@ -846,7 +813,6 @@ mod tests {
},
Timestamp::from_seconds(account_creation_timestamp),
periods,
Some(PledgeCap::Absolute(Uint128::from(100_000_000_000u128))),
deps.as_mut().storage,
)
.unwrap();
+33 -48
View File
@@ -1,4 +1,4 @@
version: "3.7"
version: '3.7'
x-network: &NETWORK
BECH32_PREFIX: nymt
@@ -23,7 +23,7 @@ services:
networks:
localnet:
ipv4_address: 172.168.10.2
command: ["genesis"]
command: [ "genesis" ]
secondary_validator:
build:
context: docker/validator
@@ -41,7 +41,7 @@ services:
ipv4_address: 172.168.10.3
depends_on:
- "genesis_validator"
command: ["secondary"]
command: [ "secondary" ]
# mixnet_contract:
# build: docker/mixnet_contract
# image: contract:latest
@@ -74,49 +74,34 @@ services:
- "genesis_validator"
- "secondary_validator"
# mongo:
# image: mongo:latest
# command:
# - --storageEngine=wiredTiger
# volumes:
# - mongo_data:/data/db
# block_explorer:
# build:
# context: https://github.com/forbole/big-dipper.git#v0.41.x-7
# image: block_explorer:v0.41.x-7
# ports:
# - "3080:3000"
# depends_on:
# - "mongo"
# environment:
# ROOT_URL: ${APP_ROOT_URL:-http://localhost}
# MONGO_URL: mongodb://mongo:27017/meteor
# PORT: 3000
# METEOR_SETTINGS: ${METEOR_SETTINGS}
# explorer:
# build:
# context: docker/explorer
# image: explorer:latest
# ports:
# - "3040:3000"
# depends_on:
# - "genesis_validator"
# - "block_explorer"
# service to update geoip binary database, for explorer-api
geoipupdate:
container_name: geoipupdate
image: maxmindinc/geoipupdate
restart: unless-stopped
environment:
GEOIPUPDATE_ACCOUNT_ID: ${GEOIPUPDATE_ACCOUNT_ID}
GEOIPUPDATE_LICENSE_KEY: ${GEOIPUPDATE_LICENSE_KEY}
GEOIPUPDATE_EDITION_IDS: ${GEOIPUPDATE_EDITION_IDS}
GEOIPUPDATE_FREQUENCY: ${GEOIPUPDATE_FREQUENCY}
networks:
- geoipupdate
volumes:
- ${GEOIP_DB_DIRECTORY}:/usr/share/GeoIP
# mongo:
# image: mongo:latest
# command:
# - --storageEngine=wiredTiger
# volumes:
# - mongo_data:/data/db
# block_explorer:
# build:
# context: https://github.com/forbole/big-dipper.git#v0.41.x-7
# image: block_explorer:v0.41.x-7
# ports:
# - "3080:3000"
# depends_on:
# - "mongo"
# environment:
# ROOT_URL: ${APP_ROOT_URL:-http://localhost}
# MONGO_URL: mongodb://mongo:27017/meteor
# PORT: 3000
# METEOR_SETTINGS: ${METEOR_SETTINGS}
# explorer:
# build:
# context: docker/explorer
# image: explorer:latest
# ports:
# - "3040:3000"
# depends_on:
# - "genesis_validator"
# - "block_explorer"
volumes:
genesis_volume:
@@ -126,11 +111,11 @@ volumes:
# contract_volume:
# mongo_data:
networks:
geoipupdate:
localnet:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.168.10.0/25
- subnet: 172.168.10.0/25
-2
View File
@@ -1,2 +0,0 @@
# The path to the geoip database file
GEOIP_DB_PATH=./geo_ip/GeoLite2-Country.mmdb
-1
View File
@@ -1,3 +1,2 @@
target
explorer-api-state.json
/geo_ip
+1 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "explorer-api"
version = "1.1.0"
version = "1.0.1"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -24,11 +24,8 @@ serde_json = "1.0.66"
thiserror = "1.0.29"
tokio = {version = "1.21.2", features = ["full"] }
maxminddb = "0.23.0"
dotenv = "0.15.0"
mixnet-contract-common = { path = "../common/cosmwasm-smart-contracts/mixnet-contract" }
contracts-common = { path = "../common/cosmwasm-smart-contracts/contracts-common" }
network-defaults = { path = "../common/network-defaults" }
logging = { path = "../common/logging"}
task = { path = "../common/task" }
validator-client = { path = "../common/client-libs/validator-client", features=["nymd-client"] }
+14 -42
View File
@@ -1,58 +1,30 @@
# Network Explorer API
Network Explorer API
====================
An API that provides data for the [Network Explorer](../explorer).
Features:
- geolocates mixnodes using https://dev.maxmind.com/geoip/geolite2-free-geolocation-data
- calculates how many nodes are in each country
- proxies mixnode API requests to add HTTPS
## GeoIP db install/update
First we need to install the geoip database.
We use https://github.com/maxmind/geoipupdate to automatically
download and update GeoLite2 binary database. For convenience we
run it as a docker container.
At the root of the repo, inside the `docker-compose.yml`, there
is a docker service `geoipupdate` for it.
Supposed you provided an `.env` file with **all the environment
variables** listed in `.env.sample-dev` (found at the root),
simply run the service through docker:
```shell
docker compose up -d geoipupdate
```
Running this command will automatically install (and update) the
db file inside the directory path provided by `GEOIP_DB_DIRECTORY`
env variable.
- geolocates mixnodes using https://app.ipbase.com/
- calculates how many nodes are in each country
- proxies mixnode API requests to add HTTPS
## Running
When starting the explorer-api, supply the environment variable
`GEOIP_DB_PATH`, pointing to the GeoLite2 binary database file.
It should be previously installed thanks to `geoipupdate` service.
For example:
```shell
GEOIP_DB_PATH=./geo_ip/GeoLite2-Country.mmdb cargo run
```
Note: explorer-api binary reads the provided `.env` file.
Supply the environment variable `GEOIP_DATABASE_PATH` with a path
that points to a GeoIP2 database file in binary format.
Run as a service and reverse proxy with `nginx` to add `https` with Lets Encrypt.
Setup nginx to inject the request IP to the header `X-Real-IP`.
Use https://github.com/maxmind/geoipupdate to automatically
provide and update the GeoIP2 database file.
# TODO / Known Issues
## TODO
- record the number of mixnodes on a given date and write to a file for later retrieval
- dependency injection
- tests
* record the number of mixnodes on a given date and write to a file for later retrieval
* dependency injection
* tests
@@ -58,10 +58,7 @@ impl GeoLocateTask {
continue;
}
match geo_ip.query(
&cache_item.mix_node().host,
Some(cache_item.mix_node().mix_port),
) {
match geo_ip.query(&cache_item.mix_node().host) {
Ok(opt) => match opt {
Some(location) => {
let location = Location::new(location);
Binary file not shown.
+9 -31
View File
@@ -4,14 +4,9 @@
use isocountry::CountryCode;
use log::warn;
use maxminddb::{geoip2::Country, MaxMindDBError, Reader};
use std::{
net::{IpAddr, ToSocketAddrs},
str::FromStr,
sync::Arc,
};
use std::{net::IpAddr, str::FromStr, sync::Arc};
const DEFAULT_DATABASE_PATH: &str = "./geo_ip/GeoLite2-Country.mmdb";
const FAKE_PORT: u16 = 1234;
const DEFAULT_DATABASE_PATH: &str = "./src/geo_ip/GeoLite2-Country.mmdb";
#[derive(Debug)]
pub enum GeoIpError {
@@ -22,7 +17,7 @@ pub enum GeoIpError {
// The current State implementation does not allow to fail on state
// creation, ie. returning Result<>. To avoid to use unwrap family,
// as a workaround, wrap the state inside an Option<>
// If Reader::open_readfile fails for some reason db will be set to None
// If Reader::open_readfile fails for some reason db will will be set to None
// and an error will be logged.
pub(crate) struct GeoIp {
pub(crate) db: Option<Reader<Vec<u8>>>,
@@ -42,9 +37,9 @@ pub(crate) struct Location {
impl GeoIp {
pub fn new() -> Self {
let db_path = std::env::var("GEOIP_DB_PATH").unwrap_or_else(|e| {
let db_path = std::env::var("GEOIP_DATABASE_PATH").unwrap_or_else(|e| {
warn!(
"Env variable GEOIP_DB_PATH is not set: {} - Fallback to {}",
"Env variable GEOIP_DATABASE_PATH is not set: {} - Fallback to {}",
e, DEFAULT_DATABASE_PATH
);
DEFAULT_DATABASE_PATH.to_string()
@@ -57,27 +52,10 @@ impl GeoIp {
GeoIp { db: reader }
}
pub fn query(&self, address: &str, port: Option<u16>) -> Result<Option<Location>, GeoIpError> {
let ip: IpAddr = FromStr::from_str(address).or_else(|_| {
debug!(
"Fail to create IpAddr from {}. Trying using internal lookup...",
&address
);
let p = port.unwrap_or(FAKE_PORT);
let socket_addr = (address, p)
.to_socket_addrs()
.map_err(|e| {
error!("Fail to resolve IP address from {}:{}: {}", &address, p, e);
GeoIpError::NoValidIP
})?
.next()
.ok_or_else(|| {
error!("Fail to resolve IP address from {}:{}", &address, p);
GeoIpError::NoValidIP
})?;
let ip = socket_addr.ip();
debug!("Internal lookup succeed, resolved ip: {}", ip);
Ok(ip)
pub fn query(&self, address: &str) -> Result<Option<Location>, GeoIpError> {
let ip: IpAddr = FromStr::from_str(address).map_err(|e| {
error!("Fail to create IpAddr from {}: {}", &address, e);
GeoIpError::NoValidIP
})?;
let result = self
.db
+1 -1
View File
@@ -39,7 +39,7 @@ fn find_location(request: &Request<'_>) -> Result<Location, (Status, LocationErr
let location = geo_ip
.0
.clone()
.query(&ip, None)
.query(&ip)
.map_err(|e| match e {
GeoIpError::NoValidIP => (Status::Forbidden, LocationError::NoIP),
GeoIpError::InternalError => {
+15 -3
View File
@@ -4,9 +4,7 @@ extern crate rocket;
extern crate rocket_okapi;
use clap::Parser;
use dotenv::dotenv;
use log::info;
use logging::setup_logging;
use network_defaults::setup_env;
use task::ShutdownNotifier;
@@ -32,7 +30,6 @@ const COUNTRY_DATA_REFRESH_INTERVAL: u64 = 60 * 15; // every 15 minutes
#[tokio::main]
async fn main() {
dotenv().ok();
setup_logging();
let args = commands::Cli::parse();
setup_env(args.config_env_file);
@@ -116,3 +113,18 @@ async fn wait_for_signal() {
},
}
}
fn setup_logging() {
let mut log_builder = pretty_env_logger::formatted_timed_builder();
if let Ok(s) = ::std::env::var("RUST_LOG") {
log_builder.parse_filters(&s);
} else {
// default to 'Info'
log_builder.filter(None, log::LevelFilter::Info);
}
log_builder
.filter_module("tokio_reactor", log::LevelFilter::Warn)
.filter_module("reqwest", log::LevelFilter::Warn)
.init();
}
+1 -3
View File
@@ -4,7 +4,7 @@
use crate::client::ThreadsafeValidatorClient;
use crate::helpers::best_effort_small_dec_to_f64;
use crate::mix_node::models::EconomicDynamicsStats;
use contracts_common::truncate_decimal;
use mixnet_contract_common::rewarding::helpers::truncate_decimal;
use mixnet_contract_common::MixId;
pub(crate) async fn retrieve_mixnode_econ_stats(
@@ -41,8 +41,6 @@ pub(crate) async fn retrieve_mixnode_econ_stats(
Some(EconomicDynamicsStats {
stake_saturation: best_effort_small_dec_to_f64(stake_saturation.saturation) as f32,
uncapped_saturation: best_effort_small_dec_to_f64(stake_saturation.uncapped_saturation)
as f32,
active_set_inclusion_probability: inclusion_probability.in_active,
reserve_set_inclusion_probability: inclusion_probability.in_reserve,
// drop precision for compatibility sake
-6
View File
@@ -3,7 +3,6 @@
use crate::cache::Cache;
use crate::mix_nodes::location::Location;
use contracts_common::Percent;
use mixnet_contract_common::Delegation;
use mixnet_contract_common::{Addr, Coin, Layer, MixId, MixNode};
use serde::Deserialize;
@@ -25,7 +24,6 @@ pub(crate) enum MixnodeStatus {
pub(crate) struct PrettyDetailedMixNodeBond {
// I leave this to @MS to refactor this type as a lot of things here are redundant thanks to
// the existence of `MixNodeDetails`
pub mix_id: MixId,
pub location: Option<Location>,
pub status: MixnodeStatus,
pub pledge_amount: Coin,
@@ -34,12 +32,9 @@ pub(crate) struct PrettyDetailedMixNodeBond {
pub layer: Layer,
pub mix_node: MixNode,
pub stake_saturation: f32,
pub uncapped_saturation: f32,
pub avg_uptime: u8,
pub estimated_operator_apy: f64,
pub estimated_delegators_apy: f64,
pub operating_cost: Coin,
pub profit_margin_percent: Percent,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, JsonSchema)]
@@ -154,7 +149,6 @@ pub(crate) struct NodeStats {
#[derive(Clone, Serialize, Deserialize, JsonSchema)]
pub(crate) struct EconomicDynamicsStats {
pub(crate) stake_saturation: f32,
pub(crate) uncapped_saturation: f32,
pub(crate) active_set_inclusion_probability: SelectionChance,
pub(crate) reserve_set_inclusion_probability: SelectionChance,
+13 -5
View File
@@ -126,6 +126,19 @@ impl ThreadsafeMixNodesCache {
self.mixnodes.read().await.get_mixnode(mix_id)
}
pub(crate) async fn get_mixnode_by_identity(
&self,
pubkey: &str,
) -> Option<MixNodeBondAnnotated> {
let all_nodes = self.get_mixnodes().await?;
for (_, node) in all_nodes {
if node.mix_node().identity_key == pubkey {
return Some(node);
}
}
None
}
pub(crate) async fn get_mixnodes(&self) -> Option<HashMap<MixId, MixNodeBondAnnotated>> {
self.mixnodes.read().await.get_mixnodes()
}
@@ -141,7 +154,6 @@ impl ThreadsafeMixNodesCache {
let rewarding_info = &node.mixnode_details.rewarding_details;
PrettyDetailedMixNodeBond {
mix_id,
location: location.and_then(|l| l.location.clone()),
status: mixnodes_guard.determine_node_status(mix_id),
pledge_amount: truncate_reward(rewarding_info.operator, denom),
@@ -151,12 +163,8 @@ impl ThreadsafeMixNodesCache {
mix_node: node.mixnode_details.bond_information.mix_node.clone(),
avg_uptime: node.performance.round_to_integer(),
stake_saturation: best_effort_small_dec_to_f64(node.stake_saturation) as f32,
uncapped_saturation: best_effort_small_dec_to_f64(node.uncapped_stake_saturation)
as f32,
estimated_operator_apy: best_effort_small_dec_to_f64(node.estimated_operator_apy),
estimated_delegators_apy: best_effort_small_dec_to_f64(node.estimated_delegators_apy),
operating_cost: rewarding_info.cost_params.interval_operating_cost.clone(),
profit_margin_percent: rewarding_info.cost_params.profit_margin_percent,
}
}
+13 -11
View File
@@ -1,7 +1,7 @@
// Copyright 2021-2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use mixnet_contract_common::{MixId, MixNode};
use mixnet_contract_common::MixNode;
use rocket::serde::json::Json;
use rocket::{Route, State};
use rocket_okapi::okapi::openapi3::OpenApi;
@@ -20,39 +20,41 @@ pub fn ping_make_default_routes(settings: &OpenApiSettings) -> (Vec<Route>, Open
openapi_get_routes_spec![settings: index]
}
// TODO: I'm not deprecating this one explicitly since we don't have
// a decision on whether nodes should be accessed (as in using URL) by id or identity key
#[openapi(tag = "ping")]
#[get("/<mix_id>")]
#[get("/<pubkey>")]
pub(crate) async fn index(
mix_id: MixId,
pubkey: &str,
state: &State<ExplorerApiStateContext>,
) -> Option<Json<PingResponse>> {
match state.inner.ping.clone().get(mix_id).await {
match state.inner.ping.clone().get(pubkey).await {
Some(cache_value) => {
trace!("Returning cached value for {}", mix_id);
trace!("Returning cached value for {}", pubkey);
Some(Json(PingResponse {
pending: cache_value.pending,
ports: cache_value.ports,
}))
}
None => {
trace!("No cache value for {}", mix_id);
trace!("No cache value for {}", pubkey);
match state.inner.get_mix_node(mix_id).await {
match state.inner.get_mix_node_by_pubkey(pubkey).await {
Some(node) => {
// set status to pending, so that any HTTP requests are pending
state.inner.ping.set_pending(mix_id).await;
state.inner.ping.set_pending(pubkey).await;
// do the check
let ports = Some(port_check(node.mix_node()).await);
trace!("Tested mix node {}: {:?}", mix_id, ports);
trace!("Tested mix node {}: {:?}", pubkey, ports);
let response = PingResponse {
ports,
pending: false,
};
// cache for 1 min
trace!("Caching value for {}", mix_id);
state.inner.ping.set(mix_id, response.clone()).await;
trace!("Caching value for {}", pubkey);
state.inner.ping.set(pubkey, response.clone()).await;
// return response
Some(Json(response))
+7 -8
View File
@@ -2,12 +2,11 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use mixnet_contract_common::MixId;
use serde::Deserialize;
use serde::Serialize;
use tokio::sync::RwLock;
pub(crate) type PingCache = HashMap<MixId, PingCacheItem>;
pub(crate) type PingCache = HashMap<String, PingCacheItem>;
const PING_TTL: Duration = Duration::from_secs(60 * 5); // 5 mins, before port check will be re-tried (only while pending)
const CACHE_TTL: Duration = Duration::from_secs(60 * 60); // 1 hour, to cache result from port check
@@ -24,11 +23,11 @@ impl ThreadsafePingCache {
}
}
pub(crate) async fn get(&self, mix_id: MixId) -> Option<PingResponse> {
pub(crate) async fn get(&self, identity_key: &str) -> Option<PingResponse> {
self.inner
.read()
.await
.get(&mix_id)
.get(identity_key)
.filter(|cache_item| cache_item.valid_until > SystemTime::now())
.map(|cache_item| {
if cache_item.pending {
@@ -44,9 +43,9 @@ impl ThreadsafePingCache {
})
}
pub(crate) async fn set_pending(&self, mix_id: MixId) {
pub(crate) async fn set_pending(&self, identity_key: &str) {
self.inner.write().await.insert(
mix_id,
identity_key.to_string(),
PingCacheItem {
pending: true,
valid_until: SystemTime::now() + PING_TTL,
@@ -55,9 +54,9 @@ impl ThreadsafePingCache {
);
}
pub(crate) async fn set(&self, mix_id: MixId, item: PingResponse) {
pub(crate) async fn set(&self, identity_key: &str, item: PingResponse) {
self.inner.write().await.insert(
mix_id,
identity_key.to_string(),
PingCacheItem {
pending: false,
valid_until: SystemTime::now() + CACHE_TTL,
+8 -1
View File
@@ -3,7 +3,7 @@ use std::path::Path;
use chrono::{DateTime, Utc};
use log::info;
use mixnet_contract_common::MixId;
use mixnet_contract_common::{IdentityKeyRef, MixId};
use serde::{Deserialize, Serialize};
use crate::client::ThreadsafeValidatorClient;
@@ -41,6 +41,13 @@ impl ExplorerApiState {
pub(crate) async fn get_mix_node(&self, mix_id: MixId) -> Option<MixNodeBondAnnotated> {
self.mixnodes.get_mixnode(mix_id).await
}
pub(crate) async fn get_mix_node_by_pubkey(
&self,
pubkey: IdentityKeyRef<'_>,
) -> Option<MixNodeBondAnnotated> {
self.mixnodes.get_mixnode_by_identity(pubkey).await
}
}
#[derive(Debug, Serialize, Deserialize)]
+1 -2
View File
@@ -26,8 +26,7 @@
"react-router-dom": "6",
"react-simple-maps": "^2.3.0",
"react-tooltip": "^4.2.21",
"use-clipboard-copy": "^0.2.0",
"big.js": "^6.2.1"
"use-clipboard-copy": "^0.2.0"
},
"devDependencies": {
"@babel/core": "^7.15.0",
-1
View File
@@ -14,7 +14,6 @@ export const VALIDATORS_API = `${VALIDATOR_BASE_URL}/validators`;
export const BLOCK_API = `${VALIDATOR_API_BASE_URL}/block`;
export const COUNTRY_DATA_API = `${API_BASE_URL}/countries`;
export const UPTIME_STORY_API = `${VALIDATOR_API_BASE_URL}/api/v1/status/mixnode`; // add ID then '/history' to this.
export const UPTIME_STORY_API_GATEWAY = `${VALIDATOR_API_BASE_URL}/api/v1/status/gateway`; // add ID then '/history' or '/report' to this.
// errors
export const MIXNODE_API_ERROR = "We're having trouble finding that record, please try again or Contact Us.";
+1 -9
View File
@@ -2,7 +2,6 @@ import {
BLOCK_API,
COUNTRY_DATA_API,
GATEWAYS_API,
UPTIME_STORY_API_GATEWAY,
MIXNODE_API,
MIXNODE_PING,
MIXNODES_API,
@@ -16,8 +15,6 @@ import {
DelegationsResponse,
UniqDelegationsResponse,
GatewayResponse,
GatewayReportResponse,
UptimeStoryResponse,
MixNodeDescriptionResponse,
MixNodeResponse,
MixNodeResponseItem,
@@ -26,6 +23,7 @@ import {
StatsResponse,
StatusResponse,
SummaryOverviewResponse,
UptimeStoryResponse,
ValidatorsResponse,
} from '../typeDefs/explorer-api';
@@ -94,12 +92,6 @@ export class Api {
return res.json();
};
static fetchGatewayUptimeStoryById = async (id: string): Promise<UptimeStoryResponse> =>
(await fetch(`${UPTIME_STORY_API_GATEWAY}/${id}/history`)).json();
static fetchGatewayReportById = async (id: string): Promise<GatewayReportResponse> =>
(await fetch(`${UPTIME_STORY_API_GATEWAY}/${id}/report`)).json();
static fetchValidators = async (): Promise<ValidatorsResponse> => {
const res = await fetch(VALIDATORS_API);
const json = await res.json();
+36 -57
View File
@@ -1,12 +1,9 @@
import * as React from 'react';
import { Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import { Tooltip } from '@nymproject/react/tooltip/Tooltip';
import { CopyToClipboard } from '@nymproject/react/clipboard/CopyToClipboard';
import { Box } from '@mui/system';
import { cellStyles } from './Universal-DataGrid';
import { currencyToString } from '../utils/currency';
import { GatewayEnrichedRowType } from './Gateways';
import { MixnodeRowType } from './MixNodes';
export type ColumnsType = {
@@ -46,60 +43,42 @@ function formatCellValues(val: string | number, field: string) {
export const DetailTable: React.FC<{
tableName: string;
columnsData: ColumnsType[];
rows: MixnodeRowType[] | GatewayEnrichedRowType[];
}> = ({ tableName, columnsData, rows }: UniversalTableProps) => {
const theme = useTheme();
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label={tableName}>
<TableHead>
<TableRow>
{columnsData?.map(({ field, title, flex, tooltipInfo }) => (
<TableCell key={field} sx={{ fontSize: 14, fontWeight: 600, flex }}>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
{tooltipInfo && (
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Tooltip
title={tooltipInfo}
id={field}
placement="top-start"
textColor={theme.palette.nym.networkExplorer.tooltip.color}
bgColor={theme.palette.nym.networkExplorer.tooltip.background}
maxWidth={230}
arrow
/>
</Box>
)}
{title}
</Box>
rows: MixnodeRowType[];
}> = ({ tableName, columnsData, rows }: UniversalTableProps) => (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label={tableName}>
<TableHead>
<TableRow>
{columnsData?.map(({ field, title, flex }) => (
<TableCell key={field} sx={{ fontSize: 14, fontWeight: 600, flex }}>
{title}
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.map((eachRow) => (
<TableRow key={eachRow.id} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
{columnsData?.map((_, index) => (
<TableCell
key={_.title}
component="th"
scope="row"
variant="body"
sx={{
...cellStyles,
padding: 2,
width: 200,
fontSize: 14,
}}
data-testid={`${_.title.replace(/ /g, '-')}-value`}
>
{formatCellValues(eachRow[columnsData[index].field], columnsData[index].field)}
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.map((eachRow) => (
<TableRow key={eachRow.id} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
{columnsData?.map((data, index) => (
<TableCell
key={data.title}
component="th"
scope="row"
variant="body"
sx={{
...cellStyles,
padding: 2,
width: 200,
fontSize: 14,
}}
data-testid={`${data.title.replace(/ /g, '-')}-value`}
>
{formatCellValues(eachRow[columnsData[index].field], columnsData[index].field)}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
};
))}
</TableBody>
</Table>
</TableContainer>
);
+3 -28
View File
@@ -1,48 +1,23 @@
import { GatewayResponse, GatewayResponseItem, GatewayReportResponse } from '../typeDefs/explorer-api';
import { GatewayResponse } from '../typeDefs/explorer-api';
export type GatewayRowType = {
id: string;
owner: string;
identityKey: string;
identity_key: string;
bond: number;
host: string;
location: string;
};
export type GatewayEnrichedRowType = GatewayRowType & {
routingScore: string;
avgUptime: string;
clientsPort: number;
mixPort: number;
};
export function gatewayToGridRow(arrayOfGateways: GatewayResponse): GatewayRowType[] {
return !arrayOfGateways
? []
: arrayOfGateways.map((gw) => ({
id: gw.owner,
owner: gw.owner,
identityKey: gw.gateway.identity_key || '',
identity_key: gw.gateway.identity_key || '',
location: gw?.gateway?.location || '',
bond: gw.pledge_amount.amount || 0,
host: gw.gateway.host || '',
}));
}
export function gatewayEnrichedToGridRow(
gateway: GatewayResponseItem,
report: GatewayReportResponse,
): GatewayEnrichedRowType {
return {
id: gateway.owner,
owner: gateway.owner,
identityKey: gateway.gateway.identity_key || '',
location: gateway?.gateway?.location || '',
bond: gateway.pledge_amount.amount || 0,
host: gateway.gateway.host || '',
clientsPort: gateway.gateway.clients_port || 0,
mixPort: gateway.gateway.mix_port || 0,
routingScore: `${report.most_recent}%`,
avgUptime: `${report.last_day || report.last_hour}%`,
};
}
@@ -6,16 +6,14 @@ export const EconomicsInfoColumns: ColumnsType[] = [
title: 'Estimated Total Reward',
flex: 1,
headerAlign: 'left',
tooltipInfo:
'Estimated node reward (total for the operator and delegators) in the current epoch. There are roughly 24 epochs in a day.',
tooltipInfo: 'Estimated reward per epoch for this profit margin if your node is selected in the active set.',
},
{
field: 'estimatedOperatorReward',
title: 'Estimated Operator Reward',
flex: 1,
headerAlign: 'left',
tooltipInfo:
"Estimated operator's reward (including PM and Operating Cost) in the current epoch. There are roughly 24 epochs in a day.",
tooltipInfo: 'Estimated reward per epoch for this profit margin if your node is selected in the active set.',
},
{
field: 'selectionChance',
@@ -31,7 +29,7 @@ export const EconomicsInfoColumns: ColumnsType[] = [
flex: 1,
headerAlign: 'left',
tooltipInfo:
'Level of stake saturation for this node. Nodes receive more rewards the higher their saturation level, up to 100%. Beyond 100% no additional rewards are granted. The current stake saturation level is: 750k NYM, computed as S/K where S is total amount of tokens available to stakeholders and K is the number of nodes in the reward set.',
'Level of stake saturation for this node. Nodes receive more rewards the higher their saturation level, up to 100%. Beyond 100% no additional rewards are granted. The current stake saturation level is: 1 million NYM, computed as S/K where S is total amount of tokens available to stakeholders and K is the number of nodes in the reward set.',
},
{
field: 'profitMargin',
@@ -39,15 +37,7 @@ export const EconomicsInfoColumns: ColumnsType[] = [
flex: 1,
headerAlign: 'left',
tooltipInfo:
'Percentage of the delegators rewards that the operator takes as fee before rewards are distributed to the delegators.',
},
{
field: 'operatingCost',
title: 'Operating Cost',
flex: 1,
headerAlign: 'left',
tooltipInfo:
'Monthly operational cost of running this node. This cost is set by the operator and it influences how the rewards are split between the operator and delegators.',
'Percentage of the delegates rewards that the operator takes as fee before rewards are distributed to the delegates.',
},
{
field: 'avgUptime',
@@ -26,9 +26,6 @@ const row: EconomicsInfoRowWithIndex = {
profitMargin: {
value: '10 %',
},
operatingCost: {
value: '11121 NYM',
},
stakeSaturation: {
value: '80 %',
progressBarValue: 80,
@@ -67,9 +64,6 @@ const emptyRow: EconomicsInfoRowWithIndex = {
profitMargin: {
value: '-',
},
operatingCost: {
value: '-',
},
stakeSaturation: {
value: '-',
progressBarValue: 0,
@@ -1,11 +1,25 @@
import { currencyToString, unymToNym } from '../../../utils/currency';
import { currencyToString } from '../../../utils/currency';
import { useMixnodeContext } from '../../../context/mixnode';
import { ApiState, MixNodeEconomicDynamicsStatsResponse } from '../../../typeDefs/explorer-api';
import { EconomicsInfoRowWithIndex } from './types';
import { toPercentIntegerString } from '../../../utils';
const selectionChance = (economicDynamicsStats: ApiState<MixNodeEconomicDynamicsStatsResponse> | undefined) =>
economicDynamicsStats?.data?.active_set_inclusion_probability || '-';
const selectionChance = (economicDynamicsStats: ApiState<MixNodeEconomicDynamicsStatsResponse> | undefined) => {
const inclusionProbability = economicDynamicsStats?.data?.active_set_inclusion_probability;
// TODO: when v2 will be deployed, remove cases: VeryHigh, Moderate and VeryLow
switch (inclusionProbability) {
case 'VeryLow':
return 'Very Low';
case 'VeryHigh':
return 'Very High';
case 'High':
case 'Good':
case 'Low':
case 'Moderate':
return inclusionProbability;
default:
return '-';
}
};
export const EconomicsInfoRows = (): EconomicsInfoRowWithIndex => {
const { economicDynamicsStats, mixNode } = useMixnodeContext();
@@ -14,14 +28,10 @@ export const EconomicsInfoRows = (): EconomicsInfoRowWithIndex => {
currencyToString((economicDynamicsStats?.data?.estimated_total_node_reward || '').toString()) || '-';
const estimatedOperatorRewards =
currencyToString((economicDynamicsStats?.data?.estimated_operator_reward || '').toString()) || '-';
const stakeSaturation = economicDynamicsStats?.data?.uncapped_saturation || '-';
const profitMargin = mixNode?.data?.profit_margin_percent
? toPercentIntegerString(mixNode?.data?.profit_margin_percent)
: '-';
const stakeSaturation = economicDynamicsStats?.data?.stake_saturation || '-';
const profitMargin = mixNode?.data?.mix_node.profit_margin_percent || '-';
const avgUptime = economicDynamicsStats?.data?.current_interval_uptime;
const opCost = mixNode?.data?.operating_cost;
return {
id: 1,
estimatedTotalReward: {
@@ -40,9 +50,6 @@ export const EconomicsInfoRows = (): EconomicsInfoRowWithIndex => {
profitMargin: {
value: profitMargin ? `${profitMargin} %` : '-',
},
operatingCost: {
value: opCost ? `${unymToNym(opCost.amount, 6)} NYM` : '-',
},
avgUptime: {
value: avgUptime ? `${avgUptime} %` : '-',
},
@@ -10,7 +10,6 @@ export interface EconomicsInfoRow {
stakeSaturation: EconomicsRowsType;
profitMargin: EconomicsRowsType;
avgUptime: EconomicsRowsType;
operatingCost: EconomicsRowsType;
}
export type EconomicsInfoRowWithIndex = EconomicsInfoRow & { id: number };

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