Skip to content

Commit fb77f49

Browse files
committed
Refactor: Replace manual key hash conversions with type-safe utilities, update imports, and adjust serialization logic across modules for consistency.
1 parent f77d2dc commit fb77f49

File tree

10 files changed

+50
-55
lines changed

10 files changed

+50
-55
lines changed

codec/src/map_parameters.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ pub fn map_certificate(
327327
}),
328328
alonzo::Certificate::PoolRetirement(pool_key_hash, epoch) => Ok(TxCertificateWithPos {
329329
cert: TxCertificate::PoolRetirement(PoolRetirement {
330-
operator: pool_key_hash.to_vec(),
330+
operator: to_pool_id(pool_key_hash),
331331
epoch: *epoch,
332332
}),
333333
tx_identifier,
@@ -395,7 +395,7 @@ pub fn map_certificate(
395395
Ok(TxCertificateWithPos {
396396
cert: TxCertificate::StakeDelegation(StakeDelegation {
397397
stake_address: map_stake_address(cred, network_id),
398-
operator: pool_key_hash.to_vec(),
398+
operator: to_pool_id(pool_key_hash),
399399
}),
400400
tx_identifier,
401401
cert_index: cert_index.try_into().unwrap(),
@@ -415,8 +415,8 @@ pub fn map_certificate(
415415
pool_metadata,
416416
} => Ok(TxCertificateWithPos {
417417
cert: TxCertificate::PoolRegistration(PoolRegistration {
418-
operator: operator.to_vec(),
419-
vrf_key_hash: vrf_keyhash.to_vec(),
418+
operator: to_pool_id(operator),
419+
vrf_key_hash: to_vrf_key(vrf_keyhash),
420420
pledge: *pledge,
421421
cost: *cost,
422422
margin: Ratio {
@@ -435,7 +435,7 @@ pub fn map_certificate(
435435
.into_iter()
436436
.map(|v| {
437437
StakeAddress::new(
438-
StakeCredential::AddrKeyHash(v.to_vec()),
438+
StakeCredential::AddrKeyHash(to_hash(v)),
439439
network_id.clone(),
440440
)
441441
})
@@ -455,7 +455,7 @@ pub fn map_certificate(
455455
conway::Certificate::PoolRetirement(pool_key_hash, epoch) => {
456456
Ok(TxCertificateWithPos {
457457
cert: TxCertificate::PoolRetirement(PoolRetirement {
458-
operator: pool_key_hash.to_vec(),
458+
operator: to_pool_id(pool_key_hash),
459459
epoch: *epoch,
460460
}),
461461
tx_identifier,
@@ -494,7 +494,7 @@ pub fn map_certificate(
494494
Ok(TxCertificateWithPos {
495495
cert: TxCertificate::StakeAndVoteDelegation(StakeAndVoteDelegation {
496496
stake_address: map_stake_address(cred, network_id),
497-
operator: pool_key_hash.to_vec(),
497+
operator: to_pool_id(pool_key_hash),
498498
drep: map_drep(drep),
499499
}),
500500
tx_identifier,
@@ -507,7 +507,7 @@ pub fn map_certificate(
507507
cert: TxCertificate::StakeRegistrationAndDelegation(
508508
StakeRegistrationAndDelegation {
509509
stake_address: map_stake_address(cred, network_id),
510-
operator: pool_key_hash.to_vec(),
510+
operator: to_pool_id(pool_key_hash),
511511
deposit: *coin,
512512
},
513513
),
@@ -533,7 +533,7 @@ pub fn map_certificate(
533533
cert: TxCertificate::StakeRegistrationAndStakeAndVoteDelegation(
534534
StakeRegistrationAndStakeAndVoteDelegation {
535535
stake_address: map_stake_address(cred, network_id),
536-
operator: pool_key_hash.to_vec(),
536+
operator: to_pool_id(pool_key_hash),
537537
drep: map_drep(drep),
538538
deposit: *coin,
539539
},

common/src/address.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ impl StakeAddress {
398398
NetworkId::Testnet => bech32::Hrp::parse("stake_test")?,
399399
};
400400

401-
let data = self.to_binary()?;
401+
let data = self.to_binary();
402402
Ok(bech32::encode::<bech32::Bech32>(hrp, &data.as_slice())?)
403403
}
404404

@@ -431,20 +431,20 @@ impl StakeAddress {
431431
}
432432

433433
/// Convert to binary format (29 bytes)
434-
pub fn to_binary(&self) -> Result<Vec<u8>> {
434+
pub fn to_binary(&self) -> Vec<u8> {
435435
let network_bits = match self.network {
436436
NetworkId::Mainnet => 0b1u8,
437437
NetworkId::Testnet => 0b0u8,
438438
};
439439

440-
let (stake_bits, stake_hash): (u8, &KeyHash) = match &self.credential {
441-
StakeCredential::AddrKeyHash(data) => (0b1110, data),
442-
StakeCredential::ScriptHash(data) => (0b1111, data),
440+
let (stake_bits, stake_hash): (u8, &Vec<u8>) = match &self.credential {
441+
StakeCredential::AddrKeyHash(data) => (0b1110, &data.to_vec()),
442+
StakeCredential::ScriptHash(data) => (0b1111, &data.to_vec()),
443443
};
444444

445445
let mut data = vec![network_bits | (stake_bits << 4)];
446-
data.extend(stake_hash.as_ref());
447-
data.try_into().map_err(|_| anyhow!("Invalid hash size for stake address"))
446+
data.extend(stake_hash);
447+
data
448448
}
449449

450450
/// Read from binary format (29 bytes)
@@ -505,9 +505,7 @@ impl<C> minicbor::Encode<C> for StakeAddress {
505505
e: &mut minicbor::Encoder<W>,
506506
_ctx: &mut C,
507507
) -> Result<(), minicbor::encode::Error<W::Error>> {
508-
let data = self
509-
.to_binary()
510-
.map_err(|_| minicbor::encode::Error::message("Failed to convert to binary"))?;
508+
let data = self.to_binary();
511509
e.bytes(&data.as_slice())?;
512510
Ok(())
513511
}
@@ -944,7 +942,7 @@ mod tests {
944942
#[test]
945943
fn stake_addresses_encode_mainnet_stake() {
946944
let address = mainnet_stake_address();
947-
let binary = address.to_binary().unwrap();
945+
let binary = address.to_binary();
948946

949947
// CBOR encoding wraps the raw 29-byte stake address in a byte string:
950948
// - 0x58: CBOR major type 2 (byte string) with 1-byte length follows
@@ -965,7 +963,7 @@ mod tests {
965963
fn stake_addresses_decode_mainnet_stake() {
966964
let binary = {
967965
let mut v = vec![0x58, 0x1d];
968-
v.extend_from_slice(&mainnet_stake_address().to_binary().unwrap().as_slice());
966+
v.extend_from_slice(&mainnet_stake_address().to_binary().as_slice());
969967
v
970968
};
971969

common/src/snapshot/pool_params.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
use super::streaming_snapshot::{
1616
cbor, Coin, Nullable, PoolMetadata, Relay, RewardAccount, Set, UnitInterval,
1717
};
18-
use crate::{PoolId, VrfKeyHash};
1918
use crate::types::AddrKeyhash;
19+
use crate::{PoolId, VrfKeyHash};
2020

2121
#[derive(Debug, Clone, PartialEq, Eq)]
2222
pub struct PoolParams {

modules/accounts_state/src/snapshot.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,15 +195,15 @@ mod tests {
195195
use super::*;
196196
use acropolis_common::stake_addresses::StakeAddressState;
197197
use acropolis_common::NetworkId::Mainnet;
198-
use acropolis_common::{PoolId, StakeAddress, StakeCredential};
198+
use acropolis_common::{KeyHash, PoolId, StakeAddress, StakeCredential};
199199

200200
// Helper function to create stake addresses for testing
201201
fn create_test_stake_address(id: u8) -> StakeAddress {
202-
let mut hash = vec![0u8; 28];
202+
let mut hash = [0u8; 28];
203203
hash[0] = id;
204204
StakeAddress {
205205
network: Mainnet,
206-
credential: StakeCredential::AddrKeyHash(hash),
206+
credential: StakeCredential::AddrKeyHash(KeyHash::new(hash)),
207207
}
208208
}
209209

modules/accounts_state/src/state.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -993,14 +993,14 @@ impl State {
993993
#[cfg(test)]
994994
mod tests {
995995
use super::*;
996-
use acropolis_common::crypto::keyhash_256;
996+
use acropolis_common::crypto::{keyhash_224, keyhash_256};
997997
use acropolis_common::{
998998
protocol_params::ConwayParams, rational_number::RationalNumber, Anchor, Committee,
999999
Constitution, CostModel, DRepVotingThresholds, NetworkId, PoolVotingThresholds, Pot,
10001000
PotDelta, Ratio, Registration, StakeAddress, StakeAddressDelta, StakeAndVoteDelegation,
10011001
StakeCredential, StakeRegistrationAndStakeAndVoteDelegation,
10021002
StakeRegistrationAndVoteDelegation, TxCertificateWithPos, TxIdentifier, VoteDelegation,
1003-
Withdrawal,
1003+
VrfKeyHash, Withdrawal,
10041004
};
10051005

10061006
// Helper to create a StakeAddress from a byte slice
@@ -1392,10 +1392,7 @@ mod tests {
13921392

13931393
// Get the KeyHash once
13941394
let spo1_hash = spo1.get_hash();
1395-
13961395
let drep_key_hash = test_keyhash_from_bytes(&DREP_HASH);
1397-
let drep_script_hash = test_keyhash_from_bytes(&DREP_HASH);
1398-
13991396
let pool_id_1 = PoolId::new(*spo1_hash);
14001397

14011398
let certificates = vec![
@@ -1419,16 +1416,16 @@ mod tests {
14191416
TxCertificateWithPos {
14201417
cert: TxCertificate::VoteDelegation(VoteDelegation {
14211418
stake_address: spo1.clone(),
1422-
drep: DRepChoice::Key(DREP_HASH.to_vec()),
1419+
drep: DRepChoice::Key(drep_key_hash),
14231420
}),
14241421
tx_identifier,
14251422
cert_index: 0,
14261423
},
14271424
TxCertificateWithPos {
14281425
cert: TxCertificate::StakeAndVoteDelegation(StakeAndVoteDelegation {
14291426
stake_address: spo2.clone(),
1430-
operator: spo1.get_hash().to_vec(),
1431-
drep: DRepChoice::Script(DREP_HASH.to_vec()),
1427+
operator: pool_id_1,
1428+
drep: DRepChoice::Script(drep_key_hash),
14321429
}),
14331430
tx_identifier,
14341431
cert_index: 0,
@@ -1448,7 +1445,7 @@ mod tests {
14481445
cert: TxCertificate::StakeRegistrationAndStakeAndVoteDelegation(
14491446
StakeRegistrationAndStakeAndVoteDelegation {
14501447
stake_address: spo4.clone(),
1451-
operator: spo1.get_hash().to_vec(),
1448+
operator: pool_id_1,
14521449
drep: DRepChoice::NoConfidence,
14531450
deposit: 1,
14541451
},

modules/historical_accounts_state/src/immutable_historical_account_store.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,10 @@ impl ImmutableHistoricalAccountStore {
212212
&self,
213213
account: &StakeAddress,
214214
) -> Result<Option<Vec<DelegationUpdate>>> {
215-
let mut immutable_delegations = self
216-
.collect_partition::<DelegationUpdate>(&self.delegation_history, &account.get_hash())?;
215+
let mut immutable_delegations = self.collect_partition::<DelegationUpdate>(
216+
&self.delegation_history,
217+
&account.get_hash().into_inner(),
218+
)?;
217219

218220
self.merge_pending(
219221
account,
@@ -229,8 +231,10 @@ impl ImmutableHistoricalAccountStore {
229231
&self,
230232
account: &StakeAddress,
231233
) -> Result<Option<Vec<AccountWithdrawal>>> {
232-
let mut immutable_mirs =
233-
self.collect_partition::<AccountWithdrawal>(&self.mir_history, &account.get_hash())?;
234+
let mut immutable_mirs = self.collect_partition::<AccountWithdrawal>(
235+
&self.mir_history,
236+
&account.get_hash().into_inner(),
237+
)?;
234238

235239
self.merge_pending(account, |e| e.mir_history.as_ref(), &mut immutable_mirs).await;
236240

@@ -326,7 +330,7 @@ impl ImmutableHistoricalAccountStore {
326330

327331
fn make_epoch_key(account: &StakeAddress, epoch: u32) -> [u8; 32] {
328332
let mut key = [0u8; 32];
329-
key[..28].copy_from_slice(&account.get_credential().get_hash());
333+
key[..28].copy_from_slice(&account.get_credential().get_hash().into_inner());
330334
key[28..32].copy_from_slice(&epoch.to_be_bytes());
331335
key
332336
}

modules/rest_blockfrost/src/handlers/epochs.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ use acropolis_common::{
1515
spdd::{SPDDStateQuery, SPDDStateQueryResponse},
1616
utils::query_state,
1717
},
18-
serialization::Bech32WithHrp,
1918
NetworkId, PoolId, StakeAddress, StakeCredential,
2019
};
2120
use anyhow::{anyhow, Result};

modules/rest_blockfrost/src/handlers/pools.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@ use acropolis_common::{
1717
utils::query_state,
1818
},
1919
rest_helper::ToCheckedF64,
20-
serialization::Bech32WithHrp,
21-
PoolRetirement, PoolUpdateAction, StakeCredential, TxIdentifier,
22-
PoolId, PoolRetirement, PoolUpdateAction, StakeCredential, TxHash,
20+
PoolId, PoolRetirement, PoolUpdateAction, StakeCredential, TxIdentifier,
2321
};
2422
use anyhow::Result;
2523
use caryatid_sdk::Context;

modules/rest_blockfrost/src/types.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use acropolis_common::{
77
rest_helper::ToCheckedF64,
88
serialization::{DisplayFromBech32, PoolPrefix},
99
AssetAddressEntry, AssetMetadataStandard, AssetMintRecord, KeyHash, PolicyAsset,
10-
PoolEpochState, PoolUpdateAction, Relay, TxHash, VrfKeyHash, Vote,
10+
PoolEpochState, PoolUpdateAction, Relay, TxHash, Vote, VrfKeyHash,
1111
};
1212
use anyhow::Result;
1313
use num_traits::ToPrimitive;

modules/spo_state/src/state.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use acropolis_common::{
1010
params::TECHNICAL_PARAMETER_POOL_RETIRE_MAX_EPOCH,
1111
queries::governance::VoteRecord,
1212
stake_addresses::StakeAddressMap,
13-
BlockInfo, KeyHash, PoolMetadata, PoolRetirement, PoolUpdateEvent, Relay,
14-
StakeAddress, TxCertificate, TxIdentifier, Voter, VotingProcedures,
13+
BlockInfo, KeyHash, PoolId, PoolMetadata, PoolRegistration, PoolRetirement, PoolUpdateEvent,
14+
Relay, StakeAddress, TxCertificate, TxHash, TxIdentifier, Voter, VotingProcedures,
1515
};
1616
use anyhow::Result;
1717
use imbl::HashMap;
@@ -671,7 +671,8 @@ mod tests {
671671
use acropolis_common::hash::Hash;
672672
use acropolis_common::{
673673
state_history::{StateHistory, StateHistoryStore},
674-
PoolRetirement, Ratio, StakeAddress, TxCertificate, TxCertificateWithPos, TxIdentifier, VrfKeyHash
674+
PoolRetirement, Ratio, StakeAddress, TxCertificate, TxCertificateWithPos, TxIdentifier,
675+
VrfKeyHash,
675676
};
676677
use tokio::sync::Mutex;
677678

@@ -868,7 +869,7 @@ mod tests {
868869
assert!(state.handle_tx_certs(&block, &msg).is_ok());
869870

870871
assert_eq!(1, state.spos.len());
871-
let spo = state.spos.get(pool_id);
872+
let spo = state.spos.get(&pool_id);
872873
assert!(spo.is_some());
873874

874875
block.number = 1;
@@ -908,7 +909,7 @@ mod tests {
908909
});
909910
assert!(state.handle_tx_certs(&block, &msg).is_ok());
910911
assert_eq!(1, state.spos.len());
911-
let spo = state.spos.get(pool_id);
912+
let spo = state.spos.get(&pool_id);
912913
assert!(spo.is_some());
913914
history.lock().await.commit(block.number, state);
914915

@@ -1038,7 +1039,7 @@ mod tests {
10381039
let mut state = State::new(&save_blocks_store_config());
10391040
let mut block = new_block(0);
10401041
let mut msg = new_certs_msg();
1041-
let spo_id = keyhash_224(&[1_u8]);
1042+
let spo_id = test_pool_id_from_bytes(&[1]);
10421043
msg.certificates.push(TxCertificateWithPos {
10431044
cert: TxCertificate::PoolRegistration(default_pool_registration(spo_id.clone(), None)),
10441045
tx_identifier: TxIdentifier::default(),
@@ -1047,11 +1048,9 @@ mod tests {
10471048
let spo_id = test_pool_id_from_bytes(&[1]);
10481049

10491050
msg.certificates.push(TxCertificateWithPos {
1050-
PoolRegistrationWithPos {
1051-
reg: default_pool_registration(spo_id, None),
1052-
tx_hash: TxHash::default(),
1053-
cert_index: 0,
1054-
},
1051+
cert: TxCertificate::PoolRegistration(default_pool_registration(spo_id.clone(), None)),
1052+
tx_identifier: TxIdentifier::default(),
1053+
cert_index: 0,
10551054
});
10561055
assert!(state.handle_tx_certs(&block, &msg).is_ok());
10571056
block = new_block(2);

0 commit comments

Comments
 (0)