merge in binary changes

This commit is contained in:
Tommy Verrall
2022-12-05 15:55:53 +01:00
61 changed files with 1926 additions and 2217 deletions
@@ -1,13 +1,13 @@
[
{
"id": "nym-testing",
"description": "coconuts",
"id": "Coconut",
"description": "Bandwidth Test",
"items": [
{
"id": "nym-coconut",
"description": "nym-credentials",
"address": "<input service provider address>",
"gateway": "<input these values>"
"id": "cocos",
"description": "testing",
"address": "51RhttA7LhKp573QWUU74uaFuoyb4Bg2cqNUaiuTRAMb.GW9e3T5TQvn5iyvdTVnhTWaZ9WLCaBvA8XVdnw4xL9DW@EVupP2tRUeZo5Y6RpBHAbm8kSntpgNyZNL6yCr7BDEoG",
"gateway": "EVupP2tRUeZo5Y6RpBHAbm8kSntpgNyZNL6yCr7BDEoG"
}
]
}
+6
View File
@@ -2,6 +2,12 @@
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).
## [Unreleased]
### Changed
- gateway: Renamed flag from `enabled/disabled_credentials_mode` to `only-coconut-credentials`
## [v1.1.1](https://github.com/nymtech/nym/tree/v1.1.1) (2022-11-29)
### Added
Generated
-42
View File
@@ -923,7 +923,6 @@ dependencies = [
name = "credential"
version = "0.1.0"
dependencies = [
"async-trait",
"bip39",
"cfg-if 0.1.10",
"clap 3.2.8",
@@ -935,7 +934,6 @@ dependencies = [
"crypto",
"network-defaults",
"pemstore",
"pickledb",
"rand 0.7.3",
"serde",
"thiserror",
@@ -2745,12 +2743,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "linked-hash-map"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]]
name = "lioness"
version = "0.1.2"
@@ -3934,19 +3926,6 @@ dependencies = [
"indexmap",
]
[[package]]
name = "pickledb"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9161694d67f6c5163519d42be942ae36bbdb55f439460144f105bc4f9f7d1d61"
dependencies = [
"bincode",
"serde",
"serde_cbor",
"serde_json",
"serde_yaml",
]
[[package]]
name = "pin-project"
version = "1.0.10"
@@ -5057,18 +5036,6 @@ dependencies = [
"serde",
]
[[package]]
name = "serde_yaml"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a521f2940385c165a24ee286aa8599633d162077a54bdcae2a6fd5a7bfa7a0"
dependencies = [
"indexmap",
"ryu",
"serde",
"yaml-rust",
]
[[package]]
name = "sha-1"
version = "0.8.2"
@@ -6938,15 +6905,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "yaml-rust"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]
[[package]]
name = "yansi"
version = "0.5.1"
@@ -186,13 +186,10 @@ impl TopologyRefresher {
/// # Arguments
///
/// * `topology`: active topology constructed from validator api data
/// * `mixnodes_count`: total number of active mixnodes
fn check_layer_distribution(
&self,
active_topology: &NymTopology,
mixnodes_count: usize,
) -> bool {
fn check_layer_distribution(&self, active_topology: &NymTopology) -> bool {
let mixes = active_topology.mixes();
let mixnodes_count = active_topology.num_mixnodes();
if active_topology.gateways().is_empty() {
return false;
}
@@ -257,11 +254,10 @@ impl TopologyRefresher {
Ok(gateways) => gateways,
};
let mixnodes_count = mixnodes.len();
let topology = nym_topology_from_detailed(mixnodes, gateways)
.filter_system_version(&self.client_version);
if !self.check_layer_distribution(&topology, mixnodes_count) {
if !self.check_layer_distribution(&topology) {
warn!("The current filtered active topology has extremely skewed layer distribution. It cannot be used.");
None
} else {
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use config::NymConfig;
use config::{NymConfig, DB_FILE_NAME};
use nymsphinx::params::PacketSize;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
@@ -412,7 +412,7 @@ impl<T: NymConfig> Client<T> {
T::default_data_directory(Some(id)).join("reply_key_store")
}
fn default_database_path(id: &str) -> PathBuf {
T::default_data_directory(Some(id)).join("db.sqlite")
T::default_data_directory(Some(id)).join(DB_FILE_NAME)
}
}
-2
View File
@@ -6,11 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-trait = "0.1.52"
bip39 = "1.0.1"
cfg-if = "0.1"
clap = { version = "3.2", features = ["cargo", "derive"] }
pickledb = "0.4.1"
rand = "0.7.3"
serde = { version = "1.0", features = ["derive"] }
thiserror = "1.0"
+70 -164
View File
@@ -1,14 +1,12 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use async_trait::async_trait;
use clap::{Args, Subcommand};
use completions::ArgShell;
use pickledb::PickleDb;
use rand::rngs::OsRng;
use std::str::FromStr;
use coconut_interface::{Attribute, Base58, BlindSignRequest, Bytable, Parameters};
use coconut_interface::{Base58, Parameters};
use credential_storage::storage::Storage;
use credential_storage::PersistentStorage;
use credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
@@ -20,16 +18,12 @@ use validator_client::{CoconutApiClient, Config};
use crate::client::Client;
use crate::error::{CredentialClientError, Result};
use crate::state::{KeyPair, RequestData, State};
use crate::state::{KeyPair, State};
#[derive(Subcommand)]
pub(crate) enum Commands {
/// Deposit funds for buying coconut credential
Deposit(Deposit),
/// Lists the tx hashes of previous deposits
ListDeposits(ListDeposits),
/// Get a credential for a given deposit
GetCredential(GetCredential),
pub(crate) enum Command {
/// Run the binary
Run(Run),
/// Generate shell completions
Completions(ArgShell),
@@ -38,169 +32,81 @@ pub(crate) enum Commands {
GenerateFigSpec,
}
#[async_trait]
pub(crate) trait Execute {
async fn execute(&self, db: &mut PickleDb, shared_storage: PersistentStorage) -> Result<()>;
}
#[derive(Args)]
pub(crate) struct Run {
/// Home directory of the client that is supposed to use the credential.
#[clap(long)]
pub(crate) client_home_directory: std::path::PathBuf,
#[derive(Args, Clone)]
pub(crate) struct Deposit {
/// The nymd URL that should be used
#[clap(long)]
nymd_url: String,
/// A mnemonic for the account that does the deposit
pub(crate) nymd_url: String,
/// A mnemonic for the account that buys the credential
#[clap(long)]
mnemonic: String,
/// The amount that needs to be deposited
pub(crate) mnemonic: String,
/// The amount of utokens the credential will hold
#[clap(long)]
amount: u64,
pub(crate) amount: u64,
}
#[async_trait]
impl Execute for Deposit {
async fn execute(&self, db: &mut PickleDb, _shared_storage: PersistentStorage) -> Result<()> {
let mut rng = OsRng;
let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng));
let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng));
pub(crate) async fn deposit(nymd_url: &str, mnemonic: &str, amount: u64) -> Result<State> {
let mut rng = OsRng;
let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng));
let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng));
let client = Client::new(&self.nymd_url, &self.mnemonic);
let tx_hash = client
.deposit(
self.amount,
signing_keypair.public_key.clone(),
encryption_keypair.public_key.clone(),
None,
)
.await?;
let state = State {
amount: self.amount,
tx_hash: tx_hash.clone(),
signing_keypair,
encryption_keypair,
blind_request_data: None,
signature: None,
};
db.set(&tx_hash, &state).unwrap();
println!("{:?}", state);
Ok(())
}
}
#[derive(Args, Clone)]
pub(crate) struct ListDeposits {}
#[async_trait]
impl Execute for ListDeposits {
async fn execute(&self, db: &mut PickleDb, _shared_storage: PersistentStorage) -> Result<()> {
for kv in db.iter() {
println!("{:?}", kv.get_value::<State>());
}
Ok(())
}
}
#[derive(Args, Clone)]
pub(crate) struct GetCredential {
/// The hash of a successful deposit transaction
#[clap(long)]
tx_hash: String,
/// The nymd URL that should be used
#[clap(long)]
nymd_url: String,
/// If we want to get the signature without attaching a blind sign request; it is expected that
/// there is already a signature stored on the signer
#[clap(long, parse(from_flag))]
__no_request: bool,
}
#[async_trait]
impl Execute for GetCredential {
async fn execute(&self, db: &mut PickleDb, shared_storage: PersistentStorage) -> Result<()> {
let mut state = db
.get::<State>(&self.tx_hash)
.ok_or(CredentialClientError::NoDeposit)?;
let network_details = NymNetworkDetails::new_from_env();
let config = Config::try_from_nym_network_details(&network_details)?;
let client = validator_client::Client::new_query(config)?;
let coconut_api_clients = CoconutApiClient::all_coconut_api_clients(&client).await?;
let params = Parameters::new(TOTAL_ATTRIBUTES).unwrap();
let bandwidth_credential_attributes = if self.__no_request {
if let Some(blind_request_data) = state.blind_request_data {
let serial_number =
Attribute::try_from_byte_slice(&blind_request_data.serial_number)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?;
let binding_number =
Attribute::try_from_byte_slice(&blind_request_data.binding_number)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?;
let pedersen_commitments_openings = vec![
Attribute::try_from_byte_slice(&blind_request_data.first_attribute)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?,
Attribute::try_from_byte_slice(&blind_request_data.second_attribute)
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?,
];
let blind_sign_request =
BlindSignRequest::from_bytes(blind_request_data.blind_sign_req.as_slice())
.map_err(|_| CredentialClientError::CorruptedBlindSignRequest)?;
BandwidthVoucher::new_with_blind_sign_req(
[serial_number, binding_number],
[&state.amount.to_string(), VOUCHER_INFO],
Hash::from_str(&self.tx_hash)
.map_err(|_| CredentialClientError::InvalidTxHash)?,
identity::PrivateKey::from_base58_string(&state.signing_keypair.private_key)?,
encryption::PrivateKey::from_base58_string(
&state.encryption_keypair.private_key,
)?,
pedersen_commitments_openings,
blind_sign_request,
)
} else {
return Err(CredentialClientError::NoLocalBlindSignRequest);
}
} else {
BandwidthVoucher::new(
&params,
state.amount.to_string(),
VOUCHER_INFO.to_string(),
Hash::from_str(&self.tx_hash).map_err(|_| CredentialClientError::InvalidTxHash)?,
identity::PrivateKey::from_base58_string(&state.signing_keypair.private_key)?,
encryption::PrivateKey::from_base58_string(&state.encryption_keypair.private_key)?,
)
};
// Back up the blind sign req data, in case of sporadic failures
state.blind_request_data = Some(RequestData::new(
bandwidth_credential_attributes.get_private_attributes(),
bandwidth_credential_attributes.pedersen_commitments_openings(),
bandwidth_credential_attributes.blind_sign_request(),
)?);
db.set(&self.tx_hash, &state).unwrap();
let signature = obtain_aggregate_signature(
&params,
&bandwidth_credential_attributes,
&coconut_api_clients,
let client = Client::new(nymd_url, mnemonic);
let tx_hash = client
.deposit(
amount,
signing_keypair.public_key.clone(),
encryption_keypair.public_key.clone(),
None,
)
.await?;
shared_storage
.insert_coconut_credential(
state.amount.to_string(),
VOUCHER_INFO.to_string(),
bandwidth_credential_attributes.get_private_attributes()[0].to_bs58(),
bandwidth_credential_attributes.get_private_attributes()[1].to_bs58(),
signature.to_bs58(),
)
.await?;
state.signature = Some(signature.to_bs58());
db.set(&self.tx_hash, &state).unwrap();
println!("Signature: {:?}", state.signature);
let state = State {
amount,
tx_hash: tx_hash.clone(),
signing_keypair,
encryption_keypair,
};
Ok(())
}
Ok(state)
}
pub(crate) async fn get_credential(state: &State, shared_storage: PersistentStorage) -> Result<()> {
let network_details = NymNetworkDetails::new_from_env();
let config = Config::try_from_nym_network_details(&network_details)?;
let client = validator_client::Client::new_query(config)?;
let coconut_api_clients = CoconutApiClient::all_coconut_api_clients(&client).await?;
let params = Parameters::new(TOTAL_ATTRIBUTES).unwrap();
let bandwidth_credential_attributes = BandwidthVoucher::new(
&params,
state.amount.to_string(),
VOUCHER_INFO.to_string(),
Hash::from_str(&state.tx_hash).map_err(|_| CredentialClientError::InvalidTxHash)?,
identity::PrivateKey::from_base58_string(&state.signing_keypair.private_key)?,
encryption::PrivateKey::from_base58_string(&state.encryption_keypair.private_key)?,
);
let signature = obtain_aggregate_signature(
&params,
&bandwidth_credential_attributes,
&coconut_api_clients,
)
.await?;
shared_storage
.insert_coconut_credential(
state.amount.to_string(),
VOUCHER_INFO.to_string(),
bandwidth_credential_attributes.get_private_attributes()[0].to_bs58(),
bandwidth_credential_attributes.get_private_attributes()[1].to_bs58(),
signature.to_bs58(),
)
.await?;
Ok(())
}
-12
View File
@@ -23,18 +23,6 @@ pub enum CredentialClientError {
#[error("Credential error: {0}")]
Credential(#[from] CredentialError),
#[error("No previous deposit with that tx hash")]
NoDeposit,
#[error("Wrong number of attributes")]
WrongAttributeNumber,
#[error("Could not find any backed up blind sign request data")]
NoLocalBlindSignRequest,
#[error("The local blind sign request data is corrupted")]
CorruptedBlindSignRequest,
#[error("The tx hash provided is not valid")]
InvalidTxHash,
+14 -32
View File
@@ -9,14 +9,13 @@ cfg_if::cfg_if! {
mod error;
mod state;
use commands::{Commands, Execute};
use error::Result;
use network_defaults::setup_env;
use clap::CommandFactory;
use completions::fig_generate;
use commands::*;
use config::{DATA_DIR, DB_FILE_NAME};
use clap::Parser;
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
use clap::{CommandFactory, Parser};
#[derive(Parser)]
#[clap(author = "Nymtech", version, about)]
@@ -25,43 +24,26 @@ cfg_if::cfg_if! {
#[clap(short, long)]
pub(crate) config_env_file: Option<std::path::PathBuf>,
/// Path where the sqlite credental database will be located.
/// It should point to a $HOME/$CLIENT_ID/data/db.sqlite file of
/// the client that is supposed to use the credential.
#[clap(long)]
pub(crate) credential_db_path: std::path::PathBuf,
#[clap(subcommand)]
command: Commands,
pub(crate) command: Command,
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Cli::parse();
setup_env(args.config_env_file.clone());
let shared_storage = credential_storage::initialise_storage(args.credential_db_path.clone()).await;
let mut db = match PickleDb::load(
"credential.db",
PickleDbDumpPolicy::AutoDump,
SerializationMethod::Json,
) {
Ok(db) => db,
Err(_) => PickleDb::new(
"credential.db",
PickleDbDumpPolicy::AutoDump,
SerializationMethod::Json,
),
};
let bin_name = "nym-credential-client";
match &args.command {
Commands::Deposit(m) => m.execute(&mut db, shared_storage).await?,
Commands::ListDeposits(m) => m.execute(&mut db, shared_storage).await?,
Commands::GetCredential(m) => m.execute(&mut db, shared_storage).await?,
Commands::Completions(s) => s.generate(&mut crate::Cli::into_app(), bin_name),
Commands::GenerateFigSpec => fig_generate(&mut crate::Cli::into_app(), bin_name)
match args.command {
Command::Run(r) => {
let db_path = r.client_home_directory.join(DATA_DIR).join(DB_FILE_NAME);
let shared_storage = credential_storage::initialise_storage(db_path).await;
let state = deposit(&r.nymd_url, &r.mnemonic, r.amount).await?;
get_credential(&state, shared_storage).await?;
}
Command::Completions(c) => c.generate(&mut crate::Cli::into_app(), bin_name),
Command::GenerateFigSpec => fig_generate(&mut crate::Cli::into_app(), bin_name)
}
Ok(())
-34
View File
@@ -1,13 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use coconut_interface::{Attribute, BlindSignRequest, Bytable, PrivateAttribute};
use serde::{Deserialize, Serialize};
use crypto::asymmetric::{encryption, identity};
use crate::error::{CredentialClientError, Result};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct KeyPair {
pub public_key: String,
@@ -38,35 +35,4 @@ pub(crate) struct State {
pub tx_hash: String,
pub signing_keypair: KeyPair,
pub encryption_keypair: KeyPair,
pub blind_request_data: Option<RequestData>,
pub signature: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct RequestData {
pub serial_number: Vec<u8>,
pub binding_number: Vec<u8>,
pub first_attribute: Vec<u8>,
pub second_attribute: Vec<u8>,
pub blind_sign_req: Vec<u8>,
}
impl RequestData {
pub fn new(
private_attributes: Vec<PrivateAttribute>,
attributes: &[Attribute],
blind_sign_request: &BlindSignRequest,
) -> Result<Self> {
if private_attributes.len() != 2 || attributes.len() != 2 {
Err(CredentialClientError::WrongAttributeNumber)
} else {
Ok(RequestData {
serial_number: private_attributes[0].to_byte_vec(),
binding_number: private_attributes[1].to_byte_vec(),
first_attribute: attributes[0].to_byte_vec(),
second_attribute: attributes[1].to_byte_vec(),
blind_sign_req: blind_sign_request.to_bytes(),
})
}
}
}
@@ -1,6 +1,5 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{validator_api, ValidatorClientError};
use coconut_dkg_common::types::NodeIndex;
#[cfg(feature = "nymd-client")]
@@ -10,9 +9,10 @@ use coconut_dkg_common::{
#[cfg(feature = "nymd-client")]
use coconut_interface::Base58;
use coconut_interface::VerificationKey;
use mixnet_contract_common::families::{Family, FamilyHead};
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::MixId;
use mixnet_contract_common::{GatewayBond, IdentityKeyRef};
use mixnet_contract_common::{IdentityKey, MixId};
#[cfg(feature = "nymd-client")]
use std::str::FromStr;
use validator_api_requests::coconut::{
@@ -220,6 +220,7 @@ impl Client<QueryNymdClient> {
impl<C> Client<C> {
// use case: somebody initialised client without a contract in order to upload and initialise one
// and now they want to actually use it without making new client
pub fn set_mixnet_contract_address(&mut self, mixnet_contract_address: cosmrs::AccountId) {
self.nymd
.set_mixnet_contract_address(mixnet_contract_address)
@@ -229,6 +230,56 @@ impl<C> Client<C> {
self.nymd.mixnet_contract_address().clone()
}
pub async fn get_all_node_families(&self) -> Result<Vec<Family>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
let mut families = Vec::new();
let mut start_after = None;
loop {
let paged_response = self
.nymd
.get_all_node_families_paged(start_after.take(), None)
.await?;
families.extend(paged_response.families);
if let Some(start_after_res) = paged_response.start_next_after {
start_after = Some(start_after_res)
} else {
break;
}
}
Ok(families)
}
pub async fn get_all_family_members(
&self,
) -> Result<Vec<(IdentityKey, FamilyHead)>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
let mut members = Vec::new();
let mut start_after = None;
loop {
let paged_response = self
.nymd
.get_all_family_members_paged(start_after.take(), None)
.await?;
members.extend(paged_response.members);
if let Some(start_after_res) = paged_response.start_next_after {
start_after = Some(start_after_res)
} else {
break;
}
}
Ok(members)
}
// basically handles paging for us
pub async fn get_all_nymd_rewarded_set_mixnodes(
&self,
@@ -7,6 +7,7 @@ use crate::nymd::NymdClient;
use async_trait::async_trait;
use cosmrs::AccountId;
use mixnet_contract_common::delegation::{MixNodeDelegationResponse, OwnerProxySubKey};
use mixnet_contract_common::families::Family;
use mixnet_contract_common::mixnode::{
MixNodeDetails, MixnodeRewardingDetailsResponse, PagedMixnodesDetailsResponse,
PagedUnbondedMixnodesResponse, StakeSaturationResponse, UnbondedMixnodeResponse,
@@ -20,9 +21,9 @@ use mixnet_contract_common::{
CurrentIntervalResponse, EpochEventId, GatewayBondResponse, GatewayOwnershipResponse,
IdentityKey, IntervalEventId, LayerDistribution, MixId, MixOwnershipResponse,
MixnodeDetailsResponse, PagedAllDelegationsResponse, PagedDelegatorDelegationsResponse,
PagedGatewayResponse, PagedMixNodeDelegationsResponse, PagedMixnodeBondsResponse,
PagedRewardedSetResponse, PendingEpochEventsResponse, PendingIntervalEventsResponse,
QueryMsg as MixnetQueryMsg,
PagedFamiliesResponse, PagedGatewayResponse, PagedMembersResponse,
PagedMixNodeDelegationsResponse, PagedMixnodeBondsResponse, PagedRewardedSetResponse,
PendingEpochEventsResponse, PendingIntervalEventsResponse, QueryMsg as MixnetQueryMsg,
};
use serde::Deserialize;
@@ -73,6 +74,24 @@ pub trait MixnetQueryClient {
.await
}
async fn get_all_node_families_paged(
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedFamiliesResponse, NymdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllFamiliesPaged { limit, start_after })
.await
}
async fn get_all_family_members_paged(
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedMembersResponse, NymdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllMembersPaged { limit, start_after })
.await
}
// mixnode-related:
async fn get_mixnode_bonds_paged(
@@ -357,6 +376,20 @@ pub trait MixnetQueryClient {
})
.await
}
async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NymdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByLabel {
label: label.to_string(),
})
.await
}
async fn get_node_family_by_head(&self, head: &str) -> Result<Option<Family>, NymdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByHead {
head: head.to_string(),
})
.await
}
}
#[async_trait]
@@ -11,7 +11,7 @@ use cosmrs::AccountId;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use mixnet_contract_common::reward_params::{IntervalRewardingParamsUpdate, Performance};
use mixnet_contract_common::{
ContractStateParams, ExecuteMsg as MixnetExecuteMsg, Gateway, MixId, MixNode,
ContractStateParams, ExecuteMsg as MixnetExecuteMsg, Gateway, LayerAssignment, MixId, MixNode,
};
#[async_trait]
@@ -108,7 +108,7 @@ pub trait MixnetSigningClient {
async fn advance_current_epoch(
&self,
new_rewarded_set: Vec<MixId>,
new_rewarded_set: Vec<LayerAssignment>,
expected_active_set_size: u32,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
@@ -136,6 +136,147 @@ pub trait MixnetSigningClient {
.await
}
// family related
async fn create_family(
&self,
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamily {
owner_signature,
label,
},
vec![],
)
.await
}
async fn create_family_on_behalf(
&self,
owner_address: String,
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamilyOnBehalf {
owner_address,
owner_signature,
label,
},
vec![],
)
.await
}
async fn join_family(
&self,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamily {
signature,
family_head,
},
vec![],
)
.await
}
async fn join_family_on_behalf(
&self,
member_address: String,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamilyOnBehalf {
member_address,
signature,
family_head,
},
vec![],
)
.await
}
async fn leave_family(
&self,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamily {
signature,
family_head,
},
vec![],
)
.await
}
async fn leave_family_on_behalf(
&self,
member_address: String,
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamilyOnBehalf {
member_address,
signature,
family_head,
},
vec![],
)
.await
}
async fn kick_family_member(
&self,
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMember { signature, member },
vec![],
)
.await
}
async fn kick_family_member_on_behalf(
&self,
head_address: String,
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMemberOnBehalf {
head_address,
signature,
member,
},
vec![],
)
.await
}
// mixnode-related:
async fn bond_mixnode(
+12 -8
View File
@@ -11,6 +11,10 @@ use std::{fs, io};
pub mod defaults;
pub const CONFIG_DIR: &str = "config";
pub const DATA_DIR: &str = "data";
pub const DB_FILE_NAME: &str = "db.sqlite";
pub trait NymConfig: Default + Serialize + DeserializeOwned {
fn template() -> &'static str;
@@ -23,17 +27,17 @@ pub trait NymConfig: Default + Serialize + DeserializeOwned {
// default, most probable, implementations; can be easily overridden where required
fn default_config_directory(id: Option<&str>) -> PathBuf {
if let Some(id) = id {
Self::default_root_directory().join(id).join("config")
Self::default_root_directory().join(id).join(CONFIG_DIR)
} else {
Self::default_root_directory().join("config")
Self::default_root_directory().join(CONFIG_DIR)
}
}
fn default_data_directory(id: Option<&str>) -> PathBuf {
if let Some(id) = id {
Self::default_root_directory().join(id).join("data")
Self::default_root_directory().join(id).join(DATA_DIR)
} else {
Self::default_root_directory().join("data")
Self::default_root_directory().join(DATA_DIR)
}
}
@@ -47,17 +51,17 @@ pub trait NymConfig: Default + Serialize + DeserializeOwned {
fn try_default_config_directory(id: Option<&str>) -> Option<PathBuf> {
if let Some(id) = id {
Self::try_default_root_directory().map(|d| d.join(id).join("config"))
Self::try_default_root_directory().map(|d| d.join(id).join(CONFIG_DIR))
} else {
Self::try_default_root_directory().map(|d| d.join("config"))
Self::try_default_root_directory().map(|d| d.join(CONFIG_DIR))
}
}
fn try_default_data_directory(id: Option<&str>) -> Option<PathBuf> {
if let Some(id) = id {
Self::try_default_root_directory().map(|d| d.join(id).join("data"))
Self::try_default_root_directory().map(|d| d.join(id).join(DATA_DIR))
} else {
Self::try_default_root_directory().map(|d| d.join("data"))
Self::try_default_root_directory().map(|d| d.join(DATA_DIR))
}
}
@@ -1,7 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::MixId;
use crate::{IdentityKey, MixId};
use cosmwasm_std::{Addr, Coin, Decimal};
use thiserror::Error;
@@ -133,4 +133,40 @@ pub enum MixnetContractError {
#[error("Mixnode {mix_id} appears multiple times in the provided rewarded set update!")]
DuplicateRewardedSetNode { mix_id: MixId },
#[error("Family with head {head} does not exist!")]
FamilyDoesNotExist { head: String },
#[error("Family with label '{0}' already exists")]
FamilyWithLabelExists(String),
#[error("Invalid layer expected 1, 2 or 3, got {0}")]
InvalidLayer(u8),
#[error("Head already has a family")]
FamilyCanHaveOnlyOne,
#[error("Already member of family {0}")]
AlreadyMemberOfFamily(String),
#[error("Can't join own family, family head {head}, member {member}")]
CantJoinOwnFamily {
head: IdentityKey,
member: IdentityKey,
},
#[error("Can't leave own family, family head {head}, member {member}")]
CantLeaveOwnFamily {
head: IdentityKey,
member: IdentityKey,
},
#[error("{member} is not a member of family {head}")]
NotAMember {
head: IdentityKey,
member: IdentityKey,
},
#[error("Feature is not yet implemented")]
NotImplemented,
}
@@ -0,0 +1,63 @@
use crate::{IdentityKey, IdentityKeyRef};
use cosmwasm_std::Addr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/NodeFamily.ts")
)]
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, JsonSchema)]
pub struct Family {
head: FamilyHead,
proxy: Option<String>,
label: String,
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/NodeFamilyHead.ts")
)]
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, JsonSchema)]
pub struct FamilyHead(IdentityKey);
impl FamilyHead {
pub fn new(identity: IdentityKeyRef<'_>) -> Self {
FamilyHead(identity.to_string())
}
pub fn identity(&self) -> IdentityKeyRef<'_> {
&self.0
}
}
impl Family {
pub fn new(head: FamilyHead, proxy: Option<Addr>, label: &str) -> Self {
Family {
head,
proxy: proxy.map(|p| p.to_string()),
label: label.to_string(),
}
}
#[allow(dead_code)]
pub fn head(&self) -> &FamilyHead {
&self.head
}
pub fn head_identity(&self) -> IdentityKeyRef<'_> {
self.head.identity()
}
#[allow(dead_code)]
pub fn proxy(&self) -> Option<&String> {
self.proxy.as_ref()
}
#[allow(dead_code)]
pub fn label(&self) -> &str {
&self.label
}
}
@@ -8,6 +8,7 @@ mod constants;
pub mod delegation;
pub mod error;
pub mod events;
pub mod families;
pub mod gateway;
pub mod helpers;
mod interval;
@@ -36,7 +36,6 @@ impl RewardedSetNodeStatus {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct MixNodeDetails {
pub bond_information: MixNodeBond,
pub rewarding_details: MixNodeRewarding,
}
@@ -579,6 +578,29 @@ impl From<Layer> for String {
}
}
impl TryFrom<u8> for Layer {
type Error = MixnetContractError;
fn try_from(i: u8) -> Result<Layer, MixnetContractError> {
match i {
1 => Ok(Layer::One),
2 => Ok(Layer::Two),
3 => Ok(Layer::Three),
_ => Err(MixnetContractError::InvalidLayer(i)),
}
}
}
impl From<Layer> for u8 {
fn from(layer: Layer) -> u8 {
match layer {
Layer::One => 1,
Layer::Two => 2,
Layer::Three => 3,
}
}
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
@@ -8,7 +8,7 @@ use crate::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use crate::reward_params::{
IntervalRewardParams, IntervalRewardingParamsUpdate, Performance, RewardingParams,
};
use crate::{delegation, ContractStateParams, MixId, Percent};
use crate::{delegation, ContractStateParams, Layer, LayerAssignment, MixId, Percent};
use crate::{Gateway, IdentityKey, MixNode};
use cosmwasm_std::Decimal;
use schemars::JsonSchema;
@@ -73,6 +73,51 @@ impl InitialRewardingParams {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
AssignNodeLayer {
mix_id: MixId,
layer: Layer,
},
// Families
/// Only owner of the node can crate the family with node as head
CreateFamily {
owner_signature: String,
label: String,
},
/// Family head needs to sign the joining node IdentityKey
JoinFamily {
signature: String,
family_head: IdentityKey,
},
LeaveFamily {
signature: String,
family_head: IdentityKey,
},
KickFamilyMember {
signature: String,
member: IdentityKey,
},
CreateFamilyOnBehalf {
owner_address: String,
owner_signature: String,
label: String,
},
/// Family head needs to sign the joining node IdentityKey
JoinFamilyOnBehalf {
member_address: String,
signature: String,
family_head: IdentityKey,
},
LeaveFamilyOnBehalf {
member_address: String,
signature: String,
family_head: IdentityKey,
},
KickFamilyMemberOnBehalf {
head_address: String,
signature: String,
member: IdentityKey,
},
// state/sys-params-related
UpdateRewardingValidatorAddress {
address: String,
@@ -94,7 +139,8 @@ pub enum ExecuteMsg {
force_immediately: bool,
},
AdvanceCurrentEpoch {
new_rewarded_set: Vec<MixId>,
new_rewarded_set: Vec<LayerAssignment>,
// families_in_layer: HashMap<String, Layer>,
expected_active_set_size: u32,
},
ReconcileEpochEvents {
@@ -194,6 +240,29 @@ pub enum ExecuteMsg {
impl ExecuteMsg {
pub fn default_memo(&self) -> String {
match self {
ExecuteMsg::AssignNodeLayer { mix_id, layer } => {
format!("assigning mix {} for layer {:?}", mix_id, layer)
}
ExecuteMsg::CreateFamily { .. } => "crating node family with".to_string(),
ExecuteMsg::JoinFamily { family_head, .. } => {
format!("joining family {}", family_head)
}
ExecuteMsg::LeaveFamily { family_head, .. } => {
format!("leaving family {}", family_head)
}
ExecuteMsg::KickFamilyMember { member, .. } => {
format!("kicking {} from family", member)
}
ExecuteMsg::CreateFamilyOnBehalf { .. } => "crating node family with".to_string(),
ExecuteMsg::JoinFamilyOnBehalf { family_head, .. } => {
format!("joining family {}", family_head)
}
ExecuteMsg::LeaveFamilyOnBehalf { family_head, .. } => {
format!("leaving family {}", family_head)
}
ExecuteMsg::KickFamilyMemberOnBehalf { member, .. } => {
format!("kicking {} from family", member)
}
ExecuteMsg::UpdateRewardingValidatorAddress { address } => {
format!("updating rewarding validator to {}", address)
}
@@ -286,6 +355,27 @@ impl ExecuteMsg {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
// families
GetAllFamiliesPaged {
limit: Option<u32>,
start_after: Option<String>,
},
GetAllMembersPaged {
limit: Option<u32>,
start_after: Option<String>,
},
GetFamilyByHead {
head: String,
},
GetFamilyByLabel {
label: String,
},
GetFamilyMembersByHead {
head: String,
},
GetFamilyMembersByLabel {
label: String,
},
// state/sys-params-related
GetContractVersion {},
GetRewardingValidatorAddress {},
@@ -340,7 +430,6 @@ pub enum QueryMsg {
mix_identity: IdentityKey,
},
GetLayerDistribution {},
// gateway-related:
GetGateways {
start_after: Option<IdentityKey>,
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::error::MixnetContractError;
use crate::families::{Family, FamilyHead};
use crate::{Layer, RewardedSetNodeStatus};
use cosmwasm_std::Addr;
use cosmwasm_std::Coin;
@@ -21,6 +22,27 @@ pub type BlockHeight = u64;
pub type EpochEventId = u32;
pub type IntervalEventId = u32;
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, PartialEq)]
pub struct LayerAssignment {
mix_id: MixId,
layer: Layer,
}
impl LayerAssignment {
pub fn new(mix_id: MixId, layer: Layer) -> Self {
LayerAssignment { mix_id, layer }
}
pub fn mix_id(&self) -> MixId {
self.mix_id
}
pub fn layer(&self) -> Layer {
self.layer
}
}
#[derive(Debug, Default, Serialize, Deserialize, Copy, Clone, Eq, PartialEq)]
pub struct LayerDistribution {
pub layer1: u64,
@@ -126,3 +148,15 @@ pub struct PagedRewardedSetResponse {
pub nodes: Vec<(MixId, RewardedSetNodeStatus)>,
pub start_next_after: Option<MixId>,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
pub struct PagedFamiliesResponse {
pub families: Vec<Family>,
pub start_next_after: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
pub struct PagedMembersResponse {
pub members: Vec<(IdentityKey, FamilyHead)>,
pub start_next_after: Option<String>,
}
@@ -1,7 +1,7 @@
use cosmwasm_std::{Coin, Timestamp};
use mixnet_contract_common::{
mixnode::{MixNodeConfigUpdate, MixNodeCostParams},
Gateway, MixId, MixNode,
Gateway, IdentityKey, MixId, MixNode,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -57,6 +57,25 @@ impl VestingSpecification {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
// Families
/// Only owner of the node can crate the family with node as head
CreateFamily {
owner_signature: String,
label: String,
},
/// Family head needs to sign the joining node IdentityKey
JoinFamily {
signature: String,
family_head: IdentityKey,
},
LeaveFamily {
signature: String,
family_head: IdentityKey,
},
KickFamilyMember {
signature: String,
member: IdentityKey,
},
TrackReward {
amount: Coin,
address: String,
@@ -134,6 +153,10 @@ pub enum ExecuteMsg {
impl ExecuteMsg {
pub fn name(&self) -> &str {
match self {
ExecuteMsg::CreateFamily { .. } => "VestingExecuteMsg::CreateFamily",
ExecuteMsg::JoinFamily { .. } => "VestingExecuteMsg::JoinFamily",
ExecuteMsg::LeaveFamily { .. } => "VestingExecuteMsg::LeaveFamily",
ExecuteMsg::KickFamilyMember { .. } => "VestingExecuteMsg::KickFamilyMember",
ExecuteMsg::TrackReward { .. } => "VestingExecuteMsg::TrackReward",
ExecuteMsg::ClaimOperatorReward { .. } => "VestingExecuteMsg::ClaimOperatorReward",
ExecuteMsg::ClaimDelegatorReward { .. } => "VestingExecuteMsg::ClaimDelegatorReward",
+4
View File
@@ -84,6 +84,10 @@ impl NymTopology {
&self.mixes
}
pub fn num_mixnodes(&self) -> usize {
self.mixes.values().flat_map(|m| m.iter()).count()
}
pub fn mixes_as_vec(&self) -> Vec<mix::Node> {
let mut mixes: Vec<mix::Node> = vec![];
+1
View File
@@ -0,0 +1 @@
Cargo.lock
-1786
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -35,6 +35,9 @@ pub const INTERVAL_EVENTS_MAX_RETRIEVAL_LIMIT: u32 = 250;
pub const REWARDED_SET_DEFAULT_RETRIEVAL_LIMIT: u32 = 500;
pub const REWARDED_SET_MAX_RETRIEVAL_LIMIT: u32 = 1000;
pub const FAMILIES_DEFAULT_RETRIEVAL_LIMIT: u32 = 10;
pub const FAMILIES_MAX_RETRIEVAL_LIMIT: u32 = 20;
// storage keys
pub(crate) const DELEGATION_PK_NAMESPACE: &str = "dl";
pub(crate) const DELEGATION_OWNER_IDX_NAMESPACE: &str = "dlo";
@@ -69,3 +72,7 @@ pub(crate) const UNBONDED_MIXNODES_IDENTITY_IDX_NAMESPACE: &str = "umi";
pub(crate) const REWARDING_PARAMS_KEY: &str = "rparams";
pub(crate) const PENDING_REWARD_POOL_KEY: &str = "prp";
pub(crate) const MIXNODES_REWARDING_PK_NAMESPACE: &str = "mnr";
pub(crate) const FAMILIES_INDEX_NAMESPACE: &str = "faml2";
pub(crate) const FAMILIES_MAP_NAMESPACE: &str = "fam2";
pub(crate) const MEMBERS_MAP_NAMESPACE: &str = "memb2";
+82 -1
View File
@@ -1,6 +1,5 @@
// Copyright 2021-2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::constants::{INITIAL_GATEWAY_PLEDGE_AMOUNT, INITIAL_MIXNODE_PLEDGE_AMOUNT};
use crate::interval::storage as interval_storage;
use crate::mixnet_contract_settings::storage as mixnet_params_storage;
@@ -82,6 +81,69 @@ pub fn execute(
msg: ExecuteMsg,
) -> Result<Response, MixnetContractError> {
match msg {
ExecuteMsg::AssignNodeLayer { mix_id, layer } => {
crate::mixnodes::transactions::assign_mixnode_layer(deps, info, mix_id, layer)
}
// families
ExecuteMsg::CreateFamily {
owner_signature,
label,
} => crate::families::transactions::try_create_family(deps, info, owner_signature, &label),
ExecuteMsg::JoinFamily {
signature,
family_head,
} => crate::families::transactions::try_join_family(deps, info, signature, family_head),
ExecuteMsg::LeaveFamily {
signature,
family_head,
} => crate::families::transactions::try_leave_family(deps, info, signature, family_head),
ExecuteMsg::KickFamilyMember { signature, member } => {
crate::families::transactions::try_head_kick_member(deps, info, signature, &member)
}
ExecuteMsg::CreateFamilyOnBehalf {
owner_address,
owner_signature,
label,
} => crate::families::transactions::try_create_family_on_behalf(
deps,
info,
owner_address,
owner_signature,
&label,
),
ExecuteMsg::JoinFamilyOnBehalf {
member_address,
signature,
family_head,
} => crate::families::transactions::try_join_family_on_behalf(
deps,
info,
member_address,
signature,
family_head,
),
ExecuteMsg::LeaveFamilyOnBehalf {
member_address,
signature,
family_head,
} => crate::families::transactions::try_leave_family_on_behalf(
deps,
info,
member_address,
signature,
family_head,
),
ExecuteMsg::KickFamilyMemberOnBehalf {
head_address,
signature,
member,
} => crate::families::transactions::try_head_kick_member_on_behalf(
deps,
info,
head_address,
signature,
&member,
),
// state/sys-params-related
ExecuteMsg::UpdateRewardingValidatorAddress { address } => {
crate::mixnet_contract_settings::transactions::try_update_rewarding_validator_address(
@@ -129,6 +191,7 @@ pub fn execute(
),
ExecuteMsg::AdvanceCurrentEpoch {
new_rewarded_set,
// families_in_layer,
expected_active_set_size,
} => crate::interval::transactions::try_advance_epoch(
deps,
@@ -285,6 +348,24 @@ pub fn query(
msg: QueryMsg,
) -> Result<QueryResponse, MixnetContractError> {
let query_res = match msg {
QueryMsg::GetAllFamiliesPaged { limit, start_after } => to_binary(
&crate::families::queries::get_all_families_paged(deps.storage, start_after, limit)?,
),
QueryMsg::GetAllMembersPaged { limit, start_after } => to_binary(
&crate::families::queries::get_all_members_paged(deps.storage, start_after, limit)?,
),
QueryMsg::GetFamilyByHead { head } => to_binary(
&crate::families::queries::get_family_by_head(&head, deps.storage)?,
),
QueryMsg::GetFamilyByLabel { label } => to_binary(
&crate::families::queries::get_family_by_label(&label, deps.storage)?,
),
QueryMsg::GetFamilyMembersByHead { head } => to_binary(
&crate::families::queries::get_family_members_by_head(&head, deps.storage)?,
),
QueryMsg::GetFamilyMembersByLabel { label } => to_binary(
&crate::families::queries::get_family_members_by_label(&label, deps.storage)?,
),
QueryMsg::GetContractVersion {} => {
to_binary(&crate::mixnet_contract_settings::queries::query_contract_version())
}
+3
View File
@@ -0,0 +1,3 @@
pub mod queries;
pub mod storage;
pub mod transactions;
+107
View File
@@ -0,0 +1,107 @@
use std::collections::HashSet;
use crate::constants::{FAMILIES_DEFAULT_RETRIEVAL_LIMIT, FAMILIES_MAX_RETRIEVAL_LIMIT};
use super::storage::{families, get_family, get_members, MEMBERS};
use cosmwasm_std::{Order, Storage};
use cw_storage_plus::Bound;
use mixnet_contract_common::families::{Family, FamilyHead};
use mixnet_contract_common::{error::MixnetContractError, IdentityKeyRef};
use mixnet_contract_common::{IdentityKey, PagedFamiliesResponse, PagedMembersResponse};
pub fn get_family_by_label(
label: &str,
storage: &dyn Storage,
) -> Result<Option<Family>, MixnetContractError> {
Ok(families()
.idx
.label
.item(storage, label.to_string())?
.map(|o| o.1))
}
pub fn get_family_by_head(
head: IdentityKeyRef<'_>,
storage: &dyn Storage,
) -> Result<Family, MixnetContractError> {
let family_head = FamilyHead::new(head);
get_family(&family_head, storage)
}
pub fn get_family_members_by_head(
head: IdentityKeyRef<'_>,
storage: &dyn Storage,
) -> Result<HashSet<String>, MixnetContractError> {
let family_head = FamilyHead::new(head);
let family = get_family(&family_head, storage)?;
get_members(&family, storage)
}
pub fn get_family_members_by_label(
label: &str,
storage: &dyn Storage,
) -> Result<Option<HashSet<String>>, MixnetContractError> {
if let Some(family) = families()
.idx
.label
.item(storage, label.to_string())?
.map(|o| o.1)
{
Ok(Some(get_members(&family, storage)?))
} else {
Ok(None)
}
}
pub fn get_all_families_paged(
storage: &dyn Storage,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedFamiliesResponse, MixnetContractError> {
let limit = limit
.unwrap_or(FAMILIES_DEFAULT_RETRIEVAL_LIMIT)
.min(FAMILIES_MAX_RETRIEVAL_LIMIT) as usize;
let start = start_after.map(Bound::exclusive);
let response = families()
.range(storage, start, None, Order::Ascending)
.take(limit)
.filter_map(|r| r.ok())
.map(|(_key, family)| family)
.collect::<Vec<Family>>();
let start_next_after = response
.last()
.map(|response| response.head_identity().to_string());
Ok(PagedFamiliesResponse {
families: response,
start_next_after,
})
}
pub fn get_all_members_paged(
storage: &dyn Storage,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedMembersResponse, MixnetContractError> {
let limit = limit
.unwrap_or(FAMILIES_DEFAULT_RETRIEVAL_LIMIT)
.min(FAMILIES_MAX_RETRIEVAL_LIMIT) as usize;
let start = start_after.map(Bound::exclusive);
let response = MEMBERS
.range(storage, start, None, Order::Ascending)
.take(limit)
.filter_map(|r| r.ok())
.collect::<Vec<(IdentityKey, FamilyHead)>>();
let start_next_after = response.last().map(|r| r.0.clone());
Ok(PagedMembersResponse {
members: response,
start_next_after,
})
}
+99
View File
@@ -0,0 +1,99 @@
use std::collections::HashSet;
use cosmwasm_std::{Order, StdError, Storage};
use cw_storage_plus::{Index, IndexList, IndexedMap, Map, UniqueIndex};
use mixnet_contract_common::families::{Family, FamilyHead};
use mixnet_contract_common::{error::MixnetContractError, IdentityKey, IdentityKeyRef};
use crate::constants::{FAMILIES_INDEX_NAMESPACE, FAMILIES_MAP_NAMESPACE, MEMBERS_MAP_NAMESPACE};
pub struct FamilyIndex<'a> {
pub label: UniqueIndex<'a, String, Family>,
}
impl<'a> IndexList<Family> for FamilyIndex<'a> {
fn get_indexes(&'_ self) -> Box<dyn Iterator<Item = &'_ dyn Index<Family>> + '_> {
let v: Vec<&dyn Index<Family>> = vec![&self.label];
Box::new(v.into_iter())
}
}
// storage access function.
pub fn families<'a>() -> IndexedMap<'a, String, Family, FamilyIndex<'a>> {
let indexes = FamilyIndex {
label: UniqueIndex::new(|d| d.label().to_string(), FAMILIES_INDEX_NAMESPACE),
};
IndexedMap::new(FAMILIES_MAP_NAMESPACE, indexes)
}
pub const MEMBERS: Map<IdentityKey, FamilyHead> = Map::new(MEMBERS_MAP_NAMESPACE);
pub fn get_members(
family: &Family,
store: &dyn Storage,
) -> Result<HashSet<IdentityKey>, MixnetContractError> {
Ok(MEMBERS
.range(store, None, None, Order::Ascending)
.filter_map(|res| res.ok())
.filter(|(_member, head)| head == family.head())
.map(|(member, _storage_key)| member)
.collect())
}
pub fn get_family(head: &FamilyHead, store: &dyn Storage) -> Result<Family, MixnetContractError> {
let key = head.identity();
if let Some(family) = families().may_load(store, key.to_string())? {
Ok(family)
} else {
Err(MixnetContractError::FamilyDoesNotExist {
head: head.identity().to_string(),
})
}
}
pub fn create_family(f: &Family, store: &mut dyn Storage) -> Result<(), MixnetContractError> {
match families().save(store, f.head_identity().to_string(), f) {
Ok(()) => Ok(()),
Err(e) => match &e {
StdError::GenericErr { msg } => {
if msg.starts_with("Violates unique constraint") {
Err(MixnetContractError::FamilyWithLabelExists(
f.label().to_string(),
))
} else {
Err(e.into())
}
}
_ => Err(e.into()),
},
}
}
pub fn add_family_member(
f: &Family,
store: &mut dyn Storage,
member: IdentityKeyRef<'_>,
) -> Result<(), MixnetContractError> {
Ok(MEMBERS.save(store, member.to_string(), f.head())?)
}
pub fn remove_family_member(store: &mut dyn Storage, member: IdentityKeyRef<'_>) {
MEMBERS.remove(store, member.to_string())
}
#[allow(dead_code)]
pub fn is_family_member(
store: &dyn Storage,
f: &Family,
member: IdentityKeyRef<'_>,
) -> Result<bool, MixnetContractError> {
let m = get_members(f, store)?;
Ok(m.contains(member))
}
pub fn is_any_member(
store: &dyn Storage,
member: IdentityKeyRef<'_>,
) -> Result<Option<FamilyHead>, MixnetContractError> {
Ok(MEMBERS.may_load(store, member.to_string())?)
}
@@ -0,0 +1,414 @@
use crate::support::helpers::{
ensure_bonded, validate_family_signature, validate_node_identity_signature,
};
use cosmwasm_std::{Addr, DepsMut, MessageInfo, Response};
use mixnet_contract_common::families::{Family, FamilyHead};
use mixnet_contract_common::{error::MixnetContractError, IdentityKey, IdentityKeyRef};
use super::storage::{
add_family_member, create_family, get_family, is_any_member, is_family_member,
remove_family_member,
};
/// Creates a new MixNode family with senders node as head
pub fn try_create_family(
deps: DepsMut,
info: MessageInfo,
owner_signature: String,
label: &str,
) -> Result<Response, MixnetContractError> {
_try_create_family(deps, &info.sender, owner_signature, label, None)
}
pub fn try_create_family_on_behalf(
deps: DepsMut,
info: MessageInfo,
owner_address: String,
owner_signature: String,
label: &str,
) -> Result<Response, MixnetContractError> {
let owner_address = deps.api.addr_validate(&owner_address)?;
_try_create_family(
deps,
&owner_address,
owner_signature,
label,
Some(info.sender),
)
}
fn _try_create_family(
deps: DepsMut,
owner: &Addr,
owner_signature: String,
label: &str,
proxy: Option<Addr>,
) -> Result<Response, MixnetContractError> {
let existing_bond = crate::mixnodes::storage::mixnode_bonds()
.idx
.owner
.item(deps.storage, owner.clone())?
.ok_or(MixnetContractError::NoAssociatedMixNodeBond {
owner: owner.clone(),
})?
.1;
ensure_bonded(&existing_bond)?;
validate_node_identity_signature(
deps.as_ref(),
owner,
&owner_signature,
existing_bond.identity(),
)?;
let family_head = FamilyHead::new(existing_bond.identity());
if let Ok(_family) = get_family(&family_head, deps.storage) {
return Err(MixnetContractError::FamilyCanHaveOnlyOne);
}
let family = Family::new(family_head, proxy, label);
create_family(&family, deps.storage)?;
Ok(Response::default())
}
pub fn try_join_family(
deps: DepsMut,
info: MessageInfo,
signature: String,
family_head: IdentityKey,
) -> Result<Response, MixnetContractError> {
let family_head = FamilyHead::new(&family_head);
_try_join_family(deps, &info.sender, signature, family_head)
}
pub fn try_join_family_on_behalf(
deps: DepsMut,
_info: MessageInfo,
member_address: String,
signature: String,
family_head: IdentityKey,
) -> Result<Response, MixnetContractError> {
let member_address = deps.api.addr_validate(&member_address)?;
let family_head = FamilyHead::new(&family_head);
_try_join_family(deps, &member_address, signature, family_head)
}
fn _try_join_family(
deps: DepsMut,
owner: &Addr,
signature: String,
family_head: FamilyHead,
) -> Result<Response, MixnetContractError> {
let existing_bond = crate::mixnodes::storage::mixnode_bonds()
.idx
.owner
.item(deps.storage, owner.clone())?
.ok_or(MixnetContractError::NoAssociatedMixNodeBond {
owner: owner.clone(),
})?
.1;
ensure_bonded(&existing_bond)?;
if family_head.identity() == existing_bond.identity() {
return Err(MixnetContractError::CantJoinOwnFamily {
head: family_head.identity().to_string(),
member: existing_bond.identity().to_string(),
});
}
if let Some(family) = is_any_member(deps.storage, existing_bond.identity())? {
return Err(MixnetContractError::AlreadyMemberOfFamily(
family.identity().to_string(),
));
}
validate_family_signature(
deps.as_ref(),
existing_bond.identity(),
&signature,
family_head.identity(),
)?;
let family = get_family(&family_head, deps.storage)?;
add_family_member(&family, deps.storage, existing_bond.identity())?;
Ok(Response::default())
}
pub fn try_leave_family(
deps: DepsMut,
info: MessageInfo,
signature: String,
family_head: IdentityKey,
) -> Result<Response, MixnetContractError> {
let family_head = FamilyHead::new(&family_head);
_try_leave_family(deps, &info.sender, signature, family_head)
}
pub fn try_leave_family_on_behalf(
deps: DepsMut,
_info: MessageInfo,
member_address: String,
signature: String,
family_head: IdentityKey,
) -> Result<Response, MixnetContractError> {
let family_head = FamilyHead::new(&family_head);
let member_address = deps.api.addr_validate(&member_address)?;
_try_leave_family(deps, &member_address, signature, family_head)
}
fn _try_leave_family(
deps: DepsMut,
owner: &Addr,
signature: String,
family_head: FamilyHead,
) -> Result<Response, MixnetContractError> {
let existing_bond = crate::mixnodes::storage::mixnode_bonds()
.idx
.owner
.item(deps.storage, owner.clone())?
.ok_or(MixnetContractError::NoAssociatedMixNodeBond {
owner: owner.clone(),
})?
.1;
ensure_bonded(&existing_bond)?;
if family_head.identity() == existing_bond.identity() {
return Err(MixnetContractError::CantLeaveOwnFamily {
head: family_head.identity().to_string(),
member: existing_bond.identity().to_string(),
});
}
let family = get_family(&family_head, deps.storage)?;
if !is_family_member(deps.storage, &family, existing_bond.identity())? {
return Err(MixnetContractError::NotAMember {
head: family_head.identity().to_string(),
member: existing_bond.identity().to_string(),
});
}
validate_family_signature(
deps.as_ref(),
existing_bond.identity(),
&signature,
family_head.identity(),
)?;
remove_family_member(deps.storage, existing_bond.identity());
Ok(Response::default())
}
pub fn try_head_kick_member(
deps: DepsMut,
info: MessageInfo,
owner_signature: String,
member: IdentityKeyRef,
) -> Result<Response, MixnetContractError> {
_try_head_kick_member(deps, &info.sender, owner_signature, member)
}
pub fn try_head_kick_member_on_behalf(
deps: DepsMut,
_info: MessageInfo,
head_address: String,
owner_signature: String,
member: IdentityKeyRef,
) -> Result<Response, MixnetContractError> {
let head_address = deps.api.addr_validate(&head_address)?;
_try_head_kick_member(deps, &head_address, owner_signature, member)
}
#[allow(unused_variables)]
fn _try_head_kick_member(
deps: DepsMut,
owner: &Addr,
owner_signature: String,
member: IdentityKeyRef<'_>,
) -> Result<Response, MixnetContractError> {
Err(MixnetContractError::NotImplemented)
// let existing_bond = crate::mixnodes::storage::mixnode_bonds()
// .idx
// .owner
// .item(deps.storage, owner.clone())?
// .ok_or(MixnetContractError::NoAssociatedMixNodeBond {
// owner: owner.clone(),
// })?
// .1;
// ensure_bonded(&existing_bond)?;
// validate_node_identity_signature(
// deps.as_ref(),
// owner,
// &owner_signature,
// existing_bond.identity(),
// )?;
// let family_head = FamilyHead::new(existing_bond.identity());
// let family = get_family(&family_head, deps.storage)?;
// if !is_family_member(deps.storage, &family, member)? {
// return Err(MixnetContractError::NotAMember {
// head: family_head.identity().to_string(),
// member: existing_bond.identity().to_string(),
// });
// }
// remove_family_member(deps.storage, member);
// Ok(Response::default())
}
#[cfg(test)]
mod test {
use super::*;
use crate::families::queries::{get_family_by_head, get_family_by_label};
use crate::families::storage::is_family_member;
use crate::mixnet_contract_settings::storage::minimum_mixnode_pledge;
use crate::support::tests::{fixtures, test_helpers};
use cosmwasm_std::testing::{mock_env, mock_info};
#[test]
fn test_family_crud() {
let mut deps = test_helpers::init_contract();
let env = mock_env();
let mut rng = test_helpers::test_rng();
let head = "alice";
let malicious_head = "timmy";
let minimum_pledge = minimum_mixnode_pledge(deps.as_ref().storage).unwrap();
let (head_mixnode, head_sig, head_keypair) =
test_helpers::mixnode_with_signature(&mut rng, head);
let (malicious_mixnode, malicious_sig, _malicious_keypair) =
test_helpers::mixnode_with_signature(&mut rng, malicious_head);
let cost_params = fixtures::mix_node_cost_params_fixture();
let member = "bob";
let (member_mixnode, member_sig, _) =
test_helpers::mixnode_with_signature(&mut rng, member);
// we are informed that we didn't send enough funds
crate::mixnodes::transactions::try_add_mixnode(
deps.as_mut(),
env.clone(),
mock_info(head, &[minimum_pledge.clone()]),
head_mixnode.clone(),
cost_params.clone(),
head_sig.clone(),
)
.unwrap();
crate::mixnodes::transactions::try_add_mixnode(
deps.as_mut(),
env.clone(),
mock_info(malicious_head, &[minimum_pledge.clone()]),
malicious_mixnode.clone(),
cost_params.clone(),
malicious_sig.clone(),
)
.unwrap();
crate::mixnodes::transactions::try_add_mixnode(
deps.as_mut(),
env.clone(),
mock_info(member, &[minimum_pledge.clone()]),
member_mixnode.clone(),
cost_params.clone(),
member_sig.clone(),
)
.unwrap();
try_create_family(
deps.as_mut(),
mock_info(head.clone(), &[]),
head_sig.clone(),
"test",
)
.unwrap();
let family_head = FamilyHead::new(&head_mixnode.identity_key);
assert!(get_family(&family_head, &deps.storage).is_ok());
let nope = try_create_family(
deps.as_mut(),
mock_info(malicious_head.clone(), &[]),
malicious_sig.clone(),
"test",
);
match nope {
Ok(_) => panic!("This should fail, since family with label already exists"),
Err(e) => match e {
MixnetContractError::FamilyWithLabelExists(label) => assert_eq!(label, "test"),
_ => panic!("This should return FamilyWithLabelExists"),
},
}
let family = get_family_by_label("test", &deps.storage).unwrap();
assert!(family.is_some());
assert_eq!(family.unwrap().head_identity(), family_head.identity());
let family = get_family_by_head(family_head.identity(), &deps.storage).unwrap();
assert_eq!(family.head_identity(), family_head.identity());
let join_signature = head_keypair
.private_key()
.sign(member_mixnode.identity_key.as_bytes())
.to_base58_string();
try_join_family(
deps.as_mut(),
mock_info(member, &[]),
join_signature.clone(),
head_mixnode.identity_key.clone(),
)
.unwrap();
let family = get_family(&family_head, &deps.storage).unwrap();
assert!(is_family_member(&deps.storage, &family, &member_mixnode.identity_key).unwrap());
try_leave_family(
deps.as_mut(),
mock_info(member, &[]),
join_signature.clone(),
head_mixnode.identity_key.clone(),
)
.unwrap();
let family = get_family(&family_head, &deps.storage).unwrap();
assert!(!is_family_member(&deps.storage, &family, &member_mixnode.identity_key).unwrap());
try_join_family(
deps.as_mut(),
mock_info(member, &[]),
join_signature.clone(),
head_mixnode.identity_key.clone(),
)
.unwrap();
let family = get_family(&family_head, &deps.storage).unwrap();
assert!(is_family_member(&deps.storage, &family, &member_mixnode.identity_key).unwrap());
// try_head_kick_member(
// deps.as_mut(),
// mock_info(&head, &[]),
// head_sig.clone(),
// &member_mixnode.identity_key.clone(),
// )
// .unwrap();
// let family = get_family(&family_head, &deps.storage).unwrap();
// assert!(!is_family_member(&deps.storage, &family, &member_mixnode.identity_key).unwrap());
}
}
@@ -82,7 +82,7 @@ pub(crate) fn _try_add_gateway(
validate_node_identity_signature(
deps.as_ref(),
&owner,
owner_signature,
&owner_signature,
&gateway.identity_key,
)?;
+111 -15
View File
@@ -5,6 +5,7 @@ use super::storage;
use crate::interval::helpers::change_interval_config;
use crate::interval::pending_events::ContractExecutableEvent;
use crate::interval::storage::push_new_interval_event;
use crate::mixnodes::transactions::update_mixnode_layer;
use crate::rewards;
use crate::rewards::storage as rewards_storage;
use crate::support::helpers::{ensure_is_authorized, ensure_is_owner};
@@ -16,7 +17,7 @@ use mixnet_contract_common::events::{
new_reconcile_pending_events,
};
use mixnet_contract_common::pending_events::PendingIntervalEventKind;
use mixnet_contract_common::MixId;
use mixnet_contract_common::{LayerAssignment, MixId};
use std::collections::BTreeSet;
// those two should be called in separate tx (from advancing epoch),
@@ -202,7 +203,7 @@ pub fn try_advance_epoch(
mut deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
new_rewarded_set: Vec<MixId>,
layer_assignments: Vec<LayerAssignment>,
expected_active_set_size: u32,
) -> Result<Response, MixnetContractError> {
// Only rewarding validator can attempt to advance epoch
@@ -247,12 +248,18 @@ pub fn try_advance_epoch(
}
let updated_interval = current_interval.advance_epoch();
let num_nodes = new_rewarded_set.len();
let num_nodes = layer_assignments.len();
let new_rewarded_set = layer_assignments.iter().map(|l| l.mix_id()).collect();
// finally save updated interval and the rewarded set
storage::save_interval(deps.storage, &updated_interval)?;
update_rewarded_set(deps.storage, new_rewarded_set, expected_active_set_size)?;
for a in layer_assignments {
update_mixnode_layer(a.mix_id(), a.layer(), deps.storage)?;
}
Ok(response.add_event(new_advance_epoch_event(updated_interval, num_nodes as u32)))
}
@@ -1133,30 +1140,40 @@ mod tests {
#[cfg(test)]
mod advancing_epoch {
use super::*;
use crate::mixnodes::queries::query_mixnode_details;
use crate::rewards::models::RewardPoolChange;
use crate::support::tests::fixtures::TEST_COIN_DENOM;
use cosmwasm_std::testing::mock_info;
use cosmwasm_std::{coin, coins, BankMsg, Decimal, Empty, SubMsg};
use cosmwasm_std::{coin, coins, BankMsg, Decimal, Empty, SubMsg, Uint128};
use mixnet_contract_common::events::{
new_delegation_on_unbonded_node_event, new_rewarding_params_update_event,
};
use mixnet_contract_common::reward_params::IntervalRewardingParamsUpdate;
use mixnet_contract_common::RewardedSetNodeStatus;
use mixnet_contract_common::{Layer, RewardedSetNodeStatus};
#[test]
fn can_only_be_performed_by_specified_rewarding_validator() {
let mut test = TestSetup::new();
test.add_dummy_mixnode("1", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("2", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("3", Some(Uint128::new(100000000)));
let current_active_set = test.rewarding_params().active_set_size;
let some_sender = mock_info("foomper", &[]);
test.skip_to_current_epoch_end();
let layer_assignments = vec![
LayerAssignment::new(1, Layer::One),
LayerAssignment::new(2, Layer::Two),
LayerAssignment::new(3, Layer::Three),
];
let env = test.env();
let res = try_advance_epoch(
test.deps_mut(),
env,
some_sender,
vec![1, 2, 3],
layer_assignments.clone(),
current_active_set,
);
assert_eq!(res, Err(MixnetContractError::Unauthorized));
@@ -1168,9 +1185,10 @@ mod tests {
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments,
current_active_set,
);
println!("{:?}", res);
assert!(res.is_ok())
}
@@ -1179,13 +1197,23 @@ mod tests {
let mut test = TestSetup::new();
let current_active_set = test.rewarding_params().active_set_size;
test.add_dummy_mixnode("1", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("2", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("3", Some(Uint128::new(100000000)));
let layer_assignments = vec![
LayerAssignment::new(1, Layer::One),
LayerAssignment::new(2, Layer::Two),
LayerAssignment::new(3, Layer::Three),
];
let env = test.env();
let sender = test.rewarding_validator();
let res = try_advance_epoch(
test.deps_mut(),
env,
sender.clone(),
vec![1, 2, 3],
layer_assignments.clone(),
current_active_set,
);
assert!(matches!(
@@ -1193,6 +1221,24 @@ mod tests {
Err(MixnetContractError::EpochInProgress { .. })
));
let mixnode_1 = query_mixnode_details(test.deps.as_ref(), 1).unwrap();
assert_eq!(
mixnode_1.mixnode_details.unwrap().bond_information.layer,
Layer::One
);
let mixnode_1 = query_mixnode_details(test.deps.as_ref(), 2).unwrap();
assert_eq!(
mixnode_1.mixnode_details.unwrap().bond_information.layer,
Layer::Two
);
let mixnode_1 = query_mixnode_details(test.deps.as_ref(), 3).unwrap();
assert_eq!(
mixnode_1.mixnode_details.unwrap().bond_information.layer,
Layer::Three
);
// sanity check
test.skip_to_current_epoch_end();
let env = test.env();
@@ -1200,7 +1246,7 @@ mod tests {
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments,
current_active_set,
);
assert!(res.is_ok())
@@ -1211,17 +1257,27 @@ mod tests {
let mut test = TestSetup::new();
let current_active_set = test.rewarding_params().active_set_size;
test.add_dummy_mixnode("1", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("2", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("3", Some(Uint128::new(100000000)));
push_n_dummy_epoch_actions(&mut test, 10);
push_n_dummy_interval_actions(&mut test, 10);
test.skip_to_current_epoch_end();
let layer_assignments = vec![
LayerAssignment::new(1, Layer::One),
LayerAssignment::new(2, Layer::Two),
LayerAssignment::new(3, Layer::Three),
];
let env = test.env();
let sender = test.rewarding_validator();
try_advance_epoch(
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments,
current_active_set,
)
.unwrap();
@@ -1237,17 +1293,27 @@ mod tests {
let mut test = TestSetup::new();
let current_active_set = test.rewarding_params().active_set_size;
test.add_dummy_mixnode("1", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("2", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("3", Some(Uint128::new(100000000)));
push_n_dummy_epoch_actions(&mut test, 10);
push_n_dummy_interval_actions(&mut test, 10);
test.skip_to_current_interval_end();
let layer_assignments = vec![
LayerAssignment::new(1, Layer::One),
LayerAssignment::new(2, Layer::Two),
LayerAssignment::new(3, Layer::Three),
];
let env = test.env();
let sender = test.rewarding_validator();
try_advance_epoch(
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments,
current_active_set,
)
.unwrap();
@@ -1264,6 +1330,10 @@ mod tests {
let env = test.env();
let current_active_set = test.rewarding_params().active_set_size;
test.add_dummy_mixnode("1", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("2", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("3", Some(Uint128::new(100000000)));
let mut expected_events = Vec::new();
let mut expected_messages: Vec<SubMsg<Empty>> = Vec::new();
@@ -1310,13 +1380,19 @@ mod tests {
test.skip_to_current_interval_end();
let layer_assignments = vec![
LayerAssignment::new(1, Layer::One),
LayerAssignment::new(2, Layer::Two),
LayerAssignment::new(3, Layer::Three),
];
let env = test.env();
let sender = test.rewarding_validator();
let res = try_advance_epoch(
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments,
current_active_set,
)
.unwrap();
@@ -1343,6 +1419,10 @@ mod tests {
let mut test = TestSetup::new();
let current_active_set = test.rewarding_params().active_set_size;
test.add_dummy_mixnode("1", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("2", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("3", Some(Uint128::new(100000000)));
let start_params = test.rewarding_params();
let pool_update = Decimal::from_atomics(100_000_000u32, 0).unwrap();
@@ -1357,6 +1437,12 @@ mod tests {
)
.unwrap();
let layer_assignments = vec![
LayerAssignment::new(1, Layer::One),
LayerAssignment::new(2, Layer::Two),
LayerAssignment::new(3, Layer::Three),
];
// end of epoch - nothing has happened
let sender = test.rewarding_validator();
test.skip_to_current_epoch_end();
@@ -1365,7 +1451,7 @@ mod tests {
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments.clone(),
current_active_set,
)
.unwrap();
@@ -1384,7 +1470,7 @@ mod tests {
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments,
current_active_set,
)
.unwrap();
@@ -1413,10 +1499,20 @@ mod tests {
let mut test = TestSetup::new();
let current_active_set = test.rewarding_params().active_set_size;
test.add_dummy_mixnode("1", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("2", Some(Uint128::new(100000000)));
test.add_dummy_mixnode("3", Some(Uint128::new(100000000)));
let interval_pre = test.current_interval();
let rewarded_set_pre = test.rewarded_set();
assert!(rewarded_set_pre.is_empty());
let layer_assignments = vec![
LayerAssignment::new(1, Layer::One),
LayerAssignment::new(2, Layer::Two),
LayerAssignment::new(3, Layer::Three),
];
let sender = test.rewarding_validator();
test.skip_to_current_interval_end();
let env = test.env();
@@ -1424,7 +1520,7 @@ mod tests {
test.deps_mut(),
env,
sender,
vec![1, 2, 3],
layer_assignments,
current_active_set,
)
.unwrap();
+1
View File
@@ -7,6 +7,7 @@
mod constants;
pub mod contract;
mod delegations;
mod families;
mod gateways;
mod interval;
mod mixnet_contract_settings;
+37 -7
View File
@@ -10,10 +10,10 @@ use crate::mixnodes::helpers::{
get_mixnode_details_by_owner, must_get_mixnode_bond_by_owner, save_new_mixnode,
};
use crate::support::helpers::{
ensure_bonded, ensure_no_existing_bond, ensure_proxy_match, validate_node_identity_signature,
validate_pledge,
ensure_bonded, ensure_is_authorized, ensure_no_existing_bond, ensure_proxy_match,
validate_node_identity_signature, validate_pledge,
};
use cosmwasm_std::{coin, Addr, Coin, DepsMut, Env, MessageInfo, Response};
use cosmwasm_std::{coin, Addr, Coin, DepsMut, Env, MessageInfo, Response, Storage};
use mixnet_contract_common::error::MixnetContractError;
use mixnet_contract_common::events::{
new_mixnode_bonding_event, new_mixnode_config_update_event,
@@ -22,7 +22,37 @@ use mixnet_contract_common::events::{
};
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use mixnet_contract_common::pending_events::{PendingEpochEventKind, PendingIntervalEventKind};
use mixnet_contract_common::MixNode;
use mixnet_contract_common::{Layer, MixId, MixNode};
pub(crate) fn update_mixnode_layer(
mix_id: MixId,
layer: Layer,
storage: &mut dyn Storage,
) -> Result<(), MixnetContractError> {
let bond = if let Some(bond_information) = storage::mixnode_bonds().may_load(storage, mix_id)? {
bond_information
} else {
return Err(MixnetContractError::MixNodeBondNotFound { mix_id });
};
let mut updated_bond = bond.clone();
updated_bond.layer = layer;
storage::mixnode_bonds().replace(storage, bond.mix_id, Some(&updated_bond), Some(&bond))?;
Ok(())
}
pub fn assign_mixnode_layer(
deps: DepsMut<'_>,
info: MessageInfo,
mix_id: MixId,
layer: Layer,
) -> Result<Response, MixnetContractError> {
ensure_is_authorized(info.sender, deps.storage)?;
update_mixnode_layer(mix_id, layer, deps.storage)?;
Ok(Response::default())
}
pub fn try_add_mixnode(
deps: DepsMut<'_>,
@@ -96,7 +126,7 @@ fn _try_add_mixnode(
validate_node_identity_signature(
deps.as_ref(),
&owner,
owner_signature,
&owner_signature,
&mixnode.identity_key,
)?;
@@ -359,7 +389,7 @@ pub mod tests {
// if we don't send enough funds
let info = mock_info(sender, &[insufficient_pledge.clone()]);
let (mixnode, sig) = test_helpers::mixnode_with_signature(&mut rng, sender);
let (mixnode, sig, _) = test_helpers::mixnode_with_signature(&mut rng, sender);
let cost_params = fixtures::mix_node_cost_params_fixture();
// we are informed that we didn't send enough funds
@@ -427,7 +457,7 @@ pub mod tests {
);
let info = mock_info(sender2, &tests::fixtures::good_mixnode_pledge());
let (mixnode, sig) = test_helpers::mixnode_with_signature(&mut rng, sender2);
let (mixnode, sig, _) = test_helpers::mixnode_with_signature(&mut rng, sender2);
let result = try_add_mixnode(
deps.as_mut(),
+27 -21
View File
@@ -194,14 +194,30 @@ pub(crate) fn ensure_no_existing_bond(
Ok(())
}
pub(crate) fn validate_node_identity_signature(
pub fn validate_node_identity_signature(
deps: Deps<'_>,
owner: &Addr,
signature: String,
signature: &str,
identity: IdentityKeyRef<'_>,
) -> Result<(), MixnetContractError> {
let owner_bytes = owner.as_bytes();
validate_signature(deps, owner.as_bytes(), signature, identity)
}
pub fn validate_family_signature(
deps: Deps<'_>,
family_member: IdentityKeyRef<'_>,
signature: &str,
family_head: IdentityKeyRef<'_>,
) -> Result<(), MixnetContractError> {
validate_signature(deps, family_member.as_bytes(), signature, family_head)
}
pub(crate) fn validate_signature(
deps: Deps<'_>,
signed_bytes: &[u8],
signature: &str,
identity: IdentityKeyRef<'_>,
) -> Result<(), MixnetContractError> {
let mut identity_bytes = [0u8; 32];
let mut signature_bytes = [0u8; 64];
@@ -226,7 +242,7 @@ pub(crate) fn validate_node_identity_signature(
let res = deps
.api
.ed25519_verify(owner_bytes, &signature_bytes, &identity_bytes)
.ed25519_verify(signed_bytes, &signature_bytes, &identity_bytes)
.map_err(cosmwasm_std::StdError::verification_err)?;
if !res {
Err(MixnetContractError::InvalidEd25519Signature)
@@ -276,12 +292,7 @@ mod tests {
Err(MixnetContractError::MalformedEd25519IdentityKey(
"buffer provided to decode base58 encoded string into was too small".into()
)),
validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr1_key1.clone(),
long_bs58,
)
validate_node_identity_signature(deps.as_ref(), &address1, &sig_addr1_key1, long_bs58,)
);
assert_eq!(
@@ -300,12 +311,7 @@ mod tests {
Err(MixnetContractError::MalformedEd25519IdentityKey(
"Too few bytes provided for the public key".into()
)),
validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr1_key1.clone(),
short_bs58,
)
validate_node_identity_signature(deps.as_ref(), &address1, &sig_addr1_key1, short_bs58,)
);
assert_eq!(
@@ -325,7 +331,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr1_key1.clone(),
&sig_addr1_key1,
&keypair2.public_key().to_base58_string(),
)
);
@@ -335,7 +341,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr2_key1,
&sig_addr2_key1,
&keypair1.public_key().to_base58_string(),
)
);
@@ -345,7 +351,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address2,
sig_addr1_key1.clone(),
&sig_addr1_key1,
&keypair1.public_key().to_base58_string(),
)
);
@@ -355,7 +361,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr1_key2,
&sig_addr1_key2,
&keypair1.public_key().to_base58_string(),
)
);
@@ -363,7 +369,7 @@ mod tests {
assert!(validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr1_key1,
&sig_addr1_key1,
&keypair1.public_key().to_base58_string(),
)
.is_ok());
+3 -1
View File
@@ -46,6 +46,7 @@ pub mod test_helpers {
use cosmwasm_std::{Deps, OwnedDeps};
use cosmwasm_std::{DepsMut, MessageInfo};
use cosmwasm_std::{Env, Response, Timestamp, Uint128};
use crypto::asymmetric::identity::KeyPair;
use mixnet_contract_common::events::{
may_find_attribute, MixnetEventType, DELEGATES_REWARD_KEY, OPERATOR_REWARD_KEY,
};
@@ -556,7 +557,7 @@ pub mod test_helpers {
pub fn mixnode_with_signature(
mut rng: impl RngCore + CryptoRng,
sender: &str,
) -> (MixNode, String) {
) -> (MixNode, String, KeyPair) {
let keypair = crypto::asymmetric::identity::KeyPair::new(&mut rng);
let legit_sphinx_key = crypto::asymmetric::encryption::KeyPair::new(&mut rng);
let owner_signature = keypair
@@ -574,6 +575,7 @@ pub mod test_helpers {
..tests::fixtures::mix_node_fixture()
},
owner_signature,
keypair,
)
}
+53 -1
View File
@@ -5,7 +5,7 @@ use crate::storage::{
MIXNET_CONTRACT_ADDRESS, MIX_DENOM,
};
use crate::traits::{
DelegatingAccount, GatewayBondingAccount, MixnodeBondingAccount, VestingAccount,
DelegatingAccount, GatewayBondingAccount, MixnodeBondingAccount, NodeFamilies, VestingAccount,
};
use crate::vesting::{populate_vesting_periods, Account};
use contracts_common::ContractBuildInformation;
@@ -60,6 +60,21 @@ pub fn execute(
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::CreateFamily {
owner_signature,
label,
} => try_create_family(info, deps, owner_signature, label),
ExecuteMsg::JoinFamily {
signature,
family_head,
} => try_join_family(info, deps, signature, family_head),
ExecuteMsg::LeaveFamily {
signature,
family_head,
} => try_leave_family(info, deps, signature, family_head),
ExecuteMsg::KickFamilyMember { signature, member } => {
try_kick_family_member(info, deps, signature, member)
}
ExecuteMsg::UpdateLockedPledgeCap { address, cap } => {
try_update_locked_pledge_cap(address, cap, info, deps)
}
@@ -144,6 +159,43 @@ pub fn execute(
}
}
pub fn try_create_family(
info: MessageInfo,
deps: DepsMut,
owner_signature: String,
label: String,
) -> Result<Response, ContractError> {
let account = account_from_address(info.sender.as_ref(), deps.storage, deps.api)?;
account.try_create_family(deps.storage, owner_signature, label)
}
pub fn try_join_family(
info: MessageInfo,
deps: DepsMut,
signature: String,
family_head: String,
) -> Result<Response, ContractError> {
let account = account_from_address(info.sender.as_ref(), deps.storage, deps.api)?;
account.try_join_family(deps.storage, signature, &family_head)
}
pub fn try_leave_family(
info: MessageInfo,
deps: DepsMut,
signature: String,
family_head: String,
) -> Result<Response, ContractError> {
let account = account_from_address(info.sender.as_ref(), deps.storage, deps.api)?;
account.try_leave_family(deps.storage, signature, &family_head)
}
pub fn try_kick_family_member(
info: MessageInfo,
deps: DepsMut,
signature: String,
member: String,
) -> Result<Response, ContractError> {
let account = account_from_address(info.sender.as_ref(), deps.storage, deps.api)?;
account.try_head_kick_member(deps.storage, signature, &member)
}
/// Update locked_pledge_cap, the hard cap for staking/bonding with unvested tokens.
///
/// Callable by ADMIN only, see [instantiate].
+2
View File
@@ -1,7 +1,9 @@
pub mod bonding_account;
pub mod delegating_account;
pub mod node_families;
pub mod vesting_account;
pub use self::bonding_account::{GatewayBondingAccount, MixnodeBondingAccount};
pub use self::delegating_account::DelegatingAccount;
pub use self::node_families::NodeFamilies;
pub use self::vesting_account::VestingAccount;
@@ -0,0 +1,33 @@
use crate::errors::ContractError;
use cosmwasm_std::{Response, Storage};
use mixnet_contract_common::IdentityKeyRef;
pub trait NodeFamilies {
fn try_create_family(
&self,
storage: &dyn Storage,
owner_signature: String,
label: String,
) -> Result<Response, ContractError>;
fn try_join_family(
&self,
storage: &dyn Storage,
signature: String,
family_head: IdentityKeyRef,
) -> Result<Response, ContractError>;
fn try_leave_family(
&self,
storage: &dyn Storage,
signature: String,
family_head: IdentityKeyRef,
) -> Result<Response, ContractError>;
fn try_head_kick_member(
&self,
storage: &dyn Storage,
signature: String,
member: IdentityKeyRef<'_>,
) -> Result<Response, ContractError>;
}
@@ -16,6 +16,7 @@ use vesting_contract_common::{Period, PledgeCap, PledgeData};
mod delegating_account;
mod gateway_bonding_account;
mod mixnode_bonding_account;
mod node_families;
mod vesting_account;
fn generate_storage_key(storage: &mut dyn Storage) -> Result<u32, ContractError> {
@@ -0,0 +1,74 @@
use super::Account;
use crate::{errors::ContractError, storage::MIXNET_CONTRACT_ADDRESS, traits::NodeFamilies};
use cosmwasm_std::{wasm_execute, Response, Storage};
use mixnet_contract_common::{ExecuteMsg as MixnetExecuteMsg, IdentityKeyRef};
impl NodeFamilies for Account {
fn try_create_family(
&self,
storage: &dyn Storage,
owner_signature: String,
label: String,
) -> Result<Response, ContractError> {
let msg = MixnetExecuteMsg::CreateFamilyOnBehalf {
owner_address: self.owner_address().to_string(),
owner_signature,
label,
};
let msg = wasm_execute(MIXNET_CONTRACT_ADDRESS.load(storage)?, &msg, vec![])?;
Ok(Response::new().add_message(msg))
}
fn try_join_family(
&self,
storage: &dyn Storage,
signature: String,
family_head: IdentityKeyRef,
) -> Result<Response, ContractError> {
let msg = MixnetExecuteMsg::JoinFamilyOnBehalf {
member_address: self.owner_address().to_string(),
signature,
family_head: family_head.to_string(),
};
let msg = wasm_execute(MIXNET_CONTRACT_ADDRESS.load(storage)?, &msg, vec![])?;
Ok(Response::new().add_message(msg))
}
fn try_leave_family(
&self,
storage: &dyn Storage,
signature: String,
family_head: IdentityKeyRef,
) -> Result<Response, ContractError> {
let msg = MixnetExecuteMsg::LeaveFamilyOnBehalf {
member_address: self.owner_address().to_string(),
signature,
family_head: family_head.to_string(),
};
let msg = wasm_execute(MIXNET_CONTRACT_ADDRESS.load(storage)?, &msg, vec![])?;
Ok(Response::new().add_message(msg))
}
fn try_head_kick_member(
&self,
storage: &dyn Storage,
signature: String,
member: IdentityKeyRef<'_>,
) -> Result<Response, ContractError> {
let msg = MixnetExecuteMsg::KickFamilyMemberOnBehalf {
head_address: self.owner_address().to_string(),
signature,
member: member.to_string(),
};
let msg = wasm_execute(MIXNET_CONTRACT_ADDRESS.load(storage)?, &msg, vec![])?;
Ok(Response::new().add_message(msg))
}
}
+5 -4
View File
@@ -51,10 +51,11 @@ pub struct Init {
#[clap(long)]
mnemonic: Option<String>,
/// Set this gateway to work in a enabled credentials mode that would disallow clients to bypass bandwidth credential requirement
/// Set this gateway to work only with coconut credentials; that would disallow clients to
/// bypass bandwidth credential requirement
#[cfg(feature = "coconut")]
#[clap(long)]
enabled_credentials_mode: Option<bool>,
only_coconut_credentials: bool,
/// Enable/disable gateway anonymized statistics that get sent to a statistics aggregator server
#[clap(long)]
@@ -79,7 +80,7 @@ impl From<Init> for OverrideConfig {
mnemonic: init_config.mnemonic,
#[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode,
only_coconut_credentials: init_config.only_coconut_credentials,
enabled_statistics: init_config.enabled_statistics,
statistics_service_url: init_config.statistics_service_url,
@@ -170,7 +171,7 @@ mod tests {
statistics_service_url: None,
enabled_statistics: None,
#[cfg(feature = "coconut")]
enabled_credentials_mode: None,
only_coconut_credentials: false,
};
std::env::set_var(BECH32_PREFIX, "n");
+2 -4
View File
@@ -60,7 +60,7 @@ pub(crate) struct OverrideConfig {
mnemonic: Option<String>,
#[cfg(feature = "coconut")]
enabled_credentials_mode: Option<bool>,
only_coconut_credentials: bool,
}
pub(crate) async fn execute(args: Cli) {
@@ -153,9 +153,7 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
#[cfg(feature = "coconut")]
{
if let Some(enabled_credentials_mode) = args.enabled_credentials_mode {
config = config.with_disabled_credentials_mode(!enabled_credentials_mode);
}
config = config.with_only_coconut_credentials(args.only_coconut_credentials);
}
config
+4 -3
View File
@@ -51,10 +51,11 @@ pub struct Run {
#[clap(long)]
mnemonic: Option<String>,
/// Set this gateway to work in a enabled credentials mode that would disallow clients to bypass bandwidth credential requirement
/// Set this gateway to work only with coconut credentials; that would disallow clients to
/// bypass bandwidth credential requirement
#[cfg(feature = "coconut")]
#[clap(long)]
enabled_credentials_mode: Option<bool>,
only_coconut_credentials: bool,
/// Enable/disable gateway anonymized statistics that get sent to a statistics aggregator server
#[clap(long)]
@@ -79,7 +80,7 @@ impl From<Run> for OverrideConfig {
mnemonic: run_config.mnemonic,
#[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode,
only_coconut_credentials: run_config.only_coconut_credentials,
enabled_statistics: run_config.enabled_statistics,
statistics_service_url: run_config.statistics_service_url,
+8 -8
View File
@@ -128,8 +128,8 @@ impl Config {
}
#[cfg(feature = "coconut")]
pub fn with_disabled_credentials_mode(mut self, disabled_credentials_mode: bool) -> Self {
self.gateway.disabled_credentials_mode = disabled_credentials_mode;
pub fn with_only_coconut_credentials(mut self, only_coconut_credentials: bool) -> Self {
self.gateway.only_coconut_credentials = only_coconut_credentials;
self
}
@@ -211,8 +211,8 @@ impl Config {
self.config_directory().join(Self::config_file_name())
}
pub fn get_disabled_credentials_mode(&self) -> bool {
self.gateway.disabled_credentials_mode
pub fn get_only_coconut_credentials(&self) -> bool {
self.gateway.only_coconut_credentials
}
pub fn get_private_identity_key_file(&self) -> PathBuf {
@@ -315,10 +315,10 @@ pub struct Gateway {
/// ID specifies the human readable ID of this particular gateway.
id: String,
/// Indicates whether this gateway is running in a disabled credentials mode, thus allowing clients
/// to claim bandwidth without presenting bandwidth credentials.
/// Indicates whether this gateway is accepting only coconut credentials for accessing the
/// the mixnet, or if it also accepts non-paying clients
#[serde(default)]
disabled_credentials_mode: bool,
only_coconut_credentials: bool,
/// Address to which this mixnode will bind to and will be listening for packets.
#[serde(default = "bind_all_address")]
@@ -406,7 +406,7 @@ impl Default for Gateway {
Gateway {
version: env!("CARGO_PKG_VERSION").to_string(),
id: "".to_string(),
disabled_credentials_mode: true,
only_coconut_credentials: false,
listening_address: bind_all_address(),
announce_address: "127.0.0.1".to_string(),
mix_port: DEFAULT_MIX_LISTENING_PORT,
+3 -3
View File
@@ -19,9 +19,9 @@ version = '{{ gateway.version }}'
# Human readable ID of this particular gateway.
id = '{{ gateway.id }}'
# Indicates whether this gateway is running in a disabled credentials mode, thus allowing clients
# to claim bandwidth without presenting bandwidth credentials.
disabled_credentials_mode = {{ gateway.disabled_credentials_mode }}
# Indicates whether this gateway is accepting only coconut credentials for accessing the
# the mixnet, or if it also accepts non-paying clients
only_coconut_credentials = {{ gateway.only_coconut_credentials }}
# Socket address to which this gateway will bind to and will be listening for packets.
listening_address = '{{ gateway.listening_address }}'
@@ -45,8 +45,8 @@ pub(crate) enum RequestHandlingError {
#[error("Provided bandwidth credential did not verify correctly on {0}")]
InvalidBandwidthCredential(String),
#[error("This gateway is not running in the disabled credentials mode")]
NotInDisabledCredentialsMode,
#[error("This gateway is only accepting coconut credentials for bandwidth")]
OnlyCoconutCredentials,
#[error("Nymd Error - {0}")]
NymdError(#[from] validator_client::nymd::error::NymdError),
@@ -309,8 +309,8 @@ where
async fn handle_claim_testnet_bandwidth(
&mut self,
) -> Result<ServerResponse, RequestHandlingError> {
if !self.inner.disabled_credentials_mode {
return Err(RequestHandlingError::NotInDisabledCredentialsMode);
if self.inner.only_coconut_credentials {
return Err(RequestHandlingError::OnlyCoconutCredentials);
}
self.increase_bandwidth(FREE_TESTNET_BANDWIDTH_VALUE)
@@ -70,7 +70,7 @@ impl InitialAuthenticationError {
pub(crate) struct FreshHandler<R, S, St> {
rng: R,
local_identity: Arc<identity::KeyPair>,
pub(crate) disabled_credentials_mode: bool,
pub(crate) only_coconut_credentials: bool,
pub(crate) active_clients_store: ActiveClientsStore,
pub(crate) outbound_mix_sender: MixForwardingSender,
pub(crate) socket_connection: SocketStream<S>,
@@ -93,7 +93,7 @@ where
pub(crate) fn new(
rng: R,
conn: S,
disabled_credentials_mode: bool,
only_coconut_credentials: bool,
outbound_mix_sender: MixForwardingSender,
local_identity: Arc<identity::KeyPair>,
storage: St,
@@ -103,7 +103,7 @@ where
FreshHandler {
rng,
active_clients_store,
disabled_credentials_mode,
only_coconut_credentials,
outbound_mix_sender,
socket_connection: SocketStream::RawTcp(conn),
local_identity,
@@ -19,7 +19,7 @@ use crate::node::client_handling::websocket::connection_handler::coconut::Coconu
pub(crate) struct Listener {
address: SocketAddr,
local_identity: Arc<identity::KeyPair>,
disabled_credentials_mode: bool,
only_coconut_credentials: bool,
#[cfg(feature = "coconut")]
pub(crate) coconut_verifier: Arc<CoconutVerifier>,
@@ -29,13 +29,13 @@ impl Listener {
pub(crate) fn new(
address: SocketAddr,
local_identity: Arc<identity::KeyPair>,
disabled_credentials_mode: bool,
only_coconut_credentials: bool,
#[cfg(feature = "coconut")] coconut_verifier: Arc<CoconutVerifier>,
) -> Self {
Listener {
address,
local_identity,
disabled_credentials_mode,
only_coconut_credentials,
#[cfg(feature = "coconut")]
coconut_verifier,
}
@@ -69,7 +69,7 @@ impl Listener {
let handle = FreshHandler::new(
OsRng,
socket,
self.disabled_credentials_mode,
self.only_coconut_credentials,
outbound_mix_sender.clone(),
Arc::clone(&self.local_identity),
storage.clone(),
+1 -1
View File
@@ -192,7 +192,7 @@ where
websocket::Listener::new(
listening_address,
Arc::clone(&self.identity_keypair),
self.config.get_disabled_credentials_mode(),
self.config.get_only_coconut_credentials(),
#[cfg(feature = "coconut")]
coconut_verifier,
)
+4
View File
@@ -1,3 +1,7 @@
## UNRELEASED
- socks5-client: fix error with client failing and disconnecting unnecessarily.
## [nym-connect-v1.1.1](https://github.com/nymtech/nym/tree/nym-connect-v1.1.1) (2022-11-29)
- socks5-client: fix multiplex concurrent connections ([#1720], [#1777])
+1 -1
View File
@@ -30,7 +30,7 @@ fn main() {
//use qwerty environment
//path may need changing for your set up
let qwerty_environment = PathBuf::from("~/nym/envs/qa-qwerty.env");
let qwerty_environment = PathBuf::from("/Users/tommyvez/Documents/NYM_Production/nym/envs/qa-qwerty.env");
setup_env(Some(qwerty_environment));
println!("Starting up...");
+4
View File
@@ -73,6 +73,10 @@ fn main() {
mixnet::delegate::get_all_mix_delegations,
mixnet::delegate::undelegate_from_mixnode,
mixnet::delegate::undelegate_all_from_mixnode,
mixnet::families::create_family,
mixnet::families::join_family,
mixnet::families::leave_family,
mixnet::families::kick_family_member,
mixnet::interval::get_current_interval,
mixnet::interval::get_pending_epoch_events,
mixnet::interval::get_pending_interval_events,
@@ -0,0 +1,81 @@
use crate::error::BackendError;
use crate::state::WalletState;
use nym_types::transaction::TransactionExecuteResult;
use validator_client::nymd::traits::MixnetSigningClient;
use validator_client::nymd::Fee;
#[tauri::command]
pub async fn create_family(
signature: String,
label: String,
fee: Option<Fee>,
state: tauri::State<'_, WalletState>,
) -> Result<TransactionExecuteResult, BackendError> {
let guard = state.read().await;
let fee_amount = guard.convert_tx_fee(fee.as_ref());
let res = guard
.current_client()?
.nymd
.create_family(signature, label, fee)
.await?;
Ok(TransactionExecuteResult::from_execute_result(
res, fee_amount,
)?)
}
#[tauri::command]
pub async fn join_family(
signature: String,
family_head: String,
fee: Option<Fee>,
state: tauri::State<'_, WalletState>,
) -> Result<TransactionExecuteResult, BackendError> {
let guard = state.read().await;
let fee_amount = guard.convert_tx_fee(fee.as_ref());
let res = guard
.current_client()?
.nymd
.join_family(signature, family_head, fee)
.await?;
Ok(TransactionExecuteResult::from_execute_result(
res, fee_amount,
)?)
}
#[tauri::command]
pub async fn leave_family(
signature: String,
family_head: String,
fee: Option<Fee>,
state: tauri::State<'_, WalletState>,
) -> Result<TransactionExecuteResult, BackendError> {
let guard = state.read().await;
let fee_amount = guard.convert_tx_fee(fee.as_ref());
let res = guard
.current_client()?
.nymd
.leave_family(signature, family_head, fee)
.await?;
Ok(TransactionExecuteResult::from_execute_result(
res, fee_amount,
)?)
}
#[tauri::command]
pub async fn kick_family_member(
signature: String,
member: String,
fee: Option<Fee>,
state: tauri::State<'_, WalletState>,
) -> Result<TransactionExecuteResult, BackendError> {
let guard = state.read().await;
let fee_amount = guard.convert_tx_fee(fee.as_ref());
let res = guard
.current_client()?
.nymd
.kick_family_member(signature, member, fee)
.await?;
Ok(TransactionExecuteResult::from_execute_result(
res, fee_amount,
)?)
}
@@ -2,6 +2,7 @@ pub mod account;
pub mod admin;
pub mod bond;
pub mod delegate;
pub mod families;
pub mod interval;
pub mod rewards;
pub mod send;
+1 -1
View File
@@ -95,7 +95,7 @@ minimum_interval_monitor_threshold = {{ rewarding.minimum_interval_monitor_thres
[coconut_signer]
# Specifies whether rewarding service is enabled in this process.
# Specifies whether coconut signing protocol is enabled in this process.
enabled = {{ coconut_signer.enabled }}
# Path to the coconut verification key
+20 -1
View File
@@ -5,6 +5,7 @@ use crate::nymd_client::Client;
use crate::storage::ValidatorApiStorage;
use ::time::OffsetDateTime;
use anyhow::Result;
use mixnet_contract_common::families::FamilyHead;
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::reward_params::{Performance, RewardingParams};
use mixnet_contract_common::{
@@ -141,7 +142,11 @@ impl<C> ValidatorCacheRefresher<C> {
interval_reward_params: RewardingParams,
current_interval: Interval,
rewarded_set: &HashMap<MixId, RewardedSetNodeStatus>,
mix_to_family: Vec<(IdentityKey, FamilyHead)>,
) -> Vec<MixNodeBondAnnotated> {
let mix_to_family = mix_to_family
.into_iter()
.collect::<HashMap<IdentityKey, FamilyHead>>();
let mut annotated = Vec::new();
for mixnode in mixnodes {
let stake_saturation = mixnode
@@ -174,6 +179,10 @@ impl<C> ValidatorCacheRefresher<C> {
current_interval,
);
let family = mix_to_family
.get(&mixnode.bond_information.identity().to_string())
.cloned();
annotated.push(MixNodeBondAnnotated {
mixnode_details: mixnode,
stake_saturation,
@@ -181,6 +190,7 @@ impl<C> ValidatorCacheRefresher<C> {
performance,
estimated_operator_apy,
estimated_delegators_apy,
family,
});
}
annotated
@@ -226,10 +236,18 @@ impl<C> ValidatorCacheRefresher<C> {
let mixnodes = self.nymd_client.get_mixnodes().await?;
let gateways = self.nymd_client.get_gateways().await?;
let mix_to_family = self.nymd_client.get_all_family_members().await?;
let rewarded_set = self.get_rewarded_set_map().await;
let mixnodes = self
.annotate_node_with_details(mixnodes, rewarding_params, current_interval, &rewarded_set)
.annotate_node_with_details(
mixnodes,
rewarding_params,
current_interval,
&rewarded_set,
mix_to_family,
)
.await;
let (rewarded_set, active_set) =
@@ -322,6 +340,7 @@ impl ValidatorCache {
})
}
#[allow(clippy::too_many_arguments)]
async fn update_cache(
&self,
mixnodes: Vec<MixNodeBondAnnotated>,
@@ -25,6 +25,11 @@ pub enum RewardingError {
#[from]
source: std::num::TryFromIntError,
},
#[error("{source}")]
WeightedError {
#[from]
source: rand::distributions::WeightedError,
},
}
impl From<NymdError> for RewardingError {
+72 -22
View File
@@ -19,11 +19,14 @@ use crate::storage::ValidatorApiStorage;
use mixnet_contract_common::{
reward_params::Performance, CurrentIntervalResponse, ExecuteMsg, Interval, MixId,
};
use mixnet_contract_common::{Layer, LayerAssignment};
use rand::prelude::SliceRandom;
use rand::rngs::OsRng;
use std::collections::HashMap;
use std::collections::HashSet;
use std::time::Duration;
use tokio::time::sleep;
use validator_api_requests::models::MixNodeBondAnnotated;
use validator_client::nymd::SigningNymdClient;
pub(crate) mod error;
@@ -32,7 +35,6 @@ mod helpers;
use crate::epoch_operations::helpers::stake_to_f64;
use crate::node_status_api::ONE_DAY;
use error::RewardingError;
use mixnet_contract_common::mixnode::MixNodeDetails;
use task::ShutdownListener;
#[derive(Debug, Clone, Copy)]
@@ -57,6 +59,16 @@ pub struct RewardedSetUpdater {
storage: ValidatorApiStorage,
}
// Weight of a layer being chose is reciprocal to current count in layer
fn layer_weight(l: &Layer, layer_assignments: &HashMap<Layer, f32>) -> f32 {
let total = layer_assignments.values().fold(0., |acc, i| acc + i);
if total == 0. {
1.
} else {
1. - (layer_assignments.get(l).unwrap_or(&0.) / total)
}
}
impl RewardedSetUpdater {
pub(crate) async fn current_interval_details(
&self,
@@ -76,23 +88,62 @@ impl RewardedSetUpdater {
})
}
async fn determine_layers(
&self,
rewarded_set: &[MixNodeBondAnnotated],
) -> Result<(Vec<LayerAssignment>, HashMap<String, Layer>), RewardingError> {
let mut families_in_layer: HashMap<String, Layer> = HashMap::new();
let mut assignments = vec![];
let mut layer_assignments: HashMap<Layer, f32> = HashMap::new();
let mut rng = OsRng;
let layers = vec![Layer::One, Layer::Two, Layer::Three];
for mix in rewarded_set {
// Get layer already assigned to nodes family, if any
let family_layer = mix
.family
.as_ref()
.and_then(|h| families_in_layer.get(h.identity()));
// Same node families are always assigned to the same layer, otherwise layer selected by a random weighted choice
let layer = if let Some(layer) = family_layer {
layer.to_owned()
} else {
layers
.choose_weighted(&mut rng, |l| layer_weight(l, &layer_assignments))?
.to_owned()
};
assignments.push(LayerAssignment::new(mix.mix_id(), layer));
// layer accounting
let layer_entry = layer_assignments.entry(layer).or_insert(0.);
*layer_entry += 1.;
if let Some(ref family) = mix.family {
families_in_layer.insert(family.identity().to_string(), layer);
}
}
Ok((assignments, families_in_layer))
}
fn determine_rewarded_set(
&self,
mixnodes: Vec<MixNodeDetails>,
mixnodes: &[MixNodeBondAnnotated],
nodes_to_select: u32,
) -> Vec<MixId> {
) -> Result<Vec<MixNodeBondAnnotated>, RewardingError> {
if mixnodes.is_empty() {
return Vec::new();
return Ok(Vec::new());
}
let mut rng = OsRng;
// generate list of mixnodes and their relatively weight (by total stake)
let choices = mixnodes
.into_iter()
.iter()
.map(|mix| {
let total_stake = stake_to_f64(mix.total_stake());
(mix.mix_id(), total_stake)
let total_stake = stake_to_f64(mix.mixnode_details.total_stake());
(mix.to_owned(), total_stake)
})
.collect::<Vec<_>>();
@@ -101,11 +152,10 @@ impl RewardedSetUpdater {
// - we have invalid weights, i.e. less than zero or NaNs - it shouldn't happen in our case as we safely cast down from u128
// - all weights are zero - it's impossible in our case as the list of nodes is not empty and weight is proportional to stake. You must have non-zero stake in order to bond
// - we have more than u32::MAX values (which is incredibly unrealistic to have 4B mixnodes bonded... literally every other person on the planet would need one)
choices
.choose_multiple_weighted(&mut rng, nodes_to_select as usize, |item| item.1)
.unwrap()
.map(|(mix_id, _weight)| *mix_id)
.collect()
Ok(choices
.choose_multiple_weighted(&mut rng, nodes_to_select as usize, |item| item.1)?
.map(|(mix, _weight)| mix.to_owned())
.collect())
}
async fn reward_current_rewarded_set(
@@ -186,15 +236,19 @@ impl RewardedSetUpdater {
async fn update_rewarded_set_and_advance_epoch(
&self,
all_mixnodes: Vec<MixNodeDetails>,
all_mixnodes: &[MixNodeBondAnnotated],
) -> Result<(), RewardingError> {
// we grab rewarding parameters here as they might have gotten updated when performing epoch actions
let rewarding_parameters = self.nymd_client.get_current_rewarding_parameters().await?;
let new_rewarded_set =
self.determine_rewarded_set(all_mixnodes, rewarding_parameters.rewarded_set_size);
self.determine_rewarded_set(all_mixnodes, rewarding_parameters.rewarded_set_size)?;
let (layer_assignments, _families_in_layer) =
self.determine_layers(&new_rewarded_set).await?;
self.nymd_client
.advance_current_epoch(new_rewarded_set, rewarding_parameters.active_set_size)
.advance_current_epoch(layer_assignments, rewarding_parameters.active_set_size)
.await?;
Ok(())
@@ -219,15 +273,11 @@ impl RewardedSetUpdater {
let epoch_end = interval.current_epoch_end();
let all_nodes = self.validator_cache.mixnodes().await;
if all_nodes.is_empty() {
let all_mixnodes = self.validator_cache.mixnodes_detailed().await;
if all_mixnodes.is_empty() {
log::warn!("there don't seem to be any mixnodes on the network!")
}
// get list of all mixnodes BEFORE rewarding happens as to now be biased by rewards
// that might be given to them
let all_mixnodes = self.validator_cache.mixnodes().await;
// Reward all the nodes in the still current, soon to be previous rewarded set
log::info!("Rewarding the current rewarded set...");
if let Err(err) = self.reward_current_rewarded_set(interval).await {
@@ -257,7 +307,7 @@ impl RewardedSetUpdater {
log::info!("Advancing epoch and updating the rewarded set...");
if let Err(err) = self
.update_rewarded_set_and_advance_epoch(all_mixnodes)
.update_rewarded_set_and_advance_epoch(&all_mixnodes)
.await
{
log::error!("FAILED to advance the current epoch... - {}", err);
+21 -2
View File
@@ -4,10 +4,12 @@
use crate::config::Config;
use crate::epoch_operations::MixnodeToReward;
use config::defaults::{NymNetworkDetails, DEFAULT_VALIDATOR_API_PORT};
use mixnet_contract_common::families::{Family, FamilyHead};
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::reward_params::RewardingParams;
use mixnet_contract_common::{
CurrentIntervalResponse, ExecuteMsg, GatewayBond, MixId, RewardedSetNodeStatus,
CurrentIntervalResponse, ExecuteMsg, GatewayBond, IdentityKey, LayerAssignment, MixId,
RewardedSetNodeStatus,
};
use std::sync::Arc;
use tokio::sync::RwLock;
@@ -191,6 +193,23 @@ impl<C> Client<C> {
.await
}
#[allow(dead_code)]
pub(crate) async fn get_all_node_families(&self) -> Result<Vec<Family>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
self.0.read().await.get_all_node_families().await
}
pub(crate) async fn get_all_family_members(
&self,
) -> Result<Vec<(IdentityKey, FamilyHead)>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
self.0.read().await.get_all_family_members().await
}
pub(crate) async fn send_rewarding_messages(
&self,
nodes: &[MixnodeToReward],
@@ -237,7 +256,7 @@ impl<C> Client<C> {
pub(crate) async fn advance_current_epoch(
&self,
new_rewarded_set: Vec<MixId>,
new_rewarded_set: Vec<LayerAssignment>,
expected_active_set_size: u32,
) -> Result<(), ValidatorClientError>
where
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use cosmwasm_std::{Coin, Decimal};
use mixnet_contract_common::families::FamilyHead;
use mixnet_contract_common::mixnode::MixNodeDetails;
use mixnet_contract_common::reward_params::{Performance, RewardingParams};
use mixnet_contract_common::rewarding::RewardEstimate;
@@ -100,6 +101,7 @@ pub struct MixNodeBondAnnotated {
pub performance: Performance,
pub estimated_operator_apy: Decimal,
pub estimated_delegators_apy: Decimal,
pub family: Option<FamilyHead>,
}
impl MixNodeBondAnnotated {