Skip to content

Commit

Permalink
change: ETCM-9063 add update-governance offchain and command (#329)
Browse files Browse the repository at this point in the history
  • Loading branch information
AmbientTea authored Jan 9, 2025
1 parent 850e268 commit 3632997
Show file tree
Hide file tree
Showing 19 changed files with 690 additions and 98 deletions.
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ This changelog is based on [Keep A Changelog](https://keepachangelog.com/en/1.1.
## Changed

* `setup-main-chain-state` command now uses native Rust to upsert the D-Parameter and upsert permissioned candidates
* Changed the `smart-contracts init-governance` command to `smart-contracts governance init`

## Removed

Expand All @@ -22,6 +23,7 @@ This changelog is based on [Keep A Changelog](https://keepachangelog.com/en/1.1.

* Command `smart-contracts reserve init`
* Command `smart-contracts reserve create`
* Command `smart-contracts governance update`

# v1.4.0

Expand Down
90 changes: 90 additions & 0 deletions toolkit/cli/smart-contracts-commands/src/governance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use crate::read_private_key_from_file;
use jsonrpsee::http_client::HttpClient;
use partner_chains_cardano_offchain::{
await_tx::FixedDelayRetries, init_governance::run_init_governance,
update_governance::run_update_governance,
};
use sidechain_domain::{MainchainAddressHash, UtxoId};

#[derive(Clone, Debug, clap::Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum GovernanceCmd {
/// Initialize Partner Chain governance
Init(InitGovernanceCmd),
/// Update Partner Chain governance
Update(UpdateGovernanceCmd),
}

impl GovernanceCmd {
pub async fn execute(self) -> crate::CmdResult<()> {
match self {
Self::Init(cmd) => cmd.execute().await,
Self::Update(cmd) => cmd.execute().await,
}
}
}

#[derive(Clone, Debug, clap::Parser)]
pub struct InitGovernanceCmd {
#[clap(flatten)]
common_arguments: crate::CommonArguments,
/// Governance authority hash to be set.
#[arg(long, short = 'g')]
governance_authority: MainchainAddressHash,
/// Path to the Cardano Payment Key file.
#[arg(long, short = 'k')]
payment_key_file: String,
/// Genesis UTXO of the new chain, it will be spent durning initialization. If not set, then one will be selected from UTXOs of the payment key.
#[arg(long, short = 'c')]
genesis_utxo: Option<UtxoId>,
}

impl InitGovernanceCmd {
pub async fn execute(self) -> crate::CmdResult<()> {
let payment_key = read_private_key_from_file(&self.payment_key_file)?;
let client = HttpClient::builder().build(self.common_arguments.ogmios_url)?;

run_init_governance(
self.governance_authority,
payment_key,
self.genesis_utxo,
&client,
FixedDelayRetries::two_minutes(),
)
.await?;
Ok(())
}
}

#[derive(Clone, Debug, clap::Parser)]
pub struct UpdateGovernanceCmd {
#[clap(flatten)]
common_arguments: crate::CommonArguments,
/// Governance authority hash to be set.
#[arg(long, short = 'g')]
new_governance_authority: MainchainAddressHash,
/// Path to the Cardano Payment Key file.
#[arg(long, short = 'k')]
payment_key_file: String,
/// Genesis UTXO of the chain
#[arg(long, short = 'c')]
genesis_utxo: UtxoId,
}

impl UpdateGovernanceCmd {
pub async fn execute(self) -> crate::CmdResult<()> {
let payment_key = read_private_key_from_file(&self.payment_key_file)?;
let client = HttpClient::builder().build(self.common_arguments.ogmios_url)?;

run_update_governance(
self.new_governance_authority,
payment_key,
self.genesis_utxo,
&client,
FixedDelayRetries::two_minutes(),
)
.await?;

Ok(())
}
}
39 changes: 0 additions & 39 deletions toolkit/cli/smart-contracts-commands/src/init_governance.rs

This file was deleted.

9 changes: 5 additions & 4 deletions toolkit/cli/smart-contracts-commands/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use sidechain_domain::*;

pub mod d_parameter;
pub mod get_scripts;
pub mod init_governance;
pub mod governance;
pub mod register;
pub mod reserve;

Expand All @@ -11,8 +11,6 @@ pub mod reserve;
pub enum SmartContractsCmd {
/// Print validator addresses and policy IDs of Partner Chain smart contracts
GetScripts(get_scripts::GetScripts),
/// Initialize Partner Chain governance
InitGovernance(init_governance::InitGovernanceCmd),
/// Upsert DParameter
UpsertDParameter(d_parameter::UpsertDParameterCmd),
/// Register candidate
Expand All @@ -22,6 +20,9 @@ pub enum SmartContractsCmd {
/// Commands for management of rewards reserve
#[command(subcommand)]
Reserve(reserve::ReserveCmd),
/// Commands for management of on-chain governance
#[command(subcommand)]
Governance(governance::GovernanceCmd),
}

#[derive(Clone, Debug, clap::Parser)]
Expand All @@ -36,7 +37,7 @@ type CmdResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
impl SmartContractsCmd {
pub async fn execute(self) -> CmdResult<()> {
match self {
Self::InitGovernance(cmd) => cmd.execute().await,
Self::Governance(cmd) => cmd.execute().await,
Self::GetScripts(cmd) => cmd.execute().await,
Self::UpsertDParameter(cmd) => cmd.execute().await,
Self::Register(cmd) => cmd.execute().await,
Expand Down
12 changes: 3 additions & 9 deletions toolkit/offchain/src/await_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ impl AwaitTx for FixedDelayRetries {
let strategy = FixedInterval::new(self.delay).take(self.retries);
let _ = Retry::spawn(strategy, || async {
log::info!("Probing for transaction output '{}'", utxo_id);
let utxo = query
.query_utxo_by_id(utxo_id.tx_hash.into(), utxo_id.index.0)
.await
.map_err(|_| ())?;
let utxo = query.query_utxo_by_id(utxo_id).await.map_err(|_| ())?;
utxo.ok_or(())
})
.await
Expand Down Expand Up @@ -137,12 +134,9 @@ mod tests {
impl QueryUtxoByUtxoId for MockQueryUtxoByUtxoId {
async fn query_utxo_by_id(
&self,
tx: OgmiosTx,
index: u16,
utxo: sidechain_domain::UtxoId,
) -> Result<Option<OgmiosUtxo>, OgmiosClientError> {
let UtxoId { tx_hash: McTxHash(awaited_id), index: UtxoIndex(awaited_index) } =
awaited_utxo_id();
if tx.id == awaited_id && index == awaited_index {
if utxo == awaited_utxo_id() {
self.responses.borrow_mut().pop().unwrap()
} else {
Ok(None)
Expand Down
25 changes: 24 additions & 1 deletion toolkit/offchain/src/csl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,14 @@ pub(crate) trait InputsBuilderExt: Sized {
ex_units: &ExUnits,
) -> Result<(), JsError>;

fn add_script_utxo_input_with_data(
&mut self,
utxo: &OgmiosUtxo,
script: &PlutusScript,
data: &PlutusData,
ex_units: &ExUnits,
) -> Result<(), JsError>;

/// Adds ogmios inputs to the tx inputs builder.
fn add_key_inputs(&mut self, utxos: &[OgmiosUtxo], key: &Ed25519KeyHash)
-> Result<(), JsError>;
Expand All @@ -544,6 +552,21 @@ impl InputsBuilderExt for TxInputsBuilder {
utxo: &OgmiosUtxo,
script: &PlutusScript,
ex_units: &ExUnits,
) -> Result<(), JsError> {
self.add_script_utxo_input_with_data(
utxo,
script,
&PlutusData::new_empty_constr_plutus_data(&0u32.into()),
ex_units,
)
}

fn add_script_utxo_input_with_data(
&mut self,
utxo: &OgmiosUtxo,
script: &PlutusScript,
data: &PlutusData,
ex_units: &ExUnits,
) -> Result<(), JsError> {
let input = utxo.to_csl_tx_input();
let amount = convert_value(&utxo.value)?;
Expand All @@ -553,7 +576,7 @@ impl InputsBuilderExt for TxInputsBuilder {
&RedeemerTag::new_spend(),
// CSL will set redeemer index for the index of script input after sorting transaction inputs
&0u32.into(),
&PlutusData::new_empty_constr_plutus_data(&0u32.into()),
&data,
ex_units,
),
);
Expand Down
7 changes: 5 additions & 2 deletions toolkit/offchain/src/d_param/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use cardano_serialization_lib::{
use hex_literal::hex;
use ogmios_client::types::{Asset as OgmiosAsset, OgmiosTx, OgmiosUtxo, OgmiosValue};
use partner_chains_plutus_data::d_param::d_parameter_to_plutus_data;
use sidechain_domain::{DParameter, UtxoId};
use sidechain_domain::DParameter;

mod mint_tx {
use super::*;
Expand Down Expand Up @@ -331,7 +331,10 @@ fn governance_script_hash() -> ScriptHash {
}

fn governance_data() -> GovernanceData {
GovernanceData { policy_script: governance_script(), utxo_id: UtxoId::new([15; 32], 0) }
GovernanceData {
policy_script: governance_script(),
utxo: OgmiosUtxo { transaction: OgmiosTx { id: [15; 32] }, index: 0, ..Default::default() },
}
}

fn lesser_payment_utxo() -> OgmiosUtxo {
Expand Down
15 changes: 10 additions & 5 deletions toolkit/offchain/src/init_governance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,13 @@ pub(crate) async fn get_governance_utxo<T: QueryLedgerState + Transactions + Que

pub(crate) struct GovernanceData {
pub(crate) policy_script: plutus_script::PlutusScript,
pub(crate) utxo_id: UtxoId,
pub(crate) utxo: OgmiosUtxo,
}

impl GovernanceData {
pub fn utxo_id(&self) -> sidechain_domain::UtxoId {
self.utxo.utxo_id()
}
}

impl GovernanceData {
Expand All @@ -189,8 +195,8 @@ impl GovernanceData {

pub(crate) fn utxo_id_as_tx_input(&self) -> TransactionInput {
TransactionInput::new(
&TransactionHash::from_bytes(self.utxo_id.tx_hash.0.to_vec()).unwrap(),
self.utxo_id.index.0.into(),
&TransactionHash::from_bytes(self.utxo_id().tx_hash.0.to_vec()).unwrap(),
self.utxo_id().index.0.into(),
)
}
}
Expand All @@ -201,8 +207,7 @@ pub(crate) async fn get_governance_data<T: QueryLedgerState + Transactions + Que
) -> Result<GovernanceData, JsError> {
let utxo = get_governance_utxo(genesis_utxo, client).await?;
let policy_script = read_policy(&utxo)?;
let utxo_id = utxo.to_domain();
Ok(GovernanceData { policy_script, utxo_id })
Ok(GovernanceData { policy_script, utxo })
}

pub(crate) fn read_policy(
Expand Down
2 changes: 1 addition & 1 deletion toolkit/offchain/src/init_governance/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ fn mint_witness(
))
}

fn version_oracle_datum_output(
pub(crate) fn version_oracle_datum_output(
version_oracle_validator: PlutusScript,
version_oracle_policy: PlutusScript,
multi_sig_policy: PlutusScript,
Expand Down
2 changes: 2 additions & 0 deletions toolkit/offchain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub mod scripts_data;
pub mod test_values;
/// Module for interaction with the untyped plutus scripts
pub mod untyped_plutus;
/// Supports governance updates
pub mod update_governance;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OffchainError {
Expand Down
11 changes: 3 additions & 8 deletions toolkit/offchain/src/ogmios_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use ogmios_client::{
query_ledger_state::{ProtocolParametersResponse, QueryLedgerState, QueryUtxoByUtxoId},
query_network::{QueryNetwork, ShelleyGenesisConfigurationResponse},
transactions::{OgmiosEvaluateTransactionResponse, SubmitTransactionResponse, Transactions},
types::{OgmiosTx, OgmiosUtxo},
types::OgmiosUtxo,
};

#[derive(Clone, Default, Debug)]
Expand Down Expand Up @@ -108,13 +108,8 @@ impl QueryLedgerState for MockOgmiosClient {
impl QueryUtxoByUtxoId for MockOgmiosClient {
async fn query_utxo_by_id(
&self,
tx: OgmiosTx,
index: u16,
queried_utxo: sidechain_domain::UtxoId,
) -> Result<Option<OgmiosUtxo>, ogmios_client::OgmiosClientError> {
Ok(self
.utxos
.iter()
.find(|utxo| utxo.transaction == tx && utxo.index == index)
.cloned())
Ok(self.utxos.iter().find(|utxo| utxo.utxo_id() == queried_utxo).cloned())
}
}
11 changes: 4 additions & 7 deletions toolkit/offchain/src/permissioned_candidates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ mod tests {
use ogmios_client::types::{Asset as OgmiosAsset, OgmiosTx, OgmiosUtxo, OgmiosValue};
use partner_chains_plutus_data::permissioned_candidates::permissioned_candidates_to_plutus_data;
use sidechain_domain::{
AuraPublicKey, GrandpaPublicKey, PermissionedCandidateData, SidechainPublicKey, UtxoId,
AuraPublicKey, GrandpaPublicKey, PermissionedCandidateData, SidechainPublicKey,
};

#[test]
Expand Down Expand Up @@ -544,15 +544,12 @@ mod tests {
}
}

fn test_goveranance_utxo_id() -> UtxoId {
UtxoId::new([123u8; 32], 17)
fn test_goveranance_utxo() -> OgmiosUtxo {
OgmiosUtxo { transaction: OgmiosTx { id: [123; 32] }, index: 17, ..Default::default() }
}

fn test_governance_data() -> GovernanceData {
GovernanceData {
policy_script: test_goveranance_policy(),
utxo_id: test_goveranance_utxo_id(),
}
GovernanceData { policy_script: test_goveranance_policy(), utxo: test_goveranance_utxo() }
}

fn test_tx_context() -> TransactionContext {
Expand Down
Loading

0 comments on commit 3632997

Please sign in to comment.