Skip to content

Commit

Permalink
change: Migrate to a common Cardano network type in domain crate (#257)
Browse files Browse the repository at this point in the history
  • Loading branch information
AmbientTea authored Nov 21, 2024
1 parent 2dd19c3 commit f48c0a8
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 95 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 10 additions & 4 deletions toolkit/offchain/src/csl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use ogmios_client::{
transactions::OgmiosBudget,
types::{OgmiosUtxo, OgmiosValue},
};
use sidechain_domain::NetworkType;

pub(crate) fn plutus_script_hash(script_bytes: &[u8], language: LanguageKind) -> [u8; 28] {
// Before hashing the script, we need to prepend with byte denoting the language.
Expand Down Expand Up @@ -43,10 +44,15 @@ pub fn key_hash_address(pub_key_hash: &Ed25519KeyHash, network: NetworkIdKind) -
.to_address()
}

pub fn ogmios_network_to_csl(network: ogmios_client::query_network::Network) -> NetworkIdKind {
match network {
ogmios_client::query_network::Network::Mainnet => NetworkIdKind::Mainnet,
ogmios_client::query_network::Network::Testnet => NetworkIdKind::Testnet,
pub trait NetworkTypeExt {
fn to_csl(&self) -> NetworkIdKind;
}
impl NetworkTypeExt for NetworkType {
fn to_csl(&self) -> NetworkIdKind {
match self {
Self::Mainnet => NetworkIdKind::Mainnet,
Self::Testnet => NetworkIdKind::Testnet,
}
}
}

Expand Down
14 changes: 7 additions & 7 deletions toolkit/offchain/src/scripts_data.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{csl::ogmios_network_to_csl, plutus_script::PlutusScript, OffchainError};
use crate::{csl::NetworkTypeExt, plutus_script::PlutusScript, OffchainError};
use cardano_serialization_lib::{LanguageKind::PlutusV2, NetworkIdKind};
use chain_params::SidechainParams;
use ogmios_client::query_network::QueryNetwork;
Expand Down Expand Up @@ -64,12 +64,12 @@ impl<T: QueryNetwork> GetScriptsData for T {
&self,
pc_params: SidechainParams,
) -> Result<ScriptsData, OffchainError> {
let network = ogmios_network_to_csl(
self.shelley_genesis_configuration()
.await
.map_err(|e| OffchainError::OgmiosError(e.to_string()))?
.network,
);
let network = self
.shelley_genesis_configuration()
.await
.map_err(|e| OffchainError::OgmiosError(e.to_string()))?
.network
.to_csl();
get_scripts_data(pc_params, network)
.map_err(|e| OffchainError::InternalError(e.to_string()))
}
Expand Down
60 changes: 5 additions & 55 deletions toolkit/partner-chains-cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::io::IOContext;
use anyhow::anyhow;
use clap::{arg, Parser};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sidechain_domain::{MainchainAddressHash, UtxoId};
use sidechain_domain::{MainchainAddressHash, NetworkType, UtxoId};
use sp_core::offchain::{Duration, Timestamp};
use std::fmt::{Display, Formatter};
use std::str::FromStr;
Expand Down Expand Up @@ -260,49 +260,6 @@ impl SelectOptions for NetworkProtocol {
}
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardanoNetwork {
Mainnet,
Testnet,
}

impl CardanoNetwork {
pub fn to_network_param(&self) -> String {
match self {
CardanoNetwork::Mainnet => "mainnet".into(),
CardanoNetwork::Testnet => "testnet".into(),
}
}
}

impl From<ogmios_client::query_network::Network> for CardanoNetwork {
fn from(network: ogmios_client::query_network::Network) -> CardanoNetwork {
match network {
ogmios_client::query_network::Network::Mainnet => CardanoNetwork::Mainnet,
ogmios_client::query_network::Network::Testnet => CardanoNetwork::Testnet,
}
}
}

impl From<CardanoNetwork> for cardano_serialization_lib::NetworkIdKind {
fn from(network: CardanoNetwork) -> cardano_serialization_lib::NetworkIdKind {
match network {
CardanoNetwork::Mainnet => cardano_serialization_lib::NetworkIdKind::Mainnet,
CardanoNetwork::Testnet => cardano_serialization_lib::NetworkIdKind::Testnet,
}
}
}

impl std::fmt::Display for CardanoNetwork {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
CardanoNetwork::Mainnet => write!(f, "mainnet"),
CardanoNetwork::Testnet => write!(f, "testnet"),
}
}
}

#[derive(Deserialize)]
pub struct MainChainAddresses {
pub committee_candidates_address: String,
Expand All @@ -318,7 +275,7 @@ pub struct CardanoParameters {
pub first_slot_number: u64,
pub epoch_duration_millis: u64,
pub first_epoch_timestamp_millis: u64,
pub network: CardanoNetwork,
pub network: NetworkType,
}

impl CardanoParameters {
Expand Down Expand Up @@ -415,7 +372,7 @@ pub fn load_chain_config(context: &impl IOContext) -> anyhow::Result<ChainConfig
}
}

pub fn get_cardano_network_from_file(context: &impl IOContext) -> anyhow::Result<CardanoNetwork> {
pub fn get_cardano_network_from_file(context: &impl IOContext) -> anyhow::Result<NetworkType> {
CARDANO_NETWORK.load_from_file(context).ok_or(anyhow!(
"Cardano network not configured. Please run prepare-main-chain-config command first."
))
Expand Down Expand Up @@ -497,7 +454,7 @@ pub mod config_fields {
_marker: PhantomData,
};

pub const CARDANO_NETWORK: ConfigFieldDefinition<'static, CardanoNetwork> =
pub const CARDANO_NETWORK: ConfigFieldDefinition<'static, NetworkType> =
ConfigFieldDefinition {
config_file: CHAIN_CONFIG_FILE_PATH,
path: &["cardano", "network"],
Expand Down Expand Up @@ -731,8 +688,7 @@ pub mod config_values {

#[cfg(test)]
mod tests {
use crate::config::{config_fields::GOVERNANCE_AUTHORITY, CardanoNetwork};
use cardano_serialization_lib::NetworkIdKind;
use crate::config::config_fields::GOVERNANCE_AUTHORITY;
use sidechain_domain::MainchainAddressHash;

#[test]
Expand All @@ -756,10 +712,4 @@ mod tests {
))
);
}

#[test]
fn test_from_network_id() {
assert_eq!(NetworkIdKind::from(CardanoNetwork::Mainnet), NetworkIdKind::Mainnet);
assert_eq!(NetworkIdKind::from(CardanoNetwork::Testnet), NetworkIdKind::Testnet);
}
}
10 changes: 5 additions & 5 deletions toolkit/partner-chains-cli/src/deregister/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ use crate::config::config_fields::{
CARDANO_COLD_VERIFICATION_KEY_FILE, CARDANO_PAYMENT_SIGNING_KEY_FILE,
};
use crate::config::{
get_cardano_network_from_file, CardanoNetwork, ChainConfig, CHAIN_CONFIG_FILE_PATH,
PC_CONTRACTS_CLI_PATH,
get_cardano_network_from_file, ChainConfig, CHAIN_CONFIG_FILE_PATH, PC_CONTRACTS_CLI_PATH,
};
use crate::io::IOContext;
use crate::pc_contracts_cli_resources::{
establish_pc_contracts_cli_configuration, PcContractsCliResources,
};
use crate::{smart_contracts, CmdRun};
use anyhow::{anyhow, Context};
use sidechain_domain::NetworkType;

#[derive(Debug, clap::Parser)]
pub struct DeregisterCmd;
Expand Down Expand Up @@ -43,7 +43,7 @@ impl CmdRun for DeregisterCmd {

fn read_chain_config_file<C: IOContext>(
context: &C,
) -> Result<(crate::config::ChainConfig, crate::config::CardanoNetwork), anyhow::Error> {
) -> Result<(crate::config::ChainConfig, NetworkType), anyhow::Error> {
let chain_config = crate::config::load_chain_config(context);
let cardano_network = get_cardano_network_from_file(context);
chain_config.and_then(|chain_config| cardano_network.map(|cardano_network| (chain_config, cardano_network)))
Expand Down Expand Up @@ -81,15 +81,15 @@ fn get_mainchain_key_hex<C: IOContext>(
}

fn build_command(
cardano_network: CardanoNetwork,
cardano_network: NetworkType,
cold_vkey: String,
chain_config: ChainConfig,
pc_contracts_cli_resources: PcContractsCliResources,
payment_signing_key_path: String,
) -> String {
format!(
"{PC_CONTRACTS_CLI_PATH} deregister --network {} --ada-based-staking --spo-public-key {} {} {}",
cardano_network.to_network_param(),
cardano_network,
cold_vkey,
smart_contracts::sidechain_params_arguments(&chain_config.chain_parameters),
smart_contracts::runtime_config_arguments(
Expand Down
4 changes: 2 additions & 2 deletions toolkit/partner-chains-cli/src/ogmios/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::config::CardanoNetwork;
use anyhow::anyhow;
use jsonrpsee::http_client::HttpClient;
use ogmios_client::{
query_ledger_state::QueryLedgerState, query_network::QueryNetwork, types::OgmiosUtxo,
};
use sidechain_domain::NetworkType;

#[derive(Debug, Eq, PartialEq)]
pub enum OgmiosRequest {
Expand Down Expand Up @@ -40,7 +40,7 @@ pub struct EpochParameters {

#[derive(Clone, Debug, PartialEq)]
pub struct ShelleyGenesisConfiguration {
pub network: CardanoNetwork,
pub network: NetworkType,
pub security_parameter: u32,
pub active_slots_coefficient: f64,
pub epoch_length: u32,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,10 @@ fn get_first_epoch_era(eras_summaries: Vec<EraSummary>) -> Result<EraSummary, an

#[cfg(test)]
pub mod tests {
use sidechain_domain::NetworkType;

use super::*;
use crate::config::{CardanoNetwork, NetworkProtocol, CHAIN_CONFIG_FILE_PATH};
use crate::config::{NetworkProtocol, CHAIN_CONFIG_FILE_PATH};
use crate::ogmios::{EpochBoundary, EpochParameters, EraSummary};
use crate::prepare_configuration::prepare_cardano_params::prepare_cardano_params;
use crate::tests::{MockIO, MockIOContext};
Expand All @@ -91,7 +93,7 @@ pub mod tests {
first_slot_number: 86400,
epoch_duration_millis: 432000000,
first_epoch_timestamp_millis: 1655769600000,
network: CardanoNetwork::Testnet,
network: NetworkType::Testnet,
};

pub(crate) const PREVIEW_CARDANO_PARAMS: CardanoParameters = CardanoParameters {
Expand All @@ -101,7 +103,7 @@ pub mod tests {
first_slot_number: 0,
epoch_duration_millis: 86400000,
first_epoch_timestamp_millis: 1666656000000,
network: CardanoNetwork::Testnet,
network: NetworkType::Testnet,
};

#[test]
Expand Down Expand Up @@ -190,7 +192,7 @@ pub mod tests {

pub(crate) fn preprod_shelley_config() -> ShelleyGenesisConfiguration {
ShelleyGenesisConfiguration {
network: CardanoNetwork::Testnet,
network: NetworkType::Testnet,
security_parameter: 2160,
active_slots_coefficient: 0.05,
epoch_length: 432000,
Expand Down Expand Up @@ -234,7 +236,7 @@ pub mod tests {

pub(crate) fn preview_shelley_config() -> ShelleyGenesisConfiguration {
ShelleyGenesisConfiguration {
network: CardanoNetwork::Testnet,
network: NetworkType::Testnet,
security_parameter: 432,
active_slots_coefficient: 0.05,
epoch_length: 86400,
Expand Down
9 changes: 5 additions & 4 deletions toolkit/partner-chains-cli/src/register/register1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ use crate::{config::config_fields, *};
use anyhow::anyhow;
use cli_commands::registration_signatures::RegisterValidatorMessage;
use cli_commands::signing::sc_public_key_and_signature_for_datum;
use config::{CardanoNetwork, ServiceConfig};
use config::ServiceConfig;
use ogmios::{OgmiosRequest, OgmiosResponse};
use ogmios_client::types::OgmiosUtxo;
use partner_chains_cardano_offchain::csl::NetworkTypeExt;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sidechain_domain::{McTxHash, SidechainPublicKey, UtxoId};
use sidechain_domain::{McTxHash, NetworkType, SidechainPublicKey, UtxoId};
use sp_core::bytes::from_hex;
use sp_core::{ecdsa, Pair};
use std::str::FromStr;
Expand Down Expand Up @@ -183,15 +184,15 @@ where

fn derive_address<C: IOContext>(
context: &C,
cardano_network: CardanoNetwork,
cardano_network: NetworkType,
) -> Result<String, anyhow::Error> {
let cardano_payment_verification_key_file =
config_fields::CARDANO_PAYMENT_VERIFICATION_KEY_FILE
.prompt_with_default_from_file_and_save(context);
let key_bytes: [u8; 32] =
cardano_key::get_key_bytes_from_file(&cardano_payment_verification_key_file, context)?;
let address =
partner_chains_cardano_offchain::csl::payment_address(&key_bytes, cardano_network.into());
partner_chains_cardano_offchain::csl::payment_address(&key_bytes, cardano_network.to_csl());
address.to_bech32(None).map_err(|e| anyhow!(e.to_string()))
}

Expand Down
2 changes: 1 addition & 1 deletion toolkit/partner-chains-cli/src/register/register3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl CmdRun for Register3Cmd {

let command = format!(
"{PC_CONTRACTS_CLI_PATH} register --network {} {} --registration-utxo {} --sidechain-public-keys {}:{}:{} --sidechain-signature {} --spo-public-key {} --spo-signature {} --ada-based-staking {}",
cardano_network.to_network_param(),
cardano_network,
sidechain_param_arg,
self.registration_utxo,
self.sidechain_pub_key,
Expand Down
4 changes: 2 additions & 2 deletions toolkit/partner-chains-cli/src/setup_main_chain_state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ fn set_candidates_on_main_chain<C: IOContext>(
.run_command(&format!(
"{PC_CONTRACTS_CLI_PATH} {} --network {} {} {} {}",
command,
cardano_network.to_network_param(),
cardano_network.to_string(),
candidate_keys,
smart_contracts::sidechain_params_arguments(chain_params),
smart_contracts::runtime_config_arguments(
Expand Down Expand Up @@ -309,7 +309,7 @@ fn set_d_parameter_on_main_chain<C: IOContext>(
let cardano_network = get_cardano_network_from_file(context)?;
let command = format!(
"{PC_CONTRACTS_CLI_PATH} {pc_contracts_cli_command} --network {} --d-parameter-permissioned-candidates-count {p} --d-parameter-registered-candidates-count {r} {} {}",
cardano_network.to_network_param(),
cardano_network,
smart_contracts::sidechain_params_arguments(chain_params),
smart_contracts::runtime_config_arguments(&pc_contracts_cli_resources, &payment_signing_key_path)
);
Expand Down
19 changes: 19 additions & 0 deletions toolkit/primitives/domain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,25 @@ impl UtxoInfo {
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum NetworkType {
Mainnet,
Testnet,
}

#[cfg(feature = "std")]
impl std::fmt::Display for NetworkType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let str = match self {
Self::Mainnet => "mainnet",
Self::Testnet => "testnet",
};
write!(f, "{}", str)
}
}

#[derive(Default, Clone, PartialEq, Eq, Encode, Decode)]
#[byte_string(debug, hex_serialize, hex_deserialize)]
pub struct CommitteeHash(pub Vec<u8>);
Expand Down
1 change: 1 addition & 0 deletions toolkit/utils/ogmios-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ serde = { workspace = true }
serde_json = { workspace = true, features = ["raw_value", "arbitrary_precision"] }
thiserror = { workspace = true }
time = { workspace = true, features = ["std", "serde", "parsing"] }
sidechain-domain = { workspace = true, features = ["std"] }

[dev-dependencies]
anyhow = { workspace = true }
Expand Down
Loading

0 comments on commit f48c0a8

Please sign in to comment.