Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 12 additions & 25 deletions common/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@

use crate::cip19::{VarIntDecoder, VarIntEncoder};
use crate::types::{KeyHash, ScriptHash};
use crate::Credential;
use crate::{Credential, NetworkId};
use anyhow::{anyhow, bail, Result};
use serde_with::{hex::Hex, serde_as};
use std::borrow::Borrow;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};

/// a Byron-era address
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
Expand All @@ -28,6 +26,15 @@ pub enum AddressNetwork {
Test,
}

impl From<NetworkId> for AddressNetwork {
fn from(network: NetworkId) -> Self {
match network {
NetworkId::Mainnet => Self::Main,
NetworkId::Testnet => Self::Test,
}
}
}

impl Default for AddressNetwork {
fn default() -> Self {
Self::Main
Expand Down Expand Up @@ -201,7 +208,7 @@ impl StakeAddressPayload {
}

/// A stake address
#[derive(Debug, Clone, Eq, serde::Serialize, serde::Deserialize)]
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct StakeAddress {
/// Network id
pub network: AddressNetwork,
Expand All @@ -211,7 +218,7 @@ pub struct StakeAddress {
}

impl StakeAddress {
pub fn new(network: AddressNetwork, payload: StakeAddressPayload) -> Self {
pub fn new(payload: StakeAddressPayload, network: AddressNetwork) -> Self {
StakeAddress { network, payload }
}

Expand Down Expand Up @@ -305,26 +312,6 @@ impl Display for StakeAddress {
}
}

impl Hash for StakeAddress {
fn hash<H: Hasher>(&self, state: &mut H) {
self.network.hash(state);
std::mem::discriminant(&self.payload).hash(state);
self.get_hash().hash(state);
}
}

impl Borrow<[u8]> for StakeAddress {
fn borrow(&self) -> &[u8] {
self.get_hash()
}
}

impl PartialEq for StakeAddress {
fn eq(&self, other: &Self) -> bool {
self.network == other.network && self.payload == other.payload
}
}

impl<C> minicbor::Encode<C> for StakeAddress {
fn encode<W: minicbor::encode::Write>(
&self,
Expand Down
6 changes: 3 additions & 3 deletions common/src/queries/governance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;

use crate::{Anchor, Credential, DRepCredential, GovActionId, Lovelace, ProposalProcedure, TxHash, Vote, Voter, VotingProcedure};
use crate::{Anchor, DRepCredential, GovActionId, Lovelace, ProposalProcedure, StakeAddress, TxHash, Vote, Voter, VotingProcedure};

pub const DEFAULT_DREPS_QUERY_TOPIC: (&str, &str) =
("drep-state-query-topic", "cardano.query.dreps");
Expand Down Expand Up @@ -58,12 +58,12 @@ pub struct DRepInfo {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DRepInfoWithDelegators {
pub info: DRepInfo,
pub delegators: Vec<Credential>,
pub delegators: Vec<StakeAddress>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DRepDelegatorAddresses {
pub addresses: Vec<Credential>,
pub addresses: Vec<StakeAddress>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Expand Down
2 changes: 1 addition & 1 deletion common/src/stake_addresses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,10 +528,10 @@ mod tests {

fn create_stake_address(hash: &[u8]) -> StakeAddress {
StakeAddress::new(
AddressNetwork::Main,
StakeAddressPayload::StakeKeyHash(
hash.to_vec().try_into().expect("Invalid hash length"),
),
AddressNetwork::Main,
)
}

Expand Down
67 changes: 31 additions & 36 deletions common/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::{
address::{Address, ShelleyAddress, StakeAddress},
protocol_params,
rational_number::RationalNumber,
AddressNetwork, StakeAddressPayload,
};
use anyhow::{anyhow, bail, Error, Result};
use bech32::{Bech32, Hrp};
Expand All @@ -26,6 +25,16 @@ pub enum NetworkId {
Mainnet,
}

impl From<String> for NetworkId {
fn from(s: String) -> Self {
match s.as_str() {
"testnet" => NetworkId::Testnet,
"mainnet" => NetworkId::Mainnet,
_ => NetworkId::Mainnet,
}
}
}

/// Protocol era
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
Expand Down Expand Up @@ -613,20 +622,6 @@ impl Credential {

pub type StakeCredential = Credential;

impl StakeCredential {
pub fn to_stake_address(&self, network: Option<AddressNetwork>) -> StakeAddress {
let payload = match self {
StakeCredential::AddrKeyHash(hash) => StakeAddressPayload::StakeKeyHash(
hash.clone().try_into().expect("Invalid hash length"),
),
StakeCredential::ScriptHash(hash) => StakeAddressPayload::ScriptHash(
hash.clone().try_into().expect("Invalid hash length"),
),
};
StakeAddress::new(network.unwrap_or(AddressNetwork::Main), payload)
}
}

/// Relay single host address
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub struct SingleHostAddr {
Expand Down Expand Up @@ -739,7 +734,7 @@ pub struct PoolRegistration {
/// Pool owners by their key hash
// #[serde_as(as = "Vec<Hex>")]
#[n(6)]
pub pool_owners: Vec<Credential>,
pub pool_owners: Vec<StakeAddress>,

// Relays
#[n(7)]
Expand Down Expand Up @@ -824,8 +819,8 @@ pub struct PoolEpochState {
/// Stake delegation data
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StakeDelegation {
/// Stake credential
pub credential: StakeCredential,
/// Stake address
pub stake_address: StakeAddress,

/// Pool ID to delegate to
pub operator: KeyHash,
Expand Down Expand Up @@ -877,7 +872,7 @@ pub enum InstantaneousRewardSource {
/// Target of a MIR
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum InstantaneousRewardTarget {
StakeCredentials(Vec<(StakeCredential, i64)>),
StakeAddresses(Vec<(StakeAddress, i64)>),
OtherAccountingPot(u64),
}

Expand All @@ -894,8 +889,8 @@ pub struct MoveInstantaneousReward {
/// Register stake (Conway version) = 'reg_cert'
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Registration {
/// Stake credential
pub credential: StakeCredential,
/// Stake address
pub stake_address: StakeAddress,

/// Deposit paid
pub deposit: Lovelace,
Expand All @@ -904,8 +899,8 @@ pub struct Registration {
/// Deregister stake (Conway version) = 'unreg_cert'
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Deregistration {
/// Stake credential
pub credential: StakeCredential,
/// Stake address
pub stake_address: StakeAddress,

/// Deposit to be refunded
pub refund: Lovelace,
Expand All @@ -930,8 +925,8 @@ pub enum DRepChoice {
/// Vote delegation (simple, existing registration) = vote_deleg_cert
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VoteDelegation {
/// Stake credential
pub credential: StakeCredential,
/// Stake address
pub stake_address: StakeAddress,

// DRep choice
pub drep: DRepChoice,
Expand All @@ -940,8 +935,8 @@ pub struct VoteDelegation {
/// Stake+vote delegation (to SPO and DRep) = stake_vote_deleg_cert
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StakeAndVoteDelegation {
/// Stake credential
pub credential: StakeCredential,
/// Stake address
pub stake_address: StakeAddress,

/// Pool
pub operator: KeyHash,
Expand All @@ -953,8 +948,8 @@ pub struct StakeAndVoteDelegation {
/// Stake delegation to SPO + registration = stake_reg_deleg_cert
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StakeRegistrationAndDelegation {
/// Stake credential
pub credential: StakeCredential,
/// Stake address
pub stake_address: StakeAddress,

/// Pool
pub operator: KeyHash,
Expand All @@ -966,8 +961,8 @@ pub struct StakeRegistrationAndDelegation {
/// Vote delegation to DRep + registration = vote_reg_deleg_cert
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StakeRegistrationAndVoteDelegation {
/// Stake credential
pub credential: StakeCredential,
/// Stake address
pub stake_address: StakeAddress,

/// DRep choice
pub drep: DRepChoice,
Expand All @@ -982,7 +977,7 @@ pub struct StakeRegistrationAndVoteDelegation {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StakeRegistrationAndStakeAndVoteDelegation {
/// Stake credential
pub credential: StakeCredential,
pub stake_address: StakeAddress,

/// Pool
pub operator: KeyHash,
Expand Down Expand Up @@ -1660,8 +1655,8 @@ pub struct GovernanceOutcome {
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StakeCredentialWithPos {
pub stake_credential: StakeCredential,
pub struct StakeAddressWithPos {
pub stake_address: StakeAddress,
pub tx_index: u64,
pub cert_index: u64,
}
Expand All @@ -1673,10 +1668,10 @@ pub enum TxCertificate {
None(()),

/// Stake registration
StakeRegistration(StakeCredentialWithPos),
StakeRegistration(StakeAddressWithPos),

/// Stake de-registration
StakeDeregistration(StakeCredential),
StakeDeregistration(StakeAddress),

/// Stake Delegation to a pool
StakeDelegation(StakeDelegation),
Expand Down
3 changes: 1 addition & 2 deletions modules/accounts_state/src/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,6 @@ fn calculate_spo_rewards(
if !to_delegators.is_zero() {
let total_stake = BigDecimal::from(spo.total_stake);
for (delegator_stake_address, stake) in &spo.delegators {
let delegator_credential = delegator_stake_address.get_credential();
let proportion = BigDecimal::from(stake) / &total_stake;

// and hence how much of the total reward they get
Expand All @@ -346,7 +345,7 @@ fn calculate_spo_rewards(
delegator_stake_address);

// Pool owners don't get member rewards (seems unfair!)
if spo.pool_owners.contains(&delegator_credential) {
if spo.pool_owners.contains(&delegator_stake_address) {
debug!(
"Skipping pool owner reward account {}, losing {to_pay}",
delegator_stake_address
Expand Down
20 changes: 10 additions & 10 deletions modules/accounts_state/src/snapshot.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Acropolis AccountsState: snapshot for rewards calculations

use crate::state::{Pots, RegistrationChange};
use acropolis_common::{stake_addresses::StakeAddressMap, Credential, KeyHash, Lovelace, PoolRegistration, Ratio, StakeAddress};
use acropolis_common::{stake_addresses::StakeAddressMap, KeyHash, Lovelace, PoolRegistration, Ratio, StakeAddress};
use imbl::OrdMap;
use std::collections::HashMap;
use std::sync::Arc;
Expand Down Expand Up @@ -35,7 +35,7 @@ pub struct SnapshotSPO {
pub two_previous_reward_account_is_registered: bool,

/// Pool owners
pub pool_owners: Vec<Credential>,
pub pool_owners: Vec<StakeAddress>,
}

/// Snapshot of stake distribution taken at the end of an particular epoch
Expand Down Expand Up @@ -159,18 +159,18 @@ impl Snapshot {
pub fn get_stake_delegated_to_spo_by_addresses(
&self,
spo: &KeyHash,
addresses: &[Credential],
addresses: &[StakeAddress],
) -> Lovelace {
let Some(snapshot_spo) = self.spos.get(spo) else {
return 0;
};

let addr_set: std::collections::HashSet<_> = addresses.iter().collect();
let address_set: std::collections::HashSet<_> = addresses.iter().collect();
snapshot_spo
.delegators
.iter()
.filter_map(|(addr, amount)| {
if addr_set.contains(&addr.get_credential()) {
.filter_map(|(address, amount)| {
if address_set.contains(&address) {
Some(*amount)
} else {
None
Expand Down Expand Up @@ -321,9 +321,9 @@ mod tests {

// Extract key hashes from stake addresses for the API call
let addresses = vec![
addr2.get_credential(),
addr3.get_credential(),
addr4.get_credential(),
addr2,
addr3,
addr4,
];
let result = snapshot.get_stake_delegated_to_spo_by_addresses(&spo1, &addresses);
assert_eq!(result, 500);
Expand All @@ -347,7 +347,7 @@ mod tests {
);

// Extract key hash from stake address for the API call
let addresses = vec![addr_x.get_credential()];
let addresses = vec![addr_x];
let result = snapshot.get_stake_delegated_to_spo_by_addresses(&spo1, &addresses);
assert_eq!(result, 0);
}
Expand Down
Loading