Skip to content

Commit

Permalink
new approach
Browse files Browse the repository at this point in the history
  • Loading branch information
brentstone committed Apr 9, 2024
1 parent 85ee0d8 commit 7d2c466
Show file tree
Hide file tree
Showing 8 changed files with 396 additions and 82 deletions.
32 changes: 18 additions & 14 deletions crates/namada/src/ledger/governance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,16 @@ where
let pre_voting_end_epoch: Epoch =
self.force_read(&voting_end_epoch_key, ReadType::Pre)?;

let voter = gov_storage::get_voter_address(key)
.ok_or(Error::InvalidVoteKey(key.to_string()))?;
let validator = gov_storage::get_vote_delegation_address(key)
.ok_or(Error::InvalidVoteKey(key.to_string()))?;
let voter = gov_storage::get_voter_address(key).ok_or(
native_vp::Error::new_alloc(format!(
"Failed to parse a voter from the vote key {key}",
)),
)?;
let validator = gov_storage::get_vote_delegation_address(key).ok_or(
native_vp::Error::new_alloc(format!(
"Failed to parse a validator from the vote key {key}",
)),
)?;

// Invalid proposal id
if pre_counter <= proposal_id {
Expand Down Expand Up @@ -238,7 +244,7 @@ where
{
if delegations.is_empty() {
return Err(native_vp::Error::new_alloc(format!(
"No delegations found for {voter_address}"
"No delegations found for {voter}"
))
.into());
} else {
Expand All @@ -253,13 +259,13 @@ where
}
} else {
return Err(native_vp::Error::new_alloc(format!(
"Failed to query delegations for {voter_address}"
"Failed to query delegations for {voter}"
))
.into());
};
if !all_delegations_are_valid {
return Err(native_vp::Error::new_alloc(format!(
"Not all delegations of {voter_address} were deemed valid"
"Not all delegations of {voter} were deemed valid"
))
.into());
}
Expand All @@ -283,8 +289,7 @@ where
}

// first check if validator, then check if delegator
let is_validator =
self.is_validator(verifiers, voter, validator)?;
let is_validator = self.is_validator(verifiers, voter, validator)?;

if is_validator {
return is_valid_validator_voting_period(
Expand All @@ -294,9 +299,9 @@ where
)
.ok_or_else(|| {
native_vp::Error::new_alloc(format!(
"Validator {voter_address} voted outside of the voting \
period. Current epoch: {current_epoch}, pre voting start \
epoch: {pre_voting_start_epoch}, pre voting end epoch: \
"Validator {voter} voted outside of the voting period. \
Current epoch: {current_epoch}, pre voting start epoch: \
{pre_voting_start_epoch}, pre voting end epoch: \
{pre_voting_end_epoch}."
))
.into()
Expand All @@ -312,8 +317,7 @@ where

if !is_delegator {
return Err(native_vp::Error::new_alloc(format!(
"Address {voter_address} is neither a validator nor a \
delegator."
"Address {voter} is neither a validator nor a delegator."
))
.into());
}
Expand Down
3 changes: 2 additions & 1 deletion crates/proof_of_stake/src/epoched.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,8 @@ where
.unwrap()
}

fn get_oldest_epoch<S>(
/// Get the oldest epoch at which data is stored
pub fn get_oldest_epoch<S>(
&self,
storage: &S,
) -> namada_storage::Result<Option<Epoch>>
Expand Down
105 changes: 95 additions & 10 deletions crates/proof_of_stake/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use namada_storage::collections::lazy_map::{self, Collectable, LazyMap};
use namada_storage::{StorageRead, StorageWrite};
pub use namada_trans_token as token;
pub use parameters::{OwnedPosParams, PosParams};
use types::into_tm_voting_power;
use types::{into_tm_voting_power, DelegationEpochs};

use crate::queries::{find_bonds, has_bonds};
use crate::rewards::{
Expand Down Expand Up @@ -256,15 +256,14 @@ where
return Err(BondError::NotAValidator(validator.clone()).into());
}

let bond_handle = bond_handle(source, validator);
let total_bonded_handle = total_bonded_handle(validator);

if tracing::level_enabled!(tracing::Level::DEBUG) {
let bonds = find_bonds(storage, source, validator)?;
tracing::debug!("\nBonds before incrementing: {bonds:#?}");
}

// Initialize or update the bond at the pipeline offset
let bond_handle = bond_handle(source, validator);
let total_bonded_handle = total_bonded_handle(validator);
bond_handle.add(storage, amount, current_epoch, offset)?;
total_bonded_handle.add(storage, amount, current_epoch, offset)?;

Expand All @@ -274,9 +273,13 @@ where
}

// Add the validator to the delegation targets
let target_validators =
delegation_targets_handle(source).at(&(current_epoch + offset));
target_validators.insert(storage, validator.clone())?;
add_delegation_target(
storage,
source,
validator,
current_epoch + offset,
current_epoch,
)?;

// Update the validator set
// Allow bonding even if the validator is jailed. However, if jailed, there
Expand Down Expand Up @@ -422,6 +425,10 @@ where
let remaining_at_pipeline = bonds_handle
.get_sum(storage, pipeline_epoch, &params)?
.unwrap_or_default();
println!(
"\nREMAINING AT PIPELINE = {}",
remaining_at_pipeline.to_string_native()
);
if amount > remaining_at_pipeline {
return Err(UnbondError::UnbondAmountGreaterThanBond(
amount.to_string_native(),
Expand Down Expand Up @@ -527,10 +534,16 @@ where
let bonds_total = bonds_handle
.get_sum(storage, pipeline_epoch, &params)?
.unwrap_or_default();
println!("\nBONDS TOTAL = {}", bonds_total.to_string_native());
if bonds_total.is_zero() {
delegation_targets_handle(source)
.at(&pipeline_epoch)
.remove(storage, validator)?;
println!("Removing delegation target");
remove_delegation_target(
storage,
source,
validator,
pipeline_epoch,
current_epoch,
)?;
}

// `updatedUnbonded`
Expand Down Expand Up @@ -2151,6 +2164,15 @@ where
pipeline_epoch,
)?;

// Add the dest validator to the delegation targets
add_delegation_target(
storage,
delegator,
dest_validator,
pipeline_epoch,
current_epoch,
)?;

// Update validator set for dest validator
let is_jailed_or_inactive_at_pipeline = matches!(
validator_state_handle(dest_validator).get(
Expand Down Expand Up @@ -2930,3 +2952,66 @@ where

Ok(())
}

fn add_delegation_target<S>(
storage: &mut S,
delegator: &Address,
validator: &Address,
epoch: Epoch,
_current_epoch: Epoch,
) -> namada_storage::Result<()>
where
S: StorageRead + StorageWrite,
{
let bond_holders = delegation_targets_handle(delegator);
if let Some(delegations) = bond_holders.get(storage, validator)?.as_mut() {
let (start, end) = delegations.last_range;
if let Some(end) = end {
// Add the `last_range` pair to the `prev_ranges` and make a new
// `last_range`
delegations.prev_ranges.push((start, end));
delegations.last_range = (epoch, None);
} else {
// do nothing since the last bond is still active
}
} else {
// Make a new delegation to this source-validator pair
let first_delegation = DelegationEpochs {
prev_ranges: vec![],
last_range: (epoch, None),
};
bond_holders.insert(storage, validator.clone(), first_delegation)?;
}

// Todo: possibly update the data by pruning old pairs in
// `delegations.prev_ranges`??

Ok(())
}

fn remove_delegation_target<S>(
storage: &mut S,
delegator: &Address,
validator: &Address,
epoch: Epoch,
_current_epoch: Epoch,
) -> namada_storage::Result<()>
where
S: StorageRead + StorageWrite,
{
let validators = delegation_targets_handle(delegator);
if let Some(delegation) = validators.get(storage, validator)?.as_mut() {
debug_assert!(
delegation.last_range.1.is_none(),
"End epoch should be None since we are removing the delegation
right now!!"
);
delegation.last_range.1 = Some(epoch);
} else {
panic!("Delegation should exist since we are removing it right now!!!");
}

// TODO: possibly update the data by pruning old pairs or validators??

Ok(())
}
Loading

0 comments on commit 7d2c466

Please sign in to comment.