Skip to main content

midnight_ledger_v9/
construct.rs

1// This file is part of midnight-ledger.
2// Copyright (C) Midnight Foundation
3// SPDX-License-Identifier: Apache-2.0
4// Licensed under the Apache License, Version 2.0 (the "License");
5// You may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7// http://www.apache.org/licenses/LICENSE-2.0
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14mod mock_tx;
15mod tx_shape;
16
17use mock_tx::{mock_calls, mock_tx};
18pub use tx_shape::TransactionShape;
19
20use crate::dust::DustActions;
21use crate::error::{MalformedTransaction, PartitionFailure};
22use crate::structure::EXPECTED_CONTRACT_DEPTH;
23use crate::structure::{
24    ContractAction, ContractCall, ContractDeploy, GUARANTEED_SEGMENT, Intent,
25    IntentSigningEnvelope, LedgerParameters, MaintenanceUpdate, ProofPreimageMarker,
26    ProofPreimageVersioned, Signature, SignatureKind, SignaturesValue, SigningKey, SingleUpdate,
27    StandardTransaction, Transaction, UnshieldedOffer,
28};
29use crate::structure::{PedersenDowngradeable, ProofKind};
30use base_crypto::cost_model::CostDuration;
31use base_crypto::cost_model::RunningCost;
32use base_crypto::fab::AlignedValue;
33use base_crypto::time::Timestamp;
34use coin_structure::contract::ContractAddress;
35use itertools::Itertools;
36use onchain_runtime::context::{Effects, QueryContext, QueryResults};
37use onchain_runtime::error::TranscriptRejected;
38use onchain_runtime::ops::Op;
39use onchain_runtime::result_mode::ResultModeVerify;
40use onchain_runtime::state::{ContractOperation, ContractState, EntryPointBuf};
41use onchain_runtime::transcript::Transcript;
42use rand::{CryptoRng, Rng};
43use serde::{Deserialize, Serialize};
44use serialize::Serializable;
45use std::iter::once;
46use std::ops::Deref;
47use storage::Storable;
48use storage::arena::Sp;
49use storage::db::DB;
50use transient_crypto::commitment::PedersenRandomness;
51use transient_crypto::curve::Fr;
52use transient_crypto::fab::{AlignedValueExt, ValueReprAlignedValue};
53use transient_crypto::hash::transient_commit;
54use transient_crypto::proofs::{KeyLocation, ProofPreimage};
55use transient_crypto::repr::FieldRepr;
56use zswap::{
57    Input as ZswapInput, Offer as ZswapOffer, Output as ZswapOutput, Transient as ZswapTransient,
58    ZSWAP_TREE_HEIGHT,
59};
60
61impl<S: SignatureKind<D>, D: DB> Transaction<S, ProofPreimageMarker, PedersenRandomness, D> {
62    pub fn from_intents(
63        network_id: impl Into<String>,
64        intents: storage::storage::HashMap<
65            u16,
66            Intent<S, ProofPreimageMarker, PedersenRandomness, D>,
67            D,
68        >,
69    ) -> Self {
70        Self::new(network_id, intents, None, storage::storage::HashMap::new())
71    }
72}
73
74/// Flags whether any of `items` are claimed by some call's *fallible* transcript, and so belong
75/// in the fallible Zswap offer rather than the guaranteed one. `claims` says what counts as
76/// a claim for the item type at hand.
77fn has_claims_in_fallible<T, D: DB>(
78    items: &[T],
79    fallible_effects: &[&Effects<D>],
80    claims: impl Fn(&Effects<D>, &T) -> bool,
81) -> Vec<bool> {
82    items
83        .iter()
84        .map(|item| fallible_effects.iter().any(|effects| claims(effects, item)))
85        .collect()
86}
87
88/// Return items whose fallibility flag matches `fallible`.
89fn with_fallibility<T: Clone>(items: &[T], is_fallible: &[bool], fallible: bool) -> Vec<T> {
90    items
91        .iter()
92        .zip(is_fallible)
93        .filter(|(_, f)| **f == fallible)
94        .map(|(item, _)| item.clone())
95        .collect()
96}
97
98impl<S: SignatureKind<D>, D: DB>
99    StandardTransaction<S, ProofPreimageMarker, PedersenRandomness, D>
100{
101    pub fn new(
102        network_id: impl Into<String>,
103        intents: storage::storage::HashMap<
104            u16,
105            Intent<S, ProofPreimageMarker, PedersenRandomness, D>,
106            D,
107        >,
108        guaranteed_coins: Option<ZswapOffer<ProofPreimage, D>>,
109        fallible_coins: storage::storage::HashMap<u16, ZswapOffer<ProofPreimage, D>, D>,
110    ) -> Self {
111        let mut res = StandardTransaction {
112            network_id: network_id.into(),
113            binding_randomness: Default::default(),
114            intents,
115            guaranteed_coins: guaranteed_coins.map(|x| Sp::new(x)),
116            fallible_coins: fallible_coins.into_iter().collect(),
117        };
118        res.recompute_binding_randomness();
119        res
120    }
121
122    #[allow(clippy::too_many_arguments)]
123    pub fn add_calls<P>(
124        &self,
125        rng: &mut (impl Rng + CryptoRng),
126        segment: SegmentSpecifier,
127        calls: &[PrePartitionContractCall<D>],
128        params: &LedgerParameters,
129        ttl: Timestamp,
130        zswap_inputs: &[ZswapInput<ProofPreimage, D>],
131        zswap_outputs: &[ZswapOutput<ProofPreimage, D>],
132        zswap_transients: &[ZswapTransient<ProofPreimage, D>],
133    ) -> Result<Self, PartitionFailure<D>>
134    where
135        P: ContractCallExt<D>,
136    {
137        self.add_calls_inner::<P>(
138            rng,
139            segment,
140            calls,
141            params,
142            ttl,
143            zswap_inputs,
144            zswap_outputs,
145            zswap_transients,
146            |derived| {
147                derived.with_zswap_parts(
148                    zswap_inputs.len(),
149                    zswap_outputs.len(),
150                    zswap_transients.len(),
151                )
152            },
153        )
154    }
155
156    #[allow(clippy::too_many_arguments)]
157    pub fn add_calls_with_tx_shape<P>(
158        &self,
159        rng: &mut (impl Rng + CryptoRng),
160        segment: SegmentSpecifier,
161        calls: &[PrePartitionContractCall<D>],
162        params: &LedgerParameters,
163        ttl: Timestamp,
164        zswap_inputs: &[ZswapInput<ProofPreimage, D>],
165        zswap_outputs: &[ZswapOutput<ProofPreimage, D>],
166        zswap_transients: &[ZswapTransient<ProofPreimage, D>],
167        expected_tx_shape: &TransactionShape,
168    ) -> Result<Self, PartitionFailure<D>>
169    where
170        P: ContractCallExt<D>,
171    {
172        self.add_calls_inner::<P>(
173            rng,
174            segment,
175            calls,
176            params,
177            ttl,
178            zswap_inputs,
179            zswap_outputs,
180            zswap_transients,
181            |_| expected_tx_shape.clone(),
182        )
183    }
184
185    #[allow(clippy::too_many_arguments)]
186    fn add_calls_inner<P>(
187        &self,
188        rng: &mut (impl Rng + CryptoRng),
189        segment: SegmentSpecifier,
190        calls: &[PrePartitionContractCall<D>],
191        params: &LedgerParameters,
192        ttl: Timestamp,
193        zswap_inputs: &[ZswapInput<ProofPreimage, D>],
194        zswap_outputs: &[ZswapOutput<ProofPreimage, D>],
195        zswap_transients: &[ZswapTransient<ProofPreimage, D>],
196        choose_tx_shape: impl FnOnce(TransactionShape) -> TransactionShape,
197    ) -> Result<Self, PartitionFailure<D>>
198    where
199        P: ContractCallExt<D>,
200    {
201        let pre_transcripts = calls
202            .iter()
203            .map(|call| PreTranscript {
204                comm_comm: Some(communication_commitment(
205                    call.input.clone(),
206                    call.output.clone(),
207                    call.communication_commitment_rand,
208                )),
209                ..call.pre_transcript.clone()
210            })
211            .collect::<Vec<_>>();
212        let partitioned = partition_transcripts_inner(&pre_transcripts, params, choose_tx_shape)?;
213        let segment = match segment {
214            SegmentSpecifier::First => 1,
215            SegmentSpecifier::GuaranteedOnly
216                if partitioned.iter().any(|(_, snd)| snd.is_some()) =>
217            {
218                return Err(PartitionFailure::GuaranteedOnlyUnsatisfied);
219            }
220            SegmentSpecifier::GuaranteedOnly | SegmentSpecifier::Random => {
221                rng.gen_range(2..u16::MAX)
222            }
223            SegmentSpecifier::Specific(GUARANTEED_SEGMENT) => {
224                return Err(PartitionFailure::IllegalSegmentZero);
225            }
226            SegmentSpecifier::Specific(seg) => seg,
227        };
228        let prototypes = calls
229            .iter()
230            .zip(partitioned)
231            .map(|(call, (guaranteed, fallible))| ContractCallPrototype {
232                address: call.address,
233                entry_point: call.entry_point.clone(),
234                op: call.op.clone(),
235                guaranteed_public_transcript: guaranteed,
236                fallible_public_transcript: fallible,
237                private_transcript_outputs: call.private_transcript_outputs.clone(),
238                input: call.input.clone(),
239                output: call.output.clone(),
240                communication_commitment_rand: call.communication_commitment_rand,
241                key_location: call.key_location.clone(),
242            })
243            .collect::<Vec<_>>();
244        let fallible_effects = prototypes
245            .iter()
246            .filter_map(|proto| proto.fallible_public_transcript.as_ref())
247            .map(|transcript| &transcript.effects)
248            .collect::<Vec<_>>();
249        let zswap_input_is_fallible =
250            has_claims_in_fallible(zswap_inputs, &fallible_effects, |effects, inp| {
251                effects.claimed_nullifiers.member(&inp.nullifier)
252            });
253        let zswap_output_is_fallible =
254            has_claims_in_fallible(zswap_outputs, &fallible_effects, |effects, out| {
255                effects
256                    .claimed_shielded_spends
257                    .union(&effects.claimed_shielded_receives)
258                    .member(&out.coin_com)
259            });
260        let zswap_transient_is_fallible =
261            has_claims_in_fallible(zswap_transients, &fallible_effects, |effects, trans| {
262                effects
263                    .claimed_shielded_spends
264                    .union(&effects.claimed_shielded_receives)
265                    .member(&trans.coin_com)
266                    || effects.claimed_nullifiers.member(&trans.nullifier)
267            });
268        let intent_before = self
269            .intents
270            .get(&segment)
271            .map(|i| (*i).clone())
272            .unwrap_or_else(|| Intent::empty(rng, ttl));
273        let intent = prototypes
274            .into_iter()
275            .fold(intent_before, |i, proto| i.add_call::<P>(proto));
276        let mut res = self.set_intent(segment, intent);
277        let offer_with_fallibility = |fallible: bool| {
278            ZswapOffer::new(
279                with_fallibility(zswap_inputs, &zswap_input_is_fallible, fallible),
280                with_fallibility(zswap_outputs, &zswap_output_is_fallible, fallible),
281                with_fallibility(zswap_transients, &zswap_transient_is_fallible, fallible),
282            )
283        };
284        let guaranteed_coins =
285            offer_with_fallibility(false).map(|o| o.retarget_segment(GUARANTEED_SEGMENT));
286        let fallible_coins = offer_with_fallibility(true).map(|o| o.retarget_segment(segment));
287        let merge_into = |old: Option<&ZswapOffer<ProofPreimage, D>>,
288                          new: ZswapOffer<ProofPreimage, D>| {
289            match old {
290                Some(old) => old.merge(&new).map_err(PartitionFailure::Merge),
291                None => Ok(new),
292            }
293        };
294        if let Some(offer) = guaranteed_coins {
295            let merged = merge_into(res.guaranteed_coins.as_deref(), offer)?;
296            res.guaranteed_coins = Some(Sp::new(merged));
297        }
298        if let Some(offer) = fallible_coins {
299            let merged = merge_into(res.fallible_coins.get(&segment).as_deref(), offer)?;
300            res.fallible_coins = res.fallible_coins.insert(segment, merged);
301        }
302        res.recompute_binding_randomness();
303        Ok(res)
304    }
305
306    pub fn set_intent(
307        &self,
308        segment: u16,
309        intent: Intent<S, ProofPreimageMarker, PedersenRandomness, D>,
310    ) -> Self {
311        let mut res = self.clone();
312        res.intents = self.intents.insert(segment, intent);
313        res.recompute_binding_randomness();
314        res
315    }
316
317    pub fn recompute_binding_randomness(&mut self) {
318        self.binding_randomness = self
319            .guaranteed_coins
320            .as_ref()
321            .map(|o| o.binding_randomness())
322            .unwrap_or_else(|| PedersenRandomness::from(0))
323            + self
324                .fallible_coins
325                .values()
326                .fold(PedersenRandomness::from(0), |acc, o| {
327                    acc + o.binding_randomness()
328                })
329            + self
330                .intents
331                .values()
332                .map(|i| i.binding_randomness())
333                .fold(0.into(), |a, b| a + b);
334    }
335}
336
337impl<D: DB> ContractDeploy<D> {
338    pub fn new<R: Rng + CryptoRng + ?Sized>(rng: &mut R, initial_state: ContractState<D>) -> Self {
339        ContractDeploy {
340            initial_state,
341            nonce: rng.r#gen(),
342        }
343    }
344}
345
346impl<D: DB> MaintenanceUpdate<D> {
347    pub fn new(address: ContractAddress, updates: Vec<SingleUpdate>, counter: u32) -> Self {
348        MaintenanceUpdate {
349            address,
350            updates: updates.into(),
351            counter,
352            signatures: vec![].into(),
353        }
354    }
355
356    pub fn add_signature(mut self, idx: u32, signature: Signature) -> Self {
357        self.signatures = self
358            .signatures
359            .push(SignaturesValue(idx, signature))
360            .iter_deref()
361            .cloned()
362            .sorted()
363            .collect();
364        self
365    }
366}
367
368impl<S: SignatureKind<D>, D: DB> Intent<S, ProofPreimageMarker, PedersenRandomness, D> {
369    pub fn empty<R: Rng + CryptoRng + ?Sized>(
370        rng: &mut R,
371        ttl: Timestamp,
372    ) -> Intent<S, ProofPreimageMarker, PedersenRandomness, D> {
373        Intent::new(rng, None, None, vec![], vec![], vec![], None, ttl)
374    }
375
376    #[allow(clippy::too_many_arguments)]
377    pub fn new<R: Rng + CryptoRng + ?Sized>(
378        rng: &mut R,
379        guaranteed_unshielded_offer: Option<UnshieldedOffer<S, D>>,
380        fallible_unshielded_offer: Option<UnshieldedOffer<S, D>>,
381        calls: Vec<ContractCallPrototype<D>>,
382        updates: Vec<MaintenanceUpdate<D>>,
383        deploys: Vec<ContractDeploy<D>>,
384        dust_actions: Option<DustActions<S, ProofPreimageMarker, D>>,
385        ttl: Timestamp,
386    ) -> Intent<S, ProofPreimageMarker, PedersenRandomness, D> {
387        let intent = Intent {
388            guaranteed_unshielded_offer: guaranteed_unshielded_offer.map(|x| Sp::new(x)),
389            fallible_unshielded_offer: fallible_unshielded_offer.map(|x| Sp::new(x)),
390            actions: vec![].into(),
391            dust_actions: dust_actions.map(Sp::new),
392            ttl,
393            binding_commitment: rng.r#gen(),
394        };
395
396        let intent = calls
397            .into_iter()
398            .fold(intent, |acc, x| acc.add_call::<ProofPreimage>(x));
399
400        let intent = updates
401            .into_iter()
402            .fold(intent, |acc, x| acc.add_maintenance_update(x));
403
404        deploys.into_iter().fold(intent, |acc, x| acc.add_deploy(x))
405    }
406}
407
408impl<
409    S: SignatureKind<D>,
410    P: ProofKind<D>,
411    B: Storable<D> + PedersenDowngradeable<D> + Serializable,
412    D: DB,
413> Intent<S, P, B, D>
414{
415    #[allow(clippy::result_large_err)]
416    pub fn sign(
417        mut self,
418        rng: &mut (impl Rng + CryptoRng),
419        segment_id: u16,
420        guaranteed_signing_keys: &[SigningKey],
421        fallible_signing_keys: &[SigningKey],
422        dust_registration_signing_keys: &[SigningKey],
423    ) -> Result<Self, MalformedTransaction<D>>
424    where
425        UnshieldedOffer<S, D>: Clone,
426        P: ProofKind<D>,
427    {
428        let data = self
429            .erase_proofs()
430            .erase_signatures()
431            .data_to_sign(segment_id);
432
433        let mut sign_unshielded_offers = |unshielded_offer: &mut Option<
434            Sp<UnshieldedOffer<S, D>, D>,
435        >,
436                                          signing_keys: &[SigningKey]|
437         -> Result<(), MalformedTransaction<D>> {
438            if let Some(offer) = unshielded_offer {
439                let signatures: Vec<<S as SignatureKind<D>>::Signature<IntentSigningEnvelope<D>>> =
440                    offer
441                        .inputs
442                        .iter()
443                        .zip(signing_keys)
444                        .map(|(spend, sk)| {
445                            if spend.owner != sk.verifying_key() {
446                                return Err(MalformedTransaction::<D>::IntentSignatureKeyMismatch);
447                            }
448                            Ok(S::sign(sk, rng, &data))
449                        })
450                        .collect::<Result<Vec<_>, _>>()?;
451
452                let mut new = (*offer).deref().clone();
453                new.add_signatures(signatures);
454                *unshielded_offer = Some(Sp::new(new.clone()));
455            }
456            Ok(())
457        };
458
459        sign_unshielded_offers(
460            &mut self.guaranteed_unshielded_offer,
461            guaranteed_signing_keys,
462        )?;
463        sign_unshielded_offers(&mut self.fallible_unshielded_offer, fallible_signing_keys)?;
464
465        if let Some(da) = self.dust_actions {
466            let registrations = da
467                .registrations
468                .iter()
469                .zip(dust_registration_signing_keys.iter())
470                .map(|(reg, sk)| {
471                    let mut reg = (*reg).clone();
472                    if reg.night_key != sk.verifying_key() {
473                        return Err(MalformedTransaction::<D>::IntentSignatureKeyMismatch);
474                    }
475                    reg.signature = Some(Sp::new(S::sign(sk, rng, &data)));
476                    Ok(reg)
477                })
478                .collect::<Result<_, _>>()?;
479            self.dust_actions = Some(Sp::new(DustActions {
480                registrations,
481                spends: da.spends.clone(),
482                ctime: da.ctime,
483            }));
484        }
485
486        Ok(self)
487    }
488}
489
490impl<S: SignatureKind<D>, D: DB> Transaction<S, ProofPreimageMarker, PedersenRandomness, D> {
491    pub fn new(
492        network_id: impl Into<String>,
493        intents: storage::storage::HashMap<
494            u16,
495            Intent<S, ProofPreimageMarker, PedersenRandomness, D>,
496            D,
497        >,
498        guaranteed_coins: Option<ZswapOffer<ProofPreimage, D>>,
499        fallible_coins: storage::storage::HashMap<u16, ZswapOffer<ProofPreimage, D>, D>,
500    ) -> Self {
501        let mut stx = StandardTransaction {
502            network_id: network_id.into(),
503            intents,
504            guaranteed_coins: guaranteed_coins
505                .map(|x| Sp::new(x.retarget_segment(GUARANTEED_SEGMENT))),
506            fallible_coins: fallible_coins
507                .into_iter()
508                .map(|(seg, offer)| (seg, offer.retarget_segment(seg)))
509                .collect(),
510            binding_randomness: Default::default(),
511        };
512        stx.recompute_binding_randomness();
513        Transaction::Standard(stx)
514    }
515}
516
517#[derive_where::derive_where(Clone, Debug)]
518pub struct PrePartitionContractCall<D: DB> {
519    pub address: ContractAddress,
520    pub entry_point: EntryPointBuf,
521    pub op: ContractOperation,
522    pub pre_transcript: PreTranscript<D>,
523    pub private_transcript_outputs: Vec<AlignedValue>,
524    pub input: AlignedValue,
525    pub output: AlignedValue,
526    pub communication_commitment_rand: Fr,
527    pub key_location: KeyLocation,
528}
529
530#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
531#[serde(tag = "tag", content = "value", rename_all = "camelCase")]
532pub enum SegmentSpecifier {
533    First,
534    GuaranteedOnly,
535    Random,
536    Specific(u16),
537}
538
539#[derive(Clone, Debug)]
540pub struct ContractCallPrototype<D: DB> {
541    pub address: ContractAddress,
542    pub entry_point: EntryPointBuf,
543    pub op: ContractOperation,
544    pub guaranteed_public_transcript: Option<Transcript<D>>,
545    pub fallible_public_transcript: Option<Transcript<D>>,
546    pub private_transcript_outputs: Vec<AlignedValue>,
547    pub input: AlignedValue,
548    pub output: AlignedValue,
549    pub communication_commitment_rand: Fr,
550    pub key_location: KeyLocation,
551}
552
553pub trait ContractCallExt<D: DB> {
554    type AssociatedProof;
555    fn construct_proof(
556        call: &ContractCallPrototype<D>,
557        communication_commitment: Fr,
558    ) -> ProofPreimageVersioned;
559}
560
561impl<D: DB> ContractCallExt<D> for ProofPreimage {
562    type AssociatedProof = ProofPreimage;
563    fn construct_proof(
564        call: &ContractCallPrototype<D>,
565        communication_commitment: Fr,
566    ) -> ProofPreimageVersioned {
567        let inputs = ValueReprAlignedValue(call.input.clone()).field_vec();
568        let mut private_transcript = Vec::with_capacity(
569            call.private_transcript_outputs
570                .iter()
571                .map(|o| o.value_only_field_size())
572                .sum(),
573        );
574        for o in call.private_transcript_outputs.iter() {
575            o.value_only_field_repr(&mut private_transcript);
576        }
577        let public_transcript_iter = call
578            .guaranteed_public_transcript
579            .iter()
580            .flat_map(|t| t.program.iter_deref())
581            .chain(
582                call.fallible_public_transcript
583                    .iter()
584                    .flat_map(|t| t.program.iter_deref()),
585            );
586
587        let public_transcript_ops: Vec<_> = public_transcript_iter.collect();
588
589        let mut public_transcript_inputs =
590            Vec::with_capacity(public_transcript_ops.iter().map(|op| op.field_size()).sum());
591
592        for op in &public_transcript_ops {
593            op.field_repr(&mut public_transcript_inputs);
594        }
595
596        let mut public_transcript_outputs = Vec::new();
597        for op in &public_transcript_ops {
598            if let Op::Popeq { result, .. } = op {
599                result.value_only_field_repr(&mut public_transcript_outputs);
600            }
601        }
602
603        // This gets populated correctly during proving, ensuring it correctly uses the updated
604        // transcripts and costs.
605        let binding_input = 0u8.into();
606
607        let proof = ProofPreimage {
608            inputs,
609            private_transcript,
610            public_transcript_inputs,
611            public_transcript_outputs,
612            binding_input,
613            communications_commitment: Some((
614                communication_commitment,
615                call.communication_commitment_rand,
616            )),
617            key_location: call.key_location.clone(),
618        };
619
620        ProofPreimageVersioned::V2(std::sync::Arc::new(proof))
621    }
622}
623
624impl<D: DB> ContractCall<ProofPreimageMarker, D> {
625    pub fn new(
626        address: ContractAddress,
627        entry_point: EntryPointBuf,
628        guaranteed_transcript: Option<Transcript<D>>,
629        fallible_transcript: Option<Transcript<D>>,
630        communication_commitment: Fr,
631        proof: ProofPreimageVersioned,
632    ) -> Self {
633        ContractCall {
634            address,
635            entry_point,
636            guaranteed_transcript: guaranteed_transcript.map(Sp::new),
637            fallible_transcript: fallible_transcript.map(Sp::new),
638            communication_commitment,
639            proof,
640        }
641    }
642}
643
644impl<S: SignatureKind<D>, D: DB> Intent<S, ProofPreimageMarker, PedersenRandomness, D> {
645    pub fn add_call<P>(&self, call: ContractCallPrototype<D>) -> Self
646    where
647        P: ContractCallExt<D>,
648    {
649        let mut io_repr = Vec::with_capacity(
650            call.input.value_only_field_size() + call.output.value_only_field_size(),
651        );
652        call.input.value_only_field_repr(&mut io_repr);
653        call.output.value_only_field_repr(&mut io_repr);
654        let communication_commitment =
655            transient_commit(&io_repr, call.communication_commitment_rand);
656
657        let proof = P::construct_proof(&call, communication_commitment);
658        let call = ContractCall {
659            address: call.address,
660            entry_point: call.entry_point,
661            guaranteed_transcript: call.guaranteed_public_transcript.map(|x| Sp::new(x)),
662            fallible_transcript: call.fallible_public_transcript.map(|x| Sp::new(x)),
663            communication_commitment,
664            proof,
665        };
666        // We add the call:
667        // - Directly before the first call *claimed* by it
668        // - At the end otherwise.
669        let mut actions = Vec::new();
670        let mut already_inserted = false;
671        fn references<D: DB>(
672            caller: &ContractCall<ProofPreimageMarker, D>,
673            callee: &ContractAction<ProofPreimageMarker, D>,
674        ) -> bool {
675            match callee {
676                ContractAction::Call(call) => caller
677                    .guaranteed_transcript
678                    .iter()
679                    .chain(caller.fallible_transcript.iter())
680                    .flat_map(|t| {
681                        t.effects
682                            .claimed_contract_calls
683                            .iter()
684                            .map(|x| (*x).deref().into_inner())
685                    })
686                    .any(|(_seq, addr, ep_hash, cc)| {
687                        addr == call.address
688                            && cc == call.communication_commitment
689                            && ep_hash == call.entry_point.ep_hash()
690                    }),
691                _ => false,
692            }
693        }
694        for c in self.actions.iter_deref().cloned() {
695            if !already_inserted && references(&call, &c) {
696                actions.push(call.clone().into());
697                already_inserted = true;
698            }
699            actions.push(c);
700        }
701        if !already_inserted {
702            actions.push(call.into());
703        }
704        Intent {
705            guaranteed_unshielded_offer: self.guaranteed_unshielded_offer.clone(),
706            fallible_unshielded_offer: self.fallible_unshielded_offer.clone(),
707            actions: actions.into(),
708            dust_actions: self.dust_actions.clone(),
709            ttl: self.ttl,
710            binding_commitment: self.binding_commitment,
711        }
712    }
713
714    pub fn add_deploy(&self, deploy: ContractDeploy<D>) -> Self {
715        Intent {
716            guaranteed_unshielded_offer: self.guaranteed_unshielded_offer.clone(),
717            fallible_unshielded_offer: self.fallible_unshielded_offer.clone(),
718            actions: self
719                .actions
720                .iter_deref()
721                .cloned()
722                .chain(once(deploy.into()))
723                .collect(),
724            dust_actions: self.dust_actions.clone(),
725            ttl: self.ttl,
726            binding_commitment: self.binding_commitment,
727        }
728    }
729
730    pub fn add_maintenance_update(&self, upd: MaintenanceUpdate<D>) -> Self {
731        Intent {
732            guaranteed_unshielded_offer: self.guaranteed_unshielded_offer.clone(),
733            fallible_unshielded_offer: self.fallible_unshielded_offer.clone(),
734            actions: self
735                .actions
736                .iter_deref()
737                .cloned()
738                .chain(once(upd.into()))
739                .collect(),
740            dust_actions: self.dust_actions.clone(),
741            ttl: self.ttl,
742            binding_commitment: self.binding_commitment,
743        }
744    }
745
746    pub fn binding_randomness(&self) -> PedersenRandomness {
747        self.binding_commitment
748    }
749}
750
751#[derive(Debug)]
752pub struct PreTranscript<D: DB> {
753    pub context: QueryContext<D>,
754    pub program: Vec<Op<ResultModeVerify, D>>,
755    pub comm_comm: Option<Fr>,
756}
757
758impl<D: DB> Clone for PreTranscript<D> {
759    fn clone(&self) -> Self {
760        PreTranscript {
761            context: self.context.clone(),
762            program: self.program.clone(),
763            comm_comm: self.comm_comm,
764        }
765    }
766}
767
768const LAST_COMMITMENT_INDEX: u64 = (1 << ZSWAP_TREE_HEIGHT) - 1;
769
770impl<D: DB> PreTranscript<D> {
771    /// The chain assigns an output's index on inclusion, so the client rehearses
772    /// with a stand-in, typically the output's ordinal. A contract that stores
773    /// the index then writes as many bytes as the stand-in takes, and the real
774    /// index may take more. Packing the indices onto the last leaves of the tree,
775    /// in their original order, makes each as wide as an index can get, so the
776    /// rehearsal declares enough bytes for any tree.
777    fn with_widest_commitment_indices(&self) -> Self {
778        let mut context = self.context.clone();
779        let mut by_index = context.call_context.com_indices.iter().collect::<Vec<_>>();
780        by_index.sort_by_key(|(commitment, index)| (**index, *commitment));
781        let last_leaves = (LAST_COMMITMENT_INDEX + 1 - by_index.len() as u64)..;
782        context.call_context.com_indices = by_index
783            .into_iter()
784            .map(|(commitment, _)| commitment)
785            .zip(last_leaves)
786            .collect();
787        PreTranscript {
788            context,
789            program: self.program.clone(),
790            comm_comm: self.comm_comm,
791        }
792    }
793
794    fn no_checkpoints(&self) -> usize {
795        self.program
796            .iter()
797            .filter(|op| matches!(op, Op::Ckpt))
798            .count()
799    }
800
801    // 0-indexed!
802    fn run_to_ckpt_no(
803        &self,
804        mut n: usize,
805        params: &LedgerParameters,
806    ) -> Result<QueryResults<ResultModeVerify, D>, TranscriptRejected<D>> {
807        n += 1;
808        let prog = self
809            .program
810            .iter()
811            .cloned()
812            .take_while(|op| {
813                if matches!(op, Op::Ckpt) {
814                    n -= 1;
815                    n != 0
816                } else {
817                    true
818                }
819            })
820            .collect::<Vec<_>>();
821        self.context
822            .query(&prog, None, &params.cost_model.runtime_cost_model)
823    }
824
825    // 1-indexed!
826    #[allow(clippy::type_complexity)]
827    fn split_at(
828        &self,
829        mut n: usize,
830        params: &LedgerParameters,
831    ) -> Result<(Option<Transcript<D>>, Option<Transcript<D>>), TranscriptRejected<D>> {
832        let mut prog_guaranteed = Vec::new();
833        let mut prog_fallible = Vec::new();
834        for op in self.program.iter() {
835            if n > 0 && matches!(op, Op::Ckpt) {
836                n -= 1;
837            }
838            if n == 0 {
839                prog_fallible.push(op.clone());
840            } else {
841                prog_guaranteed.push(op.clone());
842            }
843        }
844        let guaranteed_res = self.context.query(
845            &prog_guaranteed,
846            None,
847            &params.cost_model.runtime_cost_model,
848        )?;
849        let mut continuation_context = guaranteed_res.context.clone();
850        continuation_context.effects = Effects::default();
851        let fallible_res = continuation_context.query(
852            &prog_fallible,
853            None,
854            &params.cost_model.runtime_cost_model,
855        )?;
856        let mk_transcript = |prog: Vec<Op<ResultModeVerify, D>>,
857                             res: QueryResults<ResultModeVerify, D>| {
858            if prog.is_empty() {
859                None
860            } else {
861                Some(Transcript {
862                    gas: res.gas_heuristic(params, false),
863                    effects: res.context.effects.clone(),
864                    program: prog.into(),
865                    version: Some(Sp::new(Transcript::<D>::VERSION)),
866                })
867            }
868        };
869        Ok((
870            mk_transcript(prog_guaranteed, guaranteed_res),
871            mk_transcript(prog_fallible, fallible_res),
872        ))
873    }
874}
875
876trait QueryResultsExt {
877    fn gas_heuristic(&self, params: &LedgerParameters, include_external: bool) -> RunningCost;
878}
879
880// gas_heuristic and the reserve, `mock_tx(calls, tx_shape).time_to_dismiss`,
881// together approximate Transaction::time_to_dismiss for use during transcript
882// partitioning, before the final Transaction exists. The reserve covers the
883// validation cost of every part, the calls' proof verification and VK reads
884// included, and the application cost of the non-call parts. gas_heuristic
885// covers, per call kept guaranteed, its gas with 20% overhead and its
886// application cost: state fetch/store and stack setup for its effects.
887
888impl<D: DB> QueryResultsExt for QueryResults<ResultModeVerify, D> {
889    fn gas_heuristic(&self, params: &LedgerParameters, include_external: bool) -> RunningCost {
890        const TIME_OVERHEAD: f64 = 1.2;
891        // Declared deletions are a lower bound, and any shortfall is priced as
892        // net growth; overhead is therefore applied to net growth, not churn.
893        const NET_WRITE_OVERHEAD: f64 = 1.2;
894        const DELETION_UNDERESTIMATE: f64 = 0.95;
895        let actual = self.gas_cost;
896        let churned = actual.bytes_written.min(actual.bytes_deleted);
897        let net_written = actual.bytes_written - churned;
898        let transcript_gas_cost_with_overhead = RunningCost {
899            bytes_written: churned
900                .saturating_add((net_written as f64 * NET_WRITE_OVERHEAD).ceil() as u64),
901            bytes_deleted: (actual.bytes_deleted as f64 * DELETION_UNDERESTIMATE).floor() as u64,
902            ..actual * TIME_OVERHEAD
903        };
904        if !include_external {
905            return transcript_gas_cost_with_overhead;
906        }
907        let model = &params.cost_model;
908
909        let mut application = RunningCost::ZERO;
910        application += model.map_index(EXPECTED_CONTRACT_DEPTH)
911            + model.map_insert(EXPECTED_CONTRACT_DEPTH, true)
912            + model.map_index(1)
913            + model.map_insert(1, true);
914        application += model.stack_setup_cost_for_effects(&self.context.effects);
915        application.compute_time = application.compute_time * model.guaranteed_factor;
916
917        transcript_gas_cost_with_overhead + application
918    }
919}
920
921pub fn communication_commitment(input: AlignedValue, output: AlignedValue, rand: Fr) -> Fr {
922    transient_commit(
923        &ValueReprAlignedValue(AlignedValue::concat([&input, &output])),
924        rand,
925    )
926}
927
928pub type TranscriptPair<D> = (Option<Transcript<D>>, Option<Transcript<D>>);
929
930pub fn partition_transcripts<D: DB>(
931    calls: &[PreTranscript<D>],
932    params: &LedgerParameters,
933) -> Result<Vec<TranscriptPair<D>>, PartitionFailure<D>> {
934    partition_transcripts_inner(calls, params, |derived| derived)
935}
936
937/// Splits each call's transcript into its guaranteed and fallible parts.
938/// `expected_tx_shape`'s parts add their bytes to the time-to-dismiss allowance
939/// and their cost is reserved from it.
940pub fn partition_transcripts_with_tx_shape<D: DB>(
941    calls: &[PreTranscript<D>],
942    params: &LedgerParameters,
943    expected_tx_shape: &TransactionShape,
944) -> Result<Vec<TranscriptPair<D>>, PartitionFailure<D>> {
945    partition_transcripts_inner(calls, params, |_| expected_tx_shape.clone())
946}
947
948/// `choose_tx_shape` gets the shape the calls imply and returns the one to size
949/// the partition for.
950fn partition_transcripts_inner<D: DB>(
951    calls: &[PreTranscript<D>],
952    params: &LedgerParameters,
953    choose_tx_shape: impl FnOnce(TransactionShape) -> TransactionShape,
954) -> Result<Vec<TranscriptPair<D>>, PartitionFailure<D>> {
955    if calls.is_empty() {
956        return Ok(Vec::new());
957    }
958    let n = calls.len();
959    let calls = calls
960        .iter()
961        .map(PreTranscript::with_widest_commitment_indices)
962        .collect::<Vec<_>>();
963    // Step 1: Generate a call graph between `calls`. Assert that this is a forest (no cycles,
964    //      no multiple parents).
965
966    // Gather full runs to observe all calls
967    let no_ckpts = calls
968        .iter()
969        .map(PreTranscript::no_checkpoints)
970        .collect::<Vec<_>>();
971    let full_runs = calls
972        .iter()
973        .zip(no_ckpts.iter())
974        .map(|(pt, n)| pt.run_to_ckpt_no(*n, params))
975        .collect::<Result<Vec<_>, _>>()?;
976    // Graph is a Vec of Vecs, where call_graph[i] = [a, b, c] means that calls[i] calls calls[a],
977    // calls[b] and calls[c]
978    let call_graph = full_runs
979        .iter()
980        .map(|qr| {
981            let claimed_commitments = qr
982                .context
983                .effects
984                .claimed_contract_calls
985                .iter()
986                .map(|sp| (*sp).deref().into_inner().3)
987                .collect::<Vec<_>>();
988            (0..n)
989                .filter(|i| {
990                    calls[*i]
991                        .comm_comm
992                        .map(|comm| claimed_commitments.contains(&comm))
993                        .unwrap_or(false)
994                })
995                .collect::<Vec<_>>()
996        })
997        .collect::<Vec<_>>();
998    // Identify cycles by starting at each node in turn, and asserting that the set of reachable
999    // nodes does not contain itself
1000    //
1001    // Note that this also identifies some non-cycles, such as A -> B, A -> C, B -> D, B -> D,
1002    // but this is fine as these are also not allowed.
1003    for i in 0..n {
1004        let mut visited = vec![i];
1005        let mut reachable = call_graph[i].clone();
1006        while let Some(next) = reachable.pop() {
1007            if visited.contains(&next) {
1008                return Err(PartitionFailure::NonForest);
1009            }
1010            visited.push(next);
1011            reachable.extend(&call_graph[next]);
1012        }
1013    }
1014
1015    // Step 2: Identify root nodes in the DAG.
1016    // Identify multiple parents at the same time. For each node, count how many other nodes
1017    // reference it. If that's 0, it's a root node. If it's >1, we don't have a forest.
1018    let n_callers = (0..n)
1019        .map(|i| (0..n).filter(|j| call_graph[*j].contains(&i)).count())
1020        .collect::<Vec<_>>();
1021    if n_callers.iter().any(|n| *n > 1) {
1022        return Err(PartitionFailure::NonForest);
1023    }
1024    let root_nodes = n_callers
1025        .iter()
1026        .enumerate()
1027        .filter(|(_, n)| **n == 0)
1028        .map(|(i, _)| i)
1029        .collect::<Vec<_>>();
1030
1031    // Step 3: For each root node, compute the guaranteed section budget of its closure.
1032    let closures = root_nodes
1033        .iter()
1034        .map(|r| {
1035            let mut visited = vec![];
1036            let mut frontier = vec![*r];
1037            while let Some(item) = frontier.pop() {
1038                visited.push(item);
1039                frontier.extend(&call_graph[item]);
1040            }
1041            visited
1042        })
1043        .collect::<Vec<_>>();
1044    let tx_shape = choose_tx_shape(TransactionShape::for_effects(
1045        full_runs
1046            .iter()
1047            .map(|run| (run.context.address, &run.context.effects)),
1048    ));
1049    let mock = mock_tx(&calls, &tx_shape);
1050    let reserve = mock
1051        .time_to_dismiss(params)
1052        .expect("mock transactions are disjoint by construction");
1053    let allowance = CostDuration::max(
1054        params.limits.time_to_dismiss_per_byte * mock.serialized_size() as u64,
1055        params.limits.min_time_to_dismiss,
1056    );
1057    if reserve >= allowance {
1058        return Ok(calls
1059            .iter()
1060            .map(|call| call.split_at(0, params))
1061            .collect::<Result<Vec<_>, _>>()?);
1062    }
1063    let calls_budget = allowance - reserve;
1064    let closure_sizes = closures
1065        .iter()
1066        .map(|closure| mock_calls(closure.iter().map(|i| &calls[*i])).serialized_size())
1067        .collect::<Vec<_>>();
1068    let total_size = closure_sizes.iter().sum::<usize>() as f64;
1069    let closure_budgets = closure_sizes
1070        .iter()
1071        .map(|size| calls_budget * (*size as f64 / total_size))
1072        .collect::<Vec<_>>();
1073
1074    // Step 4: Partition the root nodes:
1075    //      4a: Split root nodes on `ckpt`s.
1076    //      4b. Run up to `ckpt` and determine calls that are included. Run those entirely.
1077    //      4c. Determine the latest `ckpt` for which this fits into the previously computed
1078    //          budget.
1079
1080    // preliminary_results is a vec that, for each root, contains a pair consisting of:
1081    // the number of checkpoints to include in the guaranteed section (0 indicating entirely in the
1082    // fallible section), and a vec of the indices of the callees that are included in the
1083    // guaranteed section (a subset of the corresponding entry in call_graph).
1084    let preliminary_results = root_nodes
1085        .iter()
1086        .enumerate()
1087        .map(|(root_n, &root)| {
1088            // Run through the number of sections to put into the guaranteed transcript.
1089            // Start with the number of checkpoints + 1 (we have one more section than checkpoints),
1090            // end at 1. If none pass, 0 make it into the guaranteed section.
1091            for n in (1..no_ckpts[root] + 2).rev() {
1092                let partial_res = calls[root].run_to_ckpt_no(n - 1, params)?;
1093                let claimed = partial_res
1094                    .context
1095                    .effects
1096                    .claimed_contract_calls
1097                    .iter()
1098                    .map(|sp| (*sp).deref().into_inner().3)
1099                    .collect::<Vec<_>>();
1100                let claimed_idx = calls
1101                    .iter()
1102                    .enumerate()
1103                    .filter(|(_, pt)| {
1104                        pt.comm_comm
1105                            .map(|cc| claimed.contains(&cc))
1106                            .unwrap_or(false)
1107                    })
1108                    .map(|(i, _)| i)
1109                    .collect::<Vec<_>>();
1110                let mut required_budget = partial_res.gas_heuristic(params, true).max_time();
1111                let mut frontier = claimed_idx.clone();
1112                while let Some(next) = frontier.pop() {
1113                    required_budget += full_runs[next].gas_heuristic(params, true).max_time();
1114                    frontier.extend(&call_graph[next]);
1115                }
1116                if required_budget <= closure_budgets[root_n] {
1117                    return Ok((n, claimed_idx));
1118                }
1119            }
1120            Ok::<_, PartitionFailure<D>>((0, vec![]))
1121        })
1122        .collect::<Result<Vec<_>, _>>()?;
1123    let mut sections_in_guaranteed = vec![0; n];
1124    for (root_n, &root) in root_nodes.iter().enumerate() {
1125        sections_in_guaranteed[root] = preliminary_results[root_n].0;
1126        let mut frontier = preliminary_results[root_n].1.clone();
1127        while let Some(next) = frontier.pop() {
1128            sections_in_guaranteed[next] = no_ckpts[next] + 1;
1129            frontier.extend(&call_graph[next]);
1130        }
1131    }
1132
1133    Ok(sections_in_guaranteed
1134        .into_iter()
1135        .enumerate()
1136        .map(|(i, sections)| calls[i].split_at(sections, params))
1137        .collect::<Result<Vec<_>, _>>()?)
1138}
1139
1140#[cfg(test)]
1141mod partition_tests {
1142    use super::{has_claims_in_fallible, with_fallibility};
1143    use base_crypto::hash::HashOutput;
1144    use coin_structure::coin::{Commitment as CoinCommitment, Nullifier};
1145    use onchain_runtime::context::Effects;
1146    use storage::db::InMemoryDB;
1147
1148    fn nul(b: u8) -> Nullifier {
1149        Nullifier(HashOutput([b; 32]))
1150    }
1151
1152    fn com(b: u8) -> CoinCommitment {
1153        CoinCommitment(HashOutput([b; 32]))
1154    }
1155
1156    /// Effects claiming one nullifier and one shielded spend.
1157    fn effects(n: u8, c: u8) -> Effects<InMemoryDB> {
1158        let mut e = Effects::<InMemoryDB>::default();
1159        e.claimed_nullifiers = e.claimed_nullifiers.insert(nul(n));
1160        e.claimed_shielded_spends = e.claimed_shielded_spends.insert(com(c));
1161        e
1162    }
1163
1164    #[test]
1165    fn has_claims_in_fallible_matches_any_claiming_transcript() {
1166        let a = effects(1, 10);
1167        let b = effects(2, 20);
1168        let all = [&a, &b];
1169
1170        // Claimed by the first, the second, and by neither.
1171        let items = [nul(1), nul(2), nul(3)];
1172        let flags = has_claims_in_fallible(&items, &all, |e, n| e.claimed_nullifiers.member(n));
1173        assert_eq!(flags, vec![true, true, false]);
1174
1175        // No fallible transcripts at all => nothing is fallible.
1176        let none: [&Effects<InMemoryDB>; 0] = [];
1177        let flags = has_claims_in_fallible(&items, &none, |e, n| e.claimed_nullifiers.member(n));
1178        assert_eq!(flags, vec![false, false, false]);
1179    }
1180
1181    /// A nullifier claim must not make an output fallible, nor vice versa: the flags are
1182    /// per-item-kind, and crossing them would move coins into the wrong offer.
1183    #[test]
1184    fn has_claims_in_fallible_does_not_cross_item_kinds() {
1185        let a = effects(1, 10);
1186        let all = [&a];
1187
1188        let commitments = [com(10), com(1)];
1189        let flags = has_claims_in_fallible(&commitments, &all, |e, c| {
1190            e.claimed_shielded_spends.member(c) || e.claimed_shielded_receives.member(c)
1191        });
1192        // com(1) shares its bytes with the claimed *nullifier*, but is not a claimed spend.
1193        assert_eq!(flags, vec![true, false]);
1194    }
1195
1196    #[test]
1197    fn with_fallibility_partitions_and_preserves_order() {
1198        let items = ['a', 'b', 'c', 'd'];
1199        let flags = [false, true, false, true];
1200        assert_eq!(with_fallibility(&items, &flags, false), vec!['a', 'c']);
1201        assert_eq!(with_fallibility(&items, &flags, true), vec!['b', 'd']);
1202
1203        // Every item lands in exactly one of the two offers.
1204        let guaranteed = with_fallibility(&items, &flags, false);
1205        let fallible = with_fallibility(&items, &flags, true);
1206        assert_eq!(guaranteed.len() + fallible.len(), items.len());
1207    }
1208}
1209
1210#[cfg(test)]
1211mod gas_heuristic_tests {
1212    use super::{LAST_COMMITMENT_INDEX, PreTranscript, QueryResultsExt};
1213    use crate::structure::INITIAL_PARAMETERS;
1214    use base_crypto::cost_model::{CostDuration, RunningCost, SyntheticCost};
1215    use base_crypto::fab::AlignedValue;
1216    use base_crypto::hash::HashOutput;
1217    use coin_structure::coin::Commitment;
1218    use coin_structure::contract::ContractAddress;
1219    use onchain_runtime::context::{QueryContext, QueryResults};
1220    use onchain_runtime::ops::{Key, Op, expect_checked};
1221    use onchain_runtime::result_mode::ResultModeVerify;
1222    use onchain_runtime::state::{ChargedState, StateValue};
1223    use proptest::prelude::*;
1224    use storage::arena::Sp;
1225    use storage::db::InMemoryDB;
1226    use storage::storage::Map;
1227
1228    fn declared(actual: RunningCost) -> RunningCost {
1229        let res = QueryResults::<ResultModeVerify, InMemoryDB> {
1230            context: QueryContext::new(
1231                ChargedState::new(StateValue::Null),
1232                ContractAddress::default(),
1233            ),
1234            events: Vec::new(),
1235            gas_cost: actual,
1236        };
1237        res.gas_heuristic(&INITIAL_PARAMETERS, false)
1238    }
1239
1240    proptest! {
1241        // The declaration must survive the post-execution check. Padding writes in
1242        // proportion to churn would price churned bytes as net growth.
1243        #[test]
1244        fn declared_writes_pad_net_growth_only(
1245            written in 0u64..10_000_000,
1246            deleted in 0u64..10_000_000,
1247        ) {
1248            let actual = RunningCost {
1249                read_time: CostDuration::ZERO,
1250                compute_time: CostDuration::ZERO,
1251                bytes_written: written,
1252                bytes_deleted: deleted,
1253            };
1254            let declared = declared(actual);
1255            prop_assert!(declared.bytes_deleted <= actual.bytes_deleted);
1256            prop_assert!(declared.bytes_written >= actual.bytes_written);
1257
1258            let actual_net = SyntheticCost::from(actual).bytes_written;
1259            prop_assert!(declared.bytes_written <= actual.bytes_written + actual_net.div_ceil(5));
1260        }
1261    }
1262
1263    const CONTEXT_COM_INDICES: u8 = 1;
1264
1265    fn store_coin_index(commitment: Commitment) -> Vec<Op<ResultModeVerify, InMemoryDB>> {
1266        vec![
1267            Op::Dup { n: 2 },
1268            Op::Idx {
1269                cached: false,
1270                push_path: false,
1271                path: [
1272                    Key::Value(CONTEXT_COM_INDICES.into()),
1273                    Key::Value(expect_checked(AlignedValue::from(commitment))),
1274                ]
1275                .into_iter()
1276                .collect(),
1277            },
1278            Op::Addi { immediate: 0 },
1279            Op::Swap { n: 0 },
1280            Op::Pop,
1281        ]
1282    }
1283
1284    fn coin_context(
1285        commitment: Commitment,
1286        stored_index: u64,
1287        context_index: u64,
1288    ) -> QueryContext<InMemoryDB> {
1289        let mut context = QueryContext::new(
1290            ChargedState::new(StateValue::Cell(Sp::new(AlignedValue::from(stored_index)))),
1291            ContractAddress::default(),
1292        );
1293        context.call_context.com_indices = Map::new().insert(commitment, context_index);
1294        context
1295    }
1296
1297    fn overwrite_coin_index(
1298        context: QueryContext<InMemoryDB>,
1299        commitment: Commitment,
1300    ) -> RunningCost {
1301        context
1302            .query(
1303                &store_coin_index(commitment),
1304                None,
1305                &INITIAL_PARAMETERS.cost_model.runtime_cost_model,
1306            )
1307            .unwrap()
1308            .gas_cost
1309    }
1310
1311    #[test]
1312    fn declared_writes_cover_the_real_commitment_index() {
1313        const HELD_COIN_INDEX: u64 = 1;
1314        const OUTPUT_ORDINAL: u64 = 0;
1315        const FRESH_TREE_INDEX: u64 = 2;
1316
1317        let commitment = Commitment(HashOutput([7; 32]));
1318        let rehearsal = PreTranscript {
1319            context: coin_context(commitment, HELD_COIN_INDEX, OUTPUT_ORDINAL),
1320            program: store_coin_index(commitment),
1321            comm_comm: None,
1322        };
1323        let ordinal_declared =
1324            declared(overwrite_coin_index(rehearsal.context.clone(), commitment));
1325        let widened_declared = declared(overwrite_coin_index(
1326            rehearsal.with_widest_commitment_indices().context,
1327            commitment,
1328        ));
1329
1330        let fresh_tree = overwrite_coin_index(
1331            coin_context(commitment, HELD_COIN_INDEX, FRESH_TREE_INDEX),
1332            commitment,
1333        );
1334        assert!(fresh_tree.within_bounds(&widened_declared));
1335        assert!(
1336            fresh_tree.within_bounds(&ordinal_declared),
1337            "this assertion is here just to bring attention, but it might be fine that this fails"
1338        );
1339        let full_tree = overwrite_coin_index(
1340            coin_context(commitment, HELD_COIN_INDEX, LAST_COMMITMENT_INDEX),
1341            commitment,
1342        );
1343        assert!(
1344            !full_tree.within_bounds(&ordinal_declared),
1345            "the ordinal stand-in alone does not cover the last tree index; if this fails adjust\
1346            this test; consider removing 'with_widest_commitment_indices' if other code change now\
1347            covers this case"
1348        );
1349        assert!(
1350            full_tree.within_bounds(&widened_declared),
1351            "declared {} written bytes, the last tree index writes {}",
1352            widened_declared.bytes_written,
1353            full_tree.bytes_written
1354        );
1355    }
1356
1357    #[test]
1358    fn widest_commitment_indices_keep_their_order_and_end_at_the_last_leaf() {
1359        let first = Commitment(HashOutput([1; 32]));
1360        let second = Commitment(HashOutput([2; 32]));
1361        let third = Commitment(HashOutput([3; 32]));
1362        let mut context = QueryContext::new(
1363            ChargedState::new(StateValue::Null),
1364            ContractAddress::default(),
1365        );
1366        context.call_context.com_indices = Map::new()
1367            .insert(first, 0)
1368            .insert(second, 1)
1369            .insert(third, LAST_COMMITMENT_INDEX);
1370        let widened = PreTranscript {
1371            context,
1372            program: Vec::<Op<ResultModeVerify, InMemoryDB>>::new(),
1373            comm_comm: None,
1374        }
1375        .with_widest_commitment_indices();
1376
1377        let index = |commitment| {
1378            *widened
1379                .context
1380                .call_context
1381                .com_indices
1382                .get(&commitment)
1383                .unwrap()
1384        };
1385        assert_eq!(index(first), LAST_COMMITMENT_INDEX - 2);
1386        assert_eq!(index(second), LAST_COMMITMENT_INDEX - 1);
1387        assert_eq!(index(third), LAST_COMMITMENT_INDEX);
1388    }
1389}