1use std::sync::Arc;
43use std::time::Duration;
44
45use moonproof_utils::rt::Instant;
46
47use moonproof_ledger::base_crypto::cost_model::{CostDuration, SyntheticCost};
48use moonproof_ledger::base_crypto::time::Timestamp;
49use moonproof_ledger::ledger::structure::{LedgerParameters, SingleUpdate};
50use moonproof_ledger::onchain_runtime::state::{
51 ContractMaintenanceAuthority, ContractState, EntryPointBuf, StateValue,
52};
53use moonproof_ledger::storage::db::InMemoryDB;
54use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
55use rand::{CryptoRng, Rng};
56
57use moonproof_runtime::ir::witnesses::Witnesses;
58use moonproof_runtime::ir_executable::IrExecutable;
59
60use crate::contract::{deploy_contract, Contract};
61use crate::error::{ContractRuntimeError, Result};
62use crate::fee_balancing::FeeBalancingConfig;
63use crate::maintenance::{build_unproven_maintenance_tx, MaintenanceTxOptions};
64use crate::providers::{ErasedProviders, HasWallet, HasZkConfig, Providers, PublicDataProvider};
65use crate::submit_insert_vk_tx::{
66 submit_insert_verifier_keys_tx, SubmitInsertVerifierKeysTxOptions,
67};
68use crate::types::{CircuitId, FinalizedTxData};
69use crate::unproven_deploy_tx::{create_unproven_deploy_tx, DeployOptions};
70
71mod plan;
72
73pub use plan::{plan_incremental_deploy, CircuitWeight, CostVector, DeployPlan, PackBudget};
74
75pub const DEFAULT_MAX_TX_BYTES: usize = usize::MAX;
79
80pub const LEDGER_TX_BYTE_LIMIT: usize = 1 << 20;
84
85const BLOCK_REF_TIME_PS: u64 = 2_000_000_000_000;
88
89const NORMAL_DISPATCH_PPM: u64 = 750_000;
92
93const BLOCK_INITIALIZATION_PPM: u64 = 100_000;
97
98const TRANSACTION_SIZE_WEIGHT_PPM: u64 = 10_000;
102
103const EXTRINSIC_BASE_WEIGHT_PS: u64 = 108_157_000;
106
107pub const NORMAL_TRANSACTION_SHARE_PPM: u64 = NORMAL_DISPATCH_PPM
115 - BLOCK_INITIALIZATION_PPM
116 - TRANSACTION_SIZE_WEIGHT_PPM
117 - (EXTRINSIC_BASE_WEIGHT_PS * 1_000_000).div_ceil(BLOCK_REF_TIME_PS);
118
119const BLOCK_LENGTH_BYTES: u64 = 1024 * 1024;
122
123const EXTRINSIC_FRAMING_BYTES: u64 = 11;
127
128const NODE_TRANSACTION_BYTE_LIMIT: u64 =
131 BLOCK_LENGTH_BYTES * NORMAL_DISPATCH_PPM / 1_000_000 - EXTRINSIC_FRAMING_BYTES;
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub struct TxMeasure {
136 pub bytes: usize,
139 pub cost: SyntheticCost,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct TransactionBudget {
147 pub max_bytes: usize,
148 pub max_cost: SyntheticCost,
149}
150
151impl TransactionBudget {
152 #[must_use]
154 pub fn new(params: &LedgerParameters, max_tx_bytes: usize) -> Self {
155 let byte_limit = params
156 .limits
157 .transaction_byte_limit
158 .min(NODE_TRANSACTION_BYTE_LIMIT);
159 let block = params.limits.block_limits;
160 let scale = |v: u64| {
162 v / 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM
163 + v % 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM / 1_000_000
164 };
165 let scale_time =
166 |d: CostDuration| CostDuration::from_picoseconds(scale(d.into_picoseconds()));
167 Self {
168 max_bytes: usize::try_from(byte_limit)
169 .unwrap_or(usize::MAX)
170 .min(max_tx_bytes),
171 max_cost: SyntheticCost {
172 read_time: scale_time(block.read_time),
173 compute_time: scale_time(block.compute_time),
174 block_usage: scale(block.block_usage),
175 bytes_written: scale(block.bytes_written),
176 bytes_churned: scale(block.bytes_churned),
177 },
178 }
179 }
180
181 #[must_use]
183 pub fn excess(&self, measure: &TxMeasure) -> Option<String> {
184 if measure.bytes > self.max_bytes {
185 return Some(format!(
186 "{} bytes, over the per-transaction limit of {}",
187 measure.bytes, self.max_bytes
188 ));
189 }
190 cost_vector(&measure.cost)
191 .first_excess(cost_vector(&self.max_cost))
192 .map(|(dimension, used, cap)| {
193 format!("{used} {dimension}, over the per-transaction limit of {cap}")
194 })
195 }
196}
197
198fn cost_vector(cost: &SyntheticCost) -> CostVector {
199 CostVector {
200 read_time_ps: cost.read_time.into_picoseconds(),
201 compute_time_ps: cost.compute_time.into_picoseconds(),
202 block_usage: cost.block_usage,
203 bytes_written: cost.bytes_written,
204 bytes_churned: cost.bytes_churned,
205 }
206}
207
208pub fn measure_tx(
215 tx: &crate::tx_phase::UnprovenTx,
216 params: &LedgerParameters,
217) -> Result<TxMeasure> {
218 let serialized = tx
219 .to_tagged_bytes()
220 .map_err(|e| ContractRuntimeError::Provider {
221 provider: "measure_tx",
222 message: format!("serializing a sizing transaction: {e}"),
223 })?
224 .len();
225 let cost = tx
226 .as_inner()
227 .cost(params, true)
228 .map_err(|e| ContractRuntimeError::Provider {
229 provider: "measure_tx",
230 message: format!("the ledger's cost model refuses the transaction: {e:?}"),
231 })?;
232 Ok(TxMeasure {
233 bytes: serialized.max(usize::try_from(cost.block_usage).unwrap_or(usize::MAX)),
234 cost,
235 })
236}
237
238#[derive(Clone)]
244pub struct PlannedCircuit {
245 pub id: CircuitId,
246 pub vk: crate::types::VerifierKey,
247}
248
249pub struct PassFee {
251 pub fee_balancing: FeeBalancingConfig,
252 pub current_time: Timestamp,
254}
255
256#[moonproof_macros::async_trait]
264pub trait PassFees: Send + Sync {
265 async fn next_pass(&self) -> Result<PassFee>;
266}
267
268pub struct IncrementalDeployOptions<'a> {
270 pub deploy: DeployOptions,
276 pub circuits: Vec<PlannedCircuit>,
279 pub max_tx_bytes: usize,
282 pub ledger_parameters: LedgerParameters,
285 pub network_id: String,
288 pub pass_fees: &'a dyn PassFees,
290 pub sync_timeout: Duration,
295}
296
297impl<'a> IncrementalDeployOptions<'a> {
298 #[must_use]
301 pub fn new(
302 deploy: DeployOptions,
303 circuits: Vec<PlannedCircuit>,
304 ledger_parameters: LedgerParameters,
305 network_id: String,
306 pass_fees: &'a dyn PassFees,
307 ) -> Self {
308 Self {
309 deploy,
310 circuits,
311 max_tx_bytes: DEFAULT_MAX_TX_BYTES,
312 ledger_parameters,
313 network_id,
314 pass_fees,
315 sync_timeout: Duration::from_mins(1),
316 }
317 }
318}
319
320pub struct MaintenancePassResult {
322 pub circuits: Vec<CircuitId>,
323 pub tx: FinalizedTxData,
324}
325
326pub struct IncrementalDeployOutcome<W: Witnesses + 'static> {
328 pub contract: Contract<W>,
330 pub plan: DeployPlan,
332 pub maintenance_passes: Vec<MaintenancePassResult>,
334}
335
336const SYNC_POLL_INTERVAL: Duration = Duration::from_secs(2);
337
338pub async fn deploy_contract_incremental<W, R>(
358 rng: &mut R,
359 executable: Arc<IrExecutable<W>>,
360 providers: Arc<ErasedProviders>,
361 options: IncrementalDeployOptions<'_>,
362) -> Result<IncrementalDeployOutcome<W>>
363where
364 W: Witnesses + 'static,
365 R: Rng + CryptoRng,
366{
367 let IncrementalDeployOptions {
368 deploy: deploy_opts,
369 circuits,
370 max_tx_bytes,
371 ledger_parameters,
372 network_id,
373 pass_fees,
374 sync_timeout,
375 } = options;
376
377 let plan = plan_deploy(
378 rng,
379 executable.as_ref(),
380 providers.as_ref(),
381 &deploy_opts,
382 &circuits,
383 &TransactionBudget::new(&ledger_parameters, max_tx_bytes),
384 &ledger_parameters,
385 )
386 .await?;
387
388 let vk_of = |id: &CircuitId| {
390 circuits
391 .iter()
392 .find(|c| &c.id == id)
393 .map(|c| c.vk.clone())
394 .expect("planner only emits circuit ids drawn from `circuits`")
395 };
396
397 let mut deploy_opts = deploy_opts;
399 deploy_opts.register_circuits = Some(plan.deploy_batch.clone());
400 let contract = Box::pin(deploy_contract(
401 rng,
402 executable.clone(),
403 providers.clone(),
404 deploy_opts,
405 ))
406 .await?;
407 let address = *contract.contract_address();
408
409 if !plan.maintenance_batches.is_empty() {
412 wait_for_contract_visible(providers.as_ref(), &address, sync_timeout).await?;
413 }
414
415 let mut maintenance_passes = Vec::with_capacity(plan.maintenance_batches.len());
417 for batch in &plan.maintenance_batches {
418 let missing = filter_absent(providers.as_ref(), &address, batch).await?;
422 if missing.is_empty() {
423 continue;
424 }
425
426 let fee = pass_fees.next_pass().await?;
427 let batch_circuits: Vec<(CircuitId, crate::types::VerifierKey)> =
428 missing.iter().map(|id| (id.clone(), vk_of(id))).collect();
429
430 let tx = submit_insert_verifier_keys_tx(
431 rng,
432 providers.as_ref(),
433 SubmitInsertVerifierKeysTxOptions {
434 contract_address: address,
435 circuits: batch_circuits,
436 current_time: fee.current_time,
437 network_id: network_id.clone(),
438 fee_balancing: Some(fee.fee_balancing),
439 },
440 )
441 .await?;
442
443 wait_for_circuits_present(providers.as_ref(), &address, &missing, sync_timeout).await?;
447
448 maintenance_passes.push(MaintenancePassResult {
449 circuits: missing,
450 tx,
451 });
452 }
453
454 Ok(IncrementalDeployOutcome {
455 contract,
456 plan,
457 maintenance_passes,
458 })
459}
460
461pub async fn plan_deploy<W, C>(
480 rng: &mut (impl Rng + CryptoRng),
481 executable: &IrExecutable<W>,
482 providers: &C,
483 base: &DeployOptions,
484 circuits: &[PlannedCircuit],
485 budget: &TransactionBudget,
486 params: &LedgerParameters,
487) -> Result<DeployPlan>
488where
489 W: Witnesses + 'static,
490 C: HasWallet + HasZkConfig + ?Sized,
491{
492 let deploy_overhead =
493 measure_deploy_tx(rng, executable, providers, base, Some(Vec::new()), params).await?;
494 if let Some(excess) = budget.excess(&deploy_overhead) {
495 return Err(ContractRuntimeError::Provider {
496 provider: "plan_deploy",
497 message: format!("an empty deploy of this contract already needs {excess}"),
498 });
499 }
500 let fee = base.fee_balancing.as_ref();
501 let maintenance_overhead =
502 measure_maintenance_tx(rng, &[], &base.network_id, base.current_time, fee, params)?;
503
504 let mut weights = Vec::with_capacity(circuits.len());
505 for circuit in circuits {
506 let deploy = measure_deploy_tx(
507 rng,
508 executable,
509 providers,
510 base,
511 Some(vec![circuit.id.clone()]),
512 params,
513 )
514 .await?;
515 let maintenance = measure_maintenance_tx(
516 rng,
517 std::slice::from_ref(circuit),
518 &base.network_id,
519 base.current_time,
520 fee,
521 params,
522 )?;
523 weights.push(CircuitWeight {
524 id: circuit.id.clone(),
525 vk_bytes: circuit.vk.as_bytes().len(),
526 deploy_cost: cost_vector(&deploy.cost)
527 .saturating_sub(cost_vector(&deploy_overhead.cost)),
528 maintenance_cost: cost_vector(&maintenance.cost)
529 .saturating_sub(cost_vector(&maintenance_overhead.cost)),
530 });
531 }
532 let packed = plan_incremental_deploy(
533 &weights,
534 &PackBudget {
535 max_tx_bytes: budget.max_bytes,
536 deploy_overhead: deploy_overhead.bytes,
537 maintenance_overhead: maintenance_overhead.bytes,
538 max_cost: cost_vector(&budget.max_cost),
539 deploy_overhead_cost: cost_vector(&deploy_overhead.cost),
540 maintenance_overhead_cost: cost_vector(&maintenance_overhead.cost),
541 },
542 )?;
543
544 let (deploy_batch, spilled) = verify_deploy_batch(
547 rng,
548 executable,
549 providers,
550 base,
551 budget,
552 params,
553 packed.deploy_batch,
554 )
555 .await?;
556 let mut pending: std::collections::VecDeque<Vec<CircuitId>> = packed.maintenance_batches.into();
557 if !spilled.is_empty() {
558 pending.push_back(spilled);
559 }
560 Ok(DeployPlan {
561 deploy_batch,
562 maintenance_batches: verify_maintenance_batches(
563 rng, base, circuits, budget, params, pending,
564 )?,
565 })
566}
567
568async fn verify_deploy_batch<W, C>(
572 rng: &mut (impl Rng + CryptoRng),
573 executable: &IrExecutable<W>,
574 providers: &C,
575 base: &DeployOptions,
576 budget: &TransactionBudget,
577 params: &LedgerParameters,
578 mut batch: Vec<CircuitId>,
579) -> Result<(Vec<CircuitId>, Vec<CircuitId>)>
580where
581 W: Witnesses + 'static,
582 C: HasWallet + HasZkConfig + ?Sized,
583{
584 let mut spilled = Vec::new();
585 while !batch.is_empty() {
586 let measure = measure_deploy_tx(
587 rng,
588 executable,
589 providers,
590 base,
591 Some(batch.clone()),
592 params,
593 )
594 .await?;
595 if budget.excess(&measure).is_none() {
596 break;
597 }
598 spilled.extend(batch.pop());
599 }
600 Ok((batch, spilled))
601}
602
603fn verify_maintenance_batches(
606 rng: &mut (impl Rng + CryptoRng),
607 base: &DeployOptions,
608 circuits: &[PlannedCircuit],
609 budget: &TransactionBudget,
610 params: &LedgerParameters,
611 mut pending: std::collections::VecDeque<Vec<CircuitId>>,
612) -> Result<Vec<Vec<CircuitId>>> {
613 let by_id = |id: &CircuitId| {
614 circuits
615 .iter()
616 .find(|c| &c.id == id)
617 .cloned()
618 .ok_or_else(|| ContractRuntimeError::Provider {
619 provider: "plan_deploy",
620 message: format!("the plan names unknown circuit '{}'", id.as_str()),
621 })
622 };
623 let mut verified = Vec::new();
624 while let Some(mut batch) = pending.pop_front() {
625 let mut spilled = Vec::new();
626 loop {
627 let planned = batch.iter().map(&by_id).collect::<Result<Vec<_>>>()?;
628 let measure = measure_maintenance_tx(
629 rng,
630 &planned,
631 &base.network_id,
632 base.current_time,
633 base.fee_balancing.as_ref(),
634 params,
635 )?;
636 match budget.excess(&measure) {
637 None => break,
638 Some(excess) if batch.len() == 1 => {
639 return Err(ContractRuntimeError::Provider {
640 provider: "plan_deploy",
641 message: format!(
642 "circuit '{}' alone needs {excess} in a maintenance transaction; \
643 this circuit cannot be deployed",
644 batch[0].as_str()
645 ),
646 });
647 }
648 Some(_) => spilled.extend(batch.pop()),
649 }
650 }
651 verified.push(batch);
652 if !spilled.is_empty() {
653 pending.push_back(spilled);
654 }
655 }
656 Ok(verified)
657}
658
659pub async fn measure_deploy_tx<W, C>(
671 rng: &mut (impl Rng + CryptoRng),
672 executable: &IrExecutable<W>,
673 providers: &C,
674 base: &DeployOptions,
675 register_circuits: Option<Vec<CircuitId>>,
676 params: &LedgerParameters,
677) -> Result<TxMeasure>
678where
679 W: Witnesses + 'static,
680 C: HasWallet + HasZkConfig + ?Sized,
681{
682 let sizing = DeployOptions {
683 constructor_args: base.constructor_args.clone(),
684 initial_private_state: base.initial_private_state.clone(),
685 signing_key: None,
686 additional_coin_enc_public_key_mappings: base
687 .additional_coin_enc_public_key_mappings
688 .clone(),
689 current_time: base.current_time,
690 network_id: base.network_id.clone(),
691 persistent_state: None,
692 fee_balancing: base.fee_balancing.clone(),
693 register_circuits,
694 };
695 let unproven = create_unproven_deploy_tx(rng, executable, providers, sizing).await?;
696 let tx =
697 unproven
698 .private
699 .unproven_tx
700 .as_ref()
701 .ok_or_else(|| ContractRuntimeError::Provider {
702 provider: "measure_deploy_tx",
703 message: "sizing deploy tx was not populated".to_owned(),
704 })?;
705 measure_tx(tx, params)
706}
707
708pub(crate) fn build_sizing_maintenance_tx(
709 rng: &mut (impl Rng + CryptoRng),
710 circuits: &[PlannedCircuit],
711 network_id: &str,
712 current_time: Timestamp,
713 fee_balancing: Option<&FeeBalancingConfig>,
714) -> Result<crate::tx_phase::UnprovenTx> {
715 let sizing_sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x01u8; 32])
718 .expect("32 bytes parse into a SigningKey");
719 let sizing_state = ContractState::<InMemoryDB>::new(
720 StateValue::Null,
721 StorageHashMap::new(),
722 ContractMaintenanceAuthority {
723 committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
724 &sizing_sk,
725 )],
726 threshold: 1,
727 counter: 0,
728 },
729 );
730 let mut updates = Vec::with_capacity(circuits.len());
731 for circuit in circuits {
732 let entry: EntryPointBuf = circuit.id.as_str().as_bytes().into();
733 let ledger_vk: moonproof_ledger::transient_crypto::proofs::VerifierKey =
734 moonproof_ledger::serialize::tagged_deserialize(&mut circuit.vk.as_bytes()).map_err(
735 |e| ContractRuntimeError::Deserialize {
736 context: "measure_maintenance_tx::tagged_deserialize(VerifierKey)",
737 source: e,
738 },
739 )?;
740 updates.push(SingleUpdate::VerifierKeyInsert(
741 entry,
742 moonproof_ledger::versioned_verifier_key(ledger_vk),
743 ));
744 }
745 build_unproven_maintenance_tx(
746 rng,
747 MaintenanceTxOptions {
748 contract_address: moonproof_ledger::coin_structure::contract::ContractAddress(
749 moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
750 ),
751 on_chain_state: &sizing_state,
752 signing_key: &sizing_sk,
753 updates,
754 current_time,
755 network_id: network_id.to_owned(),
756 fee_balancing: fee_balancing.cloned(),
757 },
758 )
759}
760
761fn measure_maintenance_tx(
766 rng: &mut (impl Rng + CryptoRng),
767 circuits: &[PlannedCircuit],
768 network_id: &str,
769 current_time: Timestamp,
770 fee_balancing: Option<&FeeBalancingConfig>,
771 params: &LedgerParameters,
772) -> Result<TxMeasure> {
773 let unproven =
774 build_sizing_maintenance_tx(rng, circuits, network_id, current_time, fee_balancing)?;
775 measure_tx(&unproven, params)
776}
777
778async fn filter_absent<C: Providers + ?Sized>(
782 providers: &C,
783 address: &moonproof_ledger::coin_structure::contract::ContractAddress,
784 batch: &[CircuitId],
785) -> Result<Vec<CircuitId>> {
786 let state = providers
787 .public_data()
788 .query_contract_state(address, None)
789 .await?;
790 let Some(state) = state else {
791 return Ok(batch.to_vec());
795 };
796 Ok(batch
797 .iter()
798 .filter(|id| {
799 let entry: EntryPointBuf = id.as_str().as_bytes().into();
800 state.operations.get(&entry).is_none()
801 })
802 .cloned()
803 .collect())
804}
805
806async fn wait_for_contract_visible<C: Providers + ?Sized>(
808 providers: &C,
809 address: &moonproof_ledger::coin_structure::contract::ContractAddress,
810 timeout: Duration,
811) -> Result<()> {
812 let start = Instant::now();
813 loop {
814 if providers
815 .public_data()
816 .query_contract_state(address, None)
817 .await?
818 .is_some()
819 {
820 return Ok(());
821 }
822 if start.elapsed() >= timeout {
823 return Err(ContractRuntimeError::Provider {
824 provider: "deploy_contract_incremental",
825 message: format!(
826 "timed out after {:?} waiting for the indexer to surface deployed contract {}",
827 timeout,
828 moonproof_runtime::state::contract_address_to_hex(address),
829 ),
830 });
831 }
832 moonproof_utils::rt::sleep(SYNC_POLL_INTERVAL).await;
833 }
834}
835
836async fn wait_for_circuits_present<C: Providers + ?Sized>(
840 providers: &C,
841 address: &moonproof_ledger::coin_structure::contract::ContractAddress,
842 batch: &[CircuitId],
843 timeout: Duration,
844) -> Result<()> {
845 let start = Instant::now();
846 loop {
847 if let Some(state) = providers
848 .public_data()
849 .query_contract_state(address, None)
850 .await?
851 {
852 let all_present = batch.iter().all(|id| {
853 let entry: EntryPointBuf = id.as_str().as_bytes().into();
854 state.operations.get(&entry).is_some()
855 });
856 if all_present {
857 return Ok(());
858 }
859 }
860 if start.elapsed() >= timeout {
861 return Err(ContractRuntimeError::Provider {
862 provider: "deploy_contract_incremental",
863 message: format!(
864 "timed out after {:?} waiting for the indexer to reflect an inserted batch \
865 ({} circuit(s)) on contract {}",
866 timeout,
867 batch.len(),
868 moonproof_runtime::state::contract_address_to_hex(address),
869 ),
870 });
871 }
872 moonproof_utils::rt::sleep(SYNC_POLL_INTERVAL).await;
873 }
874}
875
876#[cfg(test)]
877mod tests {
878 use super::*;
879 use crate::providers::{FileSystemZkConfigProvider, ZkConfigProvider};
880 use crate::test_helpers::scripted_providers;
881 use crate::types::TxStatus;
882 use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
883 use moonproof_runtime::NoWitnesses;
884 use moonproof_runtime_ir::RuntimeValue;
885 use rand::rngs::StdRng;
886 use rand::SeedableRng;
887
888 const FOREIGN_CURVES: &str = "extracted_foreign_curves_provable";
889
890 fn fixtures_dir() -> std::path::PathBuf {
891 let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
892 p.pop();
893 p.push("runtime-ir/tests/fixtures");
894 p
895 }
896
897 async fn foreign_curves() -> (IrExecutable<NoWitnesses>, Vec<PlannedCircuit>) {
900 let base = IrExecutable::from_path(
901 fixtures_dir().join(format!("{FOREIGN_CURVES}.cbor")),
902 Arc::new(NoWitnesses),
903 )
904 .unwrap();
905 let zk = FileSystemZkConfigProvider::new(fixtures_dir().join(FOREIGN_CURVES));
906 let mut planned = Vec::new();
907 let mut keys = std::collections::HashMap::new();
908 for id in base.provable_circuit_ids() {
909 let vk = zk.get_verifier_key(&id).await.unwrap();
910 keys.insert(id.as_str().to_owned(), vk.clone());
911 planned.push(PlannedCircuit { id, vk });
912 }
913 (base.with_verifier_keys(keys), planned)
914 }
915
916 fn deploy_options() -> DeployOptions {
917 DeployOptions {
918 constructor_args: RuntimeValue::Null,
919 initial_private_state: RuntimeValue::Null,
920 signing_key: None,
921 additional_coin_enc_public_key_mappings: None,
922 current_time: Timestamp::from_secs(1_700_000_000),
923 network_id: "local-test".to_owned(),
924 persistent_state: None,
925 fee_balancing: None,
926 register_circuits: None,
927 }
928 }
929
930 #[test]
931 fn a_normal_transaction_gets_the_node_share_of_each_block_limit() {
932 assert_eq!(NORMAL_TRANSACTION_SHARE_PPM, 639_945);
935 let budget = TransactionBudget::new(&INITIAL_PARAMETERS, DEFAULT_MAX_TX_BYTES);
936 let block = INITIAL_PARAMETERS.limits.block_limits;
937 assert_eq!(
938 budget.max_cost.bytes_written,
939 block.bytes_written * NORMAL_TRANSACTION_SHARE_PPM / 1_000_000
940 );
941 assert_eq!(
942 budget.max_cost.compute_time.into_picoseconds(),
943 block.compute_time.into_picoseconds() / 1_000_000 * NORMAL_TRANSACTION_SHARE_PPM
944 );
945 assert_eq!(budget.max_bytes, 786_421);
946 }
947
948 #[test]
949 fn a_byte_cap_tighter_than_the_limits_wins() {
950 let budget = TransactionBudget::new(&INITIAL_PARAMETERS, 12_000);
951 assert_eq!(budget.max_bytes, 12_000);
952 }
953
954 #[test]
955 fn excess_names_the_dimension_over_its_limit() {
956 let budget = TransactionBudget::new(&INITIAL_PARAMETERS, DEFAULT_MAX_TX_BYTES);
957 let within = TxMeasure {
958 bytes: 1_000,
959 cost: SyntheticCost::ZERO,
960 };
961 assert_eq!(budget.excess(&within), None);
962 let writes_too_much = TxMeasure {
963 bytes: 1_000,
964 cost: SyntheticCost {
965 bytes_written: budget.max_cost.bytes_written + 1,
966 ..SyntheticCost::ZERO
967 },
968 };
969 let excess = budget.excess(&writes_too_much).unwrap();
970 assert!(excess.contains("bytes written"), "{excess}");
971 let too_large = TxMeasure {
972 bytes: budget.max_bytes + 1,
973 cost: SyntheticCost::ZERO,
974 };
975 assert!(budget.excess(&too_large).unwrap().contains("bytes"));
976 }
977
978 #[tokio::test]
983 async fn the_foreign_curves_deploy_is_split_by_cost_not_bytes() {
984 if !moonproof_ledger::HAS_ZKIR_V3 {
985 return;
986 }
987 let (executable, planned) = foreign_curves().await;
988 assert_eq!(planned.len(), 13);
989 let (providers, _) = scripted_providers(None, None, TxStatus::SucceedEntirely);
990 let base = deploy_options();
991 let params = INITIAL_PARAMETERS;
992 let budget = TransactionBudget::new(¶ms, DEFAULT_MAX_TX_BYTES);
993 let mut rng = StdRng::seed_from_u64(0xF0_C0);
994
995 let single_shot =
996 measure_deploy_tx(&mut rng, &executable, &providers, &base, None, ¶ms)
997 .await
998 .unwrap();
999 assert!(single_shot.bytes < budget.max_bytes, "{single_shot:?}");
1000 let excess = budget
1001 .excess(&single_shot)
1002 .expect("the single-shot deploy must exceed the cost limits");
1003 assert!(excess.contains("bytes written"), "{excess}");
1004
1005 let plan = plan_deploy(
1006 &mut rng,
1007 &executable,
1008 &providers,
1009 &base,
1010 &planned,
1011 &budget,
1012 ¶ms,
1013 )
1014 .await
1015 .unwrap();
1016 assert!(!plan.is_single_shot(), "{plan:?}");
1017 assert_eq!(plan.total_circuits(), 13);
1018
1019 let deploy = measure_deploy_tx(
1020 &mut rng,
1021 &executable,
1022 &providers,
1023 &base,
1024 Some(plan.deploy_batch.clone()),
1025 ¶ms,
1026 )
1027 .await
1028 .unwrap();
1029 assert_eq!(
1030 budget.excess(&deploy),
1031 None,
1032 "deploy batch {:?}",
1033 plan.deploy_batch
1034 );
1035 for batch in &plan.maintenance_batches {
1036 let circuits: Vec<PlannedCircuit> = batch
1037 .iter()
1038 .map(|id| planned.iter().find(|c| &c.id == id).unwrap().clone())
1039 .collect();
1040 let measure = measure_maintenance_tx(
1041 &mut rng,
1042 &circuits,
1043 &base.network_id,
1044 base.current_time,
1045 None,
1046 ¶ms,
1047 )
1048 .unwrap();
1049 assert_eq!(budget.excess(&measure), None, "maintenance batch {batch:?}");
1050 }
1051 }
1052}