Node family management (#1670)
* Family management messages * Add family queries * Add queries to client * Layer assignment message * Paged family queries, annotate mixnodes with family * Add layer assignments to epoch operations * Remove family layer peristence * Add NotImplemented error for kick Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com>
This commit is contained in:
@@ -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(
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Cargo.lock
|
||||
Generated
-1786
File diff suppressed because it is too large
Load Diff
@@ -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";
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod queries;
|
||||
pub mod storage;
|
||||
pub mod transactions;
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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,
|
||||
)?;
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
mod constants;
|
||||
pub mod contract;
|
||||
mod delegations;
|
||||
mod families;
|
||||
mod gateways;
|
||||
mod interval;
|
||||
mod mixnet_contract_settings;
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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].
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user