Skip to content

Commit fe8c1c9

Browse files
committed
### Description
Resolves issue #163 This adds `NetworkId` into the `BlockInfo` struct, and introduces this identifier into the account state, drep state, epochs state and rest_blockfrost as these all rely on querying the `StakeAddressMap`.
1 parent 32045af commit fe8c1c9

File tree

23 files changed

+164
-104
lines changed

23 files changed

+164
-104
lines changed

common/src/address.rs

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,10 @@
44

55
use crate::cip19::{VarIntDecoder, VarIntEncoder};
66
use crate::types::{KeyHash, ScriptHash};
7-
use crate::Credential;
7+
use crate::{Credential, NetworkId};
88
use anyhow::{anyhow, bail, Result};
99
use serde_with::{hex::Hex, serde_as};
10-
use std::borrow::Borrow;
1110
use std::fmt::{Display, Formatter};
12-
use std::hash::{Hash, Hasher};
1311

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

29+
impl From<NetworkId> for AddressNetwork {
30+
fn from(network: NetworkId) -> Self {
31+
match network {
32+
NetworkId::Mainnet => Self::Main,
33+
NetworkId::Testnet => Self::Test,
34+
}
35+
}
36+
}
37+
3138
impl Default for AddressNetwork {
3239
fn default() -> Self {
3340
Self::Main
@@ -201,7 +208,7 @@ impl StakeAddressPayload {
201208
}
202209

203210
/// A stake address
204-
#[derive(Debug, Clone, Eq, serde::Serialize, serde::Deserialize)]
211+
#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
205212
pub struct StakeAddress {
206213
/// Network id
207214
pub network: AddressNetwork,
@@ -211,7 +218,7 @@ pub struct StakeAddress {
211218
}
212219

213220
impl StakeAddress {
214-
pub fn new(network: AddressNetwork, payload: StakeAddressPayload) -> Self {
221+
pub fn new(payload: StakeAddressPayload, network: AddressNetwork) -> Self {
215222
StakeAddress { network, payload }
216223
}
217224

@@ -305,26 +312,6 @@ impl Display for StakeAddress {
305312
}
306313
}
307314

308-
impl Hash for StakeAddress {
309-
fn hash<H: Hasher>(&self, state: &mut H) {
310-
self.network.hash(state);
311-
std::mem::discriminant(&self.payload).hash(state);
312-
self.get_hash().hash(state);
313-
}
314-
}
315-
316-
impl Borrow<[u8]> for StakeAddress {
317-
fn borrow(&self) -> &[u8] {
318-
self.get_hash()
319-
}
320-
}
321-
322-
impl PartialEq for StakeAddress {
323-
fn eq(&self, other: &Self) -> bool {
324-
self.network == other.network && self.payload == other.payload
325-
}
326-
}
327-
328315
impl<C> minicbor::Encode<C> for StakeAddress {
329316
fn encode<W: minicbor::encode::Write>(
330317
&self,

common/src/stake_addresses.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,10 +528,10 @@ mod tests {
528528

529529
fn create_stake_address(hash: &[u8]) -> StakeAddress {
530530
StakeAddress::new(
531-
AddressNetwork::Main,
532531
StakeAddressPayload::StakeKeyHash(
533532
hash.to_vec().try_into().expect("Invalid hash length"),
534533
),
534+
AddressNetwork::Main,
535535
)
536536
}
537537

common/src/types.rs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ pub enum NetworkId {
2626
Mainnet,
2727
}
2828

29+
impl From<String> for NetworkId {
30+
fn from(s: String) -> Self {
31+
match s.as_str() {
32+
"testnet" => NetworkId::Testnet,
33+
"mainnet" => NetworkId::Mainnet,
34+
_ => NetworkId::Mainnet,
35+
}
36+
}
37+
}
38+
2939
/// Protocol era
3040
#[derive(
3141
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
@@ -120,6 +130,9 @@ pub struct BlockInfo {
120130
#[serde(default)]
121131
pub timestamp: u64,
122132

133+
/// Network ID
134+
pub network_id: NetworkId,
135+
123136
/// Protocol era
124137
pub era: Era,
125138
}
@@ -614,7 +627,7 @@ impl Credential {
614627
pub type StakeCredential = Credential;
615628

616629
impl StakeCredential {
617-
pub fn to_stake_address(&self, network: Option<AddressNetwork>) -> StakeAddress {
630+
pub fn to_stake_address(&self, network: AddressNetwork) -> StakeAddress {
618631
let payload = match self {
619632
StakeCredential::AddrKeyHash(hash) => StakeAddressPayload::StakeKeyHash(
620633
hash.clone().try_into().expect("Invalid hash length"),
@@ -623,7 +636,7 @@ impl StakeCredential {
623636
hash.clone().try_into().expect("Invalid hash length"),
624637
),
625638
};
626-
StakeAddress::new(network.unwrap_or(AddressNetwork::Main), payload)
639+
StakeAddress::new(payload, network)
627640
}
628641
}
629642

modules/accounts_state/src/snapshot.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,12 +165,12 @@ impl Snapshot {
165165
return 0;
166166
};
167167

168-
let addr_set: std::collections::HashSet<_> = addresses.iter().collect();
168+
let address_set: std::collections::HashSet<_> = addresses.iter().collect();
169169
snapshot_spo
170170
.delegators
171171
.iter()
172-
.filter_map(|(addr, amount)| {
173-
if addr_set.contains(&addr.get_credential()) {
172+
.filter_map(|(address, amount)| {
173+
if address_set.contains(&address.get_credential()) {
174174
Some(*amount)
175175
} else {
176176
None

modules/accounts_state/src/state.rs

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ use acropolis_common::{
1414
protocol_params::ProtocolParams,
1515
stake_addresses::{StakeAddressMap, StakeAddressState},
1616
BlockInfo, DRepChoice, DRepCredential, DelegatedStake, InstantaneousRewardSource,
17-
InstantaneousRewardTarget, KeyHash, Lovelace, MoveInstantaneousReward, PoolLiveStakeInfo,
18-
PoolRegistration, Pot, SPORewards, StakeAddress, StakeCredential, StakeRewardDelta,
19-
TxCertificate,
17+
InstantaneousRewardTarget, KeyHash, Lovelace, MoveInstantaneousReward, NetworkId,
18+
PoolLiveStakeInfo, PoolRegistration, Pot, SPORewards, StakeAddress, StakeCredential,
19+
StakeRewardDelta, TxCertificate,
2020
};
2121
use anyhow::Result;
2222
use imbl::OrdMap;
@@ -95,6 +95,9 @@ pub struct State {
9595
/// List of SPOs (by operator ID) retiring in the current epoch
9696
retiring_spos: Vec<KeyHash>,
9797

98+
/// Network ID
99+
network_id: NetworkId,
100+
98101
/// Map of staking address values
99102
/// Wrapped in an Arc so it doesn't get cloned in full by StateHistory
100103
stake_addresses: Arc<Mutex<StakeAddressMap>>,
@@ -550,7 +553,8 @@ impl State {
550553
// Transfer to (in theory also from) stake addresses from (to) a pot
551554
let mut total_value: u64 = 0;
552555
for (credential, value) in deltas.iter() {
553-
let stake_address = credential.to_stake_address(None); // Need to convert credential to address
556+
let stake_address =
557+
credential.to_stake_address(self.network_id.clone().into());
554558

555559
// Get old stake address state, or create one
556560
let mut stake_addresses = self.stake_addresses.lock().unwrap();
@@ -792,8 +796,8 @@ impl State {
792796

793797
/// Register a stake address, with a specified deposit if known
794798
fn register_stake_address(&mut self, credential: &StakeCredential, deposit: Option<Lovelace>) {
795-
// TODO: Handle network
796-
let stake_address = credential.to_stake_address(None);
799+
800+
let stake_address = credential.to_stake_address(self.network_id.clone().into());
797801

798802
// Stake addresses can be registered after being used in UTXOs
799803
let mut stake_addresses = self.stake_addresses.lock().unwrap();
@@ -823,8 +827,8 @@ impl State {
823827

824828
/// Deregister a stake address, with specified refund if known
825829
fn deregister_stake_address(&mut self, credential: &StakeCredential, refund: Option<Lovelace>) {
826-
// TODO: Handle network
827-
let stake_address = credential.to_stake_address(None);
830+
831+
let stake_address = credential.to_stake_address(self.network_id.clone().into());
828832

829833
// Check if it existed
830834
let mut stake_addresses = self.stake_addresses.lock().unwrap();
@@ -860,8 +864,8 @@ impl State {
860864

861865
/// Record a stake delegation
862866
fn record_stake_delegation(&mut self, credential: &StakeCredential, spo: &KeyHash) {
863-
// TODO: Handle network
864-
let stake_address = credential.to_stake_address(None);
867+
868+
let stake_address = credential.to_stake_address(self.network_id.clone().into());
865869
let mut stake_addresses = self.stake_addresses.lock().unwrap();
866870
stake_addresses.record_stake_delegation(&stake_address, spo);
867871
}
@@ -874,8 +878,8 @@ impl State {
874878

875879
/// record a drep delegation
876880
fn record_drep_delegation(&mut self, credential: &StakeCredential, drep: &DRepChoice) {
877-
// TODO: Handle network
878-
let stake_address = credential.to_stake_address(None);
881+
882+
let stake_address = credential.to_stake_address(self.network_id.clone().into());
879883
let mut stake_addresses = self.stake_addresses.lock().unwrap();
880884
stake_addresses.record_drep_delegation(&stake_address, drep);
881885
}

modules/drep_state/src/state.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use acropolis_common::{messages::{Message, StateQuery, StateQueryResponse}, quer
44
accounts::{AccountsStateQuery, AccountsStateQueryResponse, DEFAULT_ACCOUNTS_QUERY_TOPIC},
55
get_query_topic,
66
governance::{DRepActionUpdate, DRepUpdateEvent, VoteRecord},
7-
}, Anchor, Credential, DRepChoice, DRepCredential, KeyHash, Lovelace, StakeAddress, StakeCredential, TxCertificate, TxHash, Voter, VotingProcedures};
7+
}, Anchor, Credential, DRepChoice, DRepCredential, KeyHash, Lovelace, NetworkId, StakeAddress, StakeCredential, TxCertificate, TxHash, Voter, VotingProcedures};
88
use anyhow::{anyhow, Result};
99
use caryatid_sdk::Context;
1010
use serde_with::serde_as;
@@ -89,6 +89,7 @@ impl DRepStorageConfig {
8989
pub struct State {
9090
pub config: DRepStorageConfig,
9191
pub dreps: HashMap<DRepCredential, DRepRecord>,
92+
pub network_id: NetworkId,
9293
pub historical_dreps: Option<HashMap<DRepCredential, HistoricalDRepState>>,
9394
}
9495

@@ -97,6 +98,7 @@ impl State {
9798
Self {
9899
config,
99100
dreps: HashMap::new(),
101+
network_id: NetworkId::default(),
100102
historical_dreps: if config.any_enabled() {
101103
Some(HashMap::new())
102104
} else {
@@ -470,8 +472,7 @@ impl State {
470472
delegators: Vec<(&StakeCredential, &DRepChoice)>,
471473
) -> Result<()> {
472474
let stake_keys: Vec<KeyHash> = delegators.iter().map(|(sc, _)| sc.get_hash()).collect();
473-
// TODO: USE NETWORK ID
474-
let stake_addresses: Vec<StakeAddress> = delegators.iter().map(|(k, _) | k.to_stake_address(None) ).collect();
475+
let stake_addresses: Vec<StakeAddress> = delegators.iter().map(|(k, _) | k.to_stake_address(self.network_id.clone().into()) ).collect();
475476
let stake_key_to_input: HashMap<KeyHash, _> = delegators
476477
.iter()
477478
.zip(&stake_keys)

modules/epochs_state/src/epochs_history.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ impl EpochsHistoryState {
7878
#[cfg(test)]
7979
mod tests {
8080
use super::*;
81-
use acropolis_common::{BlockHash, BlockStatus, Era};
81+
use acropolis_common::{BlockHash, BlockStatus, Era, NetworkId};
8282

8383
fn make_block(epoch: u64) -> BlockInfo {
8484
BlockInfo {
@@ -89,6 +89,7 @@ mod tests {
8989
epoch,
9090
epoch_slot: 99,
9191
new_epoch: false,
92+
network_id: NetworkId::default(),
9293
timestamp: 99999,
9394
era: Era::Conway,
9495
}

modules/epochs_state/src/state.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ mod tests {
269269
crypto::keyhash_224,
270270
protocol_params::{Nonce, NonceHash},
271271
state_history::{StateHistory, StateHistoryStore},
272-
BlockHash, BlockInfo, BlockStatus, Era,
272+
BlockHash, BlockInfo, BlockStatus, Era, NetworkId,
273273
};
274274
use tokio::sync::Mutex;
275275

@@ -281,6 +281,7 @@ mod tests {
281281
hash: BlockHash::default(),
282282
epoch,
283283
epoch_slot: 99,
284+
network_id: NetworkId::default(),
284285
new_epoch: false,
285286
timestamp: 99999,
286287
era: Era::Shelley,
@@ -295,6 +296,7 @@ mod tests {
295296
hash: BlockHash::default(),
296297
epoch,
297298
epoch_slot: 99,
299+
network_id: NetworkId::default(),
298300
new_epoch: true,
299301
timestamp: 99999,
300302
era: Era::Shelley,
@@ -309,6 +311,7 @@ mod tests {
309311
hash: BlockHash::default(),
310312
epoch,
311313
epoch_slot: 99,
314+
network_id: NetworkId::default(),
312315
new_epoch: false,
313316
timestamp: 99999,
314317
era: Era::Conway,

modules/genesis_bootstrapper/src/genesis_bootstrapper.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ use acropolis_common::{
77
CardanoMessage, GenesisCompleteMessage, GenesisUTxOsMessage, Message, PotDeltasMessage,
88
UTXODeltasMessage,
99
},
10-
Address, BlockHash, BlockInfo, BlockStatus, ByronAddress, Era, Lovelace, LovelaceDelta, Pot,
11-
PotDelta, TxIdentifier, TxOutRef, TxOutput, UTXODelta, UTxOIdentifier, Value,
10+
Address, BlockHash, BlockInfo, BlockStatus, ByronAddress, Era, Lovelace, LovelaceDelta,
11+
NetworkId, Pot, PotDelta, TxIdentifier, TxOutRef, TxOutput, UTXODelta, UTxOIdentifier, Value,
1212
};
1313
use anyhow::Result;
1414
use blake2::{digest::consts::U32, Blake2b, Digest};
@@ -128,6 +128,7 @@ impl GenesisBootstrapper {
128128
hash: BlockHash::default(),
129129
epoch: 0,
130130
epoch_slot: 0,
131+
network_id: NetworkId::from(network_name),
131132
new_epoch: false,
132133
timestamp: byron_genesis.start_time,
133134
era: Era::Byron,

modules/governance_state/src/alonzo_babbage_voting.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ mod tests {
113113
use crate::alonzo_babbage_voting::AlonzoBabbageVoting;
114114
use acropolis_common::{
115115
rational_number::rational_number_from_f32, AlonzoBabbageUpdateProposal,
116-
AlonzoBabbageVotingOutcome, BlockHash, BlockInfo, BlockStatus, GenesisKeyhash,
116+
AlonzoBabbageVotingOutcome, BlockHash, BlockInfo, BlockStatus, GenesisKeyhash, NetworkId,
117117
ProtocolParamUpdate,
118118
};
119119
use anyhow::Result;
@@ -154,6 +154,7 @@ mod tests {
154154
epoch,
155155
epoch_slot: 0,
156156
era: era.try_into()?,
157+
network_id: NetworkId::default(),
157158
new_epoch: new_epoch != 0,
158159
timestamp: 0,
159160
hash: BlockHash::default(),

0 commit comments

Comments
 (0)