moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Contract-maintenance `MaintenanceUpdate` construction + signing.
//!
//! Shared helper for the three maintenance-tx entry points
//! ([`crate::submit_insert_vk_tx`], [`crate::submit_remove_vk_tx`],
//! [`crate::submit_replace_authority_tx`]). Builds an unproven
//! `Transaction<Signature, ProofPreimageMarker, PedersenRandomness,
//! InMemoryDB>` carrying a single-entry [`MaintenanceUpdate`] signed
//! by the caller's current authority key.
//!
//! # Counter + signature semantics (ported from midnight-ledger)
//!
//! - The update's `counter` field MUST equal the on-chain
//!   `ContractMaintenanceAuthority::counter` (the ledger increments
//!   it on apply).
//! - Signatures are a `Vec<SignaturesValue(committee_index,
//!   Signature)>` sorted ascending by committee index (the ledger's
//!   `well_formed` enforces ordering).
//! - `ReplaceAuthority { new_authority }` requires
//!   `new_authority.counter == update.counter + 1` — the ledger's
//!   "every new committee starts with the next counter" rule.
//!
//! Signature verification against `self.committee[idx]` uses Schnorr
//! over the bytes produced by `MaintenanceUpdate::data_to_sign()`.
//!
//! The single-authority case (committee `[vk]`, threshold 1) is
//! handled here directly; multi-signer contracts would thread
//! additional `(idx, SigningKey)` pairs through — kept simple for
//! the current port slice because no moonproof contract fixture
//! exercises the multi-party case.

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::ledger::structure::{
    MaintenanceUpdate, ProofPreimageMarker, SignaturesValue, SingleUpdate, Transaction,
};
use moonproof_ledger::onchain_runtime::state::ContractState;
use moonproof_ledger::signatures::{Signature, SigningKey};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::Array as StorageArray;
use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, Result};
use crate::fee_balancing::{apply_fee_balancing, FeeBalancingConfig};
use crate::utils::ledger_utils::ttl_one_hour;
use moonproof_runtime::state::contract_address_to_hex;

/// Options for [`build_unproven_maintenance_tx`].
pub struct MaintenanceTxOptions<'a> {
    pub contract_address: ContractAddress,
    pub on_chain_state: &'a ContractState<InMemoryDB>,
    pub signing_key: &'a SigningKey,
    pub updates: Vec<SingleUpdate>,
    pub current_time: Timestamp,
    pub network_id: String,
    pub fee_balancing: Option<FeeBalancingConfig>,
}

/// Build a maintenance-update transaction signed by the caller's
/// current authority key. Returns tagged-serialized unproven tx
/// bytes ready for the submit pipeline.
///
/// # Errors
///
/// - [`ContractRuntimeError::Serialize`] if tagged serialization
///   fails.
/// - [`ContractRuntimeError::Wallet`] if dust-fee balancing fails.
pub fn build_unproven_maintenance_tx<R>(
    rng: &mut R,
    options: MaintenanceTxOptions<'_>,
) -> Result<crate::tx_phase::UnprovenTx>
where
    R: Rng + CryptoRng,
{
    let MaintenanceTxOptions {
        contract_address,
        on_chain_state,
        signing_key,
        updates,
        current_time,
        network_id,
        fee_balancing,
    } = options;

    // (1) Assemble the MaintenanceUpdate value (counter from on-chain
    // authority; signatures slot populated below).
    let counter = on_chain_state.maintenance_authority.counter;
    let mut update = MaintenanceUpdate::<InMemoryDB> {
        address: contract_address,
        updates: StorageArray::from(updates),
        counter,
        signatures: StorageArray::from(Vec::<SignaturesValue>::new()),
    };

    // (2) Sign: locate the caller's key in the committee, sign
    // `data_to_sign()`, insert a SignaturesValue at the matching
    // index.
    let caller_index = moonproof_ledger::signatures::committee_position(
        &on_chain_state.maintenance_authority.committee,
        signing_key,
    )
    .ok_or_else(|| ContractRuntimeError::Provider {
        provider: "maintenance",
        message: format!(
            "caller's verifying key is not in the on-chain committee for contract {}",
            contract_address_to_hex(&contract_address),
        ),
    })?;
    let idx = u32::try_from(caller_index).map_err(|_| ContractRuntimeError::Provider {
        provider: "maintenance",
        message: format!("committee index {caller_index} out of u32 range"),
    })?;
    let msg = update.data_to_sign();
    let signature: Signature = signing_key.sign(rng, &msg);
    update.signatures = StorageArray::from(vec![SignaturesValue(idx, signature)]);

    // (3) Build the Intent holding the maintenance update + wrap in a
    // Transaction. `test_intents` is the same helper the deploy /
    // call paths use — passes rng, empty calls/deploys, the one
    // maintenance update, and the chain-time-derived TTL.
    let _ttl = ttl_one_hour(current_time); // currently implicit in test_intents
    let intents = crate::utils::ledger_utils::one_intent_at_segment_one(
        rng,
        Vec::new(),   // no calls
        vec![update], // one maintenance update
        Vec::new(),   // no deploys
        current_time,
    );
    let network_id_for_tx = network_id.clone();
    let tx: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> =
        Transaction::from_intents(network_id_for_tx, intents);

    // (4) Optional dust-fee balancing.
    let tx = if let Some(ref config) = fee_balancing {
        apply_fee_balancing(rng, tx, config, &network_id)?
    } else {
        tx
    };

    // (5) Wrap in the typed phase newtype.
    Ok(crate::tx_phase::UnprovenTx::new(tx))
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::hash::HashOutput;
    use moonproof_ledger::onchain_runtime::state::{
        ContractMaintenanceAuthority, EntryPointBuf, StateValue,
    };
    use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn dummy_address() -> ContractAddress {
        ContractAddress(HashOutput([0x11u8; 32]))
    }

    fn contract_state_with_committee(
        committee: Vec<moonproof_ledger::signatures::MaintenanceVerifyingKey>,
        counter: u32,
    ) -> ContractState<InMemoryDB> {
        let op_key: EntryPointBuf = b"stub"[..].into();
        ContractState::<InMemoryDB>::new(
            StateValue::Null,
            StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
            ContractMaintenanceAuthority {
                committee,
                threshold: 1,
                counter,
            },
        )
    }

    #[test]
    fn build_unproven_maintenance_tx_signs_at_committee_index() {
        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).unwrap();
        let vk = moonproof_ledger::signatures::maintenance_verifying_key(&signing_key);
        let state = contract_state_with_committee(vec![vk], 0);
        let updates = vec![SingleUpdate::VerifierKeyRemove(
            b"increment"[..].into(),
            moonproof_ledger::contract_operation_version(),
        )];
        let mut rng = StdRng::seed_from_u64(0xBEEF);
        let unproven = build_unproven_maintenance_tx(
            &mut rng,
            MaintenanceTxOptions {
                contract_address: dummy_address(),
                on_chain_state: &state,
                signing_key: &signing_key,
                updates,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".to_owned(),
                fee_balancing: None,
            },
        )
        .expect("build_unproven_maintenance_tx must succeed with a matching committee key");
        assert_ne!(unproven.to_tagged_bytes().unwrap(), [] as [u8; 0]);
    }

    #[test]
    fn build_unproven_maintenance_tx_rejects_non_committee_signer() {
        // Authority committee does NOT contain the caller's key.
        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x55u8; 32]).unwrap();
        let other = moonproof_ledger::signatures::schnorr_signing_key(&[0x66u8; 32]).unwrap();
        let state = contract_state_with_committee(
            vec![moonproof_ledger::signatures::maintenance_verifying_key(
                &other,
            )],
            0,
        );
        let updates = vec![SingleUpdate::VerifierKeyRemove(
            b"increment"[..].into(),
            moonproof_ledger::contract_operation_version(),
        )];
        let mut rng = StdRng::seed_from_u64(1);
        let err = build_unproven_maintenance_tx(
            &mut rng,
            MaintenanceTxOptions {
                contract_address: dummy_address(),
                on_chain_state: &state,
                signing_key: &signing_key,
                updates,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".to_owned(),
                fee_balancing: None,
            },
        )
        .unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("not in the on-chain committee"),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn build_unproven_maintenance_tx_with_replace_authority_update() {
        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x01u8; 32]).unwrap();
        let new_signing_key =
            moonproof_ledger::signatures::schnorr_signing_key(&[0x02u8; 32]).unwrap();
        let state = contract_state_with_committee(
            vec![moonproof_ledger::signatures::maintenance_verifying_key(
                &signing_key,
            )],
            0,
        );
        let replacement = ContractMaintenanceAuthority {
            committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
                &new_signing_key,
            )],
            threshold: 1,
            // Per ledger's well_formed: new committee counter must be
            // update.counter + 1. Our update inherits on-chain counter
            // = 0, so replacement counter must be 1.
            counter: 1,
        };
        let updates = vec![SingleUpdate::ReplaceAuthority(replacement)];
        let mut rng = StdRng::seed_from_u64(2);
        let unproven = build_unproven_maintenance_tx(
            &mut rng,
            MaintenanceTxOptions {
                contract_address: dummy_address(),
                on_chain_state: &state,
                signing_key: &signing_key,
                updates,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".to_owned(),
                fee_balancing: None,
            },
        )
        .expect("replace-authority update should serialize");
        assert_ne!(unproven.to_tagged_bytes().unwrap(), [] as [u8; 0]);
    }
}