Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add blockstamp #756

Merged
merged 6 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add RawDelegationData
  • Loading branch information
neacsu committed Aug 30, 2021
commit a8ec60b748f029f040aac38b4e86d32722381504
17 changes: 16 additions & 1 deletion common/mixnet-contract/src/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,26 @@
#![allow(clippy::field_reassign_with_default)]

use crate::{Addr, IdentityKey};
use cosmwasm_std::Coin;
use cosmwasm_std::{Coin, Uint128};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt::Display;

#[derive(Deserialize, Serialize)]
pub struct RawDelegationData {
pub amount: Uint128,
pub block_height: u64,
}

impl RawDelegationData {
pub fn new(amount: Uint128, block_height: u64) -> Self {
RawDelegationData {
amount,
block_height,
}
}
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)]
pub struct Delegation {
owner: Addr,
Expand Down
2 changes: 1 addition & 1 deletion common/mixnet-contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ mod types;
pub use cosmwasm_std::{Addr, Coin};
pub use delegation::{
Delegation, PagedGatewayDelegationsResponse, PagedMixDelegationsResponse,
PagedReverseGatewayDelegationsResponse, PagedReverseMixDelegationsResponse,
PagedReverseGatewayDelegationsResponse, PagedReverseMixDelegationsResponse, RawDelegationData,
};
pub use gateway::{Gateway, GatewayBond, GatewayOwnershipResponse, PagedGatewayResponse};
pub use mixnode::{Layer, MixNode, MixNodeBond, MixOwnershipResponse, PagedMixnodeResponse};
Expand Down
6 changes: 3 additions & 3 deletions contracts/mixnet/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ pub fn instantiate(
#[entry_point]
pub fn execute(
deps: DepsMut,
_env: Env,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
Expand All @@ -113,13 +113,13 @@ pub fn execute(
transactions::try_reward_gateway(deps, info, identity, uptime)
}
ExecuteMsg::DelegateToMixnode { mix_identity } => {
transactions::try_delegate_to_mixnode(deps, info, mix_identity)
transactions::try_delegate_to_mixnode(deps, env, info, mix_identity)
}
ExecuteMsg::UndelegateFromMixnode { mix_identity } => {
transactions::try_remove_delegation_from_mixnode(deps, info, mix_identity)
}
ExecuteMsg::DelegateToGateway { gateway_identity } => {
transactions::try_delegate_to_gateway(deps, info, gateway_identity)
transactions::try_delegate_to_gateway(deps, env, info, gateway_identity)
}
ExecuteMsg::UndelegateFromGateway { gateway_identity } => {
transactions::try_remove_delegation_from_gateway(deps, info, gateway_identity)
Expand Down
8 changes: 4 additions & 4 deletions contracts/mixnet/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ pub(crate) fn query_mixnode_delegations_paged(
Addr::unchecked(String::from_utf8(entry.0).expect(
"Non-UTF8 address used as key in bucket. The storage is corrupted!",
)),
coin(entry.1.u128(), DENOM),
coin(entry.1.amount.u128(), DENOM),
)
})
})
Expand Down Expand Up @@ -183,7 +183,7 @@ pub(crate) fn query_mixnode_delegation(
match mix_delegations_read(deps.storage, &mix_identity).may_load(address.as_bytes())? {
Some(delegation_value) => Ok(Delegation::new(
address,
coin(delegation_value.u128(), DENOM),
coin(delegation_value.amount.u128(), DENOM),
)),
None => Err(ContractError::NoMixnodeDelegationFound {
identity: mix_identity,
Expand Down Expand Up @@ -212,7 +212,7 @@ pub(crate) fn query_gateway_delegations_paged(
Addr::unchecked(String::from_utf8(entry.0).expect(
"Non-UTF8 address used as key in bucket. The storage is corrupted!",
)),
coin(entry.1.u128(), DENOM),
coin(entry.1.amount.u128(), DENOM),
)
})
})
Expand Down Expand Up @@ -267,7 +267,7 @@ pub(crate) fn query_gateway_delegation(
match gateway_delegations_read(deps.storage, &gateway_identity).may_load(address.as_bytes())? {
Some(delegation_value) => Ok(Delegation::new(
address,
coin(delegation_value.u128(), DENOM),
coin(delegation_value.amount.u128(), DENOM),
)),
None => Err(ContractError::NoGatewayDelegationFound {
identity: gateway_identity,
Expand Down
26 changes: 13 additions & 13 deletions contracts/mixnet/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use cosmwasm_storage::{
};
use mixnet_contract::{
Addr, GatewayBond, IdentityKey, IdentityKeyRef, Layer, LayerDistribution, MixNodeBond,
StateParams,
RawDelegationData, StateParams,
};

// storage prefixes
Expand Down Expand Up @@ -193,11 +193,11 @@ pub(crate) fn increase_mix_delegated_stakes(
);

// and for each of them increase the stake proportionally to the reward
for (delegator_address, amount) in delegations_chunk.into_iter() {
let reward = amount * scaled_reward_rate;
let new_amount = amount + reward;
for (delegator_address, mut delegation) in delegations_chunk.into_iter() {
let reward = delegation.amount * scaled_reward_rate;
delegation.amount += reward;
total_rewarded += reward;
mix_delegations(storage, mix_identity).save(&delegator_address, &new_amount)?;
mix_delegations(storage, mix_identity).save(&delegator_address, &delegation)?;
}
}

Expand Down Expand Up @@ -237,11 +237,11 @@ pub(crate) fn increase_gateway_delegated_stakes(
);

// and for each of them increase the stake proportionally to the reward
for (delegator_address, amount) in delegations_chunk.into_iter() {
let reward = amount * scaled_reward_rate;
let new_amount = amount + reward;
for (delegator_address, mut delegation) in delegations_chunk.into_iter() {
let reward = delegation.amount * scaled_reward_rate;
delegation.amount += reward;
total_rewarded += reward;
gateway_delegations(storage, gateway_identity).save(&delegator_address, &new_amount)?;
gateway_delegations(storage, gateway_identity).save(&delegator_address, &delegation)?;
}
}

Expand Down Expand Up @@ -293,14 +293,14 @@ pub fn gateways_owners_read(storage: &dyn Storage) -> ReadonlyBucket<IdentityKey
pub fn mix_delegations<'a>(
storage: &'a mut dyn Storage,
mix_identity: IdentityKeyRef,
) -> Bucket<'a, Uint128> {
) -> Bucket<'a, RawDelegationData> {
Bucket::multilevel(storage, &[PREFIX_MIX_DELEGATION, mix_identity.as_bytes()])
}

pub fn mix_delegations_read<'a>(
storage: &'a dyn Storage,
mix_identity: IdentityKeyRef,
) -> ReadonlyBucket<'a, Uint128> {
) -> ReadonlyBucket<'a, RawDelegationData> {
ReadonlyBucket::multilevel(storage, &[PREFIX_MIX_DELEGATION, mix_identity.as_bytes()])
}

Expand All @@ -318,7 +318,7 @@ pub fn reverse_mix_delegations_read<'a>(
pub fn gateway_delegations<'a>(
storage: &'a mut dyn Storage,
gateway_identity: IdentityKeyRef,
) -> Bucket<'a, Uint128> {
) -> Bucket<'a, RawDelegationData> {
Bucket::multilevel(
storage,
&[PREFIX_GATEWAY_DELEGATION, gateway_identity.as_bytes()],
Expand All @@ -328,7 +328,7 @@ pub fn gateway_delegations<'a>(
pub fn gateway_delegations_read<'a>(
storage: &'a dyn Storage,
gateway_identity: IdentityKeyRef,
) -> ReadonlyBucket<'a, Uint128> {
) -> ReadonlyBucket<'a, RawDelegationData> {
ReadonlyBucket::multilevel(
storage,
&[PREFIX_GATEWAY_DELEGATION, gateway_identity.as_bytes()],
Expand Down
45 changes: 25 additions & 20 deletions contracts/mixnet/src/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ use crate::queries;
use crate::storage::*;
use config::defaults::DENOM;
use cosmwasm_std::{
attr, coins, BankMsg, Coin, Decimal, DepsMut, MessageInfo, Order, Response, StdResult, Uint128,
attr, coins, BankMsg, Coin, Decimal, DepsMut, Env, MessageInfo, Order, Response, StdResult,
Uint128,
};
use cosmwasm_storage::ReadonlyBucket;
use mixnet_contract::{
Gateway, GatewayBond, IdentityKey, Layer, MixNode, MixNodeBond, StateParams,
Gateway, GatewayBond, IdentityKey, Layer, MixNode, MixNodeBond, RawDelegationData, StateParams,
};

const OLD_DELEGATIONS_CHUNK_SIZE: usize = 500;
Expand All @@ -23,7 +24,7 @@ const OLD_DELEGATIONS_CHUNK_SIZE: usize = 500;
// 3. The node unbonds
// 4. Some of the addresses that delegated in the past have not removed the delegation yet
// 5. The node rebonds with the same identity
fn find_old_delegations(delegations_bucket: ReadonlyBucket<Uint128>) -> StdResult<Coin> {
fn find_old_delegations(delegations_bucket: ReadonlyBucket<RawDelegationData>) -> StdResult<Coin> {
// I think it's incredibly unlikely to ever read more than that
// but in case we do, we should guard ourselves against possible
// out of memory errors (wasm contracts can only allocate at most 2MB
Expand All @@ -45,7 +46,7 @@ fn find_old_delegations(delegations_bucket: ReadonlyBucket<Uint128>) -> StdResul
continue;
}

let value = delegation?.1;
let value = delegation?.1.amount;
total_delegation.amount += value;
}

Expand Down Expand Up @@ -540,6 +541,7 @@ fn validate_delegation_stake(delegation: &[Coin]) -> Result<(), ContractError> {

pub(crate) fn try_delegate_to_mixnode(
deps: DepsMut,
env: Env,
info: MessageInfo,
mix_identity: IdentityKey,
) -> Result<Response, ContractError> {
Expand All @@ -565,12 +567,13 @@ pub(crate) fn try_delegate_to_mixnode(
let sender_bytes = info.sender.as_bytes();

// write the delegation
match delegation_bucket.may_load(sender_bytes)? {
Some(existing_delegation) => {
delegation_bucket.save(sender_bytes, &(existing_delegation + info.funds[0].amount))?
}
None => delegation_bucket.save(sender_bytes, &info.funds[0].amount)?,
}
let new_amount = match delegation_bucket.may_load(sender_bytes)? {
Some(existing_delegation) => existing_delegation.amount + info.funds[0].amount,
None => info.funds[0].amount,
};
// the block height is reset, if it existed
let new_delegation = RawDelegationData::new(new_amount, env.block.height);
delegation_bucket.save(sender_bytes, &new_delegation)?;

reverse_mix_delegations(deps.storage, &info.sender).save(mix_identity.as_bytes(), &())?;

Expand All @@ -593,7 +596,7 @@ pub(crate) fn try_remove_delegation_from_mixnode(
// send delegated funds back to the delegation owner
let messages = vec![BankMsg::Send {
to_address: info.sender.to_string(),
amount: coins(delegation.u128(), DENOM),
amount: coins(delegation.amount.u128(), DENOM),
}
.into()];

Expand All @@ -606,7 +609,7 @@ pub(crate) fn try_remove_delegation_from_mixnode(
existing_bond.total_delegation.amount = existing_bond
.total_delegation
.amount
.checked_sub(delegation)
.checked_sub(delegation.amount)
.unwrap();
mixnodes_bucket.save(mix_identity.as_bytes(), &existing_bond)?;
}
Expand All @@ -627,6 +630,7 @@ pub(crate) fn try_remove_delegation_from_mixnode(

pub(crate) fn try_delegate_to_gateway(
deps: DepsMut,
env: Env,
info: MessageInfo,
gateway_identity: IdentityKey,
) -> Result<Response, ContractError> {
Expand All @@ -652,12 +656,13 @@ pub(crate) fn try_delegate_to_gateway(
let sender_bytes = info.sender.as_bytes();

// write the delegation
match delegation_bucket.may_load(sender_bytes)? {
Some(existing_delegation) => {
delegation_bucket.save(sender_bytes, &(existing_delegation + info.funds[0].amount))?
}
None => delegation_bucket.save(sender_bytes, &info.funds[0].amount)?,
}
let new_amount = match delegation_bucket.may_load(sender_bytes)? {
Some(existing_delegation) => existing_delegation.amount + info.funds[0].amount,
None => info.funds[0].amount,
};
// the block height is reset, if it existed
let new_delegation = RawDelegationData::new(new_amount, env.block.height);
delegation_bucket.save(sender_bytes, &new_delegation)?;

reverse_gateway_delegations(deps.storage, &info.sender)
.save(gateway_identity.as_bytes(), &())?;
Expand All @@ -682,7 +687,7 @@ pub(crate) fn try_remove_delegation_from_gateway(
// send delegated funds back to the delegation owner
let messages = vec![BankMsg::Send {
to_address: info.sender.to_string(),
amount: coins(delegation.u128(), DENOM),
amount: coins(delegation.amount.u128(), DENOM),
}
.into()];

Expand All @@ -697,7 +702,7 @@ pub(crate) fn try_remove_delegation_from_gateway(
existing_bond.total_delegation.amount = existing_bond
.total_delegation
.amount
.checked_sub(delegation)
.checked_sub(delegation.amount)
.unwrap();
gateways_bucket.save(gateway_identity.as_bytes(), &existing_bond)?;
}
Expand Down