Skip to main content

moonproof_contracts/
maintenance.rs

1//! Contract-maintenance `MaintenanceUpdate` construction + signing.
2//!
3//! Shared helper for the three maintenance-tx entry points
4//! ([`crate::submit_insert_vk_tx`], [`crate::submit_remove_vk_tx`],
5//! [`crate::submit_replace_authority_tx`]). Builds an unproven
6//! `Transaction<Signature, ProofPreimageMarker, PedersenRandomness,
7//! InMemoryDB>` carrying a single-entry [`MaintenanceUpdate`] signed
8//! by the caller's current authority key.
9//!
10//! # Counter + signature semantics (ported from midnight-ledger)
11//!
12//! - The update's `counter` field MUST equal the on-chain
13//!   `ContractMaintenanceAuthority::counter` (the ledger increments
14//!   it on apply).
15//! - Signatures are a `Vec<SignaturesValue(committee_index,
16//!   Signature)>` sorted ascending by committee index (the ledger's
17//!   `well_formed` enforces ordering).
18//! - `ReplaceAuthority { new_authority }` requires
19//!   `new_authority.counter == update.counter + 1` — the ledger's
20//!   "every new committee starts with the next counter" rule.
21//!
22//! Signature verification against `self.committee[idx]` uses Schnorr
23//! over the bytes produced by `MaintenanceUpdate::data_to_sign()`.
24//!
25//! The single-authority case (committee `[vk]`, threshold 1) is
26//! handled here directly; multi-signer contracts would thread
27//! additional `(idx, SigningKey)` pairs through — kept simple for
28//! the current port slice because no moonproof contract fixture
29//! exercises the multi-party case.
30
31use moonproof_ledger::base_crypto::time::Timestamp;
32use moonproof_ledger::coin_structure::contract::ContractAddress;
33use moonproof_ledger::ledger::structure::{
34    MaintenanceUpdate, ProofPreimageMarker, SignaturesValue, SingleUpdate, Transaction,
35};
36use moonproof_ledger::onchain_runtime::state::ContractState;
37use moonproof_ledger::signatures::{Signature, SigningKey};
38use moonproof_ledger::storage::db::InMemoryDB;
39use moonproof_ledger::storage::storage::Array as StorageArray;
40use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
41use rand::{CryptoRng, Rng};
42
43use crate::error::{ContractRuntimeError, Result};
44use crate::fee_balancing::{apply_fee_balancing, FeeBalancingConfig};
45use crate::utils::ledger_utils::ttl_one_hour;
46use moonproof_runtime::state::contract_address_to_hex;
47
48/// Options for [`build_unproven_maintenance_tx`].
49pub struct MaintenanceTxOptions<'a> {
50    pub contract_address: ContractAddress,
51    pub on_chain_state: &'a ContractState<InMemoryDB>,
52    pub signing_key: &'a SigningKey,
53    pub updates: Vec<SingleUpdate>,
54    pub current_time: Timestamp,
55    pub network_id: String,
56    pub fee_balancing: Option<FeeBalancingConfig>,
57}
58
59/// Build a maintenance-update transaction signed by the caller's
60/// current authority key. Returns tagged-serialized unproven tx
61/// bytes ready for the submit pipeline.
62///
63/// # Errors
64///
65/// - [`ContractRuntimeError::Serialize`] if tagged serialization
66///   fails.
67/// - [`ContractRuntimeError::Wallet`] if dust-fee balancing fails.
68pub fn build_unproven_maintenance_tx<R>(
69    rng: &mut R,
70    options: MaintenanceTxOptions<'_>,
71) -> Result<crate::tx_phase::UnprovenTx>
72where
73    R: Rng + CryptoRng,
74{
75    let MaintenanceTxOptions {
76        contract_address,
77        on_chain_state,
78        signing_key,
79        updates,
80        current_time,
81        network_id,
82        fee_balancing,
83    } = options;
84
85    // (1) Assemble the MaintenanceUpdate value (counter from on-chain
86    // authority; signatures slot populated below).
87    let counter = on_chain_state.maintenance_authority.counter;
88    let mut update = MaintenanceUpdate::<InMemoryDB> {
89        address: contract_address,
90        updates: StorageArray::from(updates),
91        counter,
92        signatures: StorageArray::from(Vec::<SignaturesValue>::new()),
93    };
94
95    // (2) Sign: locate the caller's key in the committee, sign
96    // `data_to_sign()`, insert a SignaturesValue at the matching
97    // index.
98    let caller_index = moonproof_ledger::signatures::committee_position(
99        &on_chain_state.maintenance_authority.committee,
100        signing_key,
101    )
102    .ok_or_else(|| ContractRuntimeError::Provider {
103        provider: "maintenance",
104        message: format!(
105            "caller's verifying key is not in the on-chain committee for contract {}",
106            contract_address_to_hex(&contract_address),
107        ),
108    })?;
109    let idx = u32::try_from(caller_index).map_err(|_| ContractRuntimeError::Provider {
110        provider: "maintenance",
111        message: format!("committee index {caller_index} out of u32 range"),
112    })?;
113    let msg = update.data_to_sign();
114    let signature: Signature = signing_key.sign(rng, &msg);
115    update.signatures = StorageArray::from(vec![SignaturesValue(idx, signature)]);
116
117    // (3) Build the Intent holding the maintenance update + wrap in a
118    // Transaction. `test_intents` is the same helper the deploy /
119    // call paths use — passes rng, empty calls/deploys, the one
120    // maintenance update, and the chain-time-derived TTL.
121    let _ttl = ttl_one_hour(current_time); // currently implicit in test_intents
122    let intents = crate::utils::ledger_utils::one_intent_at_segment_one(
123        rng,
124        Vec::new(),   // no calls
125        vec![update], // one maintenance update
126        Vec::new(),   // no deploys
127        current_time,
128    );
129    let network_id_for_tx = network_id.clone();
130    let tx: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> =
131        Transaction::from_intents(network_id_for_tx, intents);
132
133    // (4) Optional dust-fee balancing.
134    let tx = if let Some(ref config) = fee_balancing {
135        apply_fee_balancing(rng, tx, config, &network_id)?
136    } else {
137        tx
138    };
139
140    // (5) Wrap in the typed phase newtype.
141    Ok(crate::tx_phase::UnprovenTx::new(tx))
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use moonproof_ledger::base_crypto::hash::HashOutput;
148    use moonproof_ledger::onchain_runtime::state::{
149        ContractMaintenanceAuthority, EntryPointBuf, StateValue,
150    };
151    use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
152    use rand::rngs::StdRng;
153    use rand::SeedableRng;
154
155    fn dummy_address() -> ContractAddress {
156        ContractAddress(HashOutput([0x11u8; 32]))
157    }
158
159    fn contract_state_with_committee(
160        committee: Vec<moonproof_ledger::signatures::MaintenanceVerifyingKey>,
161        counter: u32,
162    ) -> ContractState<InMemoryDB> {
163        let op_key: EntryPointBuf = b"stub"[..].into();
164        ContractState::<InMemoryDB>::new(
165            StateValue::Null,
166            StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
167            ContractMaintenanceAuthority {
168                committee,
169                threshold: 1,
170                counter,
171            },
172        )
173    }
174
175    #[test]
176    fn build_unproven_maintenance_tx_signs_at_committee_index() {
177        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).unwrap();
178        let vk = moonproof_ledger::signatures::maintenance_verifying_key(&signing_key);
179        let state = contract_state_with_committee(vec![vk], 0);
180        let updates = vec![SingleUpdate::VerifierKeyRemove(
181            b"increment"[..].into(),
182            moonproof_ledger::contract_operation_version(),
183        )];
184        let mut rng = StdRng::seed_from_u64(0xBEEF);
185        let unproven = build_unproven_maintenance_tx(
186            &mut rng,
187            MaintenanceTxOptions {
188                contract_address: dummy_address(),
189                on_chain_state: &state,
190                signing_key: &signing_key,
191                updates,
192                current_time: Timestamp::from_secs(0),
193                network_id: "local-test".to_owned(),
194                fee_balancing: None,
195            },
196        )
197        .expect("build_unproven_maintenance_tx must succeed with a matching committee key");
198        assert_ne!(unproven.to_tagged_bytes().unwrap(), [] as [u8; 0]);
199    }
200
201    #[test]
202    fn build_unproven_maintenance_tx_rejects_non_committee_signer() {
203        // Authority committee does NOT contain the caller's key.
204        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x55u8; 32]).unwrap();
205        let other = moonproof_ledger::signatures::schnorr_signing_key(&[0x66u8; 32]).unwrap();
206        let state = contract_state_with_committee(
207            vec![moonproof_ledger::signatures::maintenance_verifying_key(
208                &other,
209            )],
210            0,
211        );
212        let updates = vec![SingleUpdate::VerifierKeyRemove(
213            b"increment"[..].into(),
214            moonproof_ledger::contract_operation_version(),
215        )];
216        let mut rng = StdRng::seed_from_u64(1);
217        let err = build_unproven_maintenance_tx(
218            &mut rng,
219            MaintenanceTxOptions {
220                contract_address: dummy_address(),
221                on_chain_state: &state,
222                signing_key: &signing_key,
223                updates,
224                current_time: Timestamp::from_secs(0),
225                network_id: "local-test".to_owned(),
226                fee_balancing: None,
227            },
228        )
229        .unwrap_err();
230        let msg = format!("{err}");
231        assert!(
232            msg.contains("not in the on-chain committee"),
233            "unexpected error: {msg}"
234        );
235    }
236
237    #[test]
238    fn build_unproven_maintenance_tx_with_replace_authority_update() {
239        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x01u8; 32]).unwrap();
240        let new_signing_key =
241            moonproof_ledger::signatures::schnorr_signing_key(&[0x02u8; 32]).unwrap();
242        let state = contract_state_with_committee(
243            vec![moonproof_ledger::signatures::maintenance_verifying_key(
244                &signing_key,
245            )],
246            0,
247        );
248        let replacement = ContractMaintenanceAuthority {
249            committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
250                &new_signing_key,
251            )],
252            threshold: 1,
253            // Per ledger's well_formed: new committee counter must be
254            // update.counter + 1. Our update inherits on-chain counter
255            // = 0, so replacement counter must be 1.
256            counter: 1,
257        };
258        let updates = vec![SingleUpdate::ReplaceAuthority(replacement)];
259        let mut rng = StdRng::seed_from_u64(2);
260        let unproven = build_unproven_maintenance_tx(
261            &mut rng,
262            MaintenanceTxOptions {
263                contract_address: dummy_address(),
264                on_chain_state: &state,
265                signing_key: &signing_key,
266                updates,
267                current_time: Timestamp::from_secs(0),
268                network_id: "local-test".to_owned(),
269                fee_balancing: None,
270            },
271        )
272        .expect("replace-authority update should serialize");
273        assert_ne!(unproven.to_tagged_bytes().unwrap(), [] as [u8; 0]);
274    }
275}