moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Port of
//! `@midnight-ntwrk/midnight-js-contracts/src/submit-replace-authority-tx.ts`.
//!
//! Builds and submits a transaction that replaces the contract's
//! maintenance authority with a new signing key. After the
//! transaction finalizes successfully, the new signing key is stored
//! in the private-state provider under `contract_address`, so
//! subsequent maintenance operations use it.
//!
//! # Pre-conditions
//!
//! - Contract state exists on-chain at `contract_address`.
//! - The current signing key is stored locally in the private-state
//!   provider (the caller is currently the authority).
//!
//! # Post-success behaviour
//!
//! On `SucceedEntirely`, the caller's stored signing key for this
//! contract is replaced with `new_authority` — subsequent maintenance
//! ops will sign with the new key. Matches TS
//! `submitReplaceAuthorityTx`'s post-success call into
//! `privateStateProvider.setSigningKey`.

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::ledger::structure::SingleUpdate;
use moonproof_ledger::onchain_runtime::state::ContractMaintenanceAuthority;
use moonproof_ledger::signatures::SigningKey;
use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, ContractsError, Result};
use crate::fee_balancing::FeeBalancingConfig;
use crate::maintenance::{build_unproven_maintenance_tx, MaintenanceTxOptions};
use crate::providers::{PrivateStateProvider, Providers, PublicDataProvider};
use crate::submit_tx::{submit_tx, SubmitTxOptions};
use crate::types::FinalizedTxData;

/// Options for [`submit_replace_authority_tx`].
pub struct SubmitReplaceAuthorityTxOptions {
    pub contract_address: ContractAddress,
    pub new_authority: SigningKey,
    pub current_time: moonproof_ledger::base_crypto::time::Timestamp,
    pub network_id: String,
    pub fee_balancing: Option<FeeBalancingConfig>,
}

/// Construct + submit a replace-maintenance-authority transaction.
/// Port of TS `submitReplaceAuthorityTx`.
pub async fn submit_replace_authority_tx<R, C>(
    rng: &mut R,
    providers: &C,
    options: SubmitReplaceAuthorityTxOptions,
) -> Result<FinalizedTxData>
where
    R: Rng + CryptoRng,
    C: Providers + ?Sized,
{
    let on_chain_state = providers
        .public_data()
        .query_contract_state(&options.contract_address, None)
        .await?
        .ok_or_else(|| {
            ContractRuntimeError::NotFound(format!(
                "No contract state found on chain for contract address {}",
                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
            ))
        })?;

    let current_authority = providers
        .private_state()
        .get_signing_key(&options.contract_address)
        .await?
        .ok_or_else(|| ContractRuntimeError::Provider {
            provider: "submit_replace_authority_tx",
            message: format!(
                "Signing key for contract address {} not found",
                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
            ),
        })?;

    // The new committee's counter must equal the current update's
    // counter + 1 per ledger's `well_formed` check on
    // MaintenanceUpdate. The on-chain counter is what the new
    // update will carry; the next committee starts one beyond that.
    let next_counter = on_chain_state
        .maintenance_authority
        .counter
        .saturating_add(1);
    let new_authority_state = ContractMaintenanceAuthority {
        committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
            &options.new_authority,
        )],
        threshold: 1,
        counter: next_counter,
    };

    let unproven_tx = build_unproven_maintenance_tx(
        rng,
        MaintenanceTxOptions {
            contract_address: options.contract_address,
            on_chain_state: &on_chain_state,
            signing_key: &current_authority,
            updates: vec![SingleUpdate::ReplaceAuthority(new_authority_state)],
            current_time: options.current_time,
            network_id: options.network_id,
            fee_balancing: options.fee_balancing,
        },
    )?;

    let submit_opts = SubmitTxOptions {
        unproven_tx,
        circuit_ids: None,
        prove_config: crate::providers::ProveTxConfig::default(),
        ttl_ms: None,
    };
    let finalized = submit_tx(providers, submit_opts).await?;
    if !finalized.status.is_success() {
        return Err(ContractRuntimeError::Contracts(
            ContractsError::replace_maintenance_authority_tx_failed(finalized),
        ));
    }

    // Rotate the locally-stored signing key so subsequent maintenance
    // ops use the new authority.
    providers
        .private_state()
        .set_signing_key(&options.contract_address, options.new_authority)
        .await?;

    Ok(finalized)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::{contract_state_with_committee, dummy_address, scripted_providers};
    use crate::types::TxStatus;
    use moonproof_ledger::base_crypto::time::Timestamp;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    /// ports: `submit-replace-authority-tx.test.ts::should successfully submit replace authority transaction and update signing key`
    #[tokio::test]
    async fn happy_path_rotates_local_signing_key_to_new_authority() {
        let current = moonproof_ledger::signatures::schnorr_signing_key(&[0x55u8; 32]).unwrap();
        let new_auth = moonproof_ledger::signatures::schnorr_signing_key(&[0x66u8; 32]).unwrap();
        let state =
            contract_state_with_committee(&current, "increment", /*circuit_present*/ true);
        let (providers, ps) = scripted_providers(
            Some(current.clone()),
            Some(state),
            TxStatus::SucceedEntirely,
        );
        let mut rng = StdRng::seed_from_u64(0x300);
        let finalized = submit_replace_authority_tx(
            &mut rng,
            &providers,
            SubmitReplaceAuthorityTxOptions {
                contract_address: dummy_address(),
                new_authority: new_auth.clone(),
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap();
        assert_eq!(finalized.status, TxStatus::SucceedEntirely);

        // The post-success rotation should have called set_signing_key
        // with the new authority.
        let calls = ps.set_signing_key_calls.lock().unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].0, dummy_address());
        assert_eq!(
            calls[0].1.verifying_key(),
            new_auth.verifying_key(),
            "new authority must replace the old key"
        );
    }

    /// ports: `submit-replace-authority-tx.test.ts::should throw ReplaceMaintenanceAuthorityTxFailedError when transaction fails`
    #[tokio::test]
    async fn submit_failure_returns_replace_maintenance_authority_tx_failed() {
        let current = moonproof_ledger::signatures::schnorr_signing_key(&[0x55u8; 32]).unwrap();
        let new_auth = moonproof_ledger::signatures::schnorr_signing_key(&[0x66u8; 32]).unwrap();
        let state =
            contract_state_with_committee(&current, "increment", /*circuit_present*/ true);
        let (providers, ps) =
            scripted_providers(Some(current.clone()), Some(state), TxStatus::FailEntirely);
        let mut rng = StdRng::seed_from_u64(0x300);
        let err = submit_replace_authority_tx(
            &mut rng,
            &providers,
            SubmitReplaceAuthorityTxOptions {
                contract_address: dummy_address(),
                new_authority: new_auth,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(
                ContractsError::ReplaceMaintenanceAuthorityTxFailed { .. }
            )
        );
        assert!(format!("{err}").contains("ReplaceMaintenanceAuthorityTxFailedError"));
        // Load-bearing: failure must NOT rotate the local signing key.
        // If it did, subsequent maintenance ops would sign with a key
        // that doesn't match the on-chain authority.
        assert!(ps.set_signing_key_calls.lock().unwrap().is_empty());
    }

    /// Pre-condition: missing on-chain state.
    #[tokio::test]
    async fn pre_condition_missing_on_chain_state_returns_not_found() {
        let current = moonproof_ledger::signatures::schnorr_signing_key(&[0x55u8; 32]).unwrap();
        let new_auth = moonproof_ledger::signatures::schnorr_signing_key(&[0x66u8; 32]).unwrap();
        let (providers, _) = scripted_providers(Some(current), None, TxStatus::SucceedEntirely);
        let mut rng = StdRng::seed_from_u64(0x300);
        let err = submit_replace_authority_tx(
            &mut rng,
            &providers,
            SubmitReplaceAuthorityTxOptions {
                contract_address: dummy_address(),
                new_authority: new_auth,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        matches!(err, ContractRuntimeError::NotFound(_));
    }

    /// Pre-condition: missing local signing key.
    #[tokio::test]
    async fn pre_condition_missing_signing_key_returns_provider_error() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x55u8; 32]).unwrap();
        let new_auth = moonproof_ledger::signatures::schnorr_signing_key(&[0x66u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ true);
        let (providers, _) = scripted_providers(None, Some(state), TxStatus::SucceedEntirely);
        let mut rng = StdRng::seed_from_u64(0x300);
        let err = submit_replace_authority_tx(
            &mut rng,
            &providers,
            SubmitReplaceAuthorityTxOptions {
                contract_address: dummy_address(),
                new_authority: new_auth,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("Signing key"), "{msg}");
        assert!(msg.contains("not found"), "{msg}");
    }
}