Skip to content

Commit 8c08f44

Browse files
committed
Refactor: Replace KeyHash with StakeAddress for improved clarity and consistency across modules
1 parent d181f1c commit 8c08f44

File tree

13 files changed

+69
-97
lines changed

13 files changed

+69
-97
lines changed

codec/src/block.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ pub fn map_to_block_issuer(
1616
let digest = keyhash_224(vkey);
1717
if let Some(issuer) = shelley_genesis_delegates
1818
.values()
19-
.find(|v| v.delegate == digest.to_vec())
19+
.find(|v| v.delegate == digest)
2020
.map(|i| BlockIssuer::GenesisDelegate(i.clone()))
2121
{
2222
Some(issuer)

common/src/queries/accounts.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,17 +57,17 @@ pub enum AccountsStateQueryResponse {
5757
AccountAssets(AccountAssets),
5858
AccountAssetsTotals(AccountAssetsTotals),
5959
AccountUTxOs(AccountUTxOs),
60-
AccountsUtxoValuesMap(HashMap<KeyHash, u64>),
60+
AccountsUtxoValuesMap(HashMap<StakeAddress, u64>),
6161
AccountsUtxoValuesSum(u64),
62-
AccountsBalancesMap(HashMap<KeyHash, u64>),
62+
AccountsBalancesMap(HashMap<StakeAddress, u64>),
6363
AccountsBalancesSum(u64),
6464

6565
// Epochs-related responses
6666
ActiveStakes(u64),
67-
/// Vec<(PoolId, StakeKey, ActiveStakeAmount)>
68-
SPDDByEpoch(Vec<(PoolId, KeyHash, u64)>),
69-
/// Vec<(StakeKey, ActiveStakeAmount)>
70-
SPDDByEpochAndPool(Vec<(KeyHash, u64)>),
67+
/// Vec<(PoolId, StakeAddress, ActiveStakeAmount)>
68+
SPDDByEpoch(Vec<(PoolId, StakeAddress, u64)>),
69+
/// Vec<(StakeAddress, ActiveStakeAmount)>
70+
SPDDByEpochAndPool(Vec<(StakeAddress, u64)>),
7171

7272
// Pools-related responses
7373
OptimalPoolSizing(Option<OptimalPoolSizing>),
@@ -77,7 +77,7 @@ pub enum AccountsStateQueryResponse {
7777

7878
// DReps-related responses
7979
DrepDelegators(DrepDelegators),
80-
AccountsDrepDelegationsMap(HashMap<KeyHash, Option<DRepChoice>>),
80+
AccountsDrepDelegationsMap(HashMap<StakeAddress, Option<DRepChoice>>),
8181

8282
NotFound,
8383
Error(String),
@@ -173,7 +173,7 @@ pub struct OptimalPoolSizing {
173173

174174
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
175175
pub struct PoolDelegators {
176-
pub delegators: Vec<(KeyHash, u64)>,
176+
pub delegators: Vec<(StakeAddress, u64)>,
177177
}
178178

179179
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]

common/src/queries/pools.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::{
2-
queries::governance::VoteRecord, rational_number::RationalNumber, KeyHash, PoolEpochState,
3-
PoolId, PoolMetadata, PoolRegistration, PoolRetirement, PoolUpdateEvent, Relay,
2+
queries::governance::VoteRecord, rational_number::RationalNumber, PoolEpochState, PoolId,
3+
PoolMetadata, PoolRegistration, PoolRetirement, PoolUpdateEvent, Relay, StakeAddress,
44
};
55

66
pub const DEFAULT_POOLS_QUERY_TOPIC: (&str, &str) =
@@ -94,5 +94,5 @@ pub struct PoolActiveStakeInfo {
9494

9595
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
9696
pub struct PoolDelegators {
97-
pub delegators: Vec<(KeyHash, u64)>,
97+
pub delegators: Vec<(StakeAddress, u64)>,
9898
}

common/src/stake_addresses.rs

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -166,15 +166,15 @@ impl StakeAddressMap {
166166
}
167167

168168
/// Get Pool Delegators with live_stakes
169-
pub fn get_pool_delegators(&self, pool_operator: &PoolId) -> Vec<(KeyHash, u64)> {
169+
pub fn get_pool_delegators(&self, pool_operator: &PoolId) -> Vec<(StakeAddress, u64)> {
170170
// Find stake addresses delegated to pool_operator
171-
let delegators: Vec<(KeyHash, u64)> = self
171+
let delegators: Vec<(StakeAddress, u64)> = self
172172
.inner
173173
.iter()
174174
.filter_map(|(stake_address, sas)| match sas.delegated_spo.as_ref() {
175175
Some(delegated_spo) => {
176176
if delegated_spo.eq(pool_operator) {
177-
Some((*stake_address.get_hash(), sas.utxo_value + sas.rewards))
177+
Some((stake_address.clone(), sas.utxo_value + sas.rewards))
178178
} else {
179179
None
180180
}
@@ -212,14 +212,13 @@ impl StakeAddressMap {
212212
pub fn get_accounts_utxo_values_map(
213213
&self,
214214
stake_addresses: &[StakeAddress],
215-
) -> Option<HashMap<KeyHash, u64>> {
215+
) -> Option<HashMap<StakeAddress, u64>> {
216216
let mut map = HashMap::new();
217217

218218
for stake_address in stake_addresses {
219219
let account = self.get(stake_address)?;
220220
let utxo_value = account.utxo_value;
221-
let key_hash = stake_address.get_hash();
222-
map.insert(*key_hash, utxo_value);
221+
map.insert(stake_address.clone(), utxo_value);
223222
}
224223

225224
Some(map)
@@ -230,14 +229,13 @@ impl StakeAddressMap {
230229
pub fn get_accounts_balances_map(
231230
&self,
232231
stake_addresses: &[StakeAddress],
233-
) -> Option<HashMap<KeyHash, u64>> {
232+
) -> Option<HashMap<StakeAddress, u64>> {
234233
let mut map = HashMap::new();
235234

236235
for stake_address in stake_addresses {
237236
let account = self.get(stake_address)?;
238237
let balance = account.utxo_value + account.rewards;
239-
let key_hash = stake_address.get_hash();
240-
map.insert(*key_hash, balance);
238+
map.insert(stake_address.clone(), balance);
241239
}
242240

243241
Some(map)
@@ -248,14 +246,13 @@ impl StakeAddressMap {
248246
pub fn get_drep_delegations_map(
249247
&self,
250248
stake_addresses: &[StakeAddress],
251-
) -> Option<HashMap<KeyHash, Option<DRepChoice>>> {
249+
) -> Option<HashMap<StakeAddress, Option<DRepChoice>>> {
252250
let mut map = HashMap::new();
253251

254252
for stake_address in stake_addresses {
255253
let account = self.get(stake_address)?;
256254
let maybe_drep = account.delegated_drep.clone();
257-
let key_hash = stake_address.get_hash();
258-
map.insert(*key_hash, maybe_drep);
255+
map.insert(stake_address.clone(), maybe_drep);
259256
}
260257

261258
Some(map)
@@ -326,7 +323,7 @@ impl StakeAddressMap {
326323

327324
/// Dump current Stake Pool Delegation Distribution State
328325
/// <PoolId -> (Stake Key, Active Stakes Amount)>
329-
pub fn dump_spdd_state(&self) -> HashMap<PoolId, Vec<(KeyHash, u64)>> {
326+
pub fn dump_spdd_state(&self) -> HashMap<PoolId, Vec<(StakeAddress, u64)>> {
330327
let entries: Vec<_> = self
331328
.inner
332329
.par_iter()
@@ -335,9 +332,9 @@ impl StakeAddressMap {
335332
})
336333
.collect();
337334

338-
let mut result: HashMap<PoolId, Vec<(KeyHash, u64)>> = HashMap::new();
335+
let mut result: HashMap<PoolId, Vec<(StakeAddress, u64)>> = HashMap::new();
339336
for (spo, entry) in entries {
340-
result.entry(spo).or_default().push((entry.0.get_credential().get_hash(), entry.1));
337+
result.entry(spo).or_default().push((entry.0, entry.1));
341338
}
342339
result
343340
}
@@ -1244,8 +1241,8 @@ mod tests {
12441241
let map = stake_addresses.get_accounts_utxo_values_map(&keys).unwrap();
12451242

12461243
assert_eq!(map.len(), 2);
1247-
assert_eq!(map.get(&addr1.get_hash()).copied().unwrap(), 1000);
1248-
assert_eq!(map.get(&addr2.get_hash()).copied().unwrap(), 2000);
1244+
assert_eq!(map.get(&addr1).copied().unwrap(), 1000);
1245+
assert_eq!(map.get(&addr2).copied().unwrap(), 2000);
12491246
}
12501247

12511248
#[test]
@@ -1358,8 +1355,8 @@ mod tests {
13581355
let map = stake_addresses.get_accounts_balances_map(&addresses).unwrap();
13591356

13601357
assert_eq!(map.len(), 2);
1361-
assert_eq!(map.get(&addr1.get_hash()).copied().unwrap(), 1100);
1362-
assert_eq!(map.get(&addr2.get_hash()).copied().unwrap(), 2000);
1358+
assert_eq!(map.get(&addr1).copied().unwrap(), 1100);
1359+
assert_eq!(map.get(&addr2).copied().unwrap(), 2000);
13631360
}
13641361

13651362
#[test]
@@ -1467,14 +1464,14 @@ mod tests {
14671464

14681465
assert_eq!(map.len(), 3);
14691466
assert_eq!(
1470-
map.get(&addr1.get_hash()).unwrap(),
1467+
map.get(&addr1).unwrap(),
14711468
&Some(DRepChoice::Abstain)
14721469
);
14731470
assert_eq!(
1474-
map.get(&addr2.get_hash()).unwrap(),
1471+
map.get(&addr2).unwrap(),
14751472
&Some(DRepChoice::Key(DREP_HASH))
14761473
);
1477-
assert_eq!(map.get(&addr3.get_hash()).unwrap(), &None);
1474+
assert_eq!(map.get(&addr3).unwrap(), &None);
14781475
}
14791476

14801477
#[test]

modules/accounts_state/src/spo_distribution_store.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::collections::HashMap;
2-
2+
use std::ops::Add;
33
use acropolis_common::types::AddrKeyhash;
4-
use acropolis_common::PoolId;
4+
use acropolis_common::{PoolId, StakeAddress};
55
use anyhow::Result;
66
use fjall::{Config, Keyspace, PartitionCreateOptions};
77

modules/accounts_state/src/state.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ impl State {
172172
}
173173

174174
/// Get Pool Delegators with live_stakes
175-
pub fn get_pool_delegators(&self, pool_operator: &PoolId) -> Vec<(KeyHash, u64)> {
175+
pub fn get_pool_delegators(&self, pool_operator: &PoolId) -> Vec<(StakeAddress, u64)> {
176176
self.stake_addresses.lock().unwrap().get_pool_delegators(pool_operator)
177177
}
178178

@@ -185,7 +185,7 @@ impl State {
185185
pub fn get_accounts_utxo_values_map(
186186
&self,
187187
stake_keys: &[StakeAddress],
188-
) -> Option<HashMap<KeyHash, u64>> {
188+
) -> Option<HashMap<StakeAddress, u64>> {
189189
let stake_addresses = self.stake_addresses.lock().ok()?; // If lock fails, return None
190190
stake_addresses.get_accounts_utxo_values_map(stake_keys)
191191
}
@@ -200,7 +200,7 @@ impl State {
200200
pub fn get_accounts_balances_map(
201201
&self,
202202
stake_keys: &[StakeAddress],
203-
) -> Option<HashMap<KeyHash, u64>> {
203+
) -> Option<HashMap<StakeAddress, u64>> {
204204
let stake_addresses = self.stake_addresses.lock().ok()?; // If lock fails, return None
205205
stake_addresses.get_accounts_balances_map(stake_keys)
206206
}
@@ -220,7 +220,7 @@ impl State {
220220
pub fn get_drep_delegations_map(
221221
&self,
222222
stake_keys: &[StakeAddress],
223-
) -> Option<HashMap<KeyHash, Option<DRepChoice>>> {
223+
) -> Option<HashMap<StakeAddress, Option<DRepChoice>>> {
224224
let stake_addresses = self.stake_addresses.lock().ok()?; // If lock fails, return None
225225
stake_addresses.get_drep_delegations_map(stake_keys)
226226
}
@@ -572,7 +572,7 @@ impl State {
572572
stake_addresses.generate_spdd()
573573
}
574574

575-
pub fn dump_spdd_state(&self) -> HashMap<PoolId, Vec<(KeyHash, u64)>> {
575+
pub fn dump_spdd_state(&self) -> HashMap<PoolId, Vec<(StakeAddress, u64)>> {
576576
let stake_addresses = self.stake_addresses.lock().unwrap();
577577
stake_addresses.dump_spdd_state()
578578
}

modules/drep_state/src/state.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -474,12 +474,12 @@ impl State {
474474
context: &Arc<Context<Message>>,
475475
delegators: &[(&StakeAddress, &DRepChoice)],
476476
) -> Result<()> {
477-
let mut stake_key_to_input = HashMap::with_capacity(delegators.len());
477+
let mut stake_address_to_input = HashMap::with_capacity(delegators.len());
478478
let mut stake_addresses = Vec::with_capacity(delegators.len());
479479

480-
for &(sc, drep) in delegators {
481-
stake_addresses.push(sc.clone());
482-
stake_key_to_input.insert(sc.get_credential().get_hash(), (sc, drep));
480+
for &(stake_address, drep) in delegators {
481+
stake_addresses.push(stake_address.clone());
482+
stake_address_to_input.insert(stake_address, (stake_address, drep));
483483
}
484484

485485
let msg = Arc::new(Message::StateQuery(StateQuery::Accounts(
@@ -500,8 +500,8 @@ impl State {
500500
}
501501
};
502502

503-
for (stake_key, old_drep_opt) in result_map {
504-
let &(delegator, new_drep_choice) = match stake_key_to_input.get(&stake_key) {
503+
for (stake_address, old_drep_opt) in result_map {
504+
let &(delegator, new_drep_choice) = match stake_address_to_input.get(&stake_address) {
505505
Some(pair) => pair,
506506
None => continue,
507507
};

modules/rest_blockfrost/src/handlers/epochs.rs

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use acropolis_common::{
1515
spdd::{SPDDStateQuery, SPDDStateQueryResponse},
1616
utils::query_state,
1717
},
18-
NetworkId, PoolId, StakeAddress, StakeCredential,
18+
NetworkId, PoolId,
1919
};
2020
use anyhow::{anyhow, Result};
2121
use caryatid_sdk::Context;
@@ -486,16 +486,10 @@ pub async fn handle_epoch_total_stakes_blockfrost(
486486
.await?;
487487
let spdd_response = spdd
488488
.into_iter()
489-
.map(|(pool_id, stake_key_hash, amount)| {
490-
let stake_address = StakeAddress {
491-
network: network.clone(),
492-
credential: StakeCredential::AddrKeyHash(stake_key_hash),
493-
}
494-
.to_string()
495-
.map_err(|e| anyhow::anyhow!("Failed to convert stake address to string: {e}"))?;
489+
.map(|(pool_id, stake_address, amount)| {
496490
Ok(SPDDByEpochItemRest {
497-
pool_id: pool_id.to_vec(),
498-
stake_address,
491+
pool_id,
492+
stake_address: stake_address.to_string().unwrap(),
499493
amount,
500494
})
501495
})
@@ -623,16 +617,9 @@ pub async fn handle_epoch_pool_stakes_blockfrost(
623617
.await?;
624618
let spdd_response = spdd
625619
.into_iter()
626-
.map(|(key_hash, amount)| {
627-
let stake_address = StakeAddress {
628-
network: network.clone(),
629-
credential: StakeCredential::AddrKeyHash(key_hash),
630-
}
631-
.to_string()
632-
.map_err(|e| anyhow::anyhow!("Failed to convert stake address to string: {e}"))?;
633-
620+
.map(|(stake_address, amount)| {
634621
Ok(SPDDByEpochAndPoolItemRest {
635-
stake_address,
622+
stake_address: stake_address.to_string().unwrap(),
636623
amount,
637624
})
638625
})

modules/rest_blockfrost/src/handlers/governance.rs

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,10 @@ use crate::types::{
44
DRepInfoREST, DRepMetadataREST, DRepUpdateREST, DRepVoteREST, DRepsListREST, ProposalVoteREST,
55
VoterRoleREST,
66
};
7-
use acropolis_common::{
8-
messages::{Message, RESTResponse, StateQuery, StateQueryResponse},
9-
queries::{
10-
accounts::{AccountsStateQuery, AccountsStateQueryResponse},
11-
governance::{GovernanceStateQuery, GovernanceStateQueryResponse},
12-
},
13-
Credential, GovActionId, KeyHash, TxHash, Voter,
14-
};
7+
use acropolis_common::{messages::{Message, RESTResponse, StateQuery, StateQueryResponse}, queries::{
8+
accounts::{AccountsStateQuery, AccountsStateQueryResponse},
9+
governance::{GovernanceStateQuery, GovernanceStateQueryResponse},
10+
}, Credential, GovActionId, StakeAddress, TxHash, Voter};
1511
use anyhow::{anyhow, Result};
1612
use caryatid_sdk::Context;
1713
use reqwest::Client;
@@ -191,16 +187,15 @@ pub async fn handle_drep_delegators_blockfrost(
191187
Message::StateQueryResponse(StateQueryResponse::Governance(
192188
GovernanceStateQueryResponse::DRepDelegators(delegators),
193189
)) => {
194-
let stake_key_to_bech32: HashMap<KeyHash, String> = match delegators
190+
let stake_address_to_bech32: HashMap<StakeAddress, String> = match delegators
195191
.addresses
196192
.iter()
197193
.map(|addr| {
198194
let credential = addr.get_credential();
199195
let bech32 = credential
200196
.to_stake_bech32()
201197
.map_err(|_| anyhow!("Failed to encode stake address"))?;
202-
let key_hash = credential.get_hash();
203-
Ok((key_hash, bech32))
198+
Ok((addr.clone(), bech32))
204199
})
205200
.collect::<Result<HashMap<_, _>>>()
206201
{
@@ -229,8 +224,8 @@ pub async fn handle_drep_delegators_blockfrost(
229224
)) => {
230225
let mut response = Vec::new();
231226

232-
for (key, amount) in map {
233-
let Some(bech32) = stake_key_to_bech32.get(&key) else {
227+
for (stake_address, amount) in map {
228+
let Some(bech32) = stake_address_to_bech32.get(&stake_address) else {
234229
return Ok(RESTResponse::with_text(
235230
500,
236231
"Internal error: missing Bech32 for stake key",

modules/rest_blockfrost/src/handlers/pools.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use acropolis_common::{
1717
utils::query_state,
1818
},
1919
rest_helper::ToCheckedF64,
20-
PoolId, PoolRetirement, PoolUpdateAction, StakeCredential, TxIdentifier,
20+
PoolId, PoolRetirement, PoolUpdateAction, TxIdentifier,
2121
};
2222
use anyhow::Result;
2323
use caryatid_sdk::Context;
@@ -1004,9 +1004,9 @@ pub async fn handle_pool_delegators_blockfrost(
10041004
};
10051005

10061006
let mut delegators_rest = Vec::<PoolDelegatorRest>::new();
1007-
for (d, l) in pool_delegators {
1008-
let bech32 = StakeCredential::AddrKeyHash(d.clone())
1009-
.to_stake_bech32()
1007+
for (stake_address, l) in pool_delegators {
1008+
let bech32 = stake_address
1009+
.to_string()
10101010
.map_err(|e| anyhow::anyhow!("Invalid stake address in pool delegators: {e}"))?;
10111011
delegators_rest.push(PoolDelegatorRest {
10121012
address: bech32,

0 commit comments

Comments
 (0)