1use moonproof_ledger::base_crypto::fab::AlignedValue;
27use moonproof_ledger::base_crypto::time::Timestamp;
28use moonproof_ledger::coin_structure::coin::{PublicAddress, TokenType};
29use moonproof_ledger::coin_structure::contract::ContractAddress;
30use moonproof_ledger::ledger::construct::{
31 partition_transcripts, ContractCallPrototype, PreTranscript,
32};
33use moonproof_ledger::ledger::structure::{
34 ContractDeploy, Intent, LedgerParameters, MaintenanceUpdate, ProofPreimageMarker,
35};
36use moonproof_ledger::ledger::structure::{Transaction, UnshieldedOffer, UtxoOutput, UtxoSpend};
37use moonproof_ledger::onchain_runtime::communication_commitment;
38use moonproof_ledger::onchain_runtime::context::ClaimedUnshieldedSpendsKey;
39use moonproof_ledger::onchain_runtime::context::QueryContext;
40use moonproof_ledger::onchain_runtime::ops::Op;
41use moonproof_ledger::onchain_runtime::result_mode::{ResultModeGather, ResultModeVerify};
42use moonproof_ledger::onchain_runtime::state::{ContractOperation, ContractState};
43use moonproof_ledger::onchain_runtime::transcript::Transcript;
44use moonproof_ledger::signatures::Signature;
45use moonproof_ledger::storage::db::InMemoryDB;
46use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
47use moonproof_ledger::transient_crypto::curve::Fr;
48use moonproof_ledger::zswap::ledger::State as ZswapChainState;
49use rand::{CryptoRng, Rng};
50
51use crate::error::{ContractRuntimeError, Result};
52use crate::types::CircuitId;
53use crate::utils::zswap_utils::{
54 assert_receives_match_claims, zswap_calls_to_segmented_offer, CompactZswapLocalState,
55 EncryptionPublicKeyResolver, ZswapCallContribution,
56};
57
58#[must_use]
61pub fn ttl_one_hour(current_time: Timestamp) -> Timestamp {
62 current_time + moonproof_ledger::base_crypto::time::Duration::from_secs(60 * 60)
63}
64
65pub fn one_intent_at_segment_one<R: Rng + CryptoRng + ?Sized>(
76 rng: &mut R,
77 calls: Vec<ContractCallPrototype<InMemoryDB>>,
78 updates: Vec<MaintenanceUpdate<InMemoryDB>>,
79 deploys: Vec<ContractDeploy<InMemoryDB>>,
80 tblock: Timestamp,
81) -> moonproof_ledger::storage::storage::HashMap<
82 u16,
83 Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
84 InMemoryDB,
85> {
86 let intents = moonproof_ledger::storage::storage::HashMap::<
87 u16,
88 Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
89 InMemoryDB,
90 >::new();
91 intents.insert(
92 1,
93 Intent::new(
94 rng,
95 None,
96 None,
97 calls,
98 updates,
99 deploys,
100 None,
101 ttl_one_hour(tblock),
102 ),
103 )
104}
105
106pub fn build_contract_deploy<R: Rng + CryptoRng>(
120 rng: &mut R,
121 initial_state: ContractState<InMemoryDB>,
122) -> Result<(
123 ContractDeploy<InMemoryDB>,
124 ContractAddress,
125 ContractState<InMemoryDB>,
126)> {
127 if let Some(limit) = moonproof_ledger::MAX_CONTRACT_OPERATIONS {
128 let operations = initial_state.operations.size() as u64;
129 if operations > limit {
130 return Err(ContractRuntimeError::Provider {
131 provider: "ledger_utils::build_contract_deploy",
132 message: format!(
133 "contract declares {operations} operations; the ledger accepts at most \
134 {limit} per contract, so split it into several contracts"
135 ),
136 });
137 }
138 }
139 let deploy = ContractDeploy::new(rng, initial_state.clone());
140 let address = deploy.address();
141 Ok((deploy, address, initial_state))
142}
143
144pub fn required_operation(
149 state: &ContractState<InMemoryDB>,
150 circuit_id: &CircuitId,
151) -> Result<ContractOperation> {
152 let key: moonproof_ledger::onchain_runtime::state::EntryPointBuf =
153 circuit_id.as_str().as_bytes().into();
154 state
155 .operations
156 .get(&key)
157 .map(|op| (*op).clone())
158 .ok_or_else(|| ContractRuntimeError::Provider {
159 provider: "ledger_utils::required_operation",
160 message: format!(
161 "operation '{}' is undefined for contract state",
162 circuit_id.as_str()
163 ),
164 })
165}
166
167pub struct ContractCallPrototypeInputs {
171 pub contract_address: ContractAddress,
172 pub circuit_id: CircuitId,
173 pub initial_contract_state: ContractState<InMemoryDB>,
174 pub input: AlignedValue,
175 pub output: AlignedValue,
176 pub public_transcript_ops: Vec<Op<ResultModeGather, InMemoryDB>>,
181 pub private_transcript_outputs: Vec<AlignedValue>,
182 pub communication_commitment_rand: Fr,
183 pub popeq_read_results: Vec<AlignedValue>,
189 pub ledger_parameters: LedgerParameters,
196}
197
198pub fn build_contract_call_prototype(
209 inputs: ContractCallPrototypeInputs,
210) -> Result<moonproof_ledger::ledger::construct::ContractCallPrototype<InMemoryDB>> {
211 let ledger_parameters = inputs.ledger_parameters;
212 let call = ContractCallParts {
213 contract_address: inputs.contract_address,
214 circuit_id: inputs.circuit_id,
215 initial_contract_state: inputs.initial_contract_state,
216 caller: None,
217 input: inputs.input,
218 output: inputs.output,
219 public_transcript_ops: inputs.public_transcript_ops,
220 private_transcript_outputs: inputs.private_transcript_outputs,
221 communication_commitment_rand: inputs.communication_commitment_rand,
222 popeq_read_results: inputs.popeq_read_results,
223 };
224 build_contract_call_prototypes(vec![call], &ledger_parameters, Timestamp::from_secs(0))?
225 .pop()
226 .ok_or_else(|| ContractRuntimeError::Provider {
227 provider: "ledger_utils::partition_transcripts",
228 message: "partition_transcripts returned an empty result vector".to_owned(),
229 })
230}
231
232pub struct ContractCallParts {
234 pub contract_address: ContractAddress,
235 pub circuit_id: CircuitId,
236 pub initial_contract_state: ContractState<InMemoryDB>,
238 pub caller: Option<ContractAddress>,
241 pub input: AlignedValue,
242 pub output: AlignedValue,
243 pub public_transcript_ops: Vec<Op<ResultModeGather, InMemoryDB>>,
246 pub private_transcript_outputs: Vec<AlignedValue>,
247 pub communication_commitment_rand: Fr,
250 pub popeq_read_results: Vec<AlignedValue>,
251}
252
253pub fn build_contract_call_prototypes(
266 calls: Vec<ContractCallParts>,
267 ledger_parameters: &LedgerParameters,
268 tblock: Timestamp,
269) -> Result<Vec<moonproof_ledger::ledger::construct::ContractCallPrototype<InMemoryDB>>> {
270 struct Prepared {
271 call: ContractCallParts,
272 op: ContractOperation,
273 key_location: moonproof_ledger::transient_crypto::proofs::KeyLocation,
274 }
275 let mut prepared = Vec::with_capacity(calls.len());
276 let mut pre_transcripts = Vec::with_capacity(calls.len());
277 for mut call in calls {
278 let op = required_operation(&call.initial_contract_state, &call.circuit_id)?;
279 let location = if moonproof_ledger::ERA == moonproof_ledger::LedgerEra::V9 {
283 crate::key_location::ContractKeyLocation::for_operation(
284 call.contract_address,
285 &call.circuit_id,
286 &op,
287 )?
288 .encode()
289 } else {
290 call.circuit_id.as_str().to_owned()
291 };
292 let key_location = moonproof_ledger::transient_crypto::proofs::KeyLocation(
293 std::borrow::Cow::Owned(location),
294 );
295 let program = verify_mode_program(
296 std::mem::take(&mut call.public_transcript_ops),
297 std::mem::take(&mut call.popeq_read_results),
298 )?;
299 let mut context = QueryContext::new(
300 call.initial_contract_state.data.clone(),
301 call.contract_address,
302 );
303 context.call_context.tblock = tblock;
304 context.call_context.balance = call.initial_contract_state.balance.clone();
305 context.call_context.caller = call
306 .caller
307 .map(moonproof_ledger::coin_structure::coin::PublicAddress::Contract);
308 pre_transcripts.push(PreTranscript::<InMemoryDB> {
309 context,
310 program,
311 comm_comm: Some(communication_commitment(
312 call.input.clone(),
313 call.output.clone(),
314 call.communication_commitment_rand,
315 )),
316 });
317 prepared.push(Prepared {
318 call,
319 op,
320 key_location,
321 });
322 }
323
324 let partitioned = partition_transcripts::<InMemoryDB>(&pre_transcripts, ledger_parameters)
325 .map_err(|e| ContractRuntimeError::Provider {
326 provider: "ledger_utils::partition_transcripts",
327 message: format!("partition_transcripts failed: {e:?}"),
328 })?;
329 if partitioned.len() != prepared.len() {
330 return Err(ContractRuntimeError::Provider {
331 provider: "ledger_utils::partition_transcripts",
332 message: format!(
333 "partition_transcripts returned {} transcript pairs for {} calls",
334 partitioned.len(),
335 prepared.len()
336 ),
337 });
338 }
339 Ok(prepared
340 .into_iter()
341 .zip(partitioned)
342 .map(
343 |(p, (guaranteed_public_transcript, fallible_public_transcript))| {
344 moonproof_ledger::ledger::construct::ContractCallPrototype {
345 address: p.call.contract_address,
346 entry_point: p.call.circuit_id.as_str().as_bytes().into(),
347 op: p.op,
348 guaranteed_public_transcript,
349 fallible_public_transcript,
350 private_transcript_outputs: p.call.private_transcript_outputs,
351 input: p.call.input,
352 output: p.call.output,
353 communication_commitment_rand: p.call.communication_commitment_rand,
354 key_location: p.key_location,
355 }
356 },
357 )
358 .collect())
359}
360
361fn verify_mode_program(
365 ops: Vec<Op<ResultModeGather, InMemoryDB>>,
366 popeq_read_results: Vec<AlignedValue>,
367) -> Result<Vec<Op<ResultModeVerify, InMemoryDB>>> {
368 let mut popeq_iter = popeq_read_results.into_iter();
374 let mut popeq_drained = false;
375 let verify_mode_ops: Vec<Op<ResultModeVerify, InMemoryDB>> = ops
376 .into_iter()
377 .map(|op| {
378 op.translate::<ResultModeVerify, _>(|()| {
379 if let Some(v) = popeq_iter.next() {
380 v
381 } else {
382 popeq_drained = true;
383 AlignedValue::from(())
384 }
385 })
386 })
387 .filter(|op| match op {
388 Op::Idx { path, .. } => !path.is_empty(),
392 Op::Ins { n, .. } => *n != 0,
393 _ => true,
394 })
395 .collect();
396 if popeq_drained {
397 return Err(ContractRuntimeError::Provider {
398 provider: "ledger_utils::build_contract_call_prototype",
399 message: "circuit emitted more Op::Popeq ops than the executable's \
400 popeq_read_results supplied — every Popeq must be paired \
401 with a gather-mode read result"
402 .to_owned(),
403 });
404 }
405 let leftover = popeq_iter.count();
406 if leftover > 0 {
407 return Err(ContractRuntimeError::Provider {
408 provider: "ledger_utils::build_contract_call_prototype",
409 message: format!(
410 "executable supplied {leftover} more popeq_read_results than the \
411 circuit consumed; pair each Op::Popeq with exactly one read result"
412 ),
413 });
414 }
415 Ok(verify_mode_ops)
416}
417
418pub fn user_addressed_unshielded_outputs(
428 transcript: Option<&Transcript<InMemoryDB>>,
429) -> Result<Vec<UtxoOutput>> {
430 let Some(transcript) = transcript else {
431 return Ok(Vec::new());
432 };
433 let mut outputs = Vec::new();
434 for entry in transcript.effects.claimed_unshielded_spends.iter() {
435 let (key, value) = &*entry;
436 let ClaimedUnshieldedSpendsKey(token_type, address) = &**key;
437 let PublicAddress::User(owner) = address else {
438 continue;
439 };
440 let type_ = match token_type {
441 TokenType::Unshielded(token) => *token,
442 TokenType::Dust => continue,
443 TokenType::Shielded(token) => {
444 return Err(ContractRuntimeError::Provider {
445 provider: "ledger_utils::user_addressed_unshielded_outputs",
446 message: format!(
447 "a transcript claims an unshielded spend of shielded token {} to a \
448 user; no unshielded output can carry a shielded token",
449 hex::encode(token.0 .0)
450 ),
451 });
452 }
453 };
454 outputs.push(UtxoOutput {
455 value: **value,
456 owner: *owner,
457 type_,
458 });
459 }
460 Ok(outputs)
461}
462
463pub struct AssembledCall<'a> {
466 pub prototype: ContractCallPrototype<InMemoryDB>,
467 pub zswap_local_state: &'a CompactZswapLocalState,
468 pub zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
471}
472
473const FIRST_RANDOM_SEGMENT: u16 = 2;
478
479pub fn create_unproven_ledger_call_tx<R: Rng + CryptoRng>(
497 rng: &mut R,
498 calls: Vec<AssembledCall<'_>>,
499 resolver: &EncryptionPublicKeyResolver,
500 network_id: &str,
501 ttl: Timestamp,
502) -> Result<Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>> {
503 let segment = rng.gen_range(FIRST_RANDOM_SEGMENT..u16::MAX);
504
505 let mut guaranteed_outputs = Vec::new();
506 let mut fallible_outputs = Vec::new();
507 for call in &calls {
508 guaranteed_outputs.extend(user_addressed_unshielded_outputs(
509 call.prototype.guaranteed_public_transcript.as_ref(),
510 )?);
511 fallible_outputs.extend(user_addressed_unshielded_outputs(
512 call.prototype.fallible_public_transcript.as_ref(),
513 )?);
514 }
515
516 let contributions: Vec<ZswapCallContribution<'_>> = calls
517 .iter()
518 .map(|call| ZswapCallContribution {
519 contract_address: Some(call.prototype.address),
520 zswap_local_state: call.zswap_local_state,
521 zswap_chain_state: call.zswap_chain_state,
522 partitioned_transcript: (
523 call.prototype.guaranteed_public_transcript.as_ref(),
524 call.prototype.fallible_public_transcript.as_ref(),
525 ),
526 })
527 .collect();
528 let offers = zswap_calls_to_segmented_offer(rng, &contributions, resolver, segment)?;
529 let claims: Vec<_> = contributions
530 .iter()
531 .filter_map(|c| c.contract_address.map(|a| (a, c.partitioned_transcript)))
532 .collect();
533 assert_receives_match_claims(&claims, &offers)?;
534
535 let intent = Intent::new(
536 rng,
537 unshielded_offer(guaranteed_outputs),
538 unshielded_offer(fallible_outputs),
539 calls.into_iter().map(|call| call.prototype).collect(),
540 Vec::new(),
541 Vec::new(),
542 None,
543 ttl,
544 );
545 let intents = moonproof_ledger::storage::storage::HashMap::new().insert(segment, intent);
546 let fallible_coins = match offers.fallible {
547 Some(offer) => moonproof_ledger::storage::storage::HashMap::new().insert(segment, offer),
548 None => moonproof_ledger::storage::storage::HashMap::new(),
549 };
550 Ok(Transaction::new(
551 network_id.to_owned(),
552 intents,
553 offers.guaranteed,
554 fallible_coins,
555 ))
556}
557
558fn unshielded_offer(
561 mut outputs: Vec<UtxoOutput>,
562) -> Option<UnshieldedOffer<Signature, InMemoryDB>> {
563 outputs.sort();
564 (!outputs.is_empty()).then(|| UnshieldedOffer {
565 inputs: Vec::<UtxoSpend>::new().into(),
566 outputs: outputs.into(),
567 signatures: Vec::<Signature>::new().into(),
568 })
569}
570
571#[cfg(test)]
572mod tests {
573 use super::*;
574 use moonproof_ledger::onchain_runtime::state::{
575 ContractMaintenanceAuthority, EntryPointBuf, StateValue,
576 };
577 use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
578 use rand::rngs::StdRng;
579 use rand::SeedableRng;
580
581 fn fixture_verifier_key() -> Vec<u8> {
603 let keys = if moonproof_ledger::ERA == moonproof_ledger::LedgerEra::V9 {
604 "keys"
605 } else {
606 "keys-v2"
607 };
608 let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
609 p.pop();
610 p.push(format!(
611 "test-fixtures/contracts/counter/{keys}/increment.verifier"
612 ));
613 std::fs::read(p).unwrap()
614 }
615
616 fn dummy_contract_state_with_circuit(circuit_id: &str) -> ContractState<InMemoryDB> {
617 let vk = fixture_verifier_key();
618 let op = moonproof_ledger::contract_operation(Some(
619 moonproof_ledger::serialize::tagged_deserialize(&mut vk.as_slice()).unwrap(),
620 ));
621 let op_key: EntryPointBuf = circuit_id.as_bytes().into();
622 ContractState::<InMemoryDB>::new(
623 StateValue::Null,
624 StorageHashMap::new().insert(op_key, op),
625 ContractMaintenanceAuthority::default(),
626 )
627 }
628
629 #[test]
630 fn deploy_over_the_operations_cap_is_refused() {
631 let Some(limit) = moonproof_ledger::MAX_CONTRACT_OPERATIONS else {
632 return;
633 };
634 let state_with = |n: u64| {
635 let ops = (0..n).fold(StorageHashMap::new(), |ops, i| {
636 let key: EntryPointBuf = format!("op{i}").as_bytes().into();
637 ops.insert(key, moonproof_ledger::contract_operation(None))
638 });
639 ContractState::<InMemoryDB>::new(
640 StateValue::Null,
641 ops,
642 ContractMaintenanceAuthority::default(),
643 )
644 };
645 let mut rng = StdRng::seed_from_u64(3);
646 assert!(build_contract_deploy(&mut rng, state_with(limit)).is_ok());
647 assert!(build_contract_deploy(&mut rng, state_with(limit + 1)).is_err());
648 }
649
650 #[test]
651 fn ttl_one_hour_advances_exactly_one_hour() {
652 let base = Timestamp::from_secs(1_700_000_000);
653 let ttl = ttl_one_hour(base);
654 assert_eq!(
655 ttl,
656 base + moonproof_ledger::base_crypto::time::Duration::from_secs(3600)
657 );
658 }
659
660 #[test]
665 fn build_contract_deploy_returns_derived_address_matching_deploy() {
666 let mut rng = StdRng::seed_from_u64(0xDEAD);
667 let state = dummy_contract_state_with_circuit("noop");
668 let (deploy, address, returned_state) = build_contract_deploy(&mut rng, state).unwrap();
669 assert_eq!(deploy.address(), address);
670 let mut bytes = Vec::new();
674 moonproof_ledger::serialize::tagged_serialize(&returned_state, &mut bytes).unwrap();
675 assert_ne!(bytes, [] as [u8; 0]);
676 }
677
678 #[test]
679 fn required_operation_finds_declared_circuit() {
680 let state = dummy_contract_state_with_circuit("increment");
681 let op = required_operation(&state, &CircuitId::new("increment")).unwrap();
682 let _ = format!("{op:?}");
686 }
687
688 #[test]
690 fn required_operation_errors_on_missing_circuit() {
691 let state = dummy_contract_state_with_circuit("increment");
692 let err = required_operation(&state, &CircuitId::new("missing")).unwrap_err();
693 matches!(err, ContractRuntimeError::Provider { .. });
694 assert!(format!("{err}").contains("missing"));
695 }
696
697 #[test]
706 fn build_contract_call_prototype_populates_all_fields() {
707 let state = dummy_contract_state_with_circuit("increment");
708 let address = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32]));
709 let mut rng = StdRng::seed_from_u64(1);
710 let rand: moonproof_ledger::transient_crypto::curve::Fr = rng.r#gen();
711 let inputs = ContractCallPrototypeInputs {
712 contract_address: address,
713 circuit_id: CircuitId::new("increment"),
714 initial_contract_state: state,
715 input: AlignedValue::from(0u8),
716 output: AlignedValue::from(0u8),
717 public_transcript_ops: Vec::new(),
718 private_transcript_outputs: Vec::new(),
719 communication_commitment_rand: rand,
720 popeq_read_results: Vec::new(),
721 ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
722 };
723 let prototype = build_contract_call_prototype(inputs).unwrap();
724 assert_eq!(prototype.address, address);
725 assert_eq!(prototype.entry_point.as_ref(), b"increment");
726 let expected_location = if moonproof_ledger::ERA == moonproof_ledger::LedgerEra::V9 {
727 format!(
728 "contract:{}/increment?vk={}",
729 "33".repeat(32),
730 hex::encode(crate::key_location::hash_verifier_key(
731 &fixture_verifier_key()
732 ))
733 )
734 } else {
735 "increment".to_owned()
736 };
737 assert_eq!(prototype.key_location.0, expected_location);
738 }
739
740 #[test]
743 fn a_call_to_an_operation_without_a_verifier_key_is_refused() {
744 if moonproof_ledger::ERA != moonproof_ledger::LedgerEra::V9 {
745 return;
746 }
747 let op_key: EntryPointBuf = b"increment".as_slice().into();
748 let state = ContractState::<InMemoryDB>::new(
749 StateValue::Null,
750 StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
751 ContractMaintenanceAuthority::default(),
752 );
753 let mut rng = StdRng::seed_from_u64(1);
754 let inputs = ContractCallPrototypeInputs {
755 contract_address: ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput(
756 [0x33; 32],
757 )),
758 circuit_id: CircuitId::new("increment"),
759 initial_contract_state: state,
760 input: AlignedValue::from(0u8),
761 output: AlignedValue::from(0u8),
762 public_transcript_ops: Vec::new(),
763 private_transcript_outputs: Vec::new(),
764 communication_commitment_rand: rng.r#gen(),
765 popeq_read_results: Vec::new(),
766 ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
767 };
768 assert!(build_contract_call_prototype(inputs).is_err());
769 }
770
771 #[test]
776 fn build_contract_call_prototype_rejects_excess_popeq_results() {
777 let state = dummy_contract_state_with_circuit("increment");
778 let address = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32]));
779 let mut rng = StdRng::seed_from_u64(1);
780 let rand: moonproof_ledger::transient_crypto::curve::Fr = rng.r#gen();
781 let inputs = ContractCallPrototypeInputs {
782 contract_address: address,
783 circuit_id: CircuitId::new("increment"),
784 initial_contract_state: state,
785 input: AlignedValue::from(0u8),
786 output: AlignedValue::from(0u8),
787 public_transcript_ops: Vec::new(),
788 private_transcript_outputs: Vec::new(),
789 communication_commitment_rand: rand,
790 popeq_read_results: vec![AlignedValue::from(7u64)],
792 ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
793 };
794 let err = build_contract_call_prototype(inputs).unwrap_err();
795 let msg = format!("{err}");
796 assert!(msg.contains("more popeq_read_results"), "{msg}");
797 }
798
799 #[test]
804 fn build_contract_call_prototype_rejects_missing_popeq_result() {
805 use moonproof_ledger::onchain_runtime::ops::Op;
806 let state = dummy_contract_state_with_circuit("increment");
807 let address = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32]));
808 let mut rng = StdRng::seed_from_u64(1);
809 let rand: moonproof_ledger::transient_crypto::curve::Fr = rng.r#gen();
810 let popeq: Op<ResultModeGather, InMemoryDB> = Op::Popeq {
812 cached: false,
813 result: (),
814 };
815 let inputs = ContractCallPrototypeInputs {
816 contract_address: address,
817 circuit_id: CircuitId::new("increment"),
818 initial_contract_state: state,
819 input: AlignedValue::from(0u8),
820 output: AlignedValue::from(0u8),
821 public_transcript_ops: vec![popeq],
822 private_transcript_outputs: Vec::new(),
823 communication_commitment_rand: rand,
824 popeq_read_results: Vec::new(),
825 ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
826 };
827 let err = build_contract_call_prototype(inputs).unwrap_err();
828 let msg = format!("{err}");
829 assert!(msg.contains("more Op::Popeq"), "{msg}");
830 }
831
832 use crate::types::{CoinPublicKey, EncPublicKey};
839 use crate::utils::zswap_utils::{create_encryption_public_key_resolver, CompactZswapOutput};
840 use moonproof_ledger::base_crypto::cost_model::RunningCost;
841 use moonproof_ledger::base_crypto::hash::HashOutput;
842 use moonproof_ledger::coin_structure::coin::{
843 Commitment, Info as CoinInfo, Nullifier, QualifiedInfo, ShieldedTokenType,
844 UnshieldedTokenType, UserAddress,
845 };
846 use moonproof_ledger::coin_structure::transfer::Recipient;
847 use moonproof_ledger::onchain_runtime::context::Effects;
848
849 type UnprovenTransaction =
850 Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>;
851
852 fn address(byte: u8) -> ContractAddress {
853 ContractAddress(HashOutput([byte; 32]))
854 }
855
856 fn user(byte: u8) -> UserAddress {
857 UserAddress(HashOutput([byte; 32]))
858 }
859
860 fn unshielded_token() -> UnshieldedTokenType {
861 UnshieldedTokenType(HashOutput([0xA5; 32]))
862 }
863
864 fn shielded_token() -> ShieldedTokenType {
865 ShieldedTokenType(HashOutput([0x5A; 32]))
866 }
867
868 fn transcript(effects: Effects<InMemoryDB>) -> Transcript<InMemoryDB> {
869 Transcript {
870 gas: RunningCost::ZERO,
871 effects,
872 program: moonproof_ledger::storage::storage::Array::new(),
873 version: None,
874 }
875 }
876
877 fn spends(entries: &[(TokenType, PublicAddress, u128)]) -> Transcript<InMemoryDB> {
878 let mut effects = Effects::<InMemoryDB>::default();
879 for (token, address, value) in entries {
880 effects.claimed_unshielded_spends = effects
881 .claimed_unshielded_spends
882 .insert(ClaimedUnshieldedSpendsKey(*token, *address), *value);
883 }
884 transcript(effects)
885 }
886
887 fn shielded(
888 receives: &[Commitment],
889 sends: &[Commitment],
890 nullifiers: &[Nullifier],
891 ) -> Transcript<InMemoryDB> {
892 let mut effects = Effects::<InMemoryDB>::default();
893 for c in receives {
894 effects.claimed_shielded_receives = effects.claimed_shielded_receives.insert(*c);
895 }
896 for c in sends {
897 effects.claimed_shielded_spends = effects.claimed_shielded_spends.insert(*c);
898 }
899 for n in nullifiers {
900 effects.claimed_nullifiers = effects.claimed_nullifiers.insert(*n);
901 }
902 transcript(effects)
903 }
904
905 fn prototype(
906 at: ContractAddress,
907 guaranteed: Option<Transcript<InMemoryDB>>,
908 fallible: Option<Transcript<InMemoryDB>>,
909 ) -> ContractCallPrototype<InMemoryDB> {
910 ContractCallPrototype {
911 address: at,
912 entry_point: b"circuit".as_slice().into(),
913 op: moonproof_ledger::contract_operation(None),
914 guaranteed_public_transcript: guaranteed,
915 fallible_public_transcript: fallible,
916 private_transcript_outputs: Vec::new(),
917 input: AlignedValue::from(()),
918 output: AlignedValue::from(()),
919 communication_commitment_rand: Fr::from(0u64),
920 key_location: moonproof_ledger::transient_crypto::proofs::KeyLocation(
921 std::borrow::Cow::Borrowed("circuit"),
922 ),
923 }
924 }
925
926 fn empty_local_state() -> CompactZswapLocalState {
927 CompactZswapLocalState::empty(CoinPublicKey([0x11; 32]))
928 }
929
930 fn local_state(
931 inputs: Vec<QualifiedInfo>,
932 outputs: Vec<CompactZswapOutput>,
933 ) -> CompactZswapLocalState {
934 CompactZswapLocalState {
935 inputs,
936 outputs,
937 ..empty_local_state()
938 }
939 }
940
941 fn coin(value: u128, nonce: u8) -> CoinInfo {
942 CoinInfo {
943 nonce: moonproof_ledger::coin_structure::coin::Nonce(HashOutput([nonce; 32])),
944 type_: shielded_token(),
945 value,
946 }
947 }
948
949 fn to_contract(info: CoinInfo, at: ContractAddress) -> CompactZswapOutput {
950 CompactZswapOutput {
951 coin_info: info,
952 recipient: Recipient::Contract(at),
953 }
954 }
955
956 fn settled_for(
959 owner: ContractAddress,
960 value: u128,
961 nonce: u8,
962 ) -> (ZswapChainState<InMemoryDB>, QualifiedInfo, Nullifier) {
963 let info = coin(value, nonce);
964 let mut rng = StdRng::seed_from_u64(u64::from(nonce));
965 let output =
966 moonproof_ledger::zswap::Output::new_contract_owned(&mut rng, &info, None, owner)
967 .unwrap();
968 let offer =
969 moonproof_ledger::zswap::Offer::new(Vec::new(), vec![output], Vec::new()).unwrap();
970 let (state, indices) = ZswapChainState::<InMemoryDB>::new()
971 .try_apply(&offer, None)
972 .unwrap();
973 let commitment = info.commitment(&Recipient::Contract(owner));
974 let index = *indices.get(&commitment).unwrap();
975 let nullifier = info.nullifier(
976 &moonproof_ledger::coin_structure::transfer::SenderEvidence::Contract(owner),
977 );
978 (state, info.qualify(index), nullifier)
979 }
980
981 fn assemble(calls: Vec<AssembledCall<'_>>) -> Result<UnprovenTransaction> {
982 let resolver = create_encryption_public_key_resolver(
983 CoinPublicKey([0x11; 32]),
984 crate::utils::zswap_utils::BURN_ENCRYPTION_PUBLIC_KEY,
985 None,
986 );
987 create_unproven_ledger_call_tx(
988 &mut StdRng::seed_from_u64(9),
989 calls,
990 &resolver,
991 "local-test",
992 Timestamp::from_secs(3_600),
993 )
994 }
995
996 fn call<'a>(
997 prototype: ContractCallPrototype<InMemoryDB>,
998 zswap_local_state: &'a CompactZswapLocalState,
999 zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
1000 ) -> AssembledCall<'a> {
1001 AssembledCall {
1002 prototype,
1003 zswap_local_state,
1004 zswap_chain_state,
1005 }
1006 }
1007
1008 fn standard(
1009 tx: &UnprovenTransaction,
1010 ) -> &moonproof_ledger::ledger::structure::StandardTransaction<
1011 Signature,
1012 ProofPreimageMarker,
1013 PedersenRandomness,
1014 InMemoryDB,
1015 > {
1016 match tx {
1017 Transaction::Standard(stx) => stx,
1018 other @ Transaction::ClaimRewards(_) => {
1019 panic!("expected a standard transaction, got {other:?}")
1020 }
1021 }
1022 }
1023
1024 fn only_intent(
1025 tx: &UnprovenTransaction,
1026 ) -> (
1027 u16,
1028 Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
1029 ) {
1030 let stx = standard(tx);
1031 assert_eq!(stx.intents.size(), 1);
1032 let entry = stx.intents.iter().next().unwrap();
1033 (*entry.0, (*entry.1).clone())
1034 }
1035
1036 fn outputs_of(offer: Option<&UnshieldedOffer<Signature, InMemoryDB>>) -> Vec<UtxoOutput> {
1037 offer.map_or_else(Vec::new, |o| Vec::from(&o.outputs))
1038 }
1039
1040 fn guaranteed_commitments(tx: &UnprovenTransaction) -> Vec<Commitment> {
1041 standard(tx)
1042 .guaranteed_coins
1043 .as_ref()
1044 .map_or_else(Vec::new, |o| {
1045 o.outputs.iter().map(|out| out.coin_com).collect()
1046 })
1047 }
1048
1049 fn guaranteed_nullifiers(tx: &UnprovenTransaction) -> Vec<Nullifier> {
1050 standard(tx)
1051 .guaranteed_coins
1052 .as_ref()
1053 .map_or_else(Vec::new, |o| {
1054 o.inputs.iter().map(|inp| inp.nullifier).collect()
1055 })
1056 }
1057
1058 fn fallible_offer(
1059 tx: &UnprovenTransaction,
1060 ) -> Option<
1061 moonproof_ledger::zswap::Offer<
1062 moonproof_ledger::transient_crypto::proofs::ProofPreimage,
1063 InMemoryDB,
1064 >,
1065 > {
1066 let stx = standard(tx);
1067 assert!(stx.fallible_coins.size() <= 1);
1068 stx.fallible_coins
1069 .iter()
1070 .next()
1071 .map(|entry| (*entry.1).clone())
1072 }
1073
1074 #[test]
1076 fn user_outputs_of_no_transcript_are_empty() {
1077 assert_eq!(
1078 user_addressed_unshielded_outputs(None).unwrap(),
1079 [] as [UtxoOutput; 0]
1080 );
1081 }
1082
1083 #[test]
1085 fn user_outputs_of_no_spends_are_empty() {
1086 let t = spends(&[]);
1087 assert_eq!(
1088 user_addressed_unshielded_outputs(Some(&t)).unwrap(),
1089 [] as [UtxoOutput; 0]
1090 );
1091 }
1092
1093 #[test]
1095 fn a_user_addressed_unshielded_spend_is_an_output() {
1096 let t = spends(&[(
1097 TokenType::Unshielded(unshielded_token()),
1098 PublicAddress::User(user(1)),
1099 100,
1100 )]);
1101 assert_eq!(
1102 user_addressed_unshielded_outputs(Some(&t)).unwrap(),
1103 vec![UtxoOutput {
1104 value: 100,
1105 owner: user(1),
1106 type_: unshielded_token(),
1107 }]
1108 );
1109 }
1110
1111 #[test]
1118 fn a_user_addressed_shielded_spend_is_refused() {
1119 let t = spends(&[(
1120 TokenType::Shielded(shielded_token()),
1121 PublicAddress::User(user(2)),
1122 50,
1123 )]);
1124 let err = user_addressed_unshielded_outputs(Some(&t)).unwrap_err();
1125 assert!(format!("{err}").contains("shielded token"), "{err}");
1126 }
1127
1128 #[test]
1130 fn contract_addressed_spends_are_not_user_outputs() {
1131 let t = spends(&[(
1132 TokenType::Unshielded(unshielded_token()),
1133 PublicAddress::Contract(address(3)),
1134 100,
1135 )]);
1136 assert_eq!(
1137 user_addressed_unshielded_outputs(Some(&t)).unwrap(),
1138 [] as [UtxoOutput; 0]
1139 );
1140 }
1141
1142 #[test]
1144 fn dust_spends_are_not_user_outputs() {
1145 let t = spends(&[(TokenType::Dust, PublicAddress::User(user(1)), 100)]);
1146 assert_eq!(
1147 user_addressed_unshielded_outputs(Some(&t)).unwrap(),
1148 [] as [UtxoOutput; 0]
1149 );
1150 }
1151
1152 #[test]
1154 fn mixed_spends_keep_only_user_addressed_unshielded_ones() {
1155 let t = spends(&[
1156 (
1157 TokenType::Unshielded(unshielded_token()),
1158 PublicAddress::User(user(1)),
1159 100,
1160 ),
1161 (
1162 TokenType::Unshielded(unshielded_token()),
1163 PublicAddress::Contract(address(3)),
1164 300,
1165 ),
1166 (TokenType::Dust, PublicAddress::User(user(1)), 400),
1167 ]);
1168 assert_eq!(
1169 user_addressed_unshielded_outputs(Some(&t)).unwrap(),
1170 vec![UtxoOutput {
1171 value: 100,
1172 owner: user(1),
1173 type_: unshielded_token(),
1174 }]
1175 );
1176 }
1177
1178 fn user_spend(owner: UserAddress, value: u128) -> Transcript<InMemoryDB> {
1179 spends(&[(
1180 TokenType::Unshielded(unshielded_token()),
1181 PublicAddress::User(owner),
1182 value,
1183 )])
1184 }
1185
1186 #[test]
1188 fn no_transcripts_attach_no_unshielded_offers() {
1189 let state = empty_local_state();
1190 let tx = assemble(vec![call(prototype(address(1), None, None), &state, None)]).unwrap();
1191 let (_, intent) = only_intent(&tx);
1192 assert!(intent.guaranteed_unshielded_offer.is_none());
1193 assert!(intent.fallible_unshielded_offer.is_none());
1194 }
1195
1196 #[test]
1198 fn a_guaranteed_user_spend_attaches_a_guaranteed_offer() {
1199 let state = empty_local_state();
1200 let tx = assemble(vec![call(
1201 prototype(address(1), Some(user_spend(user(1), 500)), None),
1202 &state,
1203 None,
1204 )])
1205 .unwrap();
1206 let (_, intent) = only_intent(&tx);
1207 assert_eq!(
1208 outputs_of(intent.guaranteed_unshielded_offer.as_deref()),
1209 vec![UtxoOutput {
1210 value: 500,
1211 owner: user(1),
1212 type_: unshielded_token(),
1213 }]
1214 );
1215 assert!(intent.fallible_unshielded_offer.is_none());
1216 }
1217
1218 #[test]
1220 fn a_fallible_user_spend_attaches_a_fallible_offer() {
1221 let state = empty_local_state();
1222 let tx = assemble(vec![call(
1223 prototype(
1224 address(1),
1225 Some(spends(&[])),
1226 Some(user_spend(user(2), 300)),
1227 ),
1228 &state,
1229 None,
1230 )])
1231 .unwrap();
1232 let (_, intent) = only_intent(&tx);
1233 assert!(intent.guaranteed_unshielded_offer.is_none());
1234 assert_eq!(
1235 outputs_of(intent.fallible_unshielded_offer.as_deref()),
1236 vec![UtxoOutput {
1237 value: 300,
1238 owner: user(2),
1239 type_: unshielded_token(),
1240 }]
1241 );
1242 }
1243
1244 #[test]
1246 fn contract_addressed_spends_attach_no_offer() {
1247 let state = empty_local_state();
1248 let to_contract = spends(&[(
1249 TokenType::Unshielded(unshielded_token()),
1250 PublicAddress::Contract(address(9)),
1251 100,
1252 )]);
1253 let tx = assemble(vec![call(
1254 prototype(address(1), Some(to_contract), None),
1255 &state,
1256 None,
1257 )])
1258 .unwrap();
1259 let (_, intent) = only_intent(&tx);
1260 assert!(intent.guaranteed_unshielded_offer.is_none());
1261 assert!(intent.fallible_unshielded_offer.is_none());
1262 }
1263
1264 #[test]
1266 fn both_segments_get_their_own_offer() {
1267 let state = empty_local_state();
1268 let tx = assemble(vec![call(
1269 prototype(
1270 address(1),
1271 Some(user_spend(user(1), 100)),
1272 Some(user_spend(user(2), 200)),
1273 ),
1274 &state,
1275 None,
1276 )])
1277 .unwrap();
1278 let (_, intent) = only_intent(&tx);
1279 assert_eq!(
1280 outputs_of(intent.guaranteed_unshielded_offer.as_deref()).len(),
1281 1
1282 );
1283 assert_eq!(
1284 outputs_of(intent.fallible_unshielded_offer.as_deref())[0].owner,
1285 user(2)
1286 );
1287 }
1288
1289 fn two_call_tree(
1291 callee: (
1292 Option<Transcript<InMemoryDB>>,
1293 Option<Transcript<InMemoryDB>>,
1294 ),
1295 root: (
1296 Option<Transcript<InMemoryDB>>,
1297 Option<Transcript<InMemoryDB>>,
1298 ),
1299 ) -> Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> {
1300 let state = empty_local_state();
1301 let tx = assemble(vec![
1302 call(prototype(address(2), callee.0, callee.1), &state, None),
1303 call(prototype(address(1), root.0, root.1), &state, None),
1304 ])
1305 .unwrap();
1306 only_intent(&tx).1
1307 }
1308
1309 #[test]
1311 fn a_callee_only_guaranteed_spend_reaches_the_offer() {
1312 let intent = two_call_tree(
1313 (Some(user_spend(user(4), 100)), None),
1314 (Some(spends(&[])), None),
1315 );
1316 assert_eq!(
1317 outputs_of(intent.guaranteed_unshielded_offer.as_deref()),
1318 vec![UtxoOutput {
1319 value: 100,
1320 owner: user(4),
1321 type_: unshielded_token(),
1322 }]
1323 );
1324 }
1325
1326 #[test]
1328 fn a_callee_only_fallible_spend_reaches_the_offer() {
1329 let intent = two_call_tree(
1330 (Some(spends(&[])), Some(user_spend(user(4), 250))),
1331 (Some(spends(&[])), None),
1332 );
1333 assert!(intent.guaranteed_unshielded_offer.is_none());
1334 assert_eq!(
1335 outputs_of(intent.fallible_unshielded_offer.as_deref())[0].value,
1336 250
1337 );
1338 }
1339
1340 #[test]
1342 fn callee_and_root_spends_share_one_offer_sorted() {
1343 let intent = two_call_tree(
1344 (Some(user_spend(user(7), 100)), None),
1345 (Some(user_spend(user(3), 200)), None),
1346 );
1347 let outputs = outputs_of(intent.guaranteed_unshielded_offer.as_deref());
1348 assert_eq!(outputs.len(), 2);
1349 assert!(outputs.is_sorted(), "{outputs:?}");
1350 assert!(outputs.iter().any(|o| o.owner == user(7) && o.value == 100));
1351 assert!(outputs.iter().any(|o| o.owner == user(3) && o.value == 200));
1352 }
1353
1354 #[test]
1357 fn each_call_takes_a_random_segment_so_calls_merge() {
1358 let state = empty_local_state();
1359 let resolver = create_encryption_public_key_resolver(
1360 CoinPublicKey([0x11; 32]),
1361 EncPublicKey([0u8; 32]),
1362 None,
1363 );
1364 let mut rng = StdRng::seed_from_u64(41);
1365 let mut build = || {
1366 create_unproven_ledger_call_tx(
1367 &mut rng,
1368 vec![call(prototype(address(1), None, None), &state, None)],
1369 &resolver,
1370 "local-test",
1371 Timestamp::from_secs(3_600),
1372 )
1373 .unwrap()
1374 };
1375 let first = build();
1376 let second = build();
1377 let (a, _) = only_intent(&first);
1378 let (b, _) = only_intent(&second);
1379 assert!(a >= FIRST_RANDOM_SEGMENT && b >= FIRST_RANDOM_SEGMENT);
1380 assert_ne!(a, b);
1381 let merged = first.merge(&second).expect("two calls merge");
1382 assert_eq!(standard(&merged).intents.size(), 2);
1383 }
1384
1385 #[test]
1387 fn a_fallibly_claimed_user_output_goes_to_the_fallible_offer() {
1388 let wallet = CoinPublicKey([0x11; 32]);
1389 let info = coin(4967, 1);
1390 let commitment = info.commitment(&Recipient::User(
1391 moonproof_ledger::coin_structure::coin::PublicKey(HashOutput(wallet.0)),
1392 ));
1393 let state = local_state(
1394 Vec::new(),
1395 vec![CompactZswapOutput {
1396 coin_info: info,
1397 recipient: Recipient::User(moonproof_ledger::coin_structure::coin::PublicKey(
1398 HashOutput(wallet.0),
1399 )),
1400 }],
1401 );
1402 let tx = assemble(vec![call(
1403 prototype(
1404 address(1),
1405 Some(shielded(&[], &[], &[])),
1406 Some(shielded(&[], &[commitment], &[])),
1407 ),
1408 &state,
1409 None,
1410 )])
1411 .unwrap();
1412 let (segment, _) = only_intent(&tx);
1413 let stx = standard(&tx);
1414 assert!(stx.guaranteed_coins.is_none());
1415 assert!(stx.fallible_coins.get(&segment).is_some());
1416 let fallible = fallible_offer(&tx).unwrap();
1417 assert_eq!(
1418 fallible
1419 .outputs
1420 .iter()
1421 .map(|o| o.coin_com)
1422 .collect::<Vec<_>>(),
1423 vec![commitment]
1424 );
1425 }
1426
1427 #[test]
1429 fn a_guaranteed_user_output_stays_guaranteed() {
1430 let wallet = moonproof_ledger::coin_structure::coin::PublicKey(HashOutput([0x11; 32]));
1431 let info = coin(100, 2);
1432 let commitment = info.commitment(&Recipient::User(wallet));
1433 let state = local_state(
1434 Vec::new(),
1435 vec![CompactZswapOutput {
1436 coin_info: info,
1437 recipient: Recipient::User(wallet),
1438 }],
1439 );
1440 let tx = assemble(vec![call(
1441 prototype(address(1), Some(shielded(&[], &[commitment], &[])), None),
1442 &state,
1443 None,
1444 )])
1445 .unwrap();
1446 assert_eq!(guaranteed_commitments(&tx), vec![commitment]);
1447 assert!(fallible_offer(&tx).is_none());
1448 }
1449
1450 #[test]
1452 fn a_fallibly_claimed_input_goes_to_the_fallible_offer() {
1453 let owner = address(1);
1454 let (chain, qcoin, nullifier) = settled_for(owner, 500, 3);
1455 let state = local_state(vec![qcoin], Vec::new());
1456 let tx = assemble(vec![call(
1457 prototype(
1458 owner,
1459 Some(shielded(&[], &[], &[])),
1460 Some(shielded(&[], &[], &[nullifier])),
1461 ),
1462 &state,
1463 Some(&chain),
1464 )])
1465 .unwrap();
1466 assert!(standard(&tx).guaranteed_coins.is_none());
1467 let fallible = fallible_offer(&tx).unwrap();
1468 assert_eq!(
1469 fallible
1470 .inputs
1471 .iter()
1472 .map(|i| i.nullifier)
1473 .collect::<Vec<_>>(),
1474 vec![nullifier]
1475 );
1476 }
1477
1478 #[test]
1480 fn a_respent_contract_coin_becomes_a_fallible_transient() {
1481 let owner = address(1);
1482 let (chain, qcoin, nullifier) = settled_for(owner, 1000, 4);
1483 let info = CoinInfo::from(&qcoin);
1484 let commitment = info.commitment(&Recipient::Contract(owner));
1485 let state = local_state(vec![qcoin], vec![to_contract(info, owner)]);
1486 let tx = assemble(vec![call(
1487 prototype(
1488 owner,
1489 Some(shielded(&[], &[], &[])),
1490 Some(shielded(&[commitment], &[], &[nullifier])),
1491 ),
1492 &state,
1493 Some(&chain),
1494 )])
1495 .unwrap();
1496 let fallible = fallible_offer(&tx).unwrap();
1497 assert_eq!(fallible.inputs.len(), 0);
1498 assert_eq!(fallible.outputs.len(), 0);
1499 let transients: Vec<_> = fallible.transient.iter().collect();
1500 assert_eq!(transients.len(), 1);
1501 assert_eq!(transients[0].nullifier, nullifier);
1502 }
1503
1504 #[test]
1506 fn a_callee_spends_against_its_own_chain_state() {
1507 let callee = address(2);
1508 let (chain, qcoin, nullifier) = settled_for(callee, 1000, 5);
1509 let callee_state = local_state(vec![qcoin], Vec::new());
1510 let root_state = empty_local_state();
1511 let tx = assemble(vec![
1512 call(
1513 prototype(callee, Some(shielded(&[], &[], &[nullifier])), None),
1514 &callee_state,
1515 Some(&chain),
1516 ),
1517 call(
1518 prototype(address(1), Some(shielded(&[], &[], &[])), None),
1519 &root_state,
1520 None,
1521 ),
1522 ])
1523 .unwrap();
1524 assert_eq!(guaranteed_nullifiers(&tx), vec![nullifier]);
1525 }
1526
1527 #[test]
1529 fn the_deepest_callee_spends_and_a_middle_callee_receives() {
1530 let (a, b, c) = (address(1), address(2), address(3));
1531 let (chain, qcoin, nullifier) = settled_for(c, 1000, 6);
1532 let received = coin(50, 7);
1533 let received_commitment = received.commitment(&Recipient::Contract(b));
1534 let c_state = local_state(vec![qcoin], Vec::new());
1535 let b_state = local_state(Vec::new(), vec![to_contract(received, b)]);
1536 let a_state = empty_local_state();
1537 let tx = assemble(vec![
1538 call(
1539 prototype(c, Some(shielded(&[], &[], &[nullifier])), None),
1540 &c_state,
1541 Some(&chain),
1542 ),
1543 call(
1544 prototype(b, Some(shielded(&[received_commitment], &[], &[])), None),
1545 &b_state,
1546 None,
1547 ),
1548 call(
1549 prototype(a, Some(shielded(&[], &[], &[])), None),
1550 &a_state,
1551 None,
1552 ),
1553 ])
1554 .unwrap();
1555 assert_eq!(guaranteed_nullifiers(&tx), vec![nullifier]);
1556 assert_eq!(guaranteed_commitments(&tx), vec![received_commitment]);
1557 }
1558
1559 #[test]
1561 fn a_callee_reached_twice_keeps_both_calls_coins() {
1562 let (a, b, c) = (address(1), address(2), address(3));
1563 let (chain, qcoin, nullifier) = settled_for(b, 1000, 8);
1564 let received = coin(50, 9);
1565 let received_commitment = received.commitment(&Recipient::Contract(b));
1566 let first_b = local_state(vec![qcoin], Vec::new());
1567 let second_b = local_state(Vec::new(), vec![to_contract(received, b)]);
1568 let empty = empty_local_state();
1569 let tx = assemble(vec![
1570 call(
1571 prototype(b, Some(shielded(&[], &[], &[nullifier])), None),
1572 &first_b,
1573 Some(&chain),
1574 ),
1575 call(
1576 prototype(c, Some(shielded(&[], &[], &[])), None),
1577 &empty,
1578 None,
1579 ),
1580 call(
1581 prototype(b, Some(shielded(&[received_commitment], &[], &[])), None),
1582 &second_b,
1583 None,
1584 ),
1585 call(
1586 prototype(a, Some(shielded(&[], &[], &[])), None),
1587 &empty,
1588 None,
1589 ),
1590 ])
1591 .unwrap();
1592 assert_eq!(guaranteed_nullifiers(&tx), vec![nullifier]);
1593 assert_eq!(guaranteed_commitments(&tx), vec![received_commitment]);
1594 }
1595
1596 #[test]
1600 fn a_callees_coins_split_between_guaranteed_and_fallible() {
1601 let callee = address(2);
1602 let guaranteed_coin = coin(10, 10);
1603 let fallible_coin = coin(20, 11);
1604 let g = guaranteed_coin.commitment(&Recipient::Contract(callee));
1605 let f = fallible_coin.commitment(&Recipient::Contract(callee));
1606 let callee_state = local_state(
1607 Vec::new(),
1608 vec![
1609 to_contract(guaranteed_coin, callee),
1610 to_contract(fallible_coin, callee),
1611 ],
1612 );
1613 let root_state = empty_local_state();
1614 let tx = assemble(vec![
1615 call(
1616 prototype(
1617 callee,
1618 Some(shielded(&[g], &[], &[])),
1619 Some(shielded(&[f], &[], &[])),
1620 ),
1621 &callee_state,
1622 None,
1623 ),
1624 call(
1625 prototype(address(1), Some(shielded(&[], &[], &[])), None),
1626 &root_state,
1627 None,
1628 ),
1629 ])
1630 .unwrap();
1631 assert_eq!(guaranteed_commitments(&tx), vec![g]);
1632 let fallible = fallible_offer(&tx).unwrap();
1633 assert_eq!(
1634 fallible
1635 .outputs
1636 .iter()
1637 .map(|o| o.coin_com)
1638 .collect::<Vec<_>>(),
1639 vec![f]
1640 );
1641 }
1642
1643 #[test]
1645 fn a_coin_sent_and_received_in_the_tree_is_one_output() {
1646 let (root, callee) = (address(1), address(2));
1647 let info = coin(50, 12);
1648 let commitment = info.commitment(&Recipient::Contract(callee));
1649 let callee_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
1650 let root_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
1651 let tx = assemble(vec![
1652 call(
1653 prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
1654 &callee_state,
1655 None,
1656 ),
1657 call(
1658 prototype(root, Some(shielded(&[], &[commitment], &[])), None),
1659 &root_state,
1660 None,
1661 ),
1662 ])
1663 .unwrap();
1664 assert_eq!(guaranteed_commitments(&tx), vec![commitment]);
1665 }
1666
1667 fn mismatch(calls: Vec<AssembledCall<'_>>) -> String {
1668 format!("{}", assemble(calls).unwrap_err())
1669 }
1670
1671 fn claim_key(segment: u8, commitment: Commitment, at: ContractAddress) -> String {
1672 format!(
1673 "segment {segment} / {} / {}",
1674 hex::encode(commitment.0 .0),
1675 moonproof_runtime::state::contract_address_to_hex(&at)
1676 )
1677 }
1678
1679 #[test]
1681 fn an_unclaimed_contract_coin_is_refused() {
1682 let (root, callee) = (address(1), address(2));
1683 let info = coin(50, 13);
1684 let commitment = info.commitment(&Recipient::Contract(callee));
1685 let root_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
1686 let empty = empty_local_state();
1687 let message = mismatch(vec![
1688 call(
1689 prototype(callee, Some(shielded(&[], &[], &[])), None),
1690 &empty,
1691 None,
1692 ),
1693 call(
1694 prototype(root, Some(shielded(&[], &[commitment], &[])), None),
1695 &root_state,
1696 None,
1697 ),
1698 ]);
1699 assert!(
1700 message.contains(&format!(
1701 "{}: offered 1, claimed 0",
1702 claim_key(0, commitment, callee)
1703 )),
1704 "{message}"
1705 );
1706 }
1707
1708 #[test]
1710 fn a_receive_claim_without_an_offer_is_refused() {
1711 let (root, callee) = (address(1), address(2));
1712 let commitment = coin(50, 14).commitment(&Recipient::Contract(callee));
1713 let empty = empty_local_state();
1714 let message = mismatch(vec![
1715 call(
1716 prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
1717 &empty,
1718 None,
1719 ),
1720 call(
1721 prototype(root, Some(shielded(&[], &[], &[])), None),
1722 &empty,
1723 None,
1724 ),
1725 ]);
1726 assert!(
1727 message.contains(&format!(
1728 "{}: offered 0, claimed 1",
1729 claim_key(0, commitment, callee)
1730 )),
1731 "{message}"
1732 );
1733 }
1734
1735 #[test]
1737 fn a_coin_claimed_twice_is_refused() {
1738 let (root, callee) = (address(1), address(2));
1739 let info = coin(50, 15);
1740 let commitment = info.commitment(&Recipient::Contract(callee));
1741 let callee_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
1742 let empty = empty_local_state();
1743 let message = mismatch(vec![
1744 call(
1745 prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
1746 &callee_state,
1747 None,
1748 ),
1749 call(
1750 prototype(callee, Some(shielded(&[commitment], &[], &[])), None),
1751 &empty,
1752 None,
1753 ),
1754 call(
1755 prototype(root, Some(shielded(&[], &[], &[])), None),
1756 &empty,
1757 None,
1758 ),
1759 ]);
1760 assert!(
1761 message.contains(&format!(
1762 "{}: offered 1, claimed 2",
1763 claim_key(0, commitment, callee)
1764 )),
1765 "{message}"
1766 );
1767 }
1768
1769 #[test]
1771 fn a_coin_offered_and_claimed_in_different_segments_is_refused() {
1772 let (root, callee) = (address(1), address(2));
1773 let info = coin(50, 16);
1774 let commitment = info.commitment(&Recipient::Contract(callee));
1775 let root_state = local_state(Vec::new(), vec![to_contract(info, callee)]);
1776 let empty = empty_local_state();
1777 let message = mismatch(vec![
1778 call(
1779 prototype(
1780 callee,
1781 Some(shielded(&[], &[], &[])),
1782 Some(shielded(&[commitment], &[], &[])),
1783 ),
1784 &empty,
1785 None,
1786 ),
1787 call(
1788 prototype(root, Some(shielded(&[], &[commitment], &[])), None),
1789 &root_state,
1790 None,
1791 ),
1792 ]);
1793 assert!(
1794 message.contains(&format!(
1795 "{}: offered 1, claimed 0",
1796 claim_key(0, commitment, callee)
1797 )),
1798 "{message}"
1799 );
1800 assert!(
1801 message.contains(&format!(
1802 "{}: offered 0, claimed 1",
1803 claim_key(1, commitment, callee)
1804 )),
1805 "{message}"
1806 );
1807 }
1808}