Compare commits

..

4 Commits

Author SHA1 Message Date
Mark Sinclair c720b430b7 sdk: examples: UI to send and show sender client address 2022-11-29 14:15:47 +00:00
Mark Sinclair 934a8c3735 sdk: add headers to wasm client 2022-11-29 14:15:47 +00:00
Mark Sinclair ab1479f363 wasm-client: make headers Option<String> and add to all methods 2022-11-29 14:15:47 +00:00
Jon Häggblad 24e2eee547 Merge remote-tracking branch 'origin/release/v1.1.2' into develop 2022-11-29 12:47:52 +01:00
169 changed files with 2735 additions and 5593 deletions
+2 -2
View File
@@ -5,7 +5,7 @@ on:
- cron: '5 9 * * *'
jobs:
cargo-deny:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- name: Checkout repository code
uses: actions/checkout@v2
@@ -26,7 +26,7 @@ jobs:
path: .github/workflows/support-files/notifications/deny.message
notification:
needs: cargo-deny
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout@v2
+1 -1
View File
@@ -1,6 +1,6 @@
[
{
"os":"ubuntu-20.04",
"os":"ubuntu-latest",
"rust":"stable",
"runOnEvent":"always"
},
+1 -1
View File
@@ -6,7 +6,7 @@ on:
jobs:
build:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
+2 -2
View File
@@ -10,7 +10,7 @@ on:
jobs:
matrix_prep:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -24,7 +24,7 @@ jobs:
contracts:
# since it's going to be compiled into wasm, there's absolutely
# no point in running CI on different OS-es
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.rust == 'nightly' }}
needs: matrix_prep
strategy:
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [ubuntu-latest]
runs-on: ${{ matrix.platform }}
steps:
+4 -4
View File
@@ -5,7 +5,7 @@ on:
- cron: '14 1 * * *'
jobs:
matrix_prep:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -25,7 +25,7 @@ jobs:
steps:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
if: matrix.os == 'ubuntu-20.04'
if: matrix.os == 'ubuntu-latest'
- name: Check out repository code
uses: actions/checkout@v2
@@ -96,7 +96,7 @@ jobs:
- name: Reclaim some disk space
uses: actions-rs/cargo@v1
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-20.04' }}
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest' }}
with:
command: clean
@@ -160,7 +160,7 @@ jobs:
notification:
needs: build
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
@@ -1,6 +1,6 @@
[
{
"os":"ubuntu-20.04",
"os":"ubuntu-latest",
"rust":"stable",
"runOnEvent":"schedule"
},
@@ -17,7 +17,7 @@
},
{
"os":"ubuntu-20.04",
"os":"ubuntu-latest",
"rust":"beta",
"runOnEvent":"schedule"
},
@@ -33,7 +33,7 @@
},
{
"os":"ubuntu-20.04",
"os":"ubuntu-latest",
"rust":"nightly",
"runOnEvent":"schedule"
},
+5 -5
View File
@@ -5,7 +5,7 @@ on:
- cron: '14 2 * * *'
jobs:
matrix_prep:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -17,7 +17,7 @@ jobs:
inputFile: '.github/workflows/nightly_build_matrix_includes.json'
filter: '[?runOnEvent==`${{ github.event_name }}` || runOnEvent==`always`]'
get_release:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
needs: matrix_prep
outputs:
output1: ${{ steps.step2.outputs.latest_release }}
@@ -38,7 +38,7 @@ jobs:
steps:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
if: matrix.os == 'ubuntu-20.04'
if: matrix.os == 'ubuntu-latest'
- name: Check out latest release branch
uses: actions/checkout@v3
@@ -111,7 +111,7 @@ jobs:
- name: Reclaim some disk space
uses: actions-rs/cargo@v1
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-20.04' }}
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest' }}
with:
command: clean
@@ -175,7 +175,7 @@ jobs:
notification:
needs: [build,get_release]
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
+5 -5
View File
@@ -5,7 +5,7 @@ on:
- cron: '24 2 * * *'
jobs:
matrix_prep:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -17,7 +17,7 @@ jobs:
inputFile: '.github/workflows/nightly_build_matrix_includes.json'
filter: '[?runOnEvent==`${{ github.event_name }}` || runOnEvent==`always`]'
get_release:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
needs: matrix_prep
outputs:
output1: ${{ steps.step2.outputs.latest_release }}
@@ -38,7 +38,7 @@ jobs:
steps:
- name: Install Dependencies (Linux)
run: sudo apt-get update && sudo apt-get install libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libudev-dev squashfs-tools
if: matrix.os == 'ubuntu-20.04'
if: matrix.os == 'ubuntu-latest'
- name: Check out latest release branch
uses: actions/checkout@v3
@@ -111,7 +111,7 @@ jobs:
- name: Reclaim some disk space
uses: actions-rs/cargo@v1
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-20.04' }}
if: ${{ matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest' }}
with:
command: clean
@@ -175,7 +175,7 @@ jobs:
notification:
needs: [build,get_release]
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- name: Collect jobs status
uses: technote-space/workflow-conclusion-action@v2
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04, windows-latest, macos-latest]
platform: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [ubuntu-latest]
runs-on: ${{ matrix.platform }}
steps:
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [ubuntu-latest]
runs-on: ${{ matrix.platform }}
steps:
@@ -12,7 +12,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [ubuntu-latest]
runs-on: ${{ matrix.platform }}
steps:
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [ubuntu-20.04]
platform: [ubuntu-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
+1 -1
View File
@@ -12,7 +12,7 @@ defaults:
jobs:
test:
name: wallet tests
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -85,7 +85,7 @@ async function getMessageBody(context) {
...
],
check_run_url: 'https://api.github.com/repos/nymtech/nym/check-runs/5182940024',
labels: [ 'ubuntu-20.04' ],
labels: [ 'ubuntu-latest' ],
runner_id: 1,
runner_name: 'Hosted Agent',
runner_group_id: 2,
+1 -1
View File
@@ -7,7 +7,7 @@ on:
jobs:
wasm:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
+1 -9
View File
@@ -2,15 +2,7 @@
Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.1.2]
### Changed
- gateway: Renamed flag from `enabled/disabled_credentials_mode` to `only-coconut-credentials`
- "Family" feature for node families + layers
- Initial coconut functionality including credentials and distributed key generation
## [v1.1.1](https://github.com/nymtech/nym/tree/v1.1.1) (2022-11-29)
## Unreleased
### Added
Generated
+50 -8
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "client-core"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"client-connections",
"config",
@@ -923,6 +923,7 @@ dependencies = [
name = "credential"
version = "0.1.0"
dependencies = [
"async-trait",
"bip39",
"cfg-if 0.1.10",
"clap 3.2.8",
@@ -934,6 +935,7 @@ dependencies = [
"crypto",
"network-defaults",
"pemstore",
"pickledb",
"rand 0.7.3",
"serde",
"thiserror",
@@ -1631,7 +1633,7 @@ dependencies = [
[[package]]
name = "explorer-api"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"chrono",
"clap 3.2.8",
@@ -2743,6 +2745,12 @@ 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"
@@ -3168,7 +3176,7 @@ dependencies = [
[[package]]
name = "nym-client"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"clap 3.2.8",
"client-connections",
@@ -3208,7 +3216,7 @@ dependencies = [
[[package]]
name = "nym-gateway"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"anyhow",
"async-trait",
@@ -3255,7 +3263,7 @@ dependencies = [
[[package]]
name = "nym-mixnode"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"anyhow",
"bs58",
@@ -3297,7 +3305,7 @@ dependencies = [
[[package]]
name = "nym-network-requester"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"async-trait",
"clap 3.2.8",
@@ -3345,7 +3353,7 @@ dependencies = [
[[package]]
name = "nym-socks5-client"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"clap 3.2.8",
"client-connections",
@@ -3412,7 +3420,7 @@ dependencies = [
[[package]]
name = "nym-validator-api"
version = "1.1.1"
version = "1.1.0"
dependencies = [
"anyhow",
"async-trait",
@@ -3926,6 +3934,19 @@ 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"
@@ -5036,6 +5057,18 @@ 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"
@@ -6905,6 +6938,15 @@ 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"
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "client-core"
version = "1.1.2"
version = "1.1.0"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
edition = "2021"
@@ -186,10 +186,13 @@ impl TopologyRefresher {
/// # Arguments
///
/// * `topology`: active topology constructed from validator api data
fn check_layer_distribution(&self, active_topology: &NymTopology) -> bool {
/// * `mixnodes_count`: total number of active mixnodes
fn check_layer_distribution(
&self,
active_topology: &NymTopology,
mixnodes_count: usize,
) -> bool {
let mixes = active_topology.mixes();
let mixnodes_count = active_topology.num_mixnodes();
if active_topology.gateways().is_empty() {
return false;
}
@@ -254,10 +257,11 @@ 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) {
if !self.check_layer_distribution(&topology, mixnodes_count) {
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, DB_FILE_NAME};
use config::NymConfig;
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_FILE_NAME)
T::default_data_directory(Some(id)).join("db.sqlite")
}
}
+2
View File
@@ -6,9 +6,11 @@ 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"
+164 -70
View File
@@ -1,12 +1,14 @@
// 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::{Base58, Parameters};
use coconut_interface::{Attribute, Base58, BlindSignRequest, Bytable, Parameters};
use credential_storage::storage::Storage;
use credential_storage::PersistentStorage;
use credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
@@ -18,12 +20,16 @@ use validator_client::{CoconutApiClient, Config};
use crate::client::Client;
use crate::error::{CredentialClientError, Result};
use crate::state::{KeyPair, State};
use crate::state::{KeyPair, RequestData, State};
#[derive(Subcommand)]
pub(crate) enum Command {
/// Run the binary
Run(Run),
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),
/// Generate shell completions
Completions(ArgShell),
@@ -32,81 +38,169 @@ pub(crate) enum Command {
GenerateFigSpec,
}
#[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,
#[async_trait]
pub(crate) trait Execute {
async fn execute(&self, db: &mut PickleDb, shared_storage: PersistentStorage) -> Result<()>;
}
#[derive(Args, Clone)]
pub(crate) struct Deposit {
/// The nymd URL that should be used
#[clap(long)]
pub(crate) nymd_url: String,
/// A mnemonic for the account that buys the credential
nymd_url: String,
/// A mnemonic for the account that does the deposit
#[clap(long)]
pub(crate) mnemonic: String,
/// The amount of utokens the credential will hold
mnemonic: String,
/// The amount that needs to be deposited
#[clap(long)]
pub(crate) amount: u64,
amount: u64,
}
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));
#[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));
let client = Client::new(nymd_url, mnemonic);
let tx_hash = client
.deposit(
amount,
signing_keypair.public_key.clone(),
encryption_keypair.public_key.clone(),
None,
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,
)
.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();
let state = State {
amount,
tx_hash,
signing_keypair,
encryption_keypair,
};
println!("Signature: {:?}", state.signature);
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(())
Ok(())
}
}
+12
View File
@@ -23,6 +23,18 @@ 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,
+32 -14
View File
@@ -9,13 +9,14 @@ 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::{CommandFactory, Parser};
use clap::Parser;
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
#[derive(Parser)]
#[clap(author = "Nymtech", version, about)]
@@ -24,26 +25,43 @@ 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)]
pub(crate) command: Command,
command: Commands,
}
#[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 {
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)
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)
}
Ok(())
+34
View File
@@ -1,10 +1,13 @@
// 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,
@@ -35,4 +38,35 @@ 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 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.2"
version = "1.1.0"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
+2 -17
View File
@@ -203,23 +203,8 @@ impl NymClient {
#[cfg(feature = "coconut")]
let bandwidth_controller = {
let details = network_defaults::NymNetworkDetails::new_from_env();
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = self
.config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
let api_url = self
.config
.get_base()
.get_validator_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url);
let client_config = validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.2"
version = "1.1.0"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address"
edition = "2021"
+2 -17
View File
@@ -201,23 +201,8 @@ impl NymClient {
#[cfg(feature = "coconut")]
let bandwidth_controller = {
let details = network_defaults::NymNetworkDetails::new_from_env();
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = self
.config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
let api_url = self
.config
.get_base()
.get_validator_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url);
let client_config = validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
+6 -14
View File
@@ -168,13 +168,9 @@ impl SocksClient {
controller_sender: ControllerSender,
self_address: Recipient,
lane_queue_lengths: LaneQueueLengths,
mut shutdown_listener: ShutdownListener,
shutdown_listener: ShutdownListener,
) -> Self {
// If this task fails and exits, we don't want to send shutdown signal
shutdown_listener.mark_as_success();
let connection_id = Self::generate_random();
SocksClient {
controller_sender,
connection_id,
@@ -256,15 +252,10 @@ impl SocksClient {
.await;
let stream = self.stream.run_proxy();
let peer_addr = match stream.peer_addr() {
Ok(peer_addr) => peer_addr,
Err(err) => {
log::error!("Unable to extract the remote peer address: {err}");
return;
}
};
let local_stream_remote = peer_addr.to_string();
let local_stream_remote = stream
.peer_addr()
.expect("failed to extract peer address")
.to_string();
let connection_id = self.connection_id;
let input_sender = self.input_sender.clone();
@@ -328,6 +319,7 @@ impl SocksClient {
SocksCommand::UdpAssociate => unimplemented!(), // not handled
};
self.shutdown_listener.mark_as_success();
Ok(())
}
@@ -42,19 +42,28 @@ pub struct StringMessage {
/// Create a new binary message with a user-specified `kind`.
#[wasm_bindgen]
pub fn create_binary_message(kind: u8, payload: Vec<u8>) -> Vec<u8> {
create_binary_message_with_headers(kind, payload, "".to_string())
pub fn create_binary_message(kind: u8, payload: Vec<u8>, headers: Option<String>) -> Vec<u8> {
create_binary_message_with_headers(kind, payload, headers)
}
/// Create a new message with a UTF-8 encoded string `payload` and a user-specified `kind`.
#[wasm_bindgen]
pub fn create_binary_message_from_string(kind: u8, payload: String) -> Vec<u8> {
create_binary_message_with_headers(kind, payload.as_bytes().to_vec(), "".to_string())
pub fn create_binary_message_from_string(
kind: u8,
payload: String,
headers: Option<String>,
) -> Vec<u8> {
create_binary_message_with_headers(kind, payload.as_bytes().to_vec(), headers)
}
/// Create a new binary message with a user-specified `kind`, and `headers` as a string.
#[wasm_bindgen]
pub fn create_binary_message_with_headers(kind: u8, payload: Vec<u8>, headers: String) -> Vec<u8> {
pub fn create_binary_message_with_headers(
kind: u8,
payload: Vec<u8>,
headers: Option<String>,
) -> Vec<u8> {
let headers = headers.unwrap_or_else(|| "".to_string());
let headers = headers.as_bytes().to_vec();
let size = (headers.len() as u64).to_be_bytes().to_vec();
vec![vec![kind], size, headers, payload].concat()
@@ -169,7 +178,7 @@ mod tests {
let message_as_bytes = create_binary_message_with_headers(
42u8,
vec![0u8, 1u8, 2u8],
"test headers".to_string(),
Some("test headers".to_string()),
);
// calculate header size
@@ -197,7 +206,7 @@ mod tests {
#[wasm_bindgen_test]
fn test_binary_with_empty_headers() {
let message_as_bytes =
create_binary_message_with_headers(42u8, vec![0u8, 1u8, 2u8], "".to_string());
create_binary_message_with_headers(42u8, vec![0u8, 1u8, 2u8], Some("".to_string()));
let expected_size = 0;
@@ -1,5 +1,6 @@
// 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")]
@@ -9,10 +10,9 @@ 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,7 +220,6 @@ 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)
@@ -230,56 +229,6 @@ 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,
@@ -15,12 +15,12 @@ pub use coconut_dkg_common::event_attributes::*;
pub struct Log {
#[serde(default)]
// weird thing is that the first msg_index seems to always be undefined on the raw logs
pub msg_index: usize,
msg_index: usize,
// unless I'm missing something obvious, the "log" type in cosmjs is always an empty string
// and launchpad cosmos validator was setting it to what essentially is just the raw version of what
// we received (and we don't care about launchpad, we, as the time of writing this, work on the stargate)
// log: String,
pub events: Vec<cosmwasm_std::Event>,
events: Vec<cosmwasm_std::Event>,
}
/// Searches in logs for the first event of the given event type and in that event
@@ -7,7 +7,6 @@ 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,
@@ -21,9 +20,9 @@ use mixnet_contract_common::{
CurrentIntervalResponse, EpochEventId, GatewayBondResponse, GatewayOwnershipResponse,
IdentityKey, IntervalEventId, LayerDistribution, MixId, MixOwnershipResponse,
MixnodeDetailsResponse, PagedAllDelegationsResponse, PagedDelegatorDelegationsResponse,
PagedFamiliesResponse, PagedGatewayResponse, PagedMembersResponse,
PagedMixNodeDelegationsResponse, PagedMixnodeBondsResponse, PagedRewardedSetResponse,
PendingEpochEventsResponse, PendingIntervalEventsResponse, QueryMsg as MixnetQueryMsg,
PagedGatewayResponse, PagedMixNodeDelegationsResponse, PagedMixnodeBondsResponse,
PagedRewardedSetResponse, PendingEpochEventsResponse, PendingIntervalEventsResponse,
QueryMsg as MixnetQueryMsg,
};
use serde::Deserialize;
@@ -74,24 +73,6 @@ 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(
@@ -376,20 +357,6 @@ 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, LayerAssignment, MixId, MixNode,
ContractStateParams, ExecuteMsg as MixnetExecuteMsg, Gateway, MixId, MixNode,
};
#[async_trait]
@@ -108,7 +108,7 @@ pub trait MixnetSigningClient {
async fn advance_current_epoch(
&self,
new_rewarded_set: Vec<LayerAssignment>,
new_rewarded_set: Vec<MixId>,
expected_active_set_size: u32,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
@@ -136,147 +136,6 @@ 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(
@@ -321,35 +180,6 @@ pub trait MixnetSigningClient {
.await
}
async fn pledge_more(
&self,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::PledgeMore {},
vec![additional_pledge],
)
.await
}
async fn pledge_more_on_behalf(
&self,
owner: AccountId,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::PledgeMoreOnBehalf {
owner: owner.to_string(),
},
vec![additional_pledge],
)
.await
}
async fn unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondMixnode {}, vec![])
.await
@@ -64,21 +64,6 @@ pub trait VestingSigningClient {
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
async fn vesting_pledge_more(
&self,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
self.execute_vesting_contract(
fee,
VestingExecuteMsg::PledgeMore {
amount: additional_pledge.into(),
},
vec![],
)
.await
}
async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError>;
async fn vesting_track_unbond_mixnode(
+8 -12
View File
@@ -11,10 +11,6 @@ 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;
@@ -27,17 +23,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_DIR)
Self::default_root_directory().join(id).join("config")
} else {
Self::default_root_directory().join(CONFIG_DIR)
Self::default_root_directory().join("config")
}
}
fn default_data_directory(id: Option<&str>) -> PathBuf {
if let Some(id) = id {
Self::default_root_directory().join(id).join(DATA_DIR)
Self::default_root_directory().join(id).join("data")
} else {
Self::default_root_directory().join(DATA_DIR)
Self::default_root_directory().join("data")
}
}
@@ -51,17 +47,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_DIR))
Self::try_default_root_directory().map(|d| d.join(id).join("config"))
} else {
Self::try_default_root_directory().map(|d| d.join(CONFIG_DIR))
Self::try_default_root_directory().map(|d| d.join("config"))
}
}
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_DIR))
Self::try_default_root_directory().map(|d| d.join(id).join("data"))
} else {
Self::try_default_root_directory().map(|d| d.join(DATA_DIR))
Self::try_default_root_directory().map(|d| d.join("data"))
}
}
@@ -15,7 +15,7 @@ pub const MAX_DISPLAY_SIZE: usize = 128;
// TODO: if we are to use this for different types, it might make sense to introduce something like
// CommitmentTypeId field on the below for distinguishing different ones. it would somehow become part of the trait
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, JsonSchema)]
pub struct ContractSafeBytes(pub Vec<u8>);
pub struct ContractSafeBytes(Vec<u8>);
impl Deref for ContractSafeBytes {
type Target = Vec<u8>;
@@ -1,7 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{IdentityKey, MixId};
use crate::MixId;
use cosmwasm_std::{Addr, Coin, Decimal};
use thiserror::Error;
@@ -133,40 +133,4 @@ 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,
}
@@ -12,8 +12,6 @@ pub const EVENT_VERSION_PREFIX: &str = "v2_";
pub enum MixnetEventType {
MixnodeBonding,
PendingPledgeIncrease,
PledgeIncrease,
GatewayBonding,
GatewayUnbonding,
PendingMixnodeUnbonding,
@@ -53,8 +51,6 @@ impl ToString for MixnetEventType {
fn to_string(&self) -> String {
let event_name = match self {
MixnetEventType::MixnodeBonding => "mixnode_bonding",
MixnetEventType::PendingPledgeIncrease => "pending_pledge_increase",
MixnetEventType::PledgeIncrease => "pledge_increase",
MixnetEventType::GatewayBonding => "gateway_bonding",
MixnetEventType::GatewayUnbonding => "gateway_unbonding",
MixnetEventType::PendingMixnodeUnbonding => "pending_mixnode_unbonding",
@@ -334,19 +330,6 @@ pub fn new_mixnode_bonding_event(
.add_attribute(AMOUNT_KEY, amount.to_string())
}
pub fn new_pending_pledge_increase_event(mix_id: MixId, amount: &Coin) -> Event {
Event::new(MixnetEventType::PendingPledgeIncrease)
.add_attribute(MIX_ID_KEY, mix_id.to_string())
.add_attribute(AMOUNT_KEY, amount.to_string())
}
pub fn new_pledge_increase_event(created_at: BlockHeight, mix_id: MixId, amount: &Coin) -> Event {
Event::new(MixnetEventType::PledgeIncrease)
.add_attribute(EVENT_CREATION_HEIGHT_KEY, created_at.to_string())
.add_attribute(MIX_ID_KEY, mix_id.to_string())
.add_attribute(AMOUNT_KEY, amount.to_string())
}
pub fn new_mixnode_unbonding_event(created_at: BlockHeight, mix_id: MixId) -> Event {
Event::new(MixnetEventType::MixnodeUnbonding)
.add_attribute(EVENT_CREATION_HEIGHT_KEY, created_at.to_string())
@@ -1,63 +0,0 @@
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,7 +8,6 @@ mod constants;
pub mod delegation;
pub mod error;
pub mod events;
pub mod families;
pub mod gateway;
pub mod helpers;
mod interval;
@@ -36,6 +36,7 @@ impl RewardedSetNodeStatus {
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct MixNodeDetails {
pub bond_information: MixNodeBond,
pub rewarding_details: MixNodeRewarding,
}
@@ -324,14 +325,6 @@ impl MixNodeRewarding {
Ok(())
}
pub fn increase_operator_uint128(
&mut self,
amount: Uint128,
) -> Result<(), MixnetContractError> {
self.operator += amount.into_base_decimal()?;
Ok(())
}
pub fn increase_delegates_uint128(
&mut self,
amount: Uint128,
@@ -578,29 +571,6 @@ 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, Layer, LayerAssignment, MixId, Percent};
use crate::{delegation, ContractStateParams, MixId, Percent};
use crate::{Gateway, IdentityKey, MixNode};
use cosmwasm_std::Decimal;
use schemars::JsonSchema;
@@ -73,51 +73,6 @@ 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,
@@ -139,8 +94,7 @@ pub enum ExecuteMsg {
force_immediately: bool,
},
AdvanceCurrentEpoch {
new_rewarded_set: Vec<LayerAssignment>,
// families_in_layer: HashMap<String, Layer>,
new_rewarded_set: Vec<MixId>,
expected_active_set_size: u32,
},
ReconcileEpochEvents {
@@ -159,10 +113,6 @@ pub enum ExecuteMsg {
owner_signature: String,
owner: String,
},
PledgeMore {},
PledgeMoreOnBehalf {
owner: String,
},
UnbondMixnode {},
UnbondMixnodeOnBehalf {
owner: String,
@@ -240,29 +190,6 @@ 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)
}
@@ -296,8 +223,6 @@ impl ExecuteMsg {
ExecuteMsg::BondMixnodeOnBehalf { mix_node, .. } => {
format!("bonding mixnode {} on behalf", mix_node.identity_key)
}
ExecuteMsg::PledgeMore {} => "pledging additional tokens".into(),
ExecuteMsg::PledgeMoreOnBehalf { .. } => "pledging additional tokens on behalf".into(),
ExecuteMsg::UnbondMixnode { .. } => "unbonding mixnode".into(),
ExecuteMsg::UnbondMixnodeOnBehalf { .. } => "unbonding mixnode on behalf".into(),
ExecuteMsg::UpdateMixnodeCostParams { .. } => "updating mixnode cost parameters".into(),
@@ -355,27 +280,6 @@ 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 {},
@@ -430,6 +334,7 @@ pub enum QueryMsg {
mix_identity: IdentityKey,
},
GetLayerDistribution {},
// gateway-related:
GetGateways {
start_after: Option<IdentityKey>,
@@ -34,10 +34,6 @@ pub enum PendingEpochEventKind {
mix_id: MixId,
proxy: Option<Addr>,
},
PledgeMore {
mix_id: MixId,
amount: Coin,
},
UnbondMixnode {
mix_id: MixId,
},
@@ -82,6 +78,7 @@ pub enum PendingIntervalEventKind {
mix_id: MixId,
new_costs: MixNodeCostParams,
},
UpdateRewardingParams {
update: IntervalRewardingParamsUpdate,
},
@@ -2,7 +2,6 @@
// 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;
@@ -22,27 +21,6 @@ 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,
@@ -148,15 +126,3 @@ 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>,
}
@@ -14,7 +14,6 @@ pub const VESTING_UNDELEGATION_EVENT_TYPE: &str = "vesting_undelegation";
pub const VESTING_GATEWAY_BONDING_EVENT_TYPE: &str = "vesting_gateway_bonding";
pub const VESTING_GATEWAY_UNBONDING_EVENT_TYPE: &str = "vesting_gateway_unbonding";
pub const VESTING_MIXNODE_BONDING_EVENT_TYPE: &str = "vesting_mixnode_bonding";
pub const VESTING_PLEDGE_MORE_EVENT_TYPE: &str = "vesting_pledge_more";
pub const VESTING_MIXNODE_UNBONDING_EVENT_TYPE: &str = "vesting_mixnode_unbonding";
pub const VESTING_UPDATE_MIXNODE_CONFIG_EVENT_TYPE: &str = "vesting_update_mixnode_config";
pub const VESTING_UPDATE_MIXNODE_COST_PARAMS_EVENT_TYPE: &str =
@@ -113,10 +112,6 @@ pub fn new_vesting_mixnode_bonding_event() -> Event {
Event::new(VESTING_MIXNODE_BONDING_EVENT_TYPE)
}
pub fn new_vesting_pledge_more_event() -> Event {
Event::new(VESTING_PLEDGE_MORE_EVENT_TYPE)
}
pub fn new_vesting_update_mixnode_config_event() -> Event {
Event::new(VESTING_UPDATE_MIXNODE_CONFIG_EVENT_TYPE)
}
@@ -1,7 +1,7 @@
use cosmwasm_std::{Coin, Timestamp};
use mixnet_contract_common::{
mixnode::{MixNodeConfigUpdate, MixNodeCostParams},
Gateway, IdentityKey, MixId, MixNode,
Gateway, MixId, MixNode,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -57,25 +57,6 @@ 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,
@@ -120,9 +101,6 @@ pub enum ExecuteMsg {
owner_signature: String,
amount: Coin,
},
PledgeMore {
amount: Coin,
},
UnbondMixnode {},
TrackUnbondMixnode {
owner: String,
@@ -153,10 +131,6 @@ 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",
@@ -171,7 +145,6 @@ impl ExecuteMsg {
ExecuteMsg::WithdrawVestedCoins { .. } => "VestingExecuteMsg::WithdrawVestedCoins",
ExecuteMsg::TrackUndelegation { .. } => "VestingExecuteMsg::TrackUndelegation",
ExecuteMsg::BondMixnode { .. } => "VestingExecuteMsg::BondMixnode",
ExecuteMsg::PledgeMore { .. } => "VestingExecuteMsg::PledgeMore",
ExecuteMsg::UnbondMixnode { .. } => "VestingExecuteMsg::UnbondMixnode",
ExecuteMsg::TrackUnbondMixnode { .. } => "VestingExecuteMsg::TrackUnbondMixnode",
ExecuteMsg::BondGateway { .. } => "VestingExecuteMsg::BondGateway",
-4
View File
@@ -84,10 +84,6 @@ 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![];
-10
View File
@@ -57,10 +57,6 @@ pub enum PendingEpochEventData {
mix_id: MixId,
proxy: Option<String>,
},
PledgeMore {
mix_id: MixId,
amount: DecCoin,
},
UnbondMixnode {
mix_id: MixId,
},
@@ -95,12 +91,6 @@ impl PendingEpochEventData {
mix_id,
proxy: proxy.map(|p| p.into_string()),
}),
MixnetContractPendingEpochEventKind::PledgeMore { mix_id, amount } => {
Ok(PendingEpochEventData::PledgeMore {
mix_id,
amount: reg.attempt_convert_to_display_dec_coin(amount.into())?,
})
}
MixnetContractPendingEpochEventKind::UnbondMixnode { mix_id } => {
Ok(PendingEpochEventData::UnbondMixnode { mix_id })
}
-1
View File
@@ -1 +0,0 @@
Cargo.lock
-2
View File
@@ -3,9 +3,7 @@
## Added
- Added migration code to the mixnet contract to allow updating stored vesting contract address to make it easier to deploy any future environments ([#1759],[#1769])
- Added an option to pledge additional tokens without the need to rebond minxode ([#1679])
[#1679]: https://github.com/nymtech/nym/pull/1679
[#1759]: https://github.com/nymtech/nym/pull/1759
[#1769]: https://github.com/nymtech/nym/pull/1769
+1783
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -25,7 +25,7 @@ impl<'a> IndexList<SpendCredential> for SpendCredentialIndex<'a> {
}
}
// spent_credentials() is the storage access function.
// gateways() is the storage access function.
pub(crate) fn spent_credentials<'a>(
) -> IndexedMap<'a, &'a str, SpendCredential, SpendCredentialIndex<'a>> {
let indexes = SpendCredentialIndex {
+1 -5
View File
@@ -19,8 +19,4 @@ cw4 = { version = "0.13.4" }
schemars = "0.8"
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
thiserror = "1.0.23"
[dev-dependencies]
cw-multi-test = { version = "0.13.4" }
cw4-group = { path = "../multisig/cw4-group" }
thiserror = "1.0.23"
-264
View File
@@ -1,264 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::dealers::queries::{
query_current_dealers_paged, query_dealer_details, query_past_dealers_paged,
};
use crate::dealers::transactions::try_add_dealer;
use crate::dealings::queries::query_dealings_paged;
use crate::dealings::transactions::try_commit_dealings;
use crate::epoch_state::queries::query_current_epoch_state;
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::epoch_state::transactions::advance_epoch_state;
use crate::error::ContractError;
use crate::state::{State, ADMIN, MULTISIG, STATE};
use crate::verification_key_shares::queries::query_vk_shares_paged;
use crate::verification_key_shares::transactions::try_commit_verification_key_share;
use crate::verification_key_shares::transactions::try_verify_verification_key_share;
use coconut_dkg_common::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::{
entry_point, to_binary, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response,
};
use cw4::Cw4Contract;
/// Instantiate the contract.
///
/// `deps` contains Storage, API and Querier
/// `env` contains block, message and contract info
/// `msg` is the contract initialization message, sort of like a constructor call.
#[entry_point]
pub fn instantiate(
mut deps: DepsMut<'_>,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
let admin_addr = deps.api.addr_validate(&msg.admin)?;
let multisig_addr = deps.api.addr_validate(&msg.multisig_addr)?;
ADMIN.set(deps.branch(), Some(admin_addr))?;
MULTISIG.set(deps.branch(), Some(multisig_addr.clone()))?;
let group_addr = Cw4Contract(deps.api.addr_validate(&msg.group_addr).map_err(|_| {
ContractError::InvalidGroup {
addr: msg.group_addr.clone(),
}
})?);
let state = State {
group_addr,
multisig_addr,
mix_denom: msg.mix_denom,
};
STATE.save(deps.storage, &state)?;
CURRENT_EPOCH_STATE.save(deps.storage, &EpochState::default())?;
Ok(Response::default())
}
/// Handle an incoming message
#[entry_point]
pub fn execute(
deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::RegisterDealer {
bte_key_with_proof,
announce_address,
} => try_add_dealer(deps, info, bte_key_with_proof, announce_address),
ExecuteMsg::CommitDealing { dealing_bytes } => {
try_commit_dealings(deps, info, dealing_bytes)
}
ExecuteMsg::CommitVerificationKeyShare { share } => {
try_commit_verification_key_share(deps, env, info, share)
}
ExecuteMsg::VerifyVerificationKeyShare { owner } => {
try_verify_verification_key_share(deps, info, owner)
}
ExecuteMsg::AdvanceEpochState {} => advance_epoch_state(deps, info),
}
}
#[entry_point]
pub fn query(deps: Deps<'_>, _env: Env, msg: QueryMsg) -> Result<QueryResponse, ContractError> {
let response = match msg {
QueryMsg::GetCurrentEpochState {} => to_binary(&query_current_epoch_state(deps.storage)?)?,
QueryMsg::GetDealerDetails { dealer_address } => {
to_binary(&query_dealer_details(deps, dealer_address)?)?
}
QueryMsg::GetCurrentDealers { limit, start_after } => {
to_binary(&query_current_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetPastDealers { limit, start_after } => {
to_binary(&query_past_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetDealing {
idx,
limit,
start_after,
} => to_binary(&query_dealings_paged(deps, idx, start_after, limit)?)?,
QueryMsg::GetVerificationKeys { limit, start_after } => {
to_binary(&query_vk_shares_paged(deps, start_after, limit)?)?
}
};
Ok(response)
}
#[entry_point]
pub fn migrate(_deps: DepsMut<'_>, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
Ok(Default::default())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::support::tests::fixtures::{dealer_details_fixture, TEST_MIX_DENOM};
use crate::support::tests::helpers::{ADMIN_ADDRESS, MULTISIG_CONTRACT};
use coconut_dkg_common::dealer::DealerDetails;
use coconut_dkg_common::msg::ExecuteMsg::RegisterDealer;
use coconut_dkg_common::types::NodeIndex;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
use cosmwasm_std::{coins, Addr};
use cw4::Member;
use cw4_group::msg::InstantiateMsg as GroupInstantiateMsg;
use cw_multi_test::{App, AppBuilder, AppResponse, ContractWrapper, Executor};
fn instantiate_with_group(app: &mut App, members: &[Addr]) -> Addr {
let group_code_id = app.store_code(Box::new(ContractWrapper::new(
cw4_group::contract::execute,
cw4_group::contract::instantiate,
cw4_group::contract::query,
)));
let msg = GroupInstantiateMsg {
admin: Some(ADMIN_ADDRESS.to_string()),
members: members
.iter()
.map(|member| Member {
addr: member.to_string(),
weight: 10,
})
.collect(),
};
let group_contract_addr = app
.instantiate_contract(
group_code_id,
Addr::unchecked(ADMIN_ADDRESS),
&msg,
&[],
"group",
None,
)
.unwrap();
let coconut_dkg_code_id =
app.store_code(Box::new(ContractWrapper::new(execute, instantiate, query)));
let msg = InstantiateMsg {
group_addr: group_contract_addr.to_string(),
multisig_addr: MULTISIG_CONTRACT.to_string(),
admin: Addr::unchecked(ADMIN_ADDRESS).to_string(),
mix_denom: TEST_MIX_DENOM.to_string(),
};
app.instantiate_contract(
coconut_dkg_code_id,
Addr::unchecked(ADMIN_ADDRESS),
&msg,
&[],
"coconut dkg",
None,
)
.unwrap()
}
fn parse_node_index(res: AppResponse) -> NodeIndex {
res.events
.into_iter()
.find(|e| &e.ty == "wasm")
.unwrap()
.attributes
.into_iter()
.find(|attr| &attr.key == "node_index")
.unwrap()
.value
.parse::<u64>()
.unwrap()
}
#[test]
fn initialize_contract() {
let mut deps = mock_dependencies();
let env = mock_env();
let msg = InstantiateMsg {
group_addr: "group_addr".to_string(),
multisig_addr: "multisig_addr".to_string(),
admin: "admin".to_string(),
mix_denom: "nym".to_string(),
};
let info = mock_info("creator", &[]);
let res = instantiate(deps.as_mut(), env.clone(), info, msg);
assert!(res.is_ok())
}
#[test]
fn execute_add_dealer() {
let init_funds = coins(100, TEST_MIX_DENOM);
const MEMBER_SIZE: usize = 100;
let members: [Addr; MEMBER_SIZE] =
std::array::from_fn(|idx| Addr::unchecked(format!("member{}", idx)));
let mut app = AppBuilder::new().build(|router, _, storage| {
router
.bank
.init_balance(storage, &Addr::unchecked(ADMIN_ADDRESS), init_funds)
.unwrap();
});
let coconut_dkg_contract_addr = instantiate_with_group(&mut app, &members);
for (idx, member) in members.iter().enumerate() {
let res = app
.execute_contract(
member.clone(),
coconut_dkg_contract_addr.clone(),
&RegisterDealer {
bte_key_with_proof: "bte_key_with_proof".to_string(),
announce_address: "127.0.0.1:8000".to_string(),
},
&vec![],
)
.unwrap();
assert_eq!(parse_node_index(res), (idx + 1) as u64);
let err = app
.execute_contract(
member.clone(),
coconut_dkg_contract_addr.clone(),
&RegisterDealer {
bte_key_with_proof: "bte_key_with_proof".to_string(),
announce_address: "127.0.0.1:8000".to_string(),
},
&vec![],
)
.unwrap_err();
assert_eq!(ContractError::AlreadyADealer, err.downcast().unwrap());
}
let unauthorized_member = Addr::unchecked("not_a_member");
let err = app
.execute_contract(
unauthorized_member,
coconut_dkg_contract_addr.clone(),
&RegisterDealer {
bte_key_with_proof: "bte_key_with_proof".to_string(),
announce_address: "127.0.0.1:8000".to_string(),
},
&vec![],
)
.unwrap_err();
assert_eq!(ContractError::Unauthorized, err.downcast().unwrap());
}
}
+3 -164
View File
@@ -10,7 +10,7 @@ fn query_dealers(
deps: Deps<'_>,
start_after: Option<String>,
limit: Option<u32>,
underlying_map: &IndexedDealersMap<'_>,
underlying_map: IndexedDealersMap<'_>,
) -> StdResult<PagedDealerResponse> {
let limit = limit
.unwrap_or(storage::DEALERS_PAGE_DEFAULT_LIMIT)
@@ -55,7 +55,7 @@ pub fn query_current_dealers_paged(
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<PagedDealerResponse> {
query_dealers(deps, start_after, limit, &storage::current_dealers())
query_dealers(deps, start_after, limit, storage::current_dealers())
}
pub fn query_past_dealers_paged(
@@ -63,166 +63,5 @@ pub fn query_past_dealers_paged(
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<PagedDealerResponse> {
query_dealers(deps, start_after, limit, &storage::past_dealers())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::dealers::storage::{DEALERS_PAGE_DEFAULT_LIMIT, DEALERS_PAGE_MAX_LIMIT};
use crate::support::tests::fixtures::dealer_details_fixture;
use crate::support::tests::helpers::init_contract;
use cosmwasm_std::testing::mock_env;
use cosmwasm_std::{Addr, DepsMut};
fn fill_dealers(deps: DepsMut<'_>, mapping: &IndexedDealersMap<'_>, size: usize) {
for n in 0..size {
let dealer_details = dealer_details_fixture(n as u64);
mapping
.save(deps.storage, &dealer_details.address, &dealer_details)
.unwrap();
}
}
fn remove_dealers(deps: DepsMut<'_>, mapping: &IndexedDealersMap<'_>, size: usize) {
for n in 0..size {
let dealer_details = dealer_details_fixture(n as u64);
mapping
.remove(deps.storage, &dealer_details.address)
.unwrap();
}
}
#[test]
fn dealers_empty_on_init() {
let mut deps = init_contract();
let env = mock_env();
for mapping in [storage::current_dealers(), storage::past_dealers()] {
let page1 = query_dealers(deps.as_ref(), None, None, &mapping).unwrap();
assert_eq!(0, page1.dealers.len() as u32);
}
}
#[test]
fn dealers_paged_retrieval_obeys_limits() {
let mut deps = init_contract();
let env = mock_env();
let owner = Addr::unchecked("owner");
let limit = 2;
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1000);
let page1 = query_dealers(deps.as_ref(), None, Option::from(limit), &mapping).unwrap();
assert_eq!(limit, page1.dealers.len() as u32);
remove_dealers(deps.as_mut(), &mapping, 1000);
}
}
#[test]
fn dealers_paged_retrieval_has_default_limit() {
let mut deps = init_contract();
let env = mock_env();
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1000);
// query without explicitly setting a limit
let page1 = query_dealers(deps.as_ref(), None, None, &mapping).unwrap();
assert_eq!(DEALERS_PAGE_DEFAULT_LIMIT, page1.dealers.len() as u32);
remove_dealers(deps.as_mut(), &mapping, 1000);
}
}
#[test]
fn dealers_paged_retrieval_has_max_limit() {
let mut deps = init_contract();
let env = mock_env();
// query with a crazily high limit in an attempt to use too many resources
let crazy_limit = 1000 * DEALERS_PAGE_MAX_LIMIT;
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1000);
let page1 =
query_dealers(deps.as_ref(), None, Option::from(crazy_limit), &mapping).unwrap();
// we default to a decent sized upper bound instead
let expected_limit = DEALERS_PAGE_MAX_LIMIT;
assert_eq!(expected_limit, page1.dealers.len() as u32);
remove_dealers(deps.as_mut(), &mapping, 1000);
}
}
#[test]
fn dealers_pagination_works() {
let mut deps = init_contract();
let env = mock_env();
let per_page = 2;
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 1);
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
// page should have 1 result on it
assert_eq!(1, page1.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 1);
}
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 2);
// page1 should have 2 results on it
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
assert_eq!(2, page1.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 2);
}
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 3);
// page1 still has 2 results
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
assert_eq!(2, page1.dealers.len());
// retrieving the next page should start after the last key on this page
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealers(
deps.as_ref(),
Option::from(start_after.to_string()),
Option::from(per_page),
&mapping,
)
.unwrap();
assert_eq!(1, page2.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 3);
}
for mapping in [storage::current_dealers(), storage::past_dealers()] {
fill_dealers(deps.as_mut(), &mapping, 4);
let page1 =
query_dealers(deps.as_ref(), None, Option::from(per_page), &mapping).unwrap();
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealers(
deps.as_ref(),
Option::from(start_after.to_string()),
Option::from(per_page),
&mapping,
)
.unwrap();
// now we have 2 pages, with 2 results on the second page
assert_eq!(2, page2.dealers.len());
remove_dealers(deps.as_mut(), &mapping, 4);
}
}
query_dealers(deps, start_after, limit, storage::past_dealers())
}
@@ -3,8 +3,7 @@
use crate::dealers::storage as dealers_storage;
use crate::epoch_state::utils::check_epoch_state;
use crate::error::ContractError;
use crate::state::{State, STATE};
use crate::{ContractError, State, STATE};
use coconut_dkg_common::types::{DealerDetails, EncodedBTEPublicKeyWithProof, EpochState};
use cosmwasm_std::{Addr, DepsMut, MessageInfo, Response};
@@ -65,40 +64,3 @@ pub fn try_add_dealer(
Ok(Response::new().add_attribute("node_index", node_index.to_string()))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::epoch_state::transactions::advance_epoch_state;
use crate::support::tests::fixtures::dealer_details_fixture;
use crate::support::tests::helpers;
use crate::support::tests::helpers::ADMIN_ADDRESS;
use cosmwasm_std::testing::mock_info;
#[test]
fn invalid_state() {
let mut deps = helpers::init_contract();
let owner = Addr::unchecked("owner");
let info = mock_info(owner.as_str(), &[]);
let dealer_details = dealer_details_fixture(1);
let bte_key_with_proof = String::from("bte_key_with_proof");
let announce_address = String::from("localhost:8000");
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
let ret = try_add_dealer(
deps.as_mut(),
info.clone(),
bte_key_with_proof.clone(),
announce_address.clone(),
)
.unwrap_err();
assert_eq!(
ret,
ContractError::IncorrectEpochState {
current_state: EpochState::DealingExchange.to_string(),
expected_state: EpochState::default().to_string(),
}
);
}
}
@@ -43,159 +43,3 @@ pub fn query_dealings_paged(
start_next_after,
))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::dealings::storage::{DEALINGS_PAGE_DEFAULT_LIMIT, DEALINGS_PAGE_MAX_LIMIT};
use crate::support::tests::fixtures::dealing_bytes_fixture;
use crate::support::tests::helpers::init_contract;
use cosmwasm_std::testing::mock_env;
use cosmwasm_std::{Addr, DepsMut};
fn fill_dealings(deps: DepsMut<'_>, size: usize) {
for n in 0..size {
let dealing_share = dealing_bytes_fixture();
let sender = Addr::unchecked(format!("owner{}", n));
for idx in 0..TOTAL_DEALINGS {
DEALINGS_BYTES[idx]
.save(deps.storage, &sender, &dealing_share)
.unwrap();
}
}
}
#[test]
fn empty_on_bad_idx() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1000);
for idx in TOTAL_DEALINGS as u64..100 * TOTAL_DEALINGS as u64 {
let page1 = query_dealings_paged(deps.as_ref(), idx, None, None).unwrap();
assert_eq!(0, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_empty_on_init() {
let deps = init_contract();
for idx in 0..TOTAL_DEALINGS as u64 {
let response = query_dealings_paged(deps.as_ref(), idx, None, Option::from(2)).unwrap();
assert_eq!(0, response.dealings.len());
}
}
#[test]
fn dealings_paged_retrieval_obeys_limits() {
let mut deps = init_contract();
let env = mock_env();
let limit = 2;
fill_dealings(deps.as_mut(), 1000);
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(limit)).unwrap();
assert_eq!(limit, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_paged_retrieval_has_default_limit() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1000);
for idx in 0..TOTAL_DEALINGS as u64 {
// query without explicitly setting a limit
let page1 = query_dealings_paged(deps.as_ref(), idx, None, None).unwrap();
assert_eq!(DEALINGS_PAGE_DEFAULT_LIMIT, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_paged_retrieval_has_max_limit() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1000);
// query with a crazily high limit in an attempt to use too many resources
let crazy_limit = 1000 * DEALINGS_PAGE_MAX_LIMIT;
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(crazy_limit)).unwrap();
// we default to a decent sized upper bound instead
let expected_limit = DEALINGS_PAGE_MAX_LIMIT;
assert_eq!(expected_limit, page1.dealings.len() as u32);
}
}
#[test]
fn dealings_pagination_works() {
let mut deps = init_contract();
let env = mock_env();
fill_dealings(deps.as_mut(), 1);
let per_page = 2;
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
// page should have 1 result on it
assert_eq!(1, page1.dealings.len());
}
// save another
fill_dealings(deps.as_mut(), 2);
for idx in 0..TOTAL_DEALINGS as u64 {
// page1 should have 2 results on it
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
assert_eq!(2, page1.dealings.len());
}
fill_dealings(deps.as_mut(), 3);
for idx in 0..TOTAL_DEALINGS as u64 {
// page1 still has 2 results
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
assert_eq!(2, page1.dealings.len());
// retrieving the next page should start after the last key on this page
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealings_paged(
deps.as_ref(),
idx,
Option::from(start_after.to_string()),
Option::from(per_page),
)
.unwrap();
assert_eq!(1, page2.dealings.len());
}
fill_dealings(deps.as_mut(), 4);
for idx in 0..TOTAL_DEALINGS as u64 {
let page1 =
query_dealings_paged(deps.as_ref(), idx, None, Option::from(per_page)).unwrap();
let start_after = page1.start_next_after.unwrap();
let page2 = query_dealings_paged(
deps.as_ref(),
idx,
Option::from(start_after.to_string()),
Option::from(per_page),
)
.unwrap();
// now we have 2 pages, with 2 results on the second page
assert_eq!(2, page2.dealings.len());
}
}
}
@@ -4,7 +4,7 @@
use crate::dealers::storage as dealers_storage;
use crate::dealings::storage::DEALINGS_BYTES;
use crate::epoch_state::utils::check_epoch_state;
use crate::error::ContractError;
use crate::ContractError;
use coconut_dkg_common::types::{ContractSafeBytes, EpochState};
use cosmwasm_std::{DepsMut, MessageInfo, Response};
@@ -35,65 +35,3 @@ pub fn try_commit_dealings(
commitment: String::from("dealing"),
})
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::epoch_state::transactions::advance_epoch_state;
use crate::support::tests::fixtures::dealing_bytes_fixture;
use crate::support::tests::helpers;
use crate::support::tests::helpers::ADMIN_ADDRESS;
use coconut_dkg_common::dealer::DealerDetails;
use coconut_dkg_common::types::TOTAL_DEALINGS;
use cosmwasm_std::testing::mock_info;
use cosmwasm_std::Addr;
#[test]
fn invalid_commit_dealing() {
let mut deps = helpers::init_contract();
let owner = Addr::unchecked("owner");
let info = mock_info(owner.as_str(), &[]);
let dealing_bytes = dealing_bytes_fixture();
let ret =
try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone()).unwrap_err();
assert_eq!(
ret,
ContractError::IncorrectEpochState {
current_state: EpochState::default().to_string(),
expected_state: EpochState::DealingExchange.to_string()
}
);
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
let ret =
try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone()).unwrap_err();
assert_eq!(ret, ContractError::NotADealer);
let dealer_details = DealerDetails {
address: owner.clone(),
bte_public_key_with_proof: String::new(),
announce_address: String::new(),
assigned_index: 1,
};
dealers_storage::current_dealers()
.save(deps.as_mut().storage, &owner, &dealer_details)
.unwrap();
for dealings in DEALINGS_BYTES {
assert!(!dealings.has(deps.as_mut().storage, &owner));
let ret = try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone());
assert!(ret.is_ok());
assert!(dealings.has(deps.as_mut().storage, &owner));
}
let ret =
try_commit_dealings(deps.as_mut(), info.clone(), dealing_bytes.clone()).unwrap_err();
assert_eq!(
ret,
ContractError::AlreadyCommitted {
commitment: String::from("dealing"),
}
);
}
}
@@ -3,5 +3,4 @@
pub mod queries;
pub mod storage;
pub mod transactions;
pub mod utils;
@@ -1,28 +1,13 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::error::ContractError;
use super::storage;
use crate::ContractError;
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::Storage;
pub(crate) fn query_current_epoch_state(
storage: &dyn Storage,
) -> Result<EpochState, ContractError> {
CURRENT_EPOCH_STATE
.load(storage)
.map_err(|_| ContractError::EpochNotInitialised)
}
#[cfg(test)]
pub(crate) mod test {
use super::*;
use crate::support::tests::helpers::init_contract;
#[test]
fn query_state() {
let mut deps = init_contract();
let state = query_current_epoch_state(deps.as_mut().storage).unwrap();
assert_eq!(state, EpochState::PublicKeySubmission);
}
storage::current_epoch_state(storage)
}
@@ -1,7 +1,29 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::{ContractError, ADMIN};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::{DepsMut, MessageInfo, Response, Storage};
use cw_storage_plus::Item;
pub(crate) const CURRENT_EPOCH_STATE: Item<'_, EpochState> = Item::new("current_epoch_state");
pub(crate) fn current_epoch_state(storage: &dyn Storage) -> Result<EpochState, ContractError> {
CURRENT_EPOCH_STATE
.load(storage)
.map_err(|_| ContractError::EpochNotInitialised)
}
pub(crate) fn advance_epoch_state(
deps: DepsMut<'_>,
info: MessageInfo,
) -> Result<Response, ContractError> {
ADMIN.assert_admin(deps.as_ref(), &info.sender)?;
CURRENT_EPOCH_STATE.update::<_, ContractError>(deps.storage, |mut epoch_state| {
// TODO: When defaulting to the first state, some action will probably need to be taken on the
// rest of the contract, as we're starting with a new set of signers
epoch_state = epoch_state.next().unwrap_or_default();
Ok(epoch_state)
})?;
Ok(Response::default())
}
@@ -1,78 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::error::ContractError;
use crate::state::ADMIN;
use cosmwasm_std::{DepsMut, MessageInfo, Response};
pub(crate) fn advance_epoch_state(
deps: DepsMut<'_>,
info: MessageInfo,
) -> Result<Response, ContractError> {
ADMIN.assert_admin(deps.as_ref(), &info.sender)?;
CURRENT_EPOCH_STATE.update::<_, ContractError>(deps.storage, |mut epoch_state| {
// TODO: When defaulting to the first state, some action will probably need to be taken on the
// rest of the contract, as we're starting with a new set of signers
epoch_state = epoch_state.next().unwrap_or_default();
Ok(epoch_state)
})?;
Ok(Response::default())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::support::tests::helpers::{init_contract, ADMIN_ADDRESS};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::testing::mock_info;
use cw_controllers::AdminError;
#[test]
fn advance_state() {
let mut deps = init_contract();
let info = mock_info("requester", &[]);
let admin_info = mock_info(ADMIN_ADDRESS, &[]);
assert_eq!(
advance_epoch_state(deps.as_mut(), info).unwrap_err(),
ContractError::Admin(AdminError::NotAdmin {})
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::DealingExchange
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::VerificationKeySubmission
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::VerificationKeyValidation
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::VerificationKeyFinalization
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::InProgress
);
advance_epoch_state(deps.as_mut(), admin_info.clone()).unwrap();
assert_eq!(
CURRENT_EPOCH_STATE.load(deps.as_mut().storage).unwrap(),
EpochState::PublicKeySubmission
);
}
}
+1 -27
View File
@@ -1,8 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::error::ContractError;
use crate::{ContractError, CURRENT_EPOCH_STATE};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::Storage;
@@ -20,28 +19,3 @@ pub(crate) fn check_epoch_state(
Ok(())
}
}
#[cfg(test)]
pub(crate) mod test {
use super::*;
use crate::support::tests::helpers::init_contract;
#[test]
pub fn check_state() {
let mut deps = init_contract();
for fixed_state in EpochState::default().all_until(EpochState::InProgress) {
CURRENT_EPOCH_STATE
.save(deps.as_mut().storage, &fixed_state)
.unwrap();
for against_state in EpochState::default().all_until(EpochState::InProgress) {
let ret = check_epoch_state(deps.as_mut().storage, against_state);
if fixed_state == against_state {
assert!(ret.is_ok());
} else {
assert!(ret.is_err());
}
}
}
}
}
+24 -1
View File
@@ -1,7 +1,7 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use cosmwasm_std::StdError;
use cosmwasm_std::{Addr, StdError, VerificationError};
use cw_controllers::AdminError;
use thiserror::Error;
@@ -17,6 +17,24 @@ pub enum ContractError {
#[error("Group contract invalid address '{addr}'")]
InvalidGroup { addr: String },
#[error("No coin was sent for the deposit, you must send {denom}")]
NoDepositFound { denom: String },
#[error("Received multiple coin types")]
MultipleDenoms,
#[error("Wrong coin denomination, you must send {denom}")]
WrongDenom { denom: String },
#[error("Not enough funds sent for deposit. (received {received}, minimum {minimum})")]
InsufficientDeposit { received: u128, minimum: u128 },
#[error("Failed to perform ed25519 signature verification - {0}. This dealer will be temporarily blacklisted now.")]
Ed25519VerificationError(#[from] VerificationError),
#[error("Provided ed25519 signature did not verify correctly. This dealer will be temporarily blacklisted now.")]
InvalidEd25519Signature,
#[error("This potential dealer is not in the coconut signer group")]
Unauthorized,
@@ -34,6 +52,11 @@ pub enum ContractError {
expected_state: String,
},
// we should never ever see this error (famous last words in programming), therefore, I'd want to
// explicitly declare it so that when we ultimate do see it, it's gonna be more informative over "normal" panic
#[error("Somehow our validated address {address} is not using correct bech32 encoding")]
InvalidValidatedAddress { address: Addr },
#[error("This sender is not a dealer for the current epoch")]
NotADealer,
+137 -3
View File
@@ -1,12 +1,146 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::dealers::queries::{
query_current_dealers_paged, query_dealer_details, query_past_dealers_paged,
};
use crate::dealings::queries::query_dealings_paged;
use crate::epoch_state::queries::query_current_epoch_state;
use crate::error::ContractError;
use crate::state::{State, ADMIN, MULTISIG, STATE};
use crate::verification_key_shares::queries::query_vk_shares_paged;
use coconut_dkg_common::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::{
entry_point, to_binary, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response,
};
use cw4::Cw4Contract;
use epoch_state::storage::{advance_epoch_state, CURRENT_EPOCH_STATE};
mod constants;
pub mod contract;
mod dealers;
mod dealings;
mod epoch_state;
pub mod error;
mod error;
mod state;
mod support;
mod verification_key_shares;
/// Instantiate the contract.
///
/// `deps` contains Storage, API and Querier
/// `env` contains block, message and contract info
/// `msg` is the contract initialization message, sort of like a constructor call.
#[entry_point]
pub fn instantiate(
mut deps: DepsMut<'_>,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
let admin_addr = deps.api.addr_validate(&msg.admin)?;
let multisig_addr = deps.api.addr_validate(&msg.multisig_addr)?;
ADMIN.set(deps.branch(), Some(admin_addr))?;
MULTISIG.set(deps.branch(), Some(multisig_addr.clone()))?;
let group_addr = Cw4Contract(deps.api.addr_validate(&msg.group_addr).map_err(|_| {
ContractError::InvalidGroup {
addr: msg.group_addr.clone(),
}
})?);
let state = State {
group_addr,
multisig_addr,
mix_denom: msg.mix_denom,
};
STATE.save(deps.storage, &state)?;
CURRENT_EPOCH_STATE.save(deps.storage, &EpochState::default())?;
Ok(Response::default())
}
/// Handle an incoming message
#[entry_point]
pub fn execute(
deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::RegisterDealer {
bte_key_with_proof,
announce_address,
} => {
dealers::transactions::try_add_dealer(deps, info, bte_key_with_proof, announce_address)
}
ExecuteMsg::CommitDealing { dealing_bytes } => {
dealings::transactions::try_commit_dealings(deps, info, dealing_bytes)
}
ExecuteMsg::CommitVerificationKeyShare { share } => {
verification_key_shares::transactions::try_commit_verification_key_share(
deps, env, info, share,
)
}
ExecuteMsg::VerifyVerificationKeyShare { owner } => {
verification_key_shares::transactions::try_verify_verification_key_share(
deps, info, owner,
)
}
ExecuteMsg::AdvanceEpochState {} => advance_epoch_state(deps, info),
}
}
#[entry_point]
pub fn query(deps: Deps<'_>, _env: Env, msg: QueryMsg) -> Result<QueryResponse, ContractError> {
let response = match msg {
QueryMsg::GetCurrentEpochState {} => to_binary(&query_current_epoch_state(deps.storage)?)?,
QueryMsg::GetDealerDetails { dealer_address } => {
to_binary(&query_dealer_details(deps, dealer_address)?)?
}
QueryMsg::GetCurrentDealers { limit, start_after } => {
to_binary(&query_current_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetPastDealers { limit, start_after } => {
to_binary(&query_past_dealers_paged(deps, start_after, limit)?)?
}
QueryMsg::GetDealing {
idx,
limit,
start_after,
} => to_binary(&query_dealings_paged(deps, idx, start_after, limit)?)?,
QueryMsg::GetVerificationKeys { limit, start_after } => {
to_binary(&query_vk_shares_paged(deps, start_after, limit)?)?
}
};
Ok(response)
}
#[entry_point]
pub fn migrate(_deps: DepsMut<'_>, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
Ok(Default::default())
}
#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
#[test]
fn initialize_contract() {
let mut deps = mock_dependencies();
let env = mock_env();
let msg = InstantiateMsg {
group_addr: "group_addr".to_string(),
multisig_addr: "multisig_addr".to_string(),
admin: "admin".to_string(),
mix_denom: "nym".to_string(),
};
let info = mock_info("creator", &[]);
let res = instantiate(deps.as_mut(), env.clone(), info, msg);
assert!(res.is_ok())
}
}
-5
View File
@@ -1,5 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#[cfg(test)]
pub mod tests;
@@ -1,32 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use coconut_dkg_common::dealer::{ContractDealing, DealerDetails};
use coconut_dkg_common::types::ContractSafeBytes;
use coconut_dkg_common::verification_key::ContractVKShare;
use cosmwasm_std::Addr;
pub const TEST_MIX_DENOM: &str = "unym";
pub fn vk_share_fixture(index: u64) -> ContractVKShare {
ContractVKShare {
share: format!("share{}", index),
announce_address: format!("localhost:{}", index),
node_index: index,
owner: Addr::unchecked(format!("owner{}", index)),
verified: index % 2 == 0,
}
}
pub fn dealing_bytes_fixture() -> ContractSafeBytes {
ContractSafeBytes(vec![])
}
pub fn dealer_details_fixture(assigned_index: u64) -> DealerDetails {
DealerDetails {
address: Addr::unchecked(format!("owner{}", assigned_index)),
bte_public_key_with_proof: "".to_string(),
announce_address: "".to_string(),
assigned_index,
}
}
@@ -1,27 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::contract::instantiate;
use coconut_dkg_common::msg::InstantiateMsg;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info, MockApi, MockQuerier};
use cosmwasm_std::{Empty, MemoryStorage, OwnedDeps};
use super::fixtures::TEST_MIX_DENOM;
pub const ADMIN_ADDRESS: &str = "admin address";
pub const GROUP_CONTRACT: &str = "group contract address";
pub const MULTISIG_CONTRACT: &str = "multisig contract address";
pub fn init_contract() -> OwnedDeps<MemoryStorage, MockApi, MockQuerier<Empty>> {
let mut deps = mock_dependencies();
let msg = InstantiateMsg {
group_addr: String::from(GROUP_CONTRACT),
multisig_addr: String::from(MULTISIG_CONTRACT),
admin: String::from(ADMIN_ADDRESS),
mix_denom: TEST_MIX_DENOM.to_string(),
};
let env = mock_env();
let info = mock_info(ADMIN_ADDRESS, &[]);
instantiate(deps.as_mut(), env.clone(), info, msg).unwrap();
deps
}
@@ -1,5 +0,0 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod fixtures;
pub mod helpers;
@@ -36,147 +36,3 @@ pub fn query_vk_shares_paged(
start_next_after,
})
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::support::tests::fixtures::vk_share_fixture;
use crate::support::tests::helpers::init_contract;
use crate::verification_key_shares::storage::{
VERIFICATION_KEY_SHARES_PAGE_DEFAULT_LIMIT, VERIFICATION_KEY_SHARES_PAGE_MAX_LIMIT,
};
use cosmwasm_std::testing::mock_env;
use cosmwasm_std::Addr;
#[test]
fn vk_shares_empty_on_init() {
let deps = init_contract();
let response = query_vk_shares_paged(deps.as_ref(), None, Option::from(2)).unwrap();
assert_eq!(0, response.shares.len());
}
#[test]
fn vk_shares_paged_retrieval_obeys_limits() {
let mut deps = init_contract();
let env = mock_env();
let limit = 2;
for n in 0..1000 {
let vk_share = vk_share_fixture(n);
let sender = Addr::unchecked(format!("owner{}", n));
VK_SHARES
.save(&mut deps.storage, &sender, &vk_share)
.unwrap();
}
let page1 = query_vk_shares_paged(deps.as_ref(), None, Option::from(limit)).unwrap();
assert_eq!(limit, page1.shares.len() as u32);
}
#[test]
fn vk_shares_paged_retrieval_has_default_limit() {
let mut deps = init_contract();
let env = mock_env();
for n in 0..1000 {
let vk_share = vk_share_fixture(n);
let sender = Addr::unchecked(format!("owner{}", n));
VK_SHARES
.save(&mut deps.storage, &sender, &vk_share)
.unwrap();
}
// query without explicitly setting a limit
let page1 = query_vk_shares_paged(deps.as_ref(), None, None).unwrap();
assert_eq!(
VERIFICATION_KEY_SHARES_PAGE_DEFAULT_LIMIT,
page1.shares.len() as u32
);
}
#[test]
fn vk_shares_paged_retrieval_has_max_limit() {
let mut deps = init_contract();
let env = mock_env();
for n in 0..1000 {
let vk_share = vk_share_fixture(n);
let sender = Addr::unchecked(format!("owner{}", n));
VK_SHARES
.save(&mut deps.storage, &sender, &vk_share)
.unwrap();
}
// query with a crazily high limit in an attempt to use too many resources
let crazy_limit = 1000 * VERIFICATION_KEY_SHARES_PAGE_MAX_LIMIT;
let page1 = query_vk_shares_paged(deps.as_ref(), None, Option::from(crazy_limit)).unwrap();
// we default to a decent sized upper bound instead
let expected_limit = VERIFICATION_KEY_SHARES_PAGE_MAX_LIMIT;
assert_eq!(expected_limit, page1.shares.len() as u32);
}
#[test]
fn vk_shares_pagination_works() {
let mut deps = init_contract();
let env = mock_env();
let vk_share = vk_share_fixture(1);
let sender = Addr::unchecked(format!("owner{}", 1));
VK_SHARES
.save(&mut deps.storage, &sender, &vk_share)
.unwrap();
let per_page = 2;
let page1 = query_vk_shares_paged(deps.as_ref(), None, Option::from(per_page)).unwrap();
// page should have 1 result on it
assert_eq!(1, page1.shares.len());
// save another
let vk_share = vk_share_fixture(2);
let sender = Addr::unchecked(format!("owner{}", 2));
VK_SHARES
.save(&mut deps.storage, &sender, &vk_share)
.unwrap();
// page1 should have 2 results on it
let page1 = query_vk_shares_paged(deps.as_ref(), None, Option::from(per_page)).unwrap();
assert_eq!(2, page1.shares.len());
let vk_share = vk_share_fixture(3);
let sender = Addr::unchecked(format!("owner{}", 3));
VK_SHARES
.save(&mut deps.storage, &sender, &vk_share)
.unwrap();
// page1 still has 2 results
let page1 = query_vk_shares_paged(deps.as_ref(), None, Option::from(per_page)).unwrap();
assert_eq!(2, page1.shares.len());
// retrieving the next page should start after the last key on this page
let start_after = page1.start_next_after.unwrap();
let page2 = query_vk_shares_paged(
deps.as_ref(),
Option::from(start_after.to_string()),
Option::from(per_page),
)
.unwrap();
assert_eq!(1, page2.shares.len());
let vk_share = vk_share_fixture(4);
let sender = Addr::unchecked(format!("owner{}", 4));
VK_SHARES
.save(&mut deps.storage, &sender, &vk_share)
.unwrap();
let page2 = query_vk_shares_paged(
deps.as_ref(),
Option::from(start_after.to_string()),
Option::from(per_page),
)
.unwrap();
// now we have 2 pages, with 2 results on the second page
assert_eq!(2, page2.shares.len());
}
}
@@ -69,144 +69,3 @@ pub fn try_verify_verification_key_share(
Ok(Response::default())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::epoch_state::storage::CURRENT_EPOCH_STATE;
use crate::epoch_state::transactions::advance_epoch_state;
use crate::support::tests::helpers;
use crate::support::tests::helpers::{ADMIN_ADDRESS, MULTISIG_CONTRACT};
use coconut_dkg_common::dealer::DealerDetails;
use coconut_dkg_common::types::EpochState;
use cosmwasm_std::testing::{mock_env, mock_info};
use cosmwasm_std::Storage;
use cw_controllers::AdminError;
#[test]
fn commit_vk_share() {
let mut deps = helpers::init_contract();
let env = mock_env();
let info = mock_info("requester", &[]);
let share = "share".to_string();
let ret = try_commit_verification_key_share(
deps.as_mut(),
env.clone(),
info.clone(),
share.clone(),
)
.unwrap_err();
assert_eq!(
ret,
ContractError::IncorrectEpochState {
current_state: EpochState::default().to_string(),
expected_state: EpochState::VerificationKeySubmission.to_string()
}
);
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
let ret = try_commit_verification_key_share(
deps.as_mut(),
env.clone(),
info.clone(),
share.clone(),
)
.unwrap_err();
assert_eq!(ret, ContractError::NotADealer);
let dealer = Addr::unchecked("requester");
let dealer_details = DealerDetails {
address: dealer.clone(),
bte_public_key_with_proof: String::new(),
announce_address: String::new(),
assigned_index: 1,
};
dealers_storage::current_dealers()
.save(deps.as_mut().storage, &dealer, &dealer_details)
.unwrap();
try_commit_verification_key_share(deps.as_mut(), env.clone(), info.clone(), share.clone())
.unwrap();
let ret = try_commit_verification_key_share(
deps.as_mut(),
env.clone(),
info.clone(),
share.clone(),
)
.unwrap_err();
assert_eq!(
ret,
ContractError::AlreadyCommitted {
commitment: String::from("verification key share")
}
);
}
#[test]
fn invalid_verify_vk_share() {
let mut deps = helpers::init_contract();
let info = mock_info("requester", &[]);
let owner = Addr::unchecked("owner");
let multisig_info = mock_info(MULTISIG_CONTRACT, &[]);
let ret = try_verify_verification_key_share(deps.as_mut(), info.clone(), owner.clone())
.unwrap_err();
assert_eq!(
ret,
ContractError::IncorrectEpochState {
current_state: EpochState::default().to_string(),
expected_state: EpochState::VerificationKeyFinalization.to_string()
}
);
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
let ret =
try_verify_verification_key_share(deps.as_mut(), info, owner.clone()).unwrap_err();
assert_eq!(ret, ContractError::Admin(AdminError::NotAdmin {}));
let ret = try_verify_verification_key_share(deps.as_mut(), multisig_info, owner.clone())
.unwrap_err();
assert_eq!(
ret,
ContractError::NoCommitForOwner {
owner: owner.to_string()
}
);
}
#[test]
fn verify_vk_share() {
let mut deps = helpers::init_contract();
let env = mock_env();
let owner = Addr::unchecked("owner");
let info = mock_info(owner.as_ref(), &[]);
let share = "share".to_string();
let multisig_info = mock_info(MULTISIG_CONTRACT, &[]);
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
let dealer_details = DealerDetails {
address: owner.clone(),
bte_public_key_with_proof: String::new(),
announce_address: String::new(),
assigned_index: 1,
};
dealers_storage::current_dealers()
.save(deps.as_mut().storage, &owner, &dealer_details)
.unwrap();
try_commit_verification_key_share(deps.as_mut(), env.clone(), info.clone(), share.clone())
.unwrap();
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
advance_epoch_state(deps.as_mut(), mock_info(ADMIN_ADDRESS, &[])).unwrap();
try_verify_verification_key_share(deps.as_mut(), multisig_info, owner.clone()).unwrap();
}
}
-1
View File
@@ -13,7 +13,6 @@ multisig-contract-common = { path = "../../common/cosmwasm-smart-contracts/multi
cosmwasm-std = "1.0.0"
cosmwasm-storage = "1.0.0"
cw3 = "0.13.4"
cw4 = "0.13.4"
cw-storage-plus = "0.13.4"
cw-controllers = "0.13.4"
+3 -3
View File
@@ -42,9 +42,9 @@ pub fn mock_app(init_funds: &[Coin]) -> App {
}
pub fn contract_dkg() -> Box<dyn Contract<Empty>> {
let contract = ContractWrapper::new(
coconut_dkg::contract::execute,
coconut_dkg::contract::instantiate,
coconut_dkg::contract::query,
coconut_dkg::execute,
coconut_dkg::instantiate,
coconut_dkg::query,
);
Box::new(contract)
}
@@ -11,18 +11,15 @@ use coconut_dkg_common::msg::ExecuteMsg::{
AdvanceEpochState, CommitVerificationKeyShare, RegisterDealer,
};
use coconut_dkg_common::msg::InstantiateMsg as DkgInstantiateMsg;
use coconut_dkg_common::msg::QueryMsg::GetVerificationKeys;
use coconut_dkg_common::verification_key::PagedVKSharesResponse;
use cosmwasm_std::{coins, Addr, Decimal};
use cw4::Member;
use cw4_group::msg::InstantiateMsg as GroupInstantiateMsg;
use cw_multi_test::Executor;
use cw_utils::{Duration, Threshold};
use multisig_contract_common::msg::ExecuteMsg::{Execute, Vote};
use multisig_contract_common::msg::InstantiateMsg as MultisigInstantiateMsg;
#[test]
fn dkg_proposal() {
fn dkg_create_proposal() {
let init_funds = coins(10000000000, TEST_COIN_DENOM);
let mut app = mock_app(&init_funds);
let member1 = Member {
@@ -50,7 +47,7 @@ fn dkg_proposal() {
let msg = MultisigInstantiateMsg {
group_addr: group_contract_addr.to_string(),
threshold: Threshold::AbsolutePercentage {
percentage: Decimal::from_ratio(1u128, 1u128),
percentage: Decimal::from_ratio(2u128, 3u128),
},
max_voting_period: Duration::Time(1000),
coconut_bandwidth_contract_address: TEST_COCONUT_BANDWIDTH_CONTRACT_ADDRESS.to_string(),
@@ -91,7 +88,7 @@ fn dkg_proposal() {
};
app.migrate_contract(
Addr::unchecked(OWNER),
multisig_contract_addr.clone(),
multisig_contract_addr,
&msg,
multisig_code_id,
)
@@ -118,9 +115,6 @@ fn dkg_proposal() {
.unwrap();
}
// Proposal needs to be later then the member became part of the group
app.update_block(|block| block.height += 1);
let msg = CommitVerificationKeyShare {
share: "share".to_string(),
};
@@ -132,7 +126,6 @@ fn dkg_proposal() {
&vec![],
)
.unwrap();
let proposal_id = res
.events
.into_iter()
@@ -145,62 +138,5 @@ fn dkg_proposal() {
.value
.parse::<u64>()
.unwrap();
let mut res: PagedVKSharesResponse = app
.wrap()
.query_wasm_smart(
coconut_dkg_contract_addr.clone(),
&GetVerificationKeys {
limit: None,
start_after: None,
},
)
.unwrap();
let share = res.shares.pop().unwrap();
assert_eq!(share.share, "share".to_string());
assert_eq!(share.announce_address, "127.0.0.1:8000".to_string());
assert_eq!(share.node_index, 1);
assert_eq!(share.owner, Addr::unchecked(MEMBER1));
assert!(!share.verified);
app.execute_contract(
Addr::unchecked(MEMBER1),
multisig_contract_addr.clone(),
&Vote {
proposal_id,
vote: cw3::Vote::Yes,
},
&vec![],
)
.unwrap();
for _ in 0..2 {
app.execute_contract(
Addr::unchecked(OWNER),
coconut_dkg_contract_addr.clone(),
&AdvanceEpochState {},
&vec![],
)
.unwrap();
}
app.execute_contract(
Addr::unchecked(MEMBER1),
multisig_contract_addr.clone(),
&Execute { proposal_id },
&vec![],
)
.unwrap();
let res: PagedVKSharesResponse = app
.wrap()
.query_wasm_smart(
coconut_dkg_contract_addr,
&GetVerificationKeys {
limit: None,
start_after: None,
},
)
.unwrap();
assert!(res.shares[0].verified);
assert_eq!(1, proposal_id);
}
-7
View File
@@ -35,9 +35,6 @@ 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";
@@ -72,7 +69,3 @@ 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 -88
View File
@@ -1,5 +1,6 @@
// 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;
@@ -81,69 +82,6 @@ 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(
@@ -191,7 +129,6 @@ pub fn execute(
),
ExecuteMsg::AdvanceCurrentEpoch {
new_rewarded_set,
// families_in_layer,
expected_active_set_size,
} => crate::interval::transactions::try_advance_epoch(
deps,
@@ -231,12 +168,6 @@ pub fn execute(
owner,
owner_signature,
),
ExecuteMsg::PledgeMore {} => {
crate::mixnodes::transactions::try_increase_pledge(deps, env, info)
}
ExecuteMsg::PledgeMoreOnBehalf { owner } => {
crate::mixnodes::transactions::try_increase_pledge_on_behalf(deps, env, info, owner)
}
ExecuteMsg::UnbondMixnode {} => {
crate::mixnodes::transactions::try_remove_mixnode(deps, env, info)
}
@@ -348,24 +279,6 @@ 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
@@ -1,3 +0,0 @@
pub mod queries;
pub mod storage;
pub mod transactions;
-107
View File
@@ -1,107 +0,0 @@
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
@@ -1,99 +0,0 @@
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())?)
}
@@ -1,414 +0,0 @@
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,
)?;
+1 -263
View File
@@ -7,14 +7,13 @@ use crate::interval::helpers::change_interval_config;
use crate::interval::storage;
use crate::mixnet_contract_settings::storage as mixnet_params_storage;
use crate::mixnodes::helpers::{cleanup_post_unbond_mixnode_storage, get_mixnode_details_by_id};
use crate::mixnodes::storage as mixnodes_storage;
use crate::rewards::storage as rewards_storage;
use crate::support::helpers::send_to_proxy_or_owner;
use cosmwasm_std::{wasm_execute, Addr, Coin, DepsMut, Env, Response};
use mixnet_contract_common::error::MixnetContractError;
use mixnet_contract_common::events::{
new_active_set_update_event, new_delegation_event, new_delegation_on_unbonded_node_event,
new_mixnode_cost_params_update_event, new_mixnode_unbonding_event, new_pledge_increase_event,
new_mixnode_cost_params_update_event, new_mixnode_unbonding_event,
new_rewarding_params_update_event, new_undelegation_event,
};
use mixnet_contract_common::mixnode::MixNodeCostParams;
@@ -259,42 +258,6 @@ pub(crate) fn update_active_set_size(
Ok(Response::new().add_event(new_active_set_update_event(created_at, active_set_size)))
}
pub(crate) fn increase_pledge(
deps: DepsMut<'_>,
created_at: BlockHeight,
mix_id: MixId,
increase: Coin,
) -> Result<Response, MixnetContractError> {
// note: we have already validated the amount to know it has the correct denomination
// the target node MUST exist - we have checked it at the time of putting this event onto the queue
// we have also verified there were no preceding unbond events
let mix_details = get_mixnode_details_by_id(deps.storage, mix_id)?.ok_or(
MixnetContractError::InconsistentState {
comment:
"mixnode getting processed to increase its pledge doesn't exist in the storage"
.into(),
},
)?;
let mut updated_bond = mix_details.bond_information.clone();
let mut updated_rewarding = mix_details.rewarding_details;
updated_bond.original_pledge.amount += increase.amount;
updated_rewarding.increase_operator_uint128(increase.amount)?;
// update both, bond information and rewarding details
mixnodes_storage::mixnode_bonds().replace(
deps.storage,
mix_id,
Some(&updated_bond),
Some(&mix_details.bond_information),
)?;
rewards_storage::MIXNODE_REWARDING.save(deps.storage, mix_id, &updated_rewarding)?;
Ok(Response::new().add_event(new_pledge_increase_event(created_at, mix_id, &increase)))
}
impl ContractExecutableEvent for PendingEpochEventData {
fn execute(self, deps: DepsMut<'_>, env: &Env) -> Result<Response, MixnetContractError> {
// note that the basic validation on all those events was already performed before
@@ -311,9 +274,6 @@ impl ContractExecutableEvent for PendingEpochEventData {
mix_id,
proxy,
} => undelegate(deps, self.created_at, owner, mix_id, proxy),
PendingEpochEventKind::PledgeMore { mix_id, amount } => {
increase_pledge(deps, self.created_at, mix_id, amount)
}
PendingEpochEventKind::UnbondMixnode { mix_id } => {
unbond_mixnode(deps, env, self.created_at, mix_id)
}
@@ -1175,228 +1135,6 @@ mod tests {
}
}
#[cfg(test)]
mod increasing_pledge {
use super::*;
use cosmwasm_std::Uint128;
use mixnet_contract_common::rewarding::helpers::truncate_reward_amount;
#[test]
fn returns_hard_error_if_mixnode_doesnt_exist() {
// this should have never happened so hard error MUST be thrown here
let mut test = TestSetup::new();
let amount = test.coin(123);
let res = increase_pledge(test.deps_mut(), 123, 1, amount);
assert!(matches!(
res,
Err(MixnetContractError::InconsistentState { .. })
));
}
#[test]
fn updates_stored_bond_information_and_rewarding_details() {
let mut test = TestSetup::new();
let mix_id = test.add_dummy_mixnode("mix-owner", None);
let old_details = get_mixnode_details_by_id(test.deps().storage, mix_id)
.unwrap()
.unwrap();
let amount = test.coin(12345);
increase_pledge(test.deps_mut(), 123, mix_id, amount.clone()).unwrap();
let updated_details = get_mixnode_details_by_id(test.deps().storage, mix_id)
.unwrap()
.unwrap();
assert_eq!(
updated_details.bond_information.original_pledge.amount,
old_details.bond_information.original_pledge.amount + amount.amount
);
assert_eq!(
updated_details.rewarding_details.operator,
old_details.rewarding_details.operator
+ Decimal::from_atomics(amount.amount, 0).unwrap()
);
}
#[test]
fn without_any_events_in_between_is_equivalent_to_pledging_the_same_amount_immediately() {
let mut test = TestSetup::new();
let pledge1 = Uint128::new(150_000_000);
let pledge2 = Uint128::new(50_000_000);
let pledge3 = Uint128::new(200_000_000);
let mix_id_repledge = test.add_dummy_mixnode("mix-owner1", Some(pledge1));
let increase = test.coin(pledge2.u128());
increase_pledge(test.deps_mut(), 123, mix_id_repledge, increase).unwrap();
let mix_id_full_pledge = test.add_dummy_mixnode("mix-owner2", Some(pledge3));
test.add_immediate_delegation("alice", 123_456_789u128, mix_id_repledge);
test.add_immediate_delegation("bob", 500_000_000u128, mix_id_repledge);
test.add_immediate_delegation("carol", 111_111_111u128, mix_id_repledge);
test.add_immediate_delegation("alice", 123_456_789u128, mix_id_full_pledge);
test.add_immediate_delegation("bob", 500_000_000u128, mix_id_full_pledge);
test.add_immediate_delegation("carol", 111_111_111u128, mix_id_full_pledge);
test.skip_to_next_epoch_end();
test.update_rewarded_set(vec![mix_id_repledge, mix_id_full_pledge]);
let dist1 =
test.reward_with_distribution(mix_id_repledge, test_helpers::performance(100.0));
let dist2 =
test.reward_with_distribution(mix_id_full_pledge, test_helpers::performance(100.0));
assert_eq!(dist1, dist2)
}
#[test]
fn correctly_increases_future_rewards() {
let mut test = TestSetup::new();
let pledge1 = Uint128::new(150_000_000_000);
let pledge2 = Uint128::new(50_000_000_000);
let mix_id_repledge = test.add_dummy_mixnode("mix-owner1", Some(pledge1));
test.add_immediate_delegation("alice", 123_456_789_000u128, mix_id_repledge);
test.add_immediate_delegation("bob", 500_000_000_000u128, mix_id_repledge);
test.add_immediate_delegation("carol", 111_111_111_000u128, mix_id_repledge);
test.skip_to_next_epoch_end();
test.update_rewarded_set(vec![mix_id_repledge]);
let dist =
test.reward_with_distribution(mix_id_repledge, test_helpers::performance(100.0));
let increase = test.coin(pledge2.u128());
increase_pledge(test.deps_mut(), 123, mix_id_repledge, increase).unwrap();
let pledge3 = Uint128::new(200_000_000_000) + truncate_reward_amount(dist.operator);
let mix_id_full_pledge = test.add_dummy_mixnode("mix-owner2", Some(pledge3));
test.add_immediate_delegation("alice", 123_456_789_000u128, mix_id_full_pledge);
test.add_immediate_delegation("bob", 500_000_000_000u128, mix_id_full_pledge);
test.add_immediate_delegation("carol", 111_111_111_000u128, mix_id_full_pledge);
let lost_operator = dist.operator
- Decimal::from_atomics(truncate_reward_amount(dist.operator), 0).unwrap();
let lost_delegates = dist.delegates
- Decimal::from_atomics(truncate_reward_amount(dist.delegates), 0).unwrap();
// add the tiny bit of lost precision manually
let mut mix_rewarding_full = test.mix_rewarding(mix_id_full_pledge);
mix_rewarding_full.delegates += lost_delegates;
mix_rewarding_full.operator += lost_operator;
rewards_storage::MIXNODE_REWARDING
.save(
test.deps_mut().storage,
mix_id_full_pledge,
&mix_rewarding_full,
)
.unwrap();
test.add_immediate_delegation(
"dave",
truncate_reward_amount(dist.delegates).u128(),
mix_id_full_pledge,
);
test.skip_to_next_epoch_end();
test.update_rewarded_set(vec![mix_id_repledge, mix_id_full_pledge]);
// go through few epochs of rewarding
for _ in 0..500 {
test.skip_to_next_epoch_end();
let dist1 = test
.reward_with_distribution(mix_id_repledge, test_helpers::performance(100.0));
let dist2 = test
.reward_with_distribution(mix_id_full_pledge, test_helpers::performance(100.0));
assert_eq!(dist1, dist2)
}
}
#[test]
fn correctly_increases_future_rewards_with_more_passed_epochs() {
let mut test = TestSetup::new();
let pledge1 = Uint128::new(150_000_000_000);
let pledge2 = Uint128::new(50_000_000_000);
let mix_id_repledge = test.add_dummy_mixnode("mix-owner1", Some(pledge1));
test.add_immediate_delegation("alice", 123_456_789_000u128, mix_id_repledge);
test.add_immediate_delegation("bob", 500_000_000_000u128, mix_id_repledge);
test.add_immediate_delegation("carol", 111_111_111_000u128, mix_id_repledge);
test.skip_to_next_epoch_end();
test.update_rewarded_set(vec![mix_id_repledge]);
let mut cumulative_op_reward = Decimal::zero();
let mut cumulative_del_reward = Decimal::zero();
// go few epochs of rewarding before adding more pledge
for _ in 0..500 {
test.skip_to_next_epoch_end();
let dist = test
.reward_with_distribution(mix_id_repledge, test_helpers::performance(100.0));
cumulative_op_reward += dist.operator;
cumulative_del_reward += dist.delegates;
}
let increase = test.coin(pledge2.u128());
increase_pledge(test.deps_mut(), 123, mix_id_repledge, increase).unwrap();
let pledge3 =
Uint128::new(200_000_000_000) + truncate_reward_amount(cumulative_op_reward);
let mix_id_full_pledge = test.add_dummy_mixnode("mix-owner2", Some(pledge3));
test.add_immediate_delegation("alice", 123_456_789_000u128, mix_id_full_pledge);
test.add_immediate_delegation("bob", 500_000_000_000u128, mix_id_full_pledge);
test.add_immediate_delegation("carol", 111_111_111_000u128, mix_id_full_pledge);
let lost_operator = cumulative_op_reward
- Decimal::from_atomics(truncate_reward_amount(cumulative_op_reward), 0).unwrap();
let lost_delegates = cumulative_del_reward
- Decimal::from_atomics(truncate_reward_amount(cumulative_del_reward), 0).unwrap();
// add the tiny bit of lost precision manually
let mut mix_rewarding_full = test.mix_rewarding(mix_id_full_pledge);
mix_rewarding_full.delegates += lost_delegates;
mix_rewarding_full.operator += lost_operator;
rewards_storage::MIXNODE_REWARDING
.save(
test.deps_mut().storage,
mix_id_full_pledge,
&mix_rewarding_full,
)
.unwrap();
test.add_immediate_delegation(
"dave",
truncate_reward_amount(cumulative_del_reward).u128(),
mix_id_full_pledge,
);
test.skip_to_next_epoch_end();
test.update_rewarded_set(vec![mix_id_repledge, mix_id_full_pledge]);
// go through few more epochs of rewarding
for _ in 0..500 {
test.skip_to_next_epoch_end();
let dist1 = test
.reward_with_distribution(mix_id_repledge, test_helpers::performance(100.0));
let dist2 = test
.reward_with_distribution(mix_id_full_pledge, test_helpers::performance(100.0));
assert_eq!(dist1, dist2)
}
}
}
#[test]
fn updating_active_set_updates_rewarding_params() {
let mut test = TestSetup::new();
+15 -111
View File
@@ -5,7 +5,6 @@ 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};
@@ -17,7 +16,7 @@ use mixnet_contract_common::events::{
new_reconcile_pending_events,
};
use mixnet_contract_common::pending_events::PendingIntervalEventKind;
use mixnet_contract_common::{LayerAssignment, MixId};
use mixnet_contract_common::MixId;
use std::collections::BTreeSet;
// those two should be called in separate tx (from advancing epoch),
@@ -203,7 +202,7 @@ pub fn try_advance_epoch(
mut deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
layer_assignments: Vec<LayerAssignment>,
new_rewarded_set: Vec<MixId>,
expected_active_set_size: u32,
) -> Result<Response, MixnetContractError> {
// Only rewarding validator can attempt to advance epoch
@@ -248,18 +247,12 @@ pub fn try_advance_epoch(
}
let updated_interval = current_interval.advance_epoch();
let num_nodes = layer_assignments.len();
let new_rewarded_set = layer_assignments.iter().map(|l| l.mix_id()).collect();
let num_nodes = new_rewarded_set.len();
// 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)))
}
@@ -1140,40 +1133,30 @@ 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, Uint128};
use cosmwasm_std::{coin, coins, BankMsg, Decimal, Empty, SubMsg};
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::{Layer, RewardedSetNodeStatus};
use mixnet_contract_common::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,
layer_assignments.clone(),
vec![1, 2, 3],
current_active_set,
);
assert_eq!(res, Err(MixnetContractError::Unauthorized));
@@ -1185,10 +1168,9 @@ mod tests {
test.deps_mut(),
env,
sender,
layer_assignments,
vec![1, 2, 3],
current_active_set,
);
println!("{:?}", res);
assert!(res.is_ok())
}
@@ -1197,23 +1179,13 @@ 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(),
layer_assignments.clone(),
vec![1, 2, 3],
current_active_set,
);
assert!(matches!(
@@ -1221,24 +1193,6 @@ 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();
@@ -1246,7 +1200,7 @@ mod tests {
test.deps_mut(),
env,
sender,
layer_assignments,
vec![1, 2, 3],
current_active_set,
);
assert!(res.is_ok())
@@ -1257,27 +1211,17 @@ 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,
layer_assignments,
vec![1, 2, 3],
current_active_set,
)
.unwrap();
@@ -1293,27 +1237,17 @@ 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,
layer_assignments,
vec![1, 2, 3],
current_active_set,
)
.unwrap();
@@ -1330,10 +1264,6 @@ 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();
@@ -1380,19 +1310,13 @@ 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,
layer_assignments,
vec![1, 2, 3],
current_active_set,
)
.unwrap();
@@ -1419,10 +1343,6 @@ 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();
@@ -1437,12 +1357,6 @@ 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();
@@ -1451,7 +1365,7 @@ mod tests {
test.deps_mut(),
env,
sender,
layer_assignments.clone(),
vec![1, 2, 3],
current_active_set,
)
.unwrap();
@@ -1470,7 +1384,7 @@ mod tests {
test.deps_mut(),
env,
sender,
layer_assignments,
vec![1, 2, 3],
current_active_set,
)
.unwrap();
@@ -1499,20 +1413,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 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();
@@ -1520,7 +1424,7 @@ mod tests {
test.deps_mut(),
env,
sender,
layer_assignments,
vec![1, 2, 3],
current_active_set,
)
.unwrap();
-1
View File
@@ -7,7 +7,6 @@
mod constants;
pub mod contract;
mod delegations;
mod families;
mod gateways;
mod interval;
mod mixnet_contract_settings;
@@ -37,6 +37,7 @@ pub(crate) fn minimum_delegation_stake(
.map(|state| state.params.minimum_mixnode_delegation)?)
}
#[allow(unused)]
pub(crate) fn rewarding_denom(storage: &dyn Storage) -> Result<String, MixnetContractError> {
Ok(CONTRACT_STATE
.load(storage)
+6 -6
View File
@@ -147,7 +147,7 @@ pub(crate) fn cleanup_post_unbond_mixnode_storage(
}
#[cfg(test)]
pub(crate) mod tests {
mod tests {
use super::*;
use crate::support::tests::fixtures::{
mix_node_cost_params_fixture, mix_node_fixture, TEST_COIN_DENOM,
@@ -155,13 +155,13 @@ pub(crate) mod tests {
use crate::support::tests::test_helpers::TestSetup;
use cosmwasm_std::coin;
pub(crate) const OWNER_EXISTS: &str = "mix-owner-existing";
pub(crate) const OWNER_UNBONDING: &str = "mix-owner-unbonding";
pub(crate) const OWNER_UNBONDED: &str = "mix-owner-unbonded";
pub(crate) const OWNER_UNBONDED_LEFTOVER: &str = "mix-owner-unbonded-leftover";
const OWNER_EXISTS: &str = "mix-owner-existing";
const OWNER_UNBONDING: &str = "mix-owner-unbonding";
const OWNER_UNBONDED: &str = "mix-owner-unbonded";
const OWNER_UNBONDED_LEFTOVER: &str = "mix-owner-unbonded-leftover";
// create a mixnode that is bonded, unbonded, in the process of unbonding and unbonded with leftover mix rewarding details
pub(crate) fn setup_mix_combinations(test: &mut TestSetup) -> Vec<MixId> {
fn setup_mix_combinations(test: &mut TestSetup) -> Vec<MixId> {
let mix_id_exists = test.add_dummy_mixnode(OWNER_EXISTS, None);
let mix_id_unbonding = test.add_dummy_mixnode(OWNER_UNBONDING, None);
let mix_id_unbonded = test.add_dummy_mixnode(OWNER_UNBONDED, None);
+8 -273
View File
@@ -5,54 +5,20 @@ use super::storage;
use crate::interval::storage as interval_storage;
use crate::interval::storage::push_new_interval_event;
use crate::mixnet_contract_settings::storage as mixnet_params_storage;
use crate::mixnet_contract_settings::storage::rewarding_denom;
use crate::mixnodes::helpers::{
get_mixnode_details_by_owner, must_get_mixnode_bond_by_owner, save_new_mixnode,
};
use crate::mixnodes::helpers::{must_get_mixnode_bond_by_owner, save_new_mixnode};
use crate::support::helpers::{
ensure_bonded, ensure_is_authorized, ensure_no_existing_bond, ensure_proxy_match,
validate_node_identity_signature, validate_pledge,
ensure_bonded, ensure_no_existing_bond, ensure_proxy_match, validate_node_identity_signature,
validate_pledge,
};
use cosmwasm_std::{coin, Addr, Coin, DepsMut, Env, MessageInfo, Response, Storage};
use cosmwasm_std::{Addr, Coin, DepsMut, Env, MessageInfo, Response};
use mixnet_contract_common::error::MixnetContractError;
use mixnet_contract_common::events::{
new_mixnode_bonding_event, new_mixnode_config_update_event,
new_mixnode_pending_cost_params_update_event, new_pending_mixnode_unbonding_event,
new_pending_pledge_increase_event,
};
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use mixnet_contract_common::pending_events::{PendingEpochEventKind, PendingIntervalEventKind};
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())
}
use mixnet_contract_common::MixNode;
pub fn try_add_mixnode(
deps: DepsMut<'_>,
@@ -126,7 +92,7 @@ fn _try_add_mixnode(
validate_node_identity_signature(
deps.as_ref(),
&owner,
&owner_signature,
owner_signature,
&mixnode.identity_key,
)?;
@@ -151,54 +117,6 @@ fn _try_add_mixnode(
)))
}
pub fn try_increase_pledge(
deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
) -> Result<Response, MixnetContractError> {
_try_increase_pledge(deps, env, info.funds, info.sender, None)
}
pub fn try_increase_pledge_on_behalf(
deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
owner: String,
) -> Result<Response, MixnetContractError> {
let proxy = info.sender;
let owner = deps.api.addr_validate(&owner)?;
_try_increase_pledge(deps, env, info.funds, owner, Some(proxy))
}
pub fn _try_increase_pledge(
deps: DepsMut<'_>,
env: Env,
increase: Vec<Coin>,
owner: Addr,
proxy: Option<Addr>,
) -> Result<Response, MixnetContractError> {
let mix_details = get_mixnode_details_by_owner(deps.storage, owner.clone())?
.ok_or(MixnetContractError::NoAssociatedMixNodeBond { owner })?;
let mix_id = mix_details.mix_id();
ensure_proxy_match(&proxy, &mix_details.bond_information.proxy)?;
ensure_bonded(&mix_details.bond_information)?;
let rewarding_denom = rewarding_denom(deps.storage)?;
let pledge_increase = validate_pledge(increase, coin(1, rewarding_denom))?;
let cosmos_event = new_pending_pledge_increase_event(mix_id, &pledge_increase);
// push the event to execute it at the end of the epoch
let epoch_event = PendingEpochEventKind::PledgeMore {
mix_id,
amount: pledge_increase,
};
interval_storage::push_new_epoch_event(deps.storage, &env, epoch_event)?;
Ok(Response::new().add_event(cosmos_event))
}
pub fn try_remove_mixnode_on_behalf(
deps: DepsMut<'_>,
env: Env,
@@ -389,7 +307,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
@@ -457,7 +375,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(),
@@ -762,187 +680,4 @@ pub mod tests {
)
.is_err());
}
#[cfg(test)]
mod increasing_mixnode_pledge {
use super::*;
use crate::mixnodes::helpers::tests::{
setup_mix_combinations, OWNER_UNBONDED, OWNER_UNBONDED_LEFTOVER, OWNER_UNBONDING,
};
use crate::support::tests::test_helpers::TestSetup;
#[test]
fn is_not_allowed_if_account_doesnt_own_mixnode() {
let mut test = TestSetup::new();
let env = test.env();
let sender = mock_info("not-mix-owner", &[]);
let res = try_increase_pledge(test.deps_mut(), env, sender);
assert_eq!(
res,
Err(MixnetContractError::NoAssociatedMixNodeBond {
owner: Addr::unchecked("not-mix-owner")
})
)
}
#[test]
fn is_not_allowed_if_theres_proxy_mismatch() {
let mut test = TestSetup::new();
let env = test.env();
let owner_without_proxy = Addr::unchecked("no-proxy");
let owner_with_proxy = Addr::unchecked("with-proxy");
let proxy = Addr::unchecked("proxy");
let wrong_proxy = Addr::unchecked("unrelated-proxy");
test.add_dummy_mixnode(owner_without_proxy.as_str(), None);
test.add_dummy_mixnode_with_proxy(owner_with_proxy.as_str(), None, proxy.clone());
let res = _try_increase_pledge(
test.deps_mut(),
env.clone(),
Vec::new(),
owner_without_proxy.clone(),
Some(proxy),
);
assert_eq!(
res,
Err(MixnetContractError::ProxyMismatch {
existing: "None".to_string(),
incoming: "proxy".to_string()
})
);
let res = _try_increase_pledge(
test.deps_mut(),
env.clone(),
Vec::new(),
owner_with_proxy.clone(),
None,
);
assert_eq!(
res,
Err(MixnetContractError::ProxyMismatch {
existing: "proxy".to_string(),
incoming: "None".to_string()
})
);
let res = _try_increase_pledge(
test.deps_mut(),
env,
Vec::new(),
owner_with_proxy.clone(),
Some(wrong_proxy),
);
assert_eq!(
res,
Err(MixnetContractError::ProxyMismatch {
existing: "proxy".to_string(),
incoming: "unrelated-proxy".to_string()
})
)
}
#[test]
fn is_not_allowed_if_mixnode_has_unbonded_or_is_unbonding() {
let mut test = TestSetup::new();
let env = test.env();
// TODO: I dislike this cross-test access, but it provides us with exactly what we need
// perhaps it should be refactored a bit?
let owner_unbonding = Addr::unchecked(OWNER_UNBONDING);
let owner_unbonded = Addr::unchecked(OWNER_UNBONDED);
let owner_unbonded_leftover = Addr::unchecked(OWNER_UNBONDED_LEFTOVER);
let ids = setup_mix_combinations(&mut test);
let mix_id_unbonding = ids[1];
let res = try_increase_pledge(
test.deps_mut(),
env.clone(),
mock_info(owner_unbonding.as_str(), &[]),
);
assert_eq!(
res,
Err(MixnetContractError::MixnodeIsUnbonding {
mix_id: mix_id_unbonding
})
);
// if the nodes are gone we treat them as tey never existed in the first place
// (regardless of if there's some leftover data)
let res = try_increase_pledge(
test.deps_mut(),
env.clone(),
mock_info(owner_unbonded_leftover.as_str(), &[]),
);
assert_eq!(
res,
Err(MixnetContractError::NoAssociatedMixNodeBond {
owner: owner_unbonded_leftover
})
);
let res = try_increase_pledge(
test.deps_mut(),
env,
mock_info(owner_unbonded.as_str(), &[]),
);
assert_eq!(
res,
Err(MixnetContractError::NoAssociatedMixNodeBond {
owner: owner_unbonded
})
)
}
#[test]
fn is_not_allowed_if_no_tokens_were_sent() {
let mut test = TestSetup::new();
let env = test.env();
let owner = "mix-owner";
test.add_dummy_mixnode(owner, None);
let sender_empty = mock_info(owner, &[]);
let res = try_increase_pledge(test.deps_mut(), env.clone(), sender_empty);
assert_eq!(res, Err(MixnetContractError::NoBondFound));
let sender_zero = mock_info(owner, &[test.coin(0)]);
let res = try_increase_pledge(test.deps_mut(), env, sender_zero);
assert_eq!(
res,
Err(MixnetContractError::InsufficientPledge {
received: test.coin(0),
minimum: test.coin(1)
})
)
}
#[test]
fn with_valid_information_creates_pending_event() {
let mut test = TestSetup::new();
let env = test.env();
let owner = "mix-owner";
let mix_id = test.add_dummy_mixnode(owner, None);
let events = test.pending_epoch_events();
assert!(events.is_empty());
let sender = mock_info(owner, &[test.coin(1000)]);
try_increase_pledge(test.deps_mut(), env, sender).unwrap();
let events = test.pending_epoch_events();
assert_eq!(
events[0].kind,
PendingEpochEventKind::PledgeMore {
mix_id,
amount: test.coin(1000)
}
);
}
}
}
+21 -27
View File
@@ -194,30 +194,14 @@ pub(crate) fn ensure_no_existing_bond(
Ok(())
}
pub fn validate_node_identity_signature(
pub(crate) fn validate_node_identity_signature(
deps: Deps<'_>,
owner: &Addr,
signature: &str,
signature: String,
identity: IdentityKeyRef<'_>,
) -> Result<(), MixnetContractError> {
validate_signature(deps, owner.as_bytes(), signature, identity)
}
let owner_bytes = owner.as_bytes();
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];
@@ -242,7 +226,7 @@ pub(crate) fn validate_signature(
let res = deps
.api
.ed25519_verify(signed_bytes, &signature_bytes, &identity_bytes)
.ed25519_verify(owner_bytes, &signature_bytes, &identity_bytes)
.map_err(cosmwasm_std::StdError::verification_err)?;
if !res {
Err(MixnetContractError::InvalidEd25519Signature)
@@ -292,7 +276,12 @@ 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, long_bs58,)
validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr1_key1.clone(),
long_bs58,
)
);
assert_eq!(
@@ -311,7 +300,12 @@ 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, short_bs58,)
validate_node_identity_signature(
deps.as_ref(),
&address1,
sig_addr1_key1.clone(),
short_bs58,
)
);
assert_eq!(
@@ -331,7 +325,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address1,
&sig_addr1_key1,
sig_addr1_key1.clone(),
&keypair2.public_key().to_base58_string(),
)
);
@@ -341,7 +335,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address1,
&sig_addr2_key1,
sig_addr2_key1,
&keypair1.public_key().to_base58_string(),
)
);
@@ -351,7 +345,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address2,
&sig_addr1_key1,
sig_addr1_key1.clone(),
&keypair1.public_key().to_base58_string(),
)
);
@@ -361,7 +355,7 @@ mod tests {
validate_node_identity_signature(
deps.as_ref(),
&address1,
&sig_addr1_key2,
sig_addr1_key2,
&keypair1.public_key().to_base58_string(),
)
);
@@ -369,7 +363,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 -39
View File
@@ -28,9 +28,6 @@ pub mod test_helpers {
use crate::mixnodes::transactions::{
try_add_mixnode, try_add_mixnode_on_behalf, try_remove_mixnode,
};
use crate::rewards::queries::{
query_pending_delegator_reward, query_pending_mixnode_operator_reward,
};
use crate::rewards::storage as rewards_storage;
use crate::rewards::transactions::try_reward_mixnode;
use crate::support::tests;
@@ -40,13 +37,12 @@ pub mod test_helpers {
use cosmwasm_std::testing::mock_info;
use cosmwasm_std::testing::MockApi;
use cosmwasm_std::testing::MockQuerier;
use cosmwasm_std::{coin, Addr, BankMsg, CosmosMsg, Storage};
use cosmwasm_std::{Addr, BankMsg, CosmosMsg, Storage};
use cosmwasm_std::{Coin, Order};
use cosmwasm_std::{Decimal, Empty, MemoryStorage};
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,
};
@@ -142,10 +138,6 @@ pub mod test_helpers {
.vesting_contract_address
}
pub fn coin(&self, amount: u128) -> Coin {
coin(amount, rewarding_denom(self.deps().storage).unwrap())
}
pub fn current_interval(&self) -> Interval {
interval_storage::current_interval(self.deps().storage).unwrap()
}
@@ -316,22 +308,6 @@ pub mod test_helpers {
.unwrap();
}
#[allow(unused)]
pub fn pending_operator_reward(&mut self, mix: MixId) -> Decimal {
query_pending_mixnode_operator_reward(self.deps(), mix)
.unwrap()
.amount_earned_detailed
.expect("no reward!")
}
#[allow(unused)]
pub fn pending_delegator_reward(&mut self, delegator: &str, target: MixId) -> Decimal {
query_pending_delegator_reward(self.deps(), delegator.into(), target, None)
.unwrap()
.amount_earned_detailed
.expect("no reward!")
}
pub fn skip_to_next_epoch_end(&mut self) {
self.skip_to_next_epoch();
self.skip_to_current_epoch_end();
@@ -361,19 +337,8 @@ pub mod test_helpers {
self.env.block.time = Timestamp::from_seconds(epoch_end as u64 + 1);
let advanced = interval.advance_epoch();
assert_eq!(
interval.current_epoch_absolute_id() + 1,
advanced.current_epoch_absolute_id()
);
if interval.current_epoch_id() != interval.epochs_in_interval() - 1 {
if interval.current_epoch_id() != interval.epochs_in_interval() {
assert_eq!(interval.current_epoch_id() + 1, advanced.current_epoch_id())
} else {
assert_eq!(advanced.current_epoch_id(), 0);
assert_eq!(
interval.current_interval_id() + 1,
advanced.current_interval_id()
)
}
interval_storage::save_interval(self.deps_mut().storage, &advanced).unwrap()
@@ -557,7 +522,7 @@ pub mod test_helpers {
pub fn mixnode_with_signature(
mut rng: impl RngCore + CryptoRng,
sender: &str,
) -> (MixNode, String, KeyPair) {
) -> (MixNode, String) {
let keypair = crypto::asymmetric::identity::KeyPair::new(&mut rng);
let legit_sphinx_key = crypto::asymmetric::encryption::KeyPair::new(&mut rng);
let owner_signature = keypair
@@ -575,7 +540,6 @@ pub mod test_helpers {
..tests::fixtures::mix_node_fixture()
},
owner_signature,
keypair,
)
}
+1 -67
View File
@@ -5,7 +5,7 @@ use crate::storage::{
MIXNET_CONTRACT_ADDRESS, MIX_DENOM,
};
use crate::traits::{
DelegatingAccount, GatewayBondingAccount, MixnodeBondingAccount, NodeFamilies, VestingAccount,
DelegatingAccount, GatewayBondingAccount, MixnodeBondingAccount, VestingAccount,
};
use crate::vesting::{populate_vesting_periods, Account};
use contracts_common::ContractBuildInformation;
@@ -60,21 +60,6 @@ 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)
}
@@ -136,7 +121,6 @@ pub fn execute(
env,
deps,
),
ExecuteMsg::PledgeMore { amount } => try_pledge_more(deps, env, info, amount),
ExecuteMsg::UnbondMixnode {} => try_unbond_mixnode(info, deps),
ExecuteMsg::TrackUnbondMixnode { owner, amount } => {
try_track_unbond_mixnode(&owner, amount, info, deps)
@@ -159,43 +143,6 @@ 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].
@@ -384,19 +331,6 @@ pub fn try_bond_mixnode(
)
}
pub fn try_pledge_more(
deps: DepsMut<'_>,
env: Env,
info: MessageInfo,
amount: Coin,
) -> Result<Response, ContractError> {
let mix_denom = MIX_DENOM.load(deps.storage)?;
let additional_pledge = validate_funds(&[amount], mix_denom)?;
let account = account_from_address(info.sender.as_str(), deps.storage, deps.api)?;
account.try_pledge_additional_tokens(additional_pledge, &env, deps.storage)
}
/// Unbond a mixnode, sends [mixnet_contract_common::ExecuteMsg::UnbondMixnodeOnBehalf] to [crate::storage::MIXNET_CONTRACT_ADDRESS].
pub fn try_unbond_mixnode(info: MessageInfo, deps: DepsMut<'_>) -> Result<Response, ContractError> {
let account = account_from_address(info.sender.as_str(), deps.storage, deps.api)?;
@@ -18,13 +18,6 @@ pub trait MixnodeBondingAccount {
storage: &mut dyn Storage,
) -> Result<Response, ContractError>;
fn try_pledge_additional_tokens(
&self,
additional_pledge: Coin,
env: &Env,
storage: &mut dyn Storage,
) -> Result<Response, ContractError>;
fn try_unbond_mixnode(&self, storage: &dyn Storage) -> Result<Response, ContractError>;
fn try_track_unbond_mixnode(
-2
View File
@@ -1,9 +1,7 @@
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;
@@ -1,33 +0,0 @@
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>;
}
@@ -12,8 +12,7 @@ use mixnet_contract_common::mixnode::MixNodeCostParams;
use mixnet_contract_common::{ExecuteMsg as MixnetExecuteMsg, MixNode};
use vesting_contract_common::events::{
new_vesting_mixnode_bonding_event, new_vesting_mixnode_unbonding_event,
new_vesting_pledge_more_event, new_vesting_update_mixnode_config_event,
new_vesting_update_mixnode_cost_params_event,
new_vesting_update_mixnode_config_event, new_vesting_update_mixnode_cost_params_event,
};
use vesting_contract_common::PledgeData;
@@ -85,64 +84,6 @@ impl MixnodeBondingAccount for Account {
.add_event(new_vesting_mixnode_bonding_event()))
}
fn try_pledge_additional_tokens(
&self,
additional_pledge: Coin,
env: &Env,
storage: &mut dyn Storage,
) -> Result<Response, ContractError> {
let current_balance = self.load_balance(storage)?;
let total_pledged_after =
self.total_pledged_locked(storage, env)? + additional_pledge.amount;
let locked_pledge_cap = self.absolute_pledge_cap()?;
if locked_pledge_cap < total_pledged_after {
return Err(ContractError::LockedPledgeCapReached {
current: total_pledged_after,
cap: locked_pledge_cap,
});
}
if current_balance < additional_pledge.amount {
return Err(ContractError::InsufficientBalance(
self.owner_address().as_str().to_string(),
current_balance.u128(),
));
}
let mut pledge_data = if let Some(pledge_data) = self.load_mixnode_pledge(storage)? {
pledge_data
} else {
return Err(ContractError::NoBondFound(
self.owner_address().as_str().to_string(),
));
};
// need a second pair of eyes here to make sure updating existing timestamp on pledge data
// is not going to have some unexpected consequences
pledge_data.amount.amount += additional_pledge.amount;
pledge_data.block_time = env.block.time;
let msg = MixnetExecuteMsg::PledgeMoreOnBehalf {
owner: self.owner_address().into_string(),
};
let new_balance = Uint128::new(current_balance.u128() - additional_pledge.amount.u128());
let pledge_more_mag = wasm_execute(
MIXNET_CONTRACT_ADDRESS.load(storage)?,
&msg,
vec![additional_pledge],
)?;
self.save_balance(new_balance, storage)?;
self.save_mixnode_pledge(pledge_data, storage)?;
Ok(Response::new()
.add_message(pledge_more_mag)
.add_event(new_vesting_pledge_more_event()))
}
fn try_unbond_mixnode(&self, storage: &dyn Storage) -> Result<Response, ContractError> {
let msg = MixnetExecuteMsg::UnbondMixnodeOnBehalf {
owner: self.owner_address().into_string(),
@@ -16,7 +16,6 @@ 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> {
@@ -1,74 +0,0 @@
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))
}
}

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