Skip to content

Commit 0432374

Browse files
committed
Merge branch 'main' into lowhung/unify-hash-types
2 parents 28cbe9d + 62dbe73 commit 0432374

File tree

12 files changed

+94
-113
lines changed

12 files changed

+94
-113
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
@@ -38,7 +38,9 @@ jobs:
3838
--package acropolis_module_drep_state \
3939
--package acropolis_module_epochs_state \
4040
--package acropolis_module_genesis_bootstrapper \
41+
--package acropolis_module_governance_state \
4142
--package acropolis_module_mithril_snapshot_fetcher \
43+
--package acropolis_module_parameters_state \
4244
--package acropolis_module_snapshot_bootstrapper \
4345
--package acropolis_module_spdd_state \
4446
--package acropolis_module_spo_state \

modules/governance_state/src/alonzo_babbage_voting.rs

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,15 @@ use acropolis_common::{
55
use anyhow::{bail, Result};
66
use std::collections::{HashMap, HashSet};
77

8+
// (vote epoch, vote slot, proposal)
9+
type VoteData = (u64, u64, Box<ProtocolParamUpdate>);
10+
811
#[derive(Default)]
912
pub struct AlonzoBabbageVoting {
1013
/// map "enact epoch" (proposal enacts at this epoch end) to voting
11-
/// "voting": map voter (genesis key) => (vote epoch, vote slot, proposal)
14+
/// "voting": map voter (genesis key) => votedata
1215
/// "vote epoch/slot" --- moment, when the vote was cast for the proposal
13-
proposals: HashMap<u64, HashMap<GenesisKeyhash, (u64, u64, Box<ProtocolParamUpdate>)>>,
16+
proposals: HashMap<u64, HashMap<GenesisKeyhash, VoteData>>,
1417
slots_per_epoch: u32,
1518
update_quorum: u32,
1619
}
@@ -31,7 +34,7 @@ impl AlonzoBabbageVoting {
3134
pub fn process_update_proposals(
3235
&mut self,
3336
block_info: &BlockInfo,
34-
updates: &Vec<AlonzoBabbageUpdateProposal>,
37+
updates: &[AlonzoBabbageUpdateProposal],
3538
) -> Result<()> {
3639
if updates.is_empty() {
3740
return Ok(());
@@ -46,7 +49,7 @@ impl AlonzoBabbageVoting {
4649
}
4750

4851
for pp in updates.iter() {
49-
let entry = self.proposals.entry(pp.enactment_epoch + 1).or_insert(HashMap::new());
52+
let entry = self.proposals.entry(pp.enactment_epoch + 1).or_default();
5053
for (k, p) in &pp.proposals {
5154
// A new proposal for key k always replaces the old one
5255
entry.insert(k.clone(), (block_info.epoch, block_info.slot, p.clone()));
@@ -81,7 +84,8 @@ impl AlonzoBabbageVoting {
8184

8285
let votes: Vec<_> = proposals
8386
.iter()
84-
.filter_map(|(k, v)| (v == parameter_update).then(|| k.clone()))
87+
.filter(|&(_, v)| v == parameter_update)
88+
.map(|(k, _)| k.clone())
8589
.collect();
8690

8791
for v in &votes {
@@ -220,7 +224,7 @@ mod tests {
220224
fn extract_mainnet_parameter<T: Clone>(
221225
f: impl Fn(&ProtocolParamUpdate) -> Option<T>,
222226
) -> Result<Vec<(u64, T)>> {
223-
extract_parameter(5, 432_000, &MAINNET_PROPOSALS_JSON, f)
227+
extract_parameter(5, 432_000, MAINNET_PROPOSALS_JSON, f)
224228
}
225229

226230
const DECENTRALISATION: [(u64, f32); 39] = [
@@ -282,9 +286,9 @@ mod tests {
282286
let dcu = extract_mainnet_parameter(|p| p.decentralisation_constant)?;
283287

284288
assert_eq!(DECENTRALISATION.len(), dcu.len());
285-
for i in 0..dcu.len() {
286-
let rat = rational_number_from_f32(DECENTRALISATION[i].1)?;
287-
assert_eq!((DECENTRALISATION[i].0, rat), *dcu.get(i).unwrap());
289+
for (decent, param) in DECENTRALISATION.iter().zip(dcu) {
290+
let rat = rational_number_from_f32(decent.1)?;
291+
assert_eq!((decent.0, rat), param);
288292
}
289293

290294
Ok(())
@@ -319,7 +323,7 @@ mod tests {
319323
fn extract_sanchonet_parameter<T: Clone>(
320324
f: impl Fn(&ProtocolParamUpdate) -> Option<T>,
321325
) -> Result<Vec<(u64, T)>> {
322-
extract_parameter(3, 86_400, &SANCHONET_PROPOSALS_JSON, f)
326+
extract_parameter(3, 86_400, SANCHONET_PROPOSALS_JSON, f)
323327
}
324328

325329
const SANCHONET_PROTOCOL_VERSION: [(u64, (u64, u64)); 3] =

modules/governance_state/src/conway_voting.rs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ impl ConwayVoting {
128128
) -> Result<()> {
129129
self.votes_count += voter_votes.voting_procedures.len();
130130
for (action_id, procedure) in voter_votes.voting_procedures.iter() {
131-
let votes = self.votes.entry(action_id.clone()).or_insert_with(|| HashMap::new());
131+
let votes = self.votes.entry(action_id.clone()).or_default();
132132

133133
match self.action_status.get(action_id) {
134134
None => {
@@ -149,7 +149,7 @@ impl ConwayVoting {
149149
}
150150

151151
if let Some((prev_trans, prev_vote)) =
152-
votes.insert(voter.clone(), (transaction.clone(), procedure.clone()))
152+
votes.insert(voter.clone(), (*transaction, procedure.clone()))
153153
{
154154
// Re-voting is allowed; new vote must be treated as the proper one,
155155
// older is to be discarded.
@@ -202,8 +202,8 @@ impl ConwayVoting {
202202

203203
/// Should be called when voting is over
204204
fn end_voting(&mut self, action_id: &GovActionId) -> Result<()> {
205-
self.votes.remove(&action_id);
206-
self.proposals.remove(&action_id);
205+
self.votes.remove(action_id);
206+
self.proposals.remove(action_id);
207207

208208
Ok(())
209209
}
@@ -223,7 +223,7 @@ impl ConwayVoting {
223223
pool: VoteCount::zero(),
224224
};
225225

226-
let Some(all_votes) = self.votes.get(&action_id) else {
226+
let Some(all_votes) = self.votes.get(action_id) else {
227227
return Ok(votes);
228228
};
229229

@@ -334,10 +334,10 @@ impl ConwayVoting {
334334
spo_stake: &HashMap<PoolId, DelegatedStake>,
335335
) -> Result<Option<VotingOutcome>> {
336336
let outcome =
337-
self.is_finally_accepted(new_epoch, voting_state, &action_id, drep_stake, spo_stake)?;
338-
let expired = self.is_expired(new_epoch, &action_id)?;
337+
self.is_finally_accepted(new_epoch, voting_state, action_id, drep_stake, spo_stake)?;
338+
let expired = self.is_expired(new_epoch, action_id)?;
339339
if outcome.accepted || expired {
340-
self.end_voting(&action_id)?;
340+
self.end_voting(action_id)?;
341341
info!(
342342
"New epoch {new_epoch}: voting for {action_id} outcome: {}, expired: {expired}",
343343
outcome.accepted
@@ -362,7 +362,7 @@ impl ConwayVoting {
362362

363363
/// Function dumps information about completed (expired, ratified, enacted) governance
364364
/// actions in format, close to that of `gov_action_proposal` from `sqldb`.
365-
pub fn print_outcome_to_verify(&self, outcome: &Vec<GovernanceOutcome>) -> Result<()> {
365+
pub fn print_outcome_to_verify(&self, outcome: &[GovernanceOutcome]) -> Result<()> {
366366
let out_file_name = match &self.verification_output_file {
367367
Some(o) => o,
368368
None => return Ok(()),
@@ -416,7 +416,7 @@ impl ConwayVoting {
416416
{ratification_info},{cast},{threshold}\n",
417417
elem.voting.procedure.gov_action_id
418418
);
419-
if let Err(e) = out_file.write(&res.as_bytes()) {
419+
if let Err(e) = out_file.write(res.as_bytes()) {
420420
error!(
421421
"Cannot write 'res' to verification output {out_file_name} for writing: {e}"
422422
);
@@ -434,7 +434,7 @@ impl ConwayVoting {
434434
spo_stake: &HashMap<PoolId, DelegatedStake>,
435435
) -> Result<Vec<GovernanceOutcome>> {
436436
let mut outcome = Vec::<GovernanceOutcome>::new();
437-
let actions = self.proposals.keys().map(|a| a.clone()).collect::<Vec<_>>();
437+
let actions = self.proposals.keys().cloned().collect::<Vec<_>>();
438438

439439
for action_id in actions.iter() {
440440
info!(
@@ -443,8 +443,8 @@ impl ConwayVoting {
443443
);
444444
let one_outcome = match self.process_one_proposal(
445445
new_block.epoch,
446-
&voting_state,
447-
&action_id,
446+
voting_state,
447+
action_id,
448448
drep_stake,
449449
spo_stake,
450450
) {
@@ -508,7 +508,7 @@ impl ConwayVoting {
508508
pub fn update_action_status_with_outcomes(
509509
&mut self,
510510
epoch: u64,
511-
outcomes: &Vec<GovernanceOutcome>,
511+
outcomes: &[GovernanceOutcome],
512512
) -> Result<()> {
513513
for one_outcome in outcomes.iter() {
514514
let action_id = &one_outcome.voting.procedure.gov_action_id;
@@ -601,8 +601,8 @@ mod tests {
601601
},
602602
);
603603

604-
voting.update_action_status_with_outcomes(0, &vec![])?;
605-
voting.update_action_status_with_outcomes(1, &vec![oc1.clone()])?;
604+
voting.update_action_status_with_outcomes(0, &[])?;
605+
voting.update_action_status_with_outcomes(1, std::slice::from_ref(&oc1))?;
606606
assert_eq!(
607607
voting
608608
.action_status

modules/governance_state/src/conway_voting_test.rs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ mod tests {
88
SingleVoterVotes, TxHash, Vote, VoteCount, VoteResult, Voter, VotingProcedure,
99
};
1010
use anyhow::{anyhow, bail, Result};
11-
use serde;
12-
use serde_json;
11+
1312
use serde_with::{base64::Base64, serde_as};
1413
use std::{
1514
collections::{BTreeMap, HashMap},
@@ -83,7 +82,7 @@ mod tests {
8382
.strip_prefix("Some(")
8483
.ok_or_else(|| anyhow!("Does not have 'Some(' prefix {}", s))?;
8584
let num = wp.strip_suffix(")").ok_or_else(|| anyhow!("Must have ')' suffix {}", s))?;
86-
num.parse().map_err(|e| anyhow!("Cannot parse value {num}, error {e}")).map(|x| Some(x))
85+
num.parse().map_err(|e| anyhow!("Cannot parse value {num}, error {e}")).map(Some)
8786
}
8887
}
8988

@@ -127,12 +126,14 @@ mod tests {
127126
})
128127
.collect::<Result<Vec<(u64, HashMap<DRepCredential, Lovelace>)>>>()?;
129128

130-
let res = HashMap::from_iter(converted.into_iter());
129+
let res = HashMap::from_iter(converted);
131130

132131
Ok(res)
133132
}
134133

135-
fn map_voter_list(votes: &Vec<VotingRecord>, v: Vote) -> Result<Vec<(Voter, VotingProcedure)>> {
134+
type VoterList = Vec<(Voter, VotingProcedure)>;
135+
136+
fn map_voter_list(votes: &[VotingRecord], v: Vote) -> Result<VoterList> {
136137
votes
137138
.iter()
138139
.map(|x| {
@@ -145,14 +146,12 @@ mod tests {
145146
},
146147
))
147148
})
148-
.collect::<Result<Vec<(Voter, VotingProcedure)>>>()
149+
.collect()
149150
}
150151

151152
/// Reads list of votes: for each epoch, for each gov-action, three lists of voters:
152153
/// ([yes voters], [no voters], [abstain voters])
153-
fn read_voting_state(
154-
voting_json: &[u8],
155-
) -> Result<HashMap<(u64, GovActionId), Vec<(Voter, VotingProcedure)>>> {
154+
fn read_voting_state(voting_json: &[u8]) -> Result<HashMap<(u64, GovActionId), VoterList>> {
156155
let voting =
157156
serde_json::from_slice::<Vec<(u64, String, Vec<Vec<VotingRecord>>)>>(voting_json)?;
158157

@@ -161,8 +160,8 @@ mod tests {
161160
let action_id = GovActionId::from_bech32(action_id)?;
162161

163162
let mut vote_procs = Vec::new();
164-
if votes.len() > 0 {
165-
vote_procs = map_voter_list(votes.get(0).unwrap(), Vote::Yes)?;
163+
if !votes.is_empty() {
164+
vote_procs = map_voter_list(votes.first().unwrap(), Vote::Yes)?;
166165
vote_procs.append(&mut map_voter_list(votes.get(1).unwrap(), Vote::No)?);
167166
vote_procs.append(&mut map_voter_list(votes.get(2).unwrap(), Vote::Abstain)?);
168167
}
@@ -189,13 +188,13 @@ mod tests {
189188
// s504645304083669/961815354510517/93516758517300,c0:d1:s1
190189

191190
let records = line?.iter().map(|x| x.to_owned()).collect::<Vec<String>>();
192-
if records.len() == 0 {
191+
if records.is_empty() {
193192
continue;
194193
} else if records.len() != 17 {
195194
bail!("Wrong number of elements in csv line: {:?}", records)
196195
}
197196

198-
let action_id = records.get(0).unwrap();
197+
let action_id = records.first().unwrap();
199198
let start_epoch = records.get(6).unwrap();
200199
let proposal = records.get(9).unwrap();
201200
let ratification_epoch = records.get(11).unwrap();
@@ -220,7 +219,7 @@ mod tests {
220219

221220
fn read_protocol_params(configs_json: &[u8]) -> Result<BTreeMap<u64, ProtocolParams>> {
222221
let configs = serde_json::from_slice::<Vec<(u64, ProtocolParams)>>(configs_json)?;
223-
Ok(BTreeMap::from_iter(configs.into_iter()))
222+
Ok(BTreeMap::from_iter(configs))
224223
}
225224

226225
#[test]
@@ -310,8 +309,8 @@ mod tests {
310309
epoch,
311310
voting_state,
312311
&record.action_id,
313-
&current_drep,
314-
&current_pool,
312+
current_drep,
313+
current_pool,
315314
)?;
316315

317316
let Some(outcome) = outcome else {
@@ -320,7 +319,7 @@ mod tests {
320319
};
321320

322321
assert_eq!(outcome.accepted, record.ratification_epoch.is_some());
323-
assert_eq!(outcome.accepted, !record.expiration_epoch.is_some());
322+
assert_eq!(outcome.accepted, record.expiration_epoch.is_none());
324323
if outcome.accepted {
325324
assert_eq!(Some(epoch + 2), record.ratification_epoch)
326325
} else {

modules/governance_state/src/governance_state.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ impl GovernanceStateConfig {
7474
governance_query_topic: Self::conf(config, DEFAULT_GOVERNANCE_QUERY_TOPIC),
7575
verification_output_file: config
7676
.get_string(VERIFICATION_OUTPUT_FILE)
77-
.map(|x| Some(x))
77+
.map(Some)
7878
.unwrap_or(None),
7979
})
8080
}
@@ -94,7 +94,7 @@ impl GovernanceState {
9494
}
9595
}
9696

97-
async fn read_parameters<'a>(
97+
async fn read_parameters(
9898
parameters_s: &mut Box<dyn Subscription<Message>>,
9999
) -> Result<(BlockInfo, ProtocolParamsMessage)> {
100100
match parameters_s.read().await?.1.as_ref() {
@@ -205,7 +205,7 @@ impl GovernanceState {
205205
}
206206
}
207207
GovernanceStateQuery::GetProposalVotes { proposal } => {
208-
match locked.get_proposal_votes(&proposal) {
208+
match locked.get_proposal_votes(proposal) {
209209
Ok(votes) => {
210210
GovernanceStateQueryResponse::ProposalVotes(ProposalVotes { votes })
211211
}

modules/governance_state/src/state.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ impl State {
6565
if !epoch_blk.new_epoch {
6666
bail!("Block {epoch_blk:?} must start a new epoch");
6767
}
68-
self.current_era = epoch_blk.era.clone(); // If era is the same -- no problem
68+
self.current_era = epoch_blk.era; // If era is the same -- no problem
6969
self.alonzo_babbage_voting.advance_epoch(epoch_blk);
7070
Ok(())
7171
}
@@ -155,16 +155,14 @@ impl State {
155155
}
156156

157157
fn recalculate_voting_state(&self) -> Result<VotingRegistrationState> {
158-
let drep_stake = self.drep_stake.iter().map(|(_dr, lov)| lov).sum();
158+
let drep_stake = self.drep_stake.values().sum();
159159

160160
let committee_usize = self.conway_voting.get_conway_params()?.committee.members.len();
161-
let committee = committee_usize.try_into().or_else(|e| {
162-
Err(anyhow!(
163-
"Commitee size: conversion usize -> u64 failed, {e}"
164-
))
165-
})?;
161+
let committee = committee_usize
162+
.try_into()
163+
.map_err(|e| anyhow!("Commitee size: conversion usize -> u64 failed, {e}"))?;
166164

167-
let spo_stake = self.spo_stake.iter().map(|(_sp, ds)| ds.live).sum();
165+
let spo_stake = self.spo_stake.values().map(|ds| ds.live).sum();
168166

169167
Ok(VotingRegistrationState::new(
170168
spo_stake,
@@ -182,15 +180,17 @@ impl State {
182180
&mut self,
183181
new_block: &BlockInfo,
184182
) -> Result<GovernanceOutcomesMessage> {
185-
let mut output = GovernanceOutcomesMessage::default();
186-
output.alonzo_babbage_outcomes = self.alonzo_babbage_voting.finalize_voting(new_block)?;
183+
let mut output = GovernanceOutcomesMessage {
184+
alonzo_babbage_outcomes: self.alonzo_babbage_voting.finalize_voting(new_block)?,
185+
..Default::default()
186+
};
187187

188188
if self.current_era >= Era::Conway {
189189
// Last chance to print actual votes; later they'll be cleaned
190190
self.conway_voting.log_conway_voting_stats(new_block.epoch);
191191
let voting_state = self.recalculate_voting_state()?;
192192
let ratified = self.conway_voting.finalize_conway_voting(
193-
&new_block,
193+
new_block,
194194
&voting_state,
195195
&self.drep_stake,
196196
&self.spo_stake,

0 commit comments

Comments
 (0)