Skip to content

Commit 2f61e83

Browse files
committed
Merge branch 'main' into lowhung/unify-hash-types
# Conflicts: # modules/historical_accounts_state/src/immutable_historical_account_store.rs
2 parents 119426f + aec46a2 commit 2f61e83

File tree

19 files changed

+333
-263
lines changed

19 files changed

+333
-263
lines changed

.github/workflows/run-tests-on-push-to-main.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,10 @@ jobs:
3939
--package acropolis_module_epochs_state \
4040
--package acropolis_module_genesis_bootstrapper \
4141
--package acropolis_module_governance_state \
42+
--package acropolis_module_historical_accounts_state \
4243
--package acropolis_module_mithril_snapshot_fetcher \
4344
--package acropolis_module_parameters_state \
45+
--package acropolis_module_rest_blockfrost \
4446
--package acropolis_module_snapshot_bootstrapper \
4547
--package acropolis_module_spdd_state \
4648
--package acropolis_module_spo_state \

common/src/queries/accounts.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pub enum AccountsStateQuery {
1818
GetAccountRegistrationHistory { account: StakeAddress },
1919
GetAccountDelegationHistory { account: StakeAddress },
2020
GetAccountMIRHistory { account: StakeAddress },
21-
GetAccountWithdrawalHistory { stake_key: Vec<u8> },
21+
GetAccountWithdrawalHistory { account: StakeAddress },
2222
GetAccountAssociatedAddresses { stake_key: Vec<u8> },
2323
GetAccountAssets { stake_key: Vec<u8> },
2424
GetAccountAssetsTotals { stake_key: Vec<u8> },
@@ -52,7 +52,7 @@ pub enum AccountsStateQueryResponse {
5252
AccountRegistrationHistory(Vec<RegistrationUpdate>),
5353
AccountDelegationHistory(Vec<DelegationUpdate>),
5454
AccountMIRHistory(Vec<AccountWithdrawal>),
55-
AccountWithdrawalHistory(AccountWithdrawalHistory),
55+
AccountWithdrawalHistory(Vec<AccountWithdrawal>),
5656
AccountAssociatedAddresses(AccountAssociatedAddresses),
5757
AccountAssets(AccountAssets),
5858
AccountAssetsTotals(AccountAssetsTotals),

common/src/stake_addresses.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,8 @@ mod tests {
866866
}
867867

868868
mod withdrawal_tests {
869+
use crate::TxIdentifier;
870+
869871
use super::*;
870872

871873
#[test]
@@ -879,6 +881,7 @@ mod tests {
879881
let withdrawal = Withdrawal {
880882
address: stake_address.clone(),
881883
value: 40,
884+
tx_identifier: TxIdentifier::default(),
882885
};
883886
stake_addresses.process_withdrawal(&withdrawal);
884887

@@ -897,6 +900,7 @@ mod tests {
897900
let withdrawal = Withdrawal {
898901
address: stake_address.clone(),
899902
value: 24,
903+
tx_identifier: TxIdentifier::default(),
900904
};
901905
stake_addresses.process_withdrawal(&withdrawal);
902906
assert_eq!(stake_addresses.get(&stake_address).unwrap().rewards, 12);
@@ -905,6 +909,7 @@ mod tests {
905909
let withdrawal = Withdrawal {
906910
address: stake_address.clone(),
907911
value: 2,
912+
tx_identifier: TxIdentifier::default(),
908913
};
909914
stake_addresses.process_withdrawal(&withdrawal);
910915
assert_eq!(stake_addresses.get(&stake_address).unwrap().rewards, 10);
@@ -921,6 +926,7 @@ mod tests {
921926
let withdrawal = Withdrawal {
922927
address: stake_address.clone(),
923928
value: 0,
929+
tx_identifier: TxIdentifier::default(),
924930
};
925931

926932
stake_addresses.process_withdrawal(&withdrawal);
@@ -935,6 +941,7 @@ mod tests {
935941
let withdrawal = Withdrawal {
936942
address: stake_address.clone(),
937943
value: 10,
944+
tx_identifier: TxIdentifier::default(),
938945
};
939946

940947
// Should log error but not panic

common/src/types.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,9 @@ pub struct Withdrawal {
612612

613613
/// Value to withdraw
614614
pub value: Lovelace,
615+
616+
// Identifier of withdrawal tx
617+
pub tx_identifier: TxIdentifier,
615618
}
616619

617620
/// Treasury pot account

modules/accounts_state/src/rewards.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use std::sync::Arc;
1414
use tracing::{debug, info, warn};
1515

1616
/// Type of reward being given
17-
#[derive(Debug, Clone)]
17+
#[derive(Debug, Clone, PartialEq)]
1818
pub enum RewardType {
1919
Leader,
2020
Member,
@@ -34,7 +34,7 @@ pub struct RewardDetail {
3434
}
3535

3636
/// Result of a rewards calculation
37-
#[derive(Debug, Default)]
37+
#[derive(Debug, Default, Clone)]
3838
pub struct RewardsResult {
3939
/// Epoch these rewards were earned in (when blocks produced)
4040
pub epoch: u64,

modules/accounts_state/src/state.rs

Lines changed: 40 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Acropolis AccountsState: State storage
22
use crate::monetary::calculate_monetary_change;
3-
use crate::rewards::{calculate_rewards, RewardsResult};
3+
use crate::rewards::{calculate_rewards, RewardType, RewardsResult};
44
use crate::snapshot::Snapshot;
55
use crate::verifier::Verifier;
66
use acropolis_common::queries::accounts::OptimalPoolSizing;
@@ -117,9 +117,6 @@ pub struct State {
117117
/// Pool refunds to apply next epoch (list of reward accounts to refund to)
118118
pool_refunds: Vec<StakeAddress>,
119119

120-
/// Stake address refunds to apply next epoch
121-
stake_refunds: Vec<(StakeAddress, Lovelace)>,
122-
123120
/// MIRs to pay next epoch
124121
mirs: Vec<MoveInstantaneousReward>,
125122

@@ -325,7 +322,6 @@ impl State {
325322

326323
// Pay the refunds after snapshot, so they don't appear in active_stake
327324
reward_deltas.extend(self.pay_pool_refunds());
328-
reward_deltas.extend(self.pay_stake_refunds());
329325

330326
// Verify pots state
331327
verifier.verify_pots(epoch, &self.pots);
@@ -497,33 +493,6 @@ impl State {
497493
reward_deltas
498494
}
499495

500-
/// Pay stake address refunds
501-
fn pay_stake_refunds(&mut self) -> Vec<StakeRewardDelta> {
502-
let mut reward_deltas = Vec::<StakeRewardDelta>::new();
503-
504-
let refunds = take(&mut self.stake_refunds);
505-
if !refunds.is_empty() {
506-
info!(
507-
"{} deregistered stake addresses, total refunds {}",
508-
refunds.len(),
509-
refunds.iter().map(|(_, n)| n).sum::<Lovelace>()
510-
);
511-
}
512-
513-
// Send them their deposits back
514-
for (stake_address, deposit) in refunds {
515-
let mut stake_addresses = self.stake_addresses.lock().unwrap();
516-
reward_deltas.push(StakeRewardDelta {
517-
stake_address: stake_address.clone(), // Extract hash for delta
518-
delta: deposit as i64,
519-
});
520-
stake_addresses.add_to_reward(&stake_address, deposit);
521-
self.pots.deposits -= deposit;
522-
}
523-
524-
reward_deltas
525-
}
526-
527496
/// Pay MIRs
528497
fn pay_mirs(&mut self) -> Vec<StakeRewardDelta> {
529498
let mut reward_deltas = Vec::<StakeRewardDelta>::new();
@@ -658,36 +627,52 @@ impl State {
658627

659628
// If rewards have been calculated, save the results
660629
if let Some(task) = task.take() {
661-
if let Ok(Ok(reward_result)) = task.await {
662-
// Collect rewards to stake addresses reward deltas
663-
for rewards in reward_result.rewards.values() {
664-
reward_deltas.extend(
665-
rewards
666-
.iter()
667-
.map(|reward| StakeRewardDelta {
668-
stake_address: reward.account.clone(),
669-
delta: reward.amount as i64,
670-
})
671-
.collect::<Vec<_>>(),
672-
);
673-
}
674-
675-
// Verify them
676-
verifier.verify_rewards(reward_result.epoch, &reward_result);
677-
630+
if let Ok(Ok(rewards_result)) = task.await {
678631
// Pay the rewards
679632
let mut stake_addresses = self.stake_addresses.lock().unwrap();
680-
for (_, rewards) in reward_result.rewards {
633+
let mut filtered_rewards_result = rewards_result.clone();
634+
for (spo, rewards) in rewards_result.rewards {
681635
for reward in rewards {
682-
stake_addresses.add_to_reward(&reward.account, reward.amount);
636+
if stake_addresses.is_registered(&reward.account) {
637+
stake_addresses.add_to_reward(&reward.account, reward.amount);
638+
reward_deltas.push(StakeRewardDelta {
639+
stake_address: reward.account.clone(),
640+
delta: reward.amount as i64,
641+
});
642+
} else {
643+
warn!(
644+
"Reward account {} deregistered - paying reward {} to treasury",
645+
reward.account, reward.amount
646+
);
647+
self.pots.treasury += reward.amount;
648+
649+
// Remove from filtered version for comparison and result
650+
if let Some(rewards) = filtered_rewards_result.rewards.get_mut(&spo) {
651+
rewards.retain(|r| r.account != reward.account);
652+
}
653+
654+
if let Some((_, spor)) = filtered_rewards_result
655+
.spo_rewards
656+
.iter_mut()
657+
.find(|(fspo, _)| *fspo == spo)
658+
{
659+
spor.total_rewards -= reward.amount;
660+
if reward.rtype == RewardType::Leader {
661+
spor.operator_rewards -= reward.amount;
662+
}
663+
}
664+
}
683665
}
684666
}
685667

668+
// Verify them
669+
verifier.verify_rewards(&filtered_rewards_result);
670+
686671
// save SPO rewards
687-
spo_rewards = reward_result.spo_rewards.into_iter().collect();
672+
spo_rewards = filtered_rewards_result.spo_rewards.clone();
688673

689674
// Adjust the reserves for next time with amount actually paid
690-
self.pots.reserves -= reward_result.total_paid;
675+
self.pots.reserves -= rewards_result.total_paid;
691676
}
692677
};
693678

@@ -842,8 +827,7 @@ impl State {
842827
}
843828
};
844829

845-
// Schedule refund
846-
self.stake_refunds.push((stake_address.clone(), deposit));
830+
self.pots.deposits -= deposit;
847831

848832
// Add to registration changes
849833
self.current_epoch_registration_changes.lock().unwrap().push(RegistrationChange {
@@ -1331,6 +1315,7 @@ mod tests {
13311315
withdrawals: vec![Withdrawal {
13321316
address: stake_address.clone(),
13331317
value: 39,
1318+
tx_identifier: TxIdentifier::default(),
13341319
}],
13351320
};
13361321

modules/accounts_state/src/verifier.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,8 @@ impl Verifier {
119119
}
120120

121121
/// Verify rewards, logging any errors
122-
pub fn verify_rewards(&self, epoch: u64, rewards: &RewardsResult) {
122+
pub fn verify_rewards(&self, rewards: &RewardsResult) {
123+
let epoch = rewards.epoch;
123124
if let Some(template) = &self.rewards_file_template {
124125
let path = template.replace("{}", &epoch.to_string());
125126

modules/historical_accounts_state/src/historical_accounts_state.rs

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ impl HistoricalAccountsState {
110110
if let Message::Cardano((ref block_info, CardanoMessage::ProtocolParams(params))) =
111111
params_msg.as_ref()
112112
{
113-
Self::check_sync(&current_block, &block_info);
113+
Self::check_sync(&current_block, block_info);
114114
let mut state = state_mutex.lock().await;
115115
state.volatile.start_new_epoch(block_info.number);
116116
if let Some(shelley) = &params.params.shelley {
@@ -124,7 +124,7 @@ impl HistoricalAccountsState {
124124
CardanoMessage::StakeRewardDeltas(rewards_msg),
125125
)) = rewards_msg.as_ref()
126126
{
127-
Self::check_sync(&current_block, &block_info);
127+
Self::check_sync(&current_block, block_info);
128128
let mut state = state_mutex.lock().await;
129129
state
130130
.handle_rewards(rewards_msg)
@@ -142,12 +142,9 @@ impl HistoricalAccountsState {
142142
);
143143
let _entered = span.enter();
144144

145-
Self::check_sync(&current_block, &block_info);
145+
Self::check_sync(&current_block, block_info);
146146
let mut state = state_mutex.lock().await;
147-
state
148-
.handle_tx_certificates(tx_certs_msg, block_info.epoch as u32)
149-
.inspect_err(|e| error!("TxCertificates handling error: {e:#}"))
150-
.ok();
147+
state.handle_tx_certificates(tx_certs_msg, block_info.epoch as u32);
151148
}
152149

153150
_ => error!("Unexpected message type: {certs_message:?}"),
@@ -163,12 +160,9 @@ impl HistoricalAccountsState {
163160
);
164161
let _entered = span.enter();
165162

166-
Self::check_sync(&current_block, &block_info);
163+
Self::check_sync(&current_block, block_info);
167164
let mut state = state_mutex.lock().await;
168-
state
169-
.handle_withdrawals(withdrawals_msg)
170-
.inspect_err(|e| error!("Withdrawals handling error: {e:#}"))
171-
.ok();
165+
state.handle_withdrawals(withdrawals_msg);
172166
}
173167

174168
_ => error!("Unexpected message type: {message:?}"),
@@ -184,7 +178,7 @@ impl HistoricalAccountsState {
184178
);
185179
let _entered = span.enter();
186180

187-
Self::check_sync(&current_block, &block_info);
181+
Self::check_sync(&current_block, block_info);
188182
{
189183
let mut state = state_mutex.lock().await;
190184
state
@@ -206,8 +200,7 @@ impl HistoricalAccountsState {
206200

207201
if should_prune {
208202
let (store, cfg) = {
209-
let mut state: tokio::sync::MutexGuard<'_, State> =
210-
state_mutex.lock().await;
203+
let mut state = state_mutex.lock().await;
211204
state.prune_volatile().await;
212205
(state.immutable.clone(), state.config.clone())
213206
};
@@ -320,7 +313,7 @@ impl HistoricalAccountsState {
320313

321314
let response = match query {
322315
AccountsStateQuery::GetAccountRegistrationHistory { account } => {
323-
match state.lock().await.get_registration_history(&account).await {
316+
match state.lock().await.get_registration_history(account).await {
324317
Ok(Some(registrations)) => {
325318
AccountsStateQueryResponse::AccountRegistrationHistory(
326319
registrations,
@@ -331,7 +324,7 @@ impl HistoricalAccountsState {
331324
}
332325
}
333326
AccountsStateQuery::GetAccountDelegationHistory { account } => {
334-
match state.lock().await.get_delegation_history(&account).await {
327+
match state.lock().await.get_delegation_history(account).await {
335328
Ok(Some(delegations)) => {
336329
AccountsStateQueryResponse::AccountDelegationHistory(delegations)
337330
}
@@ -340,13 +333,21 @@ impl HistoricalAccountsState {
340333
}
341334
}
342335
AccountsStateQuery::GetAccountMIRHistory { account } => {
343-
match state.lock().await.get_mir_history(&account).await {
336+
match state.lock().await.get_mir_history(account).await {
344337
Ok(Some(mirs)) => AccountsStateQueryResponse::AccountMIRHistory(mirs),
345338
Ok(None) => AccountsStateQueryResponse::NotFound,
346339
Err(e) => AccountsStateQueryResponse::Error(e.to_string()),
347340
}
348341
}
349-
342+
AccountsStateQuery::GetAccountWithdrawalHistory { account } => {
343+
match state.lock().await.get_withdrawal_history(account).await {
344+
Ok(Some(withdrawals)) => {
345+
AccountsStateQueryResponse::AccountWithdrawalHistory(withdrawals)
346+
}
347+
Ok(None) => AccountsStateQueryResponse::NotFound,
348+
Err(e) => AccountsStateQueryResponse::Error(e.to_string()),
349+
}
350+
}
350351
_ => AccountsStateQueryResponse::Error(format!(
351352
"Unimplemented query variant: {:?}",
352353
query

0 commit comments

Comments
 (0)