Skip to content

Commit

Permalink
Change set_inactive_stake to set_active_stake
Browse files Browse the repository at this point in the history
  • Loading branch information
ii-cruz committed Dec 14, 2023
1 parent 9eac0a4 commit f23de17
Show file tree
Hide file tree
Showing 17 changed files with 114 additions and 108 deletions.
6 changes: 3 additions & 3 deletions primitives/account/src/account/staking_contract/receipts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,16 +124,16 @@ pub struct StakerReceipt {
}
convert_receipt!(StakerReceipt);

/// Receipt for set inactive stake transactions. This is necessary to be able to revert
/// Receipt for set active stake transactions. This is necessary to be able to revert
/// these transactions.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct SetInactiveStakeReceipt {
pub struct SetActiveStakeReceipt {
/// the inactivation block height before this transaction is applied
pub old_inactive_from: Option<u32>,
/// the active balance before this transaction is applied
pub old_active_balance: Coin,
}
convert_receipt!(SetInactiveStakeReceipt);
convert_receipt!(SetActiveStakeReceipt);

/// Receipt for remove stake transactions. This is necessary to be able to revert
/// these transactions.
Expand Down
49 changes: 26 additions & 23 deletions primitives/account/src/account/staking_contract/staker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
},
StakerReceipt, StakingContract, Tombstone,
},
Log, RemoveStakeReceipt, SetInactiveStakeReceipt, TransactionLog,
Log, RemoveStakeReceipt, SetActiveStakeReceipt, TransactionLog,
};

/// Struct representing a staker in the staking contract.
Expand All @@ -26,7 +26,7 @@ use crate::{
/// Actions concerning a staker are:
/// 1. Create: Creates a staker.
/// 2. Stake: Adds coins from any outside address to a staker's active balance.
/// 3. SetInactiveStake: Re-balances between active and inactive stake by setting the amount of inactive stake.
/// 3. SetActiveStake: Re-balances between active and inactive stake by setting the amount of active stake.
/// This action restarts the lock-up period of the inactive stake.
/// Inactive stake is locked up for other actions until the release block.
/// If a delegation is defined and the corresponding validator is jailed,
Expand All @@ -41,7 +41,7 @@ use crate::{
/// (*) For inactive balance to be released, the maximum of the lock-up period for inactive stake
/// and the validator's potential jail period must have passed.
///
/// Create, Stake, SetInactiveStake, and Update are incoming transactions to the staking contract.
/// Create, Stake, SetActiveStake, and Update are incoming transactions to the staking contract.
/// Unstake is an outgoing transaction from the staking contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Staker {
Expand Down Expand Up @@ -384,28 +384,29 @@ impl StakingContract {
Ok(())
}

/// Deactivates a portion of the coins from a staker's balance. The inactive balance
/// will be available to unstake after a lock up period and, if applicable,
/// Changes the active and consequentially the inactive balances of staker.
/// The active balance will be set immediately.
/// The inactive balance will be available to withdraw after a lock up period and, if applicable,
/// until the jail period is finished.
/// If the staker has already inactive stake, the corresponding balance will be overwritten and
/// the lock up period will be reset. This corresponds to editing the inactive stake balance
/// and re-adjusting the active stake balance.
pub fn set_inactive_stake(
/// If the staker has already some inactive stake, the corresponding balance will be overwritten and
/// the lock up period will be reset. This corresponds to editing the active stake balance
/// and re-adjusting the inactive stake balance.
pub fn set_active_stake(
&mut self,
store: &mut StakingContractStoreWrite,
staker_address: &Address,
new_inactive_balance: Coin,
new_active_balance: Coin,
block_number: u32,
tx_logger: &mut TransactionLog,
) -> Result<SetInactiveStakeReceipt, AccountError> {
) -> Result<SetActiveStakeReceipt, AccountError> {
// Get the staker.
let mut staker = store.expect_staker(staker_address)?;

// Fail if staker does not have sufficient funds.
let total_balance = staker.balance + staker.inactive_balance;
if total_balance < new_inactive_balance {
if total_balance < new_active_balance {
return Err(AccountError::InsufficientFunds {
needed: new_inactive_balance,
needed: new_active_balance,
balance: total_balance,
});
}
Expand All @@ -415,7 +416,7 @@ impl StakingContract {
// Store old values for receipt.
let old_inactive_from = staker.inactive_from;
let old_active_balance = staker.balance;
let new_active_balance = total_balance - new_inactive_balance;
let new_inactive_balance = total_balance - new_active_balance;

// If we are delegating to a validator, we update the active stake of the validator.
// This function never changes the staker's delegation, so the validator counter should not be updated.
Expand All @@ -438,29 +439,30 @@ impl StakingContract {
Some(Policy::election_block_after(block_number))
};

tx_logger.push_log(Log::SetInactiveStake {
tx_logger.push_log(Log::SetActiveStake {
staker_address: staker_address.clone(),
validator_address: staker.delegation.clone(),
value: new_inactive_balance,
active_balance: new_active_balance,
inactive_balance: new_inactive_balance,
inactive_from: staker.inactive_from,
});

// Update the staker entry.
store.put_staker(staker_address, staker);

Ok(SetInactiveStakeReceipt {
Ok(SetActiveStakeReceipt {
old_inactive_from,
old_active_balance,
})
}

/// Reverts a deactivate stake transaction.
pub fn revert_set_inactive_stake(
pub fn revert_set_active_stake(
&mut self,
store: &mut StakingContractStoreWrite,
staker_address: &Address,
value: Coin,
receipt: SetInactiveStakeReceipt,
receipt: SetActiveStakeReceipt,
tx_logger: &mut TransactionLog,
) -> Result<(), AccountError> {
// Get the staker.
Expand All @@ -470,7 +472,7 @@ impl StakingContract {

// Keep the old values.
let old_inactive_from = staker.inactive_from;
let old_balance = staker.balance;
let old_inactive_balance = staker.inactive_balance;

// Restore the previous inactive since and balances.
staker.inactive_from = receipt.old_inactive_from;
Expand All @@ -480,14 +482,15 @@ impl StakingContract {
// If we are delegating to a validator, we update the active stake of the validator.
// This function never changes the staker's delegation, so the validator counter should not be updated.
if let Some(validator_address) = &staker.delegation {
self.update_stake_for_validator(store, validator_address, old_balance, staker.balance);
self.update_stake_for_validator(store, validator_address, value, staker.balance);
}

// Create logs.
tx_logger.push_log(Log::SetInactiveStake {
tx_logger.push_log(Log::SetActiveStake {
staker_address: staker_address.clone(),
validator_address: staker.delegation.clone(),
value,
active_balance: value,
inactive_balance: old_inactive_balance,
inactive_from: old_inactive_from,
});

Expand Down
16 changes: 8 additions & 8 deletions primitives/account/src/account/staking_contract/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,17 +197,17 @@ impl AccountTransactionInteraction for StakingContract {
)
.map(|receipt| Some(receipt.into()))
}
IncomingStakingTransactionData::SetInactiveStake {
new_inactive_balance,
IncomingStakingTransactionData::SetActiveStake {
new_active_balance,
proof,
} => {
// Get the staker address from the proof.
let staker_address = proof.compute_signer();

self.set_inactive_stake(
self.set_active_stake(
&mut store,
&staker_address,
new_inactive_balance,
new_active_balance,
block_state.number,
tx_logger,
)
Expand Down Expand Up @@ -284,19 +284,19 @@ impl AccountTransactionInteraction for StakingContract {

self.revert_update_staker(&mut store, &staker_address, receipt, tx_logger)
}
IncomingStakingTransactionData::SetInactiveStake {
new_inactive_balance,
IncomingStakingTransactionData::SetActiveStake {
new_active_balance,
proof,
} => {
// Get the staker address from the proof.
let staker_address = proof.compute_signer();

let receipt = receipt.ok_or(AccountError::InvalidReceipt)?.try_into()?;

self.revert_set_inactive_stake(
self.revert_set_active_stake(
&mut store,
&staker_address,
new_inactive_balance,
new_active_balance,
receipt,
tx_logger,
)
Expand Down
7 changes: 4 additions & 3 deletions primitives/account/src/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,11 @@ pub enum Log {
},

#[serde(rename_all = "camelCase")]
SetInactiveStake {
SetActiveStake {
staker_address: Address,
validator_address: Option<Address>,
value: Coin,
active_balance: Coin,
inactive_balance: Coin,
inactive_from: Option<u32>,
},

Expand Down Expand Up @@ -289,7 +290,7 @@ impl Log {
validator_address,
reward_address,
} => validator_address == address || reward_address == address,
Log::SetInactiveStake {
Log::SetActiveStake {
staker_address,
validator_address,
..
Expand Down
6 changes: 3 additions & 3 deletions primitives/account/tests/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -926,7 +926,7 @@ fn can_revert_transactions() {
IncomingType::CreateStaker,
IncomingType::AddStake,
IncomingType::UpdateStaker,
IncomingType::SetInactiveStake,
IncomingType::SetActiveStake,
] {
// Don't send from the staking contract to the staking contract.
if matches!(
Expand All @@ -942,7 +942,7 @@ fn can_revert_transactions() {
| IncomingType::CreateStaker
| IncomingType::AddStake
| IncomingType::UpdateStaker
| IncomingType::SetInactiveStake
| IncomingType::SetActiveStake
) {
continue;
}
Expand All @@ -963,7 +963,7 @@ fn can_revert_transactions() {
| IncomingType::DeactivateValidator
| IncomingType::ReactivateValidator
| IncomingType::UpdateStaker
| IncomingType::SetInactiveStake
| IncomingType::SetActiveStake
)
{
continue;
Expand Down
4 changes: 2 additions & 2 deletions primitives/account/tests/staking_contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,10 +456,10 @@ impl StakerSetup {
// Deactivate part of the stake.
validator_setup
.staking_contract
.set_inactive_stake(
.set_active_stake(
&mut staking_contract_store,
&staker_address,
inactive_stake,
active_stake,
deactivation_block,
&mut TransactionLog::empty(),
)
Expand Down
19 changes: 10 additions & 9 deletions primitives/account/tests/staking_contract/staker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ use nimiq_transaction::{

use super::*;

fn make_deactivate_stake_transaction(value: u64) -> Transaction {
fn make_activate_stake_transaction(value: u64) -> Transaction {
let private_key =
PrivateKey::deserialize_from_vec(&hex::decode(STAKER_PRIVATE_KEY).unwrap()).unwrap();

let key_pair = KeyPair::from(private_key);
make_signed_incoming_transaction(
IncomingStakingTransactionData::SetInactiveStake {
new_inactive_balance: Coin::try_from(value).unwrap(),
IncomingStakingTransactionData::SetActiveStake {
new_active_balance: Coin::try_from(value).unwrap(),
proof: SignatureProof::default(),
},
0,
Expand Down Expand Up @@ -2102,7 +2102,7 @@ fn can_update_inactive_balance() {
// Test execution:
// -----------------------------------
// Can update inactive stake.
let tx = make_deactivate_stake_transaction(100_000_000);
let tx = make_activate_stake_transaction(0);

let mut tx_logs = TransactionLog::empty();
let receipt = staker_setup
Expand All @@ -2118,7 +2118,7 @@ fn can_update_inactive_balance() {
assert_eq!(
receipt,
Some(
SetInactiveStakeReceipt {
SetActiveStakeReceipt {
old_inactive_from: Some(staker_setup.effective_inactivation_block_state.number),
old_active_balance: staker_setup.active_stake,
}
Expand All @@ -2128,10 +2128,11 @@ fn can_update_inactive_balance() {

assert_eq!(
tx_logs.logs,
vec![Log::SetInactiveStake {
vec![Log::SetActiveStake {
staker_address: staker_setup.staker_address.clone(),
validator_address: Some(staker_setup.validator_address.clone()),
value: Coin::from_u64_unchecked(100_000_000),
active_balance: Coin::ZERO,
inactive_balance: Coin::from_u64_unchecked(100_000_000),
inactive_from: Some(Policy::election_block_after(
staker_setup.before_release_block_state.number
))
Expand Down Expand Up @@ -2201,7 +2202,7 @@ fn can_update_inactive_balance() {
);

// Can update inactive stake to 0.
let tx = make_deactivate_stake_transaction(0);
let tx = make_activate_stake_transaction(100_000_000);

let receipt = staker_setup
.staking_contract
Expand All @@ -2216,7 +2217,7 @@ fn can_update_inactive_balance() {
assert_eq!(
receipt,
Some(
SetInactiveStakeReceipt {
SetActiveStakeReceipt {
old_inactive_from: Some(staker_setup.effective_inactivation_block_state.number),
old_active_balance: staker_setup.active_stake,
}
Expand Down
10 changes: 5 additions & 5 deletions primitives/transaction/src/account/staking_contract/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ pub enum IncomingStakingTransactionData {
reactivate_all_stake: bool,
proof: SignatureProof,
},
SetInactiveStake {
new_inactive_balance: Coin,
SetActiveStake {
new_active_balance: Coin,
proof: SignatureProof,
},
}
Expand All @@ -92,7 +92,7 @@ impl IncomingStakingTransactionData {
| IncomingStakingTransactionData::ReactivateValidator { .. }
| IncomingStakingTransactionData::RetireValidator { .. }
| IncomingStakingTransactionData::UpdateStaker { .. }
| IncomingStakingTransactionData::SetInactiveStake { .. }
| IncomingStakingTransactionData::SetActiveStake { .. }
)
}

Expand Down Expand Up @@ -177,7 +177,7 @@ impl IncomingStakingTransactionData {
// Check that the signature is correct.
verify_transaction_signature(transaction, proof, true)?
}
IncomingStakingTransactionData::SetInactiveStake { proof, .. } => {
IncomingStakingTransactionData::SetActiveStake { proof, .. } => {
// Check that the signature is correct.
verify_transaction_signature(transaction, proof, true)?
}
Expand Down Expand Up @@ -209,7 +209,7 @@ impl IncomingStakingTransactionData {
IncomingStakingTransactionData::UpdateStaker { proof, .. } => {
*proof = signature_proof;
}
IncomingStakingTransactionData::SetInactiveStake { proof, .. } => {
IncomingStakingTransactionData::SetActiveStake { proof, .. } => {
*proof = signature_proof;
}
_ => {}
Expand Down
Loading

0 comments on commit f23de17

Please sign in to comment.