Skip to main content

midnight_ledger_v9/
verify.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
14use crate::dust::DustParameters;
15use crate::error::MalformedContractDeploy;
16use crate::error::{
17    BalanceOperation, DisjointCheckError, EffectsCheckError, MalformedTransaction,
18    SequencingCheckError, SubsetCheckFailure, TransactionApplicationError,
19};
20use crate::primitive::MultiSet;
21use crate::structure::{
22    BindingKind, ClaimRewardsTransaction, ContractAction, ContractCall, ContractDeploy,
23    ErasedIntent, FEE_TOKEN, GUARANTEED_SEGMENT, Intent, LedgerParameters, LedgerState,
24    MaintenanceUpdate, PedersenDowngradeable, ProofKind, Signature, SignatureVerifyingKey,
25    SingleUpdate, StandardTransaction, Transaction, UnshieldedOffer,
26};
27use crate::structure::{MAX_CONTRACT_OPERATIONS, SignatureKind, VerifiedTransaction};
28use crate::utils::SortedIter;
29use crate::verify::MalformedTransaction::IntentSignatureVerificationFailure;
30use base_crypto::hash::HashOutput;
31use base_crypto::time::{Duration, Timestamp};
32use coin_structure::coin::PublicAddress;
33use coin_structure::coin::{Commitment, Nullifier, TokenType};
34use coin_structure::contract::ContractAddress;
35use onchain_runtime::ops::Op;
36use onchain_runtime::state::{
37    ChargedState, ContractMaintenanceAuthority, ContractMaintenanceVerifyingKey, ContractOperation,
38    ContractState, EntryPoint, EntryPointBuf,
39};
40use onchain_runtime::transcript::Transcript;
41use serialize::{Serializable, Tagged};
42use sha2::Digest;
43use sha2::Sha256;
44use std::collections::{BTreeSet, VecDeque};
45use std::ops::Deref;
46use std::ops::Mul;
47use storage::Storable;
48use storage::arena::{ArenaHash, Sp};
49use storage::dag_memo::DagMemo;
50use storage::db::DB;
51use transient_crypto::commitment::Pedersen;
52use transient_crypto::curve::{EmbeddedFr, EmbeddedGroupAffine, Fr};
53use transient_crypto::hash::hash_to_curve;
54use transient_crypto::merkle_tree::MerkleTreeDigest;
55use transient_crypto::repr::FieldRepr;
56
57pub trait ContractStateExt<D: DB> {
58    #[allow(clippy::result_large_err)]
59    fn well_formed(&self, address: ContractAddress) -> Result<(), MalformedTransaction<D>>;
60}
61
62pub trait StateReference<D: DB> {
63    fn stateless_check(
64        &self,
65        check: impl FnOnce() -> Result<(), MalformedTransaction<D>>,
66    ) -> Result<(), MalformedTransaction<D>>;
67    fn param_check(
68        &self,
69        always: bool,
70        check: impl FnOnce(&LedgerParameters) -> Result<(), MalformedTransaction<D>>,
71    ) -> Result<(), MalformedTransaction<D>>;
72    fn op_check(
73        &self,
74        contract: ContractAddress,
75        entry_point: &EntryPointBuf,
76        check: impl FnOnce(&ContractOperation) -> Result<(), MalformedTransaction<D>>,
77    ) -> Result<(), MalformedTransaction<D>>;
78    fn maintenance_check(
79        &self,
80        contract: ContractAddress,
81        check: impl FnOnce(&ContractMaintenanceAuthority) -> Result<(), MalformedTransaction<D>>,
82    ) -> Result<(), MalformedTransaction<D>>;
83    fn generationless_fee_availability_check(
84        &self,
85        parent_intent: &ErasedIntent<D>,
86        night_key: &SignatureVerifyingKey,
87        check: impl FnOnce(u128) -> Result<(), MalformedTransaction<D>>,
88    ) -> Result<(), MalformedTransaction<D>>;
89    fn dust_spend_check(
90        &self,
91        ctime: Timestamp,
92        // Dust parameters, commitment tree root associated with the timestamp, generation root associated with the timestamp
93        check: impl FnOnce(
94            DustParameters,
95            MerkleTreeDigest,
96            MerkleTreeDigest,
97        ) -> Result<(), MalformedTransaction<D>>,
98    ) -> Result<(), MalformedTransaction<D>>;
99    fn fees_check(
100        &self,
101        check: impl FnOnce(
102            &dyn Fn(ContractAddress, &EntryPointBuf) -> Option<ContractOperation>,
103        ) -> Result<(), MalformedTransaction<D>>,
104    ) -> Result<(), MalformedTransaction<D>>;
105    fn network_check(&self, network: &str) -> Result<(), MalformedTransaction<D>>;
106    fn ref_state_hash(&self) -> ArenaHash<D::Hasher>;
107}
108
109fn get_op<D: DB>(
110    state: &LedgerState<D>,
111    contract: ContractAddress,
112    entry_point: &EntryPointBuf,
113) -> Result<Sp<ContractOperation, D>, MalformedTransaction<D>> {
114    let cstate = state
115        .index(contract)
116        .ok_or_else(|| MalformedTransaction::ContractNotPresent(contract))?;
117    cstate
118        .operations
119        .get(entry_point)
120        .ok_or_else(|| MalformedTransaction::VerifierKeyNotPresent {
121            address: contract,
122            operation: entry_point.clone(),
123        })
124}
125
126impl<D: DB> StateReference<D> for LedgerState<D> {
127    fn stateless_check(
128        &self,
129        check: impl FnOnce() -> Result<(), MalformedTransaction<D>>,
130    ) -> Result<(), MalformedTransaction<D>> {
131        check()
132    }
133    fn param_check(
134        &self,
135        _always: bool,
136        check: impl FnOnce(&LedgerParameters) -> Result<(), MalformedTransaction<D>>,
137    ) -> Result<(), MalformedTransaction<D>> {
138        check(&self.parameters)
139    }
140    fn op_check(
141        &self,
142        contract: ContractAddress,
143        entry_point: &EntryPointBuf,
144        check: impl FnOnce(&ContractOperation) -> Result<(), MalformedTransaction<D>>,
145    ) -> Result<(), MalformedTransaction<D>> {
146        check(&*get_op(self, contract, entry_point)?)
147    }
148    fn maintenance_check(
149        &self,
150        contract: ContractAddress,
151        check: impl FnOnce(&ContractMaintenanceAuthority) -> Result<(), MalformedTransaction<D>>,
152    ) -> Result<(), MalformedTransaction<D>> {
153        check(
154            &self
155                .index(contract)
156                .ok_or_else(|| MalformedTransaction::ContractNotPresent(contract))?
157                .maintenance_authority,
158        )
159    }
160    fn generationless_fee_availability_check(
161        &self,
162        parent_intent: &ErasedIntent<D>,
163        night_key: &SignatureVerifyingKey,
164        check: impl FnOnce(u128) -> Result<(), MalformedTransaction<D>>,
165    ) -> Result<(), MalformedTransaction<D>> {
166        let availability = self.dust.generationless_fee_availability(
167            &self.utxo,
168            parent_intent,
169            night_key,
170            &self.parameters.dust,
171        );
172        check(availability)
173    }
174    fn dust_spend_check(
175        &self,
176        ctime: Timestamp,
177        // Dust parameters, commitment tree root associated with the timestamp, generation root associated with the timestamp
178        check: impl FnOnce(
179            DustParameters,
180            MerkleTreeDigest,
181            MerkleTreeDigest,
182        ) -> Result<(), MalformedTransaction<D>>,
183    ) -> Result<(), MalformedTransaction<D>> {
184        let params = self.parameters.dust;
185        let commitment_root = self
186            .dust
187            .utxo
188            .root_history
189            .get(ctime)
190            .map(|x| x.0)
191            .unwrap_or_default();
192        let generation_root = self
193            .dust
194            .generation
195            .root_history
196            .get(ctime)
197            .map(|x| x.0)
198            .unwrap_or_default();
199        check(params, commitment_root, generation_root)
200    }
201    fn fees_check(
202        &self,
203        check: impl FnOnce(
204            &dyn Fn(ContractAddress, &EntryPointBuf) -> Option<ContractOperation>,
205        ) -> Result<(), MalformedTransaction<D>>,
206    ) -> Result<(), MalformedTransaction<D>> {
207        check(&|contract, entry_point| {
208            self.index(contract)
209                .and_then(|cstate| cstate.operations.get(entry_point).map(|op| (*op).clone()))
210        })
211    }
212    fn network_check(&self, network: &str) -> Result<(), MalformedTransaction<D>> {
213        if self.network_id == network {
214            Ok(())
215        } else {
216            Err(MalformedTransaction::InvalidNetworkId {
217                expected: self.network_id.clone(),
218                found: network.into(),
219            })
220        }
221    }
222    fn ref_state_hash(&self) -> ArenaHash<D::Hasher> {
223        self.state_hash()
224    }
225}
226
227pub struct RevalidationReference<D: DB> {
228    pub previously_validated_state: LedgerState<D>,
229    pub new_state: LedgerState<D>,
230}
231
232impl<D: DB> StateReference<D> for RevalidationReference<D> {
233    fn stateless_check(
234        &self,
235        _: impl FnOnce() -> Result<(), MalformedTransaction<D>>,
236    ) -> Result<(), MalformedTransaction<D>> {
237        // We've already done all of the stateless checks in the first check.
238        Ok(())
239    }
240    fn param_check(
241        &self,
242        always: bool,
243        check: impl FnOnce(&LedgerParameters) -> Result<(), MalformedTransaction<D>>,
244    ) -> Result<(), MalformedTransaction<D>> {
245        if always || self.previously_validated_state.parameters != self.new_state.parameters {
246            check(&self.new_state.parameters)
247        } else {
248            Ok(())
249        }
250    }
251    fn op_check(
252        &self,
253        contract: ContractAddress,
254        entry_point: &EntryPointBuf,
255        check: impl FnOnce(&ContractOperation) -> Result<(), MalformedTransaction<D>>,
256    ) -> Result<(), MalformedTransaction<D>> {
257        let old_op = get_op(&self.previously_validated_state, contract, entry_point)?;
258        let new_op = get_op(&self.new_state, contract, entry_point)?;
259        if old_op == new_op {
260            Ok(())
261        } else {
262            check(&new_op)
263        }
264    }
265    fn maintenance_check(
266        &self,
267        contract: ContractAddress,
268        check: impl FnOnce(&ContractMaintenanceAuthority) -> Result<(), MalformedTransaction<D>>,
269    ) -> Result<(), MalformedTransaction<D>> {
270        let auth_old = &self
271            .previously_validated_state
272            .index(contract)
273            .ok_or_else(|| MalformedTransaction::ContractNotPresent(contract))?
274            .maintenance_authority;
275        let auth_new = &self
276            .new_state
277            .index(contract)
278            .ok_or_else(|| MalformedTransaction::ContractNotPresent(contract))?
279            .maintenance_authority;
280        if auth_old == auth_new {
281            Ok(())
282        } else {
283            check(auth_new)
284        }
285    }
286    fn generationless_fee_availability_check(
287        &self,
288        parent_intent: &ErasedIntent<D>,
289        night_key: &SignatureVerifyingKey,
290        check: impl FnOnce(u128) -> Result<(), MalformedTransaction<D>>,
291    ) -> Result<(), MalformedTransaction<D>> {
292        let availability = self.new_state.dust.generationless_fee_availability(
293            &self.new_state.utxo,
294            parent_intent,
295            night_key,
296            &self.new_state.parameters.dust,
297        );
298        check(availability)
299    }
300    fn dust_spend_check(
301        &self,
302        ctime: Timestamp,
303        // Dust parameters, commitment tree root associated with the timestamp, generation root associated with the timestamp
304        check: impl FnOnce(
305            DustParameters,
306            MerkleTreeDigest,
307            MerkleTreeDigest,
308        ) -> Result<(), MalformedTransaction<D>>,
309    ) -> Result<(), MalformedTransaction<D>> {
310        let params_old = self.previously_validated_state.parameters.dust;
311        let commitment_root_old = self
312            .previously_validated_state
313            .dust
314            .utxo
315            .root_history
316            .get(ctime)
317            .map(|x| x.0)
318            .unwrap_or_default();
319        let generation_root_old = self
320            .previously_validated_state
321            .dust
322            .generation
323            .root_history
324            .get(ctime)
325            .map(|x| x.0)
326            .unwrap_or_default();
327        let params_new = self.new_state.parameters.dust;
328        let commitment_root_new = self
329            .new_state
330            .dust
331            .utxo
332            .root_history
333            .get(ctime)
334            .map(|x| x.0)
335            .unwrap_or_default();
336        let generation_root_new = self
337            .new_state
338            .dust
339            .generation
340            .root_history
341            .get(ctime)
342            .map(|x| x.0)
343            .unwrap_or_default();
344        if (params_old, commitment_root_old, generation_root_old)
345            == (params_new, commitment_root_new, generation_root_new)
346        {
347            Ok(())
348        } else {
349            check(params_new, commitment_root_new, generation_root_new)
350        }
351    }
352    fn fees_check(
353        &self,
354        check: impl FnOnce(
355            &dyn Fn(ContractAddress, &EntryPointBuf) -> Option<ContractOperation>,
356        ) -> Result<(), MalformedTransaction<D>>,
357    ) -> Result<(), MalformedTransaction<D>> {
358        check(&|contract, entry_point| {
359            self.new_state
360                .index(contract)
361                .and_then(|cstate| cstate.operations.get(entry_point).map(|op| (*op).clone()))
362        })
363    }
364    fn network_check(&self, network: &str) -> Result<(), MalformedTransaction<D>> {
365        if self.new_state.network_id == network {
366            Ok(())
367        } else {
368            Err(MalformedTransaction::InvalidNetworkId {
369                expected: self.new_state.network_id.clone(),
370                found: network.into(),
371            })
372        }
373    }
374    fn ref_state_hash(&self) -> ArenaHash<D::Hasher> {
375        self.new_state.state_hash()
376    }
377}
378
379pub(crate) enum MetadataSizeError {
380    EntryPoint(EntryPointBuf, u64),
381    Authority(u64),
382}
383
384pub(crate) fn check_entry_point_metadata_sizes<D: DB>(
385    state: &ContractState<D>,
386    limit: u64,
387) -> Result<(), MetadataSizeError> {
388    let auth_size = state.maintenance_authority.serialized_size() as u64;
389    if auth_size > limit {
390        return Err(MetadataSizeError::Authority(auth_size));
391    }
392    for entry in state.operations.iter() {
393        let size = entry.0.serialized_size() as u64 + entry.1.serialized_size() as u64;
394        if size > limit {
395            return Err(MetadataSizeError::EntryPoint((*entry.0).clone(), size));
396        }
397    }
398    Ok(())
399}
400
401impl<D: DB> ContractStateExt<D> for ContractState<D> {
402    #[instrument(skip(self))]
403    #[allow(clippy::result_large_err)]
404    fn well_formed(&self, address: ContractAddress) -> Result<(), MalformedTransaction<D>> {
405        for a in self.operations.iter() {
406            a.1.well_formed(address, a.0.as_ref())?;
407        }
408        if self.maintenance_authority.counter != 0 {
409            return Err(MalformedTransaction::NotNormalized);
410        }
411        trace!("well formed");
412        Ok(())
413    }
414}
415
416pub trait ContractOperationExt<D: DB> {
417    fn well_formed(
418        &self,
419        address: ContractAddress,
420        operation: EntryPoint,
421    ) -> Result<(), MalformedTransaction<D>>;
422}
423
424impl<D: DB> ContractOperationExt<D> for ContractOperation {
425    #[instrument(skip(self))]
426    fn well_formed(
427        &self,
428        address: ContractAddress,
429        operation: EntryPoint,
430    ) -> Result<(), MalformedTransaction<D>> {
431        if self.v2.is_none() && self.v3.is_none() {
432            warn!("no verifier key set");
433            return Err(MalformedTransaction::VerifierKeyNotSet {
434                address,
435                operation: operation.into(),
436            });
437        }
438        Ok(())
439    }
440}
441
442#[derive(Copy, Clone, Debug, PartialEq, Eq)]
443#[non_exhaustive]
444pub enum ProofVerificationMode {
445    Real,
446    #[cfg(feature = "mock-verify")]
447    CalibratedMock,
448}
449
450#[derive(Copy, Clone, Debug, PartialEq, Eq)]
451#[non_exhaustive]
452pub struct WellFormedStrictness {
453    pub enforce_balancing: bool,
454    pub verify_native_proofs: bool,
455    pub verify_contract_proofs: bool,
456    pub verify_signatures: bool,
457    pub enforce_limits: bool,
458    pub proof_verification_mode: ProofVerificationMode,
459}
460
461impl Default for WellFormedStrictness {
462    fn default() -> Self {
463        WellFormedStrictness {
464            enforce_balancing: true,
465            verify_native_proofs: true,
466            verify_contract_proofs: true,
467            verify_signatures: true,
468            enforce_limits: true,
469            proof_verification_mode: ProofVerificationMode::Real,
470        }
471    }
472}
473
474fn no_duplicates<T>(iter: T) -> bool
475where
476    T: IntoIterator,
477    T::Item: Ord + std::hash::Hash,
478{
479    let mut uniq = BTreeSet::new();
480    iter.into_iter().all(|x| uniq.insert(x))
481}
482
483impl<S: SignatureKind<D>, D: DB> UnshieldedOffer<S, D> {
484    pub fn well_formed(
485        self,
486        segment_id: u16,
487        parent: &ErasedIntent<D>,
488    ) -> Result<impl Fn() -> Result<(), MalformedTransaction<D>>, MalformedTransaction<D>> {
489        let ins = Vec::from(&self.inputs);
490        if !ins.is_sorted() {
491            return Err(MalformedTransaction::InputsNotSorted(ins));
492        }
493
494        let outs = Vec::from(&self.outputs);
495        if !outs.is_sorted() {
496            return Err(MalformedTransaction::OutputsNotSorted(outs));
497        }
498
499        if let Some(o) = outs.iter().find(|o| o.value == 0) {
500            return Err(MalformedTransaction::ZeroValueUtxo(o.clone()));
501        }
502
503        if !no_duplicates(&ins) {
504            return Err(MalformedTransaction::DuplicateInputs(ins));
505        }
506
507        let verify_input = parent.data_to_sign(segment_id);
508
509        Ok(move || {
510            if self.inputs.len() != self.signatures.len() {
511                return Err(MalformedTransaction::InputsSignaturesLengthMismatch {
512                    inputs: Vec::from(&self.inputs),
513                    erased_signatures: self.signatures.iter().map(|_| ()).collect(),
514                });
515            }
516
517            // Pair each input with the signature at the *same* index rather
518            // than `zip`ping the two iterators. `zip` stops at the shorter one,
519            // so a signature array reporting `len() == inputs.len()` but
520            // exposing fewer entries on iteration (e.g. a malformed, non-dense
521            // storage `Array`) would leave trailing inputs unverified. `get`
522            // requires a signature to exist for every spent input.
523            for (i, inp) in self.inputs.iter_deref().enumerate() {
524                let sig = self
525                    .signatures
526                    .get(i)
527                    .ok_or(IntentSignatureVerificationFailure)?;
528                S::signature_verify(&verify_input, inp.owner.clone(), sig)
529                    .then_some(())
530                    .ok_or(IntentSignatureVerificationFailure)?;
531            }
532            Ok(())
533        })
534    }
535}
536
537impl<
538    S: SignatureKind<D>,
539    P: ProofKind<D>,
540    B: Storable<D> + Serializable + PedersenDowngradeable<D> + BindingKind<S, P, D>,
541    D: DB,
542> Intent<S, P, B, D>
543{
544    pub fn well_formed(
545        &self,
546        segment_id: u16,
547        ref_state: &impl StateReference<D>,
548        strictness: WellFormedStrictness,
549        tblock: Timestamp,
550    ) -> Result<(), MalformedTransaction<D>>
551    where
552        UnshieldedOffer<S, D>: Clone,
553    {
554        if segment_id == GUARANTEED_SEGMENT {
555            return Err(MalformedTransaction::IntentAtGuaranteedSegmentId);
556        }
557
558        let erased = self.erase_proofs().erase_signatures();
559        let erased_ref = &erased;
560
561        ref_state.stateless_check(|| {
562            self.guaranteed_unshielded_offer
563                .as_ref()
564                .map(|offer| {
565                    B::when_sealed(offer.deref().clone().well_formed(segment_id, erased_ref))
566                })
567                .transpose()?;
568            self.fallible_unshielded_offer
569                .as_ref()
570                .map(|offer| {
571                    B::when_sealed(offer.deref().clone().well_formed(segment_id, erased_ref))
572                })
573                .transpose()?;
574            self.binding_commitment
575                .valid(&Intent::challenge_pre_for(self, segment_id))
576        })?;
577
578        self.actions
579            .iter()
580            .try_for_each(|action| action.well_formed(ref_state, strictness, erased_ref))?;
581        self.dust_actions
582            .as_ref()
583            .map(|dust_actions| {
584                dust_actions.well_formed(ref_state, strictness, segment_id, erased_ref, tblock)
585            })
586            .transpose()?;
587        Ok(())
588    }
589}
590
591impl<S: SignatureKind<D>, D: DB> ClaimRewardsTransaction<S, D> {
592    fn well_formed(&self) -> Result<(), MalformedTransaction<D>> {
593        S::signature_verify(
594            &self.erase_signatures().data_to_sign(),
595            self.owner.clone(),
596            &self.signature,
597        )
598        .then_some(())
599        .ok_or(IntentSignatureVerificationFailure)
600    }
601}
602
603impl<
604    S: SignatureKind<D>,
605    P: ProofKind<D> + Storable<D>,
606    B: Storable<D> + Serializable + PedersenDowngradeable<D> + BindingKind<S, P, D> + Tagged,
607    D: DB,
608> Transaction<S, P, B, D>
609where
610    Transaction<S, P, B, D>: Serializable,
611{
612    // All checks that can be done without a state.
613    #[instrument(skip(self, ref_state), fields(self = ?self.transaction_hash().0, ref_state = ?ref_state.ref_state_hash()))]
614    /// Checks if a transaction is well-formed, performing all checks possible
615    /// with a moderately stale reference state.
616    ///
617    /// `enforce_balancing` being set to [None] permits imbalanced transactions,
618    /// while [Some]([usize]) informs the balance check of the serialized
619    /// transaction size to use for transaction size cost calculation.
620    pub fn well_formed(
621        &self,
622        ref_state: &impl StateReference<D>,
623        strictness: WellFormedStrictness,
624        tblock: Timestamp,
625    ) -> Result<VerifiedTransaction<D>, MalformedTransaction<D>> {
626        ref_state.param_check(false, |params| {
627            if strictness.enforce_limits
628                && Transaction::serialized_size(self) as u64 > params.limits.transaction_byte_limit
629            {
630                Err(MalformedTransaction::TransactionTooLarge {
631                    tx_size: Transaction::serialized_size(self),
632                    limit: params.limits.transaction_byte_limit,
633                })
634            } else {
635                Ok(())
636            }
637        })?;
638
639        match self {
640            Transaction::Standard(stx) => {
641                ref_state.network_check(&stx.network_id)?;
642                ref_state.param_check(true, |params| {
643                    stx.ttl_check_weak(tblock, params.global_ttl)
644                        .map_err(MalformedTransaction::TransactionApplicationError)
645                })?;
646                // Repeats, then fees, before any check whose work grows with entries.
647                // Pricing rejects repeats too; this reports which entry repeats, and
648                // still rejects when balancing isn't enforced.
649                ref_state.stateless_check(|| stx.disjoint_check())?;
650                let mut fees = 0;
651                ref_state.param_check(true, |params| {
652                    ref_state.fees_check(|get_op| {
653                        fees = match self.fees_with_impl(params, get_op, true) {
654                            Ok(fees) => fees,
655                            Err(e) => {
656                                if strictness.enforce_balancing {
657                                    return Err(MalformedTransaction::FeeCalculation(e));
658                                } else {
659                                    0
660                                }
661                            }
662                        };
663                        Ok(())
664                    })
665                })?;
666                ref_state.stateless_check(|| {
667                    stx.guaranteed_coins
668                        .as_ref()
669                        .map(|x| {
670                            P::zswap_well_formed(x, GUARANTEED_SEGMENT)
671                                .map_err(MalformedTransaction::<D>::from)
672                        })
673                        .transpose()?;
674                    for seg_x_offer in stx.fallible_coins.iter() {
675                        if *seg_x_offer.0 == GUARANTEED_SEGMENT {
676                            return Err(MalformedTransaction::IllegallyDeclaredGuaranteed);
677                        }
678                        P::zswap_well_formed(&seg_x_offer.1.clone(), *seg_x_offer.0.deref())
679                            .map_err(|e: zswap::error::MalformedOffer| {
680                                MalformedTransaction::<D>::Zswap(e)
681                            })?;
682                    }
683                    stx.effects_check()?;
684                    stx.sequencing_check()?;
685                    stx.pedersen_check()
686                })?;
687
688                stx.balancing_check(strictness, fees)?;
689
690                for segment_intent in stx.intents.sorted_iter() {
691                    if *segment_intent.0 == GUARANTEED_SEGMENT {
692                        return Err(MalformedTransaction::IllegallyDeclaredGuaranteed);
693                    }
694                    segment_intent.1.well_formed(
695                        *segment_intent.0,
696                        ref_state,
697                        strictness,
698                        tblock,
699                    )?;
700                }
701
702                debug!("transaction well-formed");
703                Ok(VerifiedTransaction {
704                    inner: self.erase_proofs().erase_signatures(),
705                    hash: self.transaction_hash(),
706                    fees,
707                })
708            }
709            Transaction::ClaimRewards(mtx) => {
710                ref_state.network_check(&mtx.network_id)?;
711                ref_state.stateless_check(|| {
712                    B::when_sealed(Ok(
713                        // There's no point in checking this unless we actually care about signature verification
714                        move || <ClaimRewardsTransaction<S, D> as Clone>::clone(mtx).well_formed(),
715                    ))
716                })?;
717                Ok(VerifiedTransaction {
718                    inner: self.erase_proofs().erase_signatures(),
719                    hash: self.transaction_hash(),
720                    fees: 0,
721                })
722            }
723        }
724    }
725}
726
727impl<S: SignatureKind<D>, P: ProofKind<D>, B: Storable<D>, D: DB> Transaction<S, P, B, D>
728where
729    Transaction<S, P, B, D>: Serializable,
730{
731    pub fn balance(
732        &self,
733        fees: Option<u128>,
734    ) -> Result<std::collections::BTreeMap<(TokenType, u16), i128>, MalformedTransaction<D>> {
735        match self {
736            Self::Standard(stx) => stx.balance(fees),
737            Self::ClaimRewards(_) => Ok(std::collections::BTreeMap::new()),
738        }
739    }
740}
741
742impl<S: SignatureKind<D>, P: ProofKind<D>, B: Storable<D>, D: DB> StandardTransaction<S, P, B, D> {
743    pub fn balance(
744        &self,
745        fees: Option<u128>,
746    ) -> Result<std::collections::BTreeMap<(TokenType, u16), i128>, MalformedTransaction<D>> {
747        self.balance_maybe_deltas_only(fees, false)
748    }
749
750    fn balance_maybe_deltas_only(
751        &self,
752        fees: Option<u128>,
753        deltas_only: bool,
754    ) -> Result<std::collections::BTreeMap<(TokenType, u16), i128>, MalformedTransaction<D>> {
755        let mut res: std::collections::BTreeMap<(TokenType, u16), i128> =
756            std::collections::BTreeMap::new();
757
758        fn interpret(operation: BalanceOperation) -> fn(i128, i128) -> Option<i128> {
759            match operation {
760                BalanceOperation::Addition => |x: i128, y: i128| x.checked_add(y),
761                BalanceOperation::Subtraction => |x: i128, y: i128| x.checked_sub(y),
762            }
763        }
764
765        fn update_balance<T, D: DB>(
766            res: &mut std::collections::BTreeMap<(TokenType, u16), i128>,
767            token_type: TokenType,
768            segment: u16,
769            value: T,
770            operation: BalanceOperation,
771        ) -> Result<(), MalformedTransaction<D>>
772        where
773            T: TryInto<i128>,
774            T: Into<u128>,
775            T: Copy,
776            T::Error: std::fmt::Debug,
777        {
778            let bal = res.entry((token_type, segment)).or_insert(0);
779            let current_balance = *bal;
780
781            let casted_value = value.try_into().map_err(|_| {
782                MalformedTransaction::BalanceCheckConversionFailure {
783                    token_type,
784                    segment,
785                    operation_value: value.into(),
786                }
787            })?;
788
789            *bal = interpret(operation)(current_balance, casted_value).ok_or(
790                MalformedTransaction::BalanceCheckOutOfBounds {
791                    token_type,
792                    segment,
793                    current_balance,
794                    operation_value: casted_value,
795                    operation,
796                },
797            )?;
798
799            Ok(())
800        }
801
802        // Subtract any fees from the segment 0 `FEE_TOKEN` balance
803        if let Some(fee) = fees {
804            update_balance(&mut res, FEE_TOKEN, 0, fee, BalanceOperation::Subtraction)?;
805        }
806
807        for (segment, intent) in self.intents.sorted_iter() {
808            for dust_spend in intent.dust_actions.iter().flat_map(|da| da.spends.iter()) {
809                update_balance(
810                    &mut res,
811                    TokenType::Dust,
812                    0,
813                    dust_spend.v_fee,
814                    BalanceOperation::Addition,
815                )?;
816            }
817            for dust_reg in intent
818                .dust_actions
819                .iter()
820                .flat_map(|da| da.registrations.iter())
821            {
822                update_balance(
823                    &mut res,
824                    TokenType::Dust,
825                    0,
826                    dust_reg.allow_fee_payment,
827                    BalanceOperation::Addition,
828                )?;
829            }
830            for (segment, offer) in [
831                (0, intent.guaranteed_unshielded_offer.clone()),
832                (*segment, intent.fallible_unshielded_offer.clone()),
833            ] {
834                if let Some(inputs) = offer.clone().map(|o| o.inputs.clone()) {
835                    for inp in inputs.iter() {
836                        update_balance(
837                            &mut res,
838                            TokenType::Unshielded(inp.type_),
839                            segment,
840                            inp.value,
841                            BalanceOperation::Addition,
842                        )?;
843                    }
844                }
845
846                if let Some(outputs) = offer.map(|o| o.outputs.clone()) {
847                    for out in outputs.iter() {
848                        update_balance(
849                            &mut res,
850                            TokenType::Unshielded(out.type_),
851                            segment,
852                            out.value,
853                            BalanceOperation::Subtraction,
854                        )?;
855                    }
856                }
857            }
858
859            if deltas_only {
860                continue;
861            }
862            for call in intent.calls() {
863                let transcripts = call
864                    .guaranteed_transcript
865                    .iter()
866                    .map(|t| (0, t))
867                    .chain(call.fallible_transcript.iter().map(|t| (*segment, t)));
868
869                for (segment, transcript) in transcripts {
870                    for (pre_token, val) in transcript.effects.shielded_mints.clone() {
871                        let tt = call.address.custom_shielded_token_type(pre_token);
872                        update_balance(
873                            &mut res,
874                            TokenType::Shielded(tt),
875                            segment,
876                            val,
877                            BalanceOperation::Addition,
878                        )?;
879                    }
880
881                    for (pre_token, val) in transcript.effects.unshielded_mints.clone() {
882                        let tt = call.address.custom_unshielded_token_type(pre_token);
883                        update_balance(
884                            &mut res,
885                            TokenType::Unshielded(tt),
886                            segment,
887                            val,
888                            BalanceOperation::Addition,
889                        )?;
890                    }
891
892                    // NOTE: This is an input *to* the contract, so an
893                    // output of the transaction.
894                    for (tt, val) in transcript.effects.unshielded_inputs.clone() {
895                        update_balance(&mut res, tt, segment, val, BalanceOperation::Subtraction)?;
896                    }
897
898                    // NOTE: This is an output *from* the contract, so an
899                    // input to the transaction.
900                    for (tt, val) in transcript.effects.unshielded_outputs.clone() {
901                        update_balance(&mut res, tt, segment, val, BalanceOperation::Addition)?;
902                    }
903                }
904            }
905        }
906
907        for (segment, offer) in self
908            .fallible_coins
909            .sorted_iter()
910            .map(|seg_x_offer| (*seg_x_offer.0.deref(), seg_x_offer.1.deref().clone()))
911            .chain(self.guaranteed_coins.iter().map(|o| (0, o.deref().clone())))
912        {
913            for delta in offer.deltas.iter() {
914                let (val, op) = if delta.value < 0 {
915                    (
916                        i128::unsigned_abs(delta.value),
917                        BalanceOperation::Subtraction,
918                    )
919                } else {
920                    (delta.value as u128, BalanceOperation::Addition)
921                };
922                update_balance(
923                    &mut res,
924                    TokenType::Shielded(delta.token_type),
925                    segment,
926                    val,
927                    op,
928                )?;
929            }
930        }
931
932        Ok(res)
933    }
934}
935
936#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
937struct CallNode {
938    pub segment_id: u16,
939    pub addr: ContractAddress,
940    pub call_index: u32,
941}
942
943#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
944struct CallKey {
945    pub addr: ContractAddress,
946    pub ep_hash: HashOutput,
947    pub commitment: Fr,
948}
949
950fn causality_check<D: DB>(
951    guaranteed_calls: &BTreeSet<CallNode>,
952    fallible_calls: &BTreeSet<CallNode>,
953    adjacencies: std::collections::BTreeMap<CallNode, Vec<CallNode>>,
954) -> Result<(), MalformedTransaction<D>> {
955    let mut queue: VecDeque<CallNode> = fallible_calls.iter().cloned().collect();
956
957    // A transitive closure is implied here.
958    // By checking neighbors of every fallible call, we
959    // implicitly check transivity.
960    //
961    // This works because every neighbor is in the set `fallible_calls ∪ guaranteed_calls`.
962    while let Some(curr) = queue.pop_front() {
963        if let Some(neighbors) = adjacencies.get(&curr) {
964            for &succ in neighbors {
965                if guaranteed_calls.contains(&succ) {
966                    return Err(MalformedTransaction::SequencingCheckFailure(
967                        SequencingCheckError::CausalityConstraintViolation {
968                            call_predecessor: curr.call_index,
969                            call_successor: succ.call_index,
970                            call_predecessor_address: curr.addr,
971                            call_successor_address: succ.addr,
972                            segment_id_predecessor: curr.segment_id,
973                            segment_id_successor: succ.segment_id,
974                        },
975                    ));
976                }
977            }
978        }
979    }
980
981    Ok(())
982}
983
984fn call_sequencing_check<P: ProofKind<D>, D: DB>(
985    context_call_position: u32,
986    contextual_call: &ContractCall<P, D>,
987    call_lookup: &std::collections::BTreeMap<(ContractAddress, HashOutput, Fr), Vec<u32>>,
988) -> Result<Vec<(u32, u64, ContractAddress)>, MalformedTransaction<D>> {
989    // A vec of all calls to whom the current call in context (`call1`)
990    // makes calls to, which also reside in _this_ intent
991    let mut sequenced_sub_calls: Vec<(u32, u64, ContractAddress)> = Vec::new();
992
993    // For all `claimed_contract_calls`, look up that claimed call's position in
994    // _this_ intent. If its position is not greater than _this_ call's position (`call1`'s position, that is)
995    // we're in an invalid case. In other words, `call1` is calling `call2`, so `call2` must be sequentially/positionally
996    // greater than `call1`.
997    for transcript in contextual_call
998        .guaranteed_transcript
999        .as_ref()
1000        .into_iter()
1001        .chain(contextual_call.fallible_transcript.as_ref())
1002    {
1003        for claimed in transcript.effects.claimed_contract_calls.iter() {
1004            let (seq, addr, ep, cc) = claimed.deref().into_inner();
1005            if let Some(cids) = call_lookup.get(&(addr, ep, cc)) {
1006                for cid2 in cids {
1007                    if context_call_position >= *cid2 {
1008                        return Err(MalformedTransaction::SequencingCheckFailure(
1009                            SequencingCheckError::CallSequencingViolation {
1010                                call_predecessor: context_call_position,
1011                                call_successor: *cid2,
1012                                call_predecessor_address: contextual_call.address,
1013                                call_successor_address: addr,
1014                            },
1015                        ));
1016                    }
1017                    sequenced_sub_calls.push((*cid2, seq, addr));
1018                }
1019            }
1020        }
1021    }
1022
1023    Ok(sequenced_sub_calls)
1024}
1025
1026fn sequencing_correlation_check<D: DB>(
1027    contextual_call_address: ContractAddress,
1028    mut sequenced_sub_calls: Vec<(u32, u64, ContractAddress)>,
1029) -> Result<(), MalformedTransaction<D>> {
1030    sequenced_sub_calls.sort_by_key(|&(cid, s, _)| (s, cid));
1031
1032    // View our `sequenced_sub_calls` as windowed pairs.
1033    //
1034    // `sequence_id` must correlate with call position.
1035    // In other words, if the first call is sequentially less than the second call,
1036    // it must also be positionally less than the second call.
1037    for w in sequenced_sub_calls.windows(2) {
1038        let (cid_a, seq_a, addr_a) = w[0];
1039        let (cid_b, seq_b, _) = w[1];
1040
1041        if !(seq_a < seq_b && cid_a < cid_b) {
1042            return Err(MalformedTransaction::SequencingCheckFailure(
1043                SequencingCheckError::SequencingCorrelationViolation {
1044                    address_1: contextual_call_address,
1045                    address_2: addr_a,
1046                    call_position_1: cid_a,
1047                    call_position_2: cid_b,
1048                },
1049            ));
1050        }
1051    }
1052
1053    Ok(())
1054}
1055
1056fn sequencing_context_check<P: ProofKind<D>, D: DB>(
1057    adjacencies: &mut std::collections::BTreeMap<CallNode, Vec<CallNode>>,
1058    segment_id: u16,
1059    calls_in_intent: std::collections::BTreeMap<u32, &ContractCall<P, D>>,
1060    callers_for_addr: std::collections::BTreeMap<CallKey, Vec<(CallNode, bool)>>,
1061) -> Result<(), MalformedTransaction<D>> {
1062    // If a calls `b`, `b` must be contained within the 'lifetime' of the
1063    // call instruction in `a`.
1064    // Concretely, this means that:
1065    // - If the call to `b` in in `a`'s guaranteed section, it *must*
1066    //   contain only a guaranteed section.
1067    // - If the call to `b` in in `a`'s fallible section, it *must*
1068    //   contain only a fallible section.
1069    for (cid, call) in &calls_in_intent {
1070        let this_node: CallNode = CallNode {
1071            segment_id,
1072            addr: call.address,
1073            call_index: *cid,
1074        };
1075        let is_guaranteed: bool = call.guaranteed_transcript.is_some();
1076        let is_fallible: bool = call.fallible_transcript.is_some();
1077
1078        let lookup_key = CallKey {
1079            addr: call.address,
1080            ep_hash: call.entry_point.ep_hash(),
1081            commitment: call.communication_commitment,
1082        };
1083        if let Some(callers) = callers_for_addr.get(&lookup_key) {
1084            for &(caller_node, caller_guar) in callers {
1085                // If there is a caller to _this_ call, and the caller is guaranteed but _this_ call is
1086                // fallible, we're in violation of a constraint
1087                // Specified as:
1088                // - If the call to `b` is in `a`'s guaranteed section, it *must*
1089                //   contain only a guaranteed section.
1090                if caller_guar && is_fallible {
1091                    return Err(MalformedTransaction::SequencingCheckFailure(
1092                        SequencingCheckError::FallibleInGuaranteedContextViolation {
1093                            caller: caller_node.call_index,
1094                            callee: *cid,
1095                            caller_address: caller_node.addr,
1096                            callee_address: call.address,
1097                        },
1098                    ));
1099                }
1100                // If there is a caller to _this_ call, and the caller is fallible but _this_ call is
1101                // guaranteed, we're in violation of a constraint
1102                // Specified as:
1103                // - If the call to `b` in in `a`'s fallible section, it *must*
1104                //   contain only a fallible section.
1105                if !caller_guar && is_guaranteed {
1106                    return Err(MalformedTransaction::SequencingCheckFailure(
1107                        SequencingCheckError::GuaranteedInFallibleContextViolation {
1108                            caller: caller_node.call_index,
1109                            callee: *cid,
1110                            caller_address: caller_node.addr,
1111                            callee_address: call.address,
1112                        },
1113                    ));
1114                }
1115
1116                // We have an adjacency: caller -> callee
1117                adjacencies.entry(caller_node).or_default().push(this_node);
1118            }
1119        }
1120    }
1121
1122    Ok(())
1123}
1124
1125// TODO: Document this clearly
1126#[allow(clippy::type_complexity)]
1127fn relate_nodes<P: ProofKind<D>, D: DB>(
1128    guaranteed_calls: &mut BTreeSet<CallNode>,
1129    fallible_calls: &mut BTreeSet<CallNode>,
1130    calls_by_address: &mut std::collections::BTreeMap<ContractAddress, Vec<CallNode>>,
1131    adjacencies: &mut std::collections::BTreeMap<CallNode, Vec<CallNode>>,
1132    segment_id: u16,
1133    calls_in_intent: &std::collections::BTreeMap<u32, &ContractCall<P, D>>,
1134) -> Result<std::collections::BTreeMap<CallKey, Vec<(CallNode, bool)>>, MalformedTransaction<D>> {
1135    // A map from (address, entry_point_hash, commitment) to caller nodes (+ guaranteed flag)
1136    let mut callers_for_addr: std::collections::BTreeMap<CallKey, Vec<(CallNode, bool)>> =
1137        std::collections::BTreeMap::new();
1138
1139    for (cid, call) in calls_in_intent {
1140        let this_node: CallNode = CallNode {
1141            segment_id,
1142            addr: call.address,
1143            call_index: *cid,
1144        };
1145
1146        let is_guaranteed = call.guaranteed_transcript.is_some();
1147        let is_fallible = call.fallible_transcript.is_some();
1148
1149        if is_guaranteed {
1150            guaranteed_calls.insert(this_node);
1151        }
1152        if is_fallible {
1153            fallible_calls.insert(this_node);
1154        }
1155        // TODO: We should change `ContractCall` to make this invalid state unrepresentable rather than erroring, something like (but with a named type rather than `These`):
1156        // pub struct ContractCall<P: ProofKind<D>, D: DB> {
1157        //     pub address: ContractAddress,
1158        //     pub entry_point: EntryPointBuf,
1159        //     // nb: Vector is *not* sorted
1160        //     pub transcripts: These<Sp<Transcript<D>, D>, Sp<Transcript<D>, D>>,
1161        //     pub communication_commitment: Fr,
1162        //     pub proof: P::Proof,
1163        // }
1164        //
1165        // I've only not done it this way because I'm in a rush, and it'd require loooots of mechanical changes.
1166        if !(is_guaranteed || is_fallible) {
1167            return Err(MalformedTransaction::<D>::SequencingCheckFailure(
1168                SequencingCheckError::CallHasEmptyTranscripts {
1169                    segment_id,
1170                    addr: call.address,
1171                    call_index: *cid,
1172                },
1173            ));
1174        }
1175
1176        // If a contract is in two intents, the prior precedes the latter
1177        // TODO: Thomas said:
1178        // > This seems to have pretty bad worst-case time complexity. Probably O(n^2) in the number of intents, if each has a call to the same contract?
1179        // > Do we actually need to record an adjacency for each previous node, or just the one immediately preceding this one?
1180        // I've made the change, but let's verify that it's OK
1181        if let Some(&prev_node) = calls_by_address.get(&call.address).and_then(|v| v.last()) {
1182            adjacencies.entry(prev_node).or_default().push(this_node);
1183        }
1184
1185        // Add this node to the list of nodes that share the ContractAddress at this key
1186        calls_by_address
1187            .entry(call.address)
1188            .or_default()
1189            .push(this_node);
1190
1191        // Record any (a -> b) relationships in this intent, so that later we
1192        // can add “a causally precedes b” into adjacencies.
1193        for (transcript, is_guaranteed) in call
1194            .guaranteed_transcript
1195            .iter()
1196            .map(|gt| (gt, true))
1197            .chain(call.fallible_transcript.iter().map(|ft| (ft, false)))
1198        {
1199            for claimed in transcript.effects.claimed_contract_calls.iter() {
1200                let (_, addr, ep_hash, cc) = claimed.deref().into_inner();
1201                callers_for_addr
1202                    .entry(CallKey {
1203                        addr,
1204                        ep_hash,
1205                        commitment: cc,
1206                    })
1207                    .or_default()
1208                    .push((this_node, is_guaranteed));
1209            }
1210        }
1211    }
1212
1213    Ok(callers_for_addr)
1214}
1215
1216impl<S: SignatureKind<D>, P: ProofKind<D>, B: Storable<D>, D: DB> StandardTransaction<S, P, B, D> {
1217    /// Rejects entries no valid transaction repeats: each spends one coin, or is
1218    /// bound to one intent, segment or maintenance counter. Runs before fees, so
1219    /// its work is linear in the encoding however nodes are shared.
1220    #[allow(clippy::mutable_key_type)]
1221    pub(crate) fn disjoint_check(&self) -> Result<(), MalformedTransaction<D>> {
1222        let mut shielded_inputs = BTreeSet::new();
1223        let mut shielded_outputs = BTreeSet::new();
1224        let mut unshielded_inputs = BTreeSet::new();
1225        let mut registrations = std::collections::HashSet::new();
1226        let shielded_offers = self
1227            .guaranteed_coins
1228            .clone()
1229            .map(|x| x.deref().clone())
1230            .into_iter()
1231            .chain(self.fallible_coins.values());
1232
1233        for offer in shielded_offers {
1234            let mut inputs: BTreeSet<_> = offer
1235                .inputs
1236                .distinct_values()
1237                .into_iter()
1238                .map(|(input, _)| (*input).clone())
1239                .collect();
1240            let transients = offer.transient.distinct_values();
1241            inputs.extend(transients.iter().map(|(t, _)| t.as_input()));
1242
1243            let mut outputs: BTreeSet<_> = offer
1244                .outputs
1245                .distinct_values()
1246                .into_iter()
1247                .map(|(output, _)| (*output).clone())
1248                .collect();
1249            outputs.extend(transients.iter().map(|(t, _)| t.as_output()));
1250
1251            if !(shielded_inputs.is_disjoint(&inputs)) {
1252                return Err(MalformedTransaction::DisjointCheckFailure(
1253                    DisjointCheckError::ShieldedInputsDisjointFailure {
1254                        shielded_inputs: shielded_inputs
1255                            .into_iter()
1256                            .map(|x| x.erase_proof())
1257                            .collect(),
1258                        transient_inputs: inputs.into_iter().map(|x| x.erase_proof()).collect(),
1259                    },
1260                ));
1261            }
1262
1263            if !(shielded_outputs.is_disjoint(&outputs)) {
1264                return Err(MalformedTransaction::DisjointCheckFailure(
1265                    DisjointCheckError::ShieldedOutputsDisjointFailure {
1266                        shielded_outputs: shielded_outputs
1267                            .into_iter()
1268                            .map(|x| x.erase_proof())
1269                            .collect(),
1270                        transient_outputs: outputs.into_iter().map(|x| x.erase_proof()).collect(),
1271                    },
1272                ));
1273            }
1274
1275            shielded_inputs.extend(inputs);
1276            shielded_outputs.extend(outputs);
1277        }
1278
1279        // Visits a shared intent once per segment. This is linear only because a
1280        // `HashMap` pins each entry to its key's hash; a plain `Map` would not.
1281        for entry in self.intents.iter() {
1282            let intent = &*entry.1;
1283            let offers = [
1284                intent.guaranteed_unshielded_offer.as_ref(),
1285                intent.fallible_unshielded_offer.as_ref(),
1286            ];
1287            for offer in offers.into_iter().flatten() {
1288                let distinct = offer.inputs.distinct_values();
1289                let repeated: Vec<_> = distinct
1290                    .iter()
1291                    .filter(|(_, n)| *n > 1)
1292                    .map(|(input, _)| (**input).clone())
1293                    .collect();
1294                if !repeated.is_empty() {
1295                    return Err(MalformedTransaction::DuplicateInputs(repeated));
1296                }
1297                let inputs: BTreeSet<_> = distinct
1298                    .into_iter()
1299                    .map(|(input, _)| (*input).clone())
1300                    .collect();
1301                if !(unshielded_inputs.is_disjoint(&inputs)) {
1302                    return Err(MalformedTransaction::<D>::DisjointCheckFailure(
1303                        DisjointCheckError::UnshieldedInputsDisjointFailure {
1304                            unshielded_inputs,
1305                            offer_inputs: inputs,
1306                        },
1307                    ));
1308                }
1309                unshielded_inputs.extend(inputs);
1310            }
1311            for dust_actions in intent.dust_actions.iter() {
1312                for (reg, n) in dust_actions.registrations.distinct_values() {
1313                    // Keyed without the signature, so pricing an erased transaction
1314                    // agrees with checking the signed one.
1315                    let erased = Sp::<_, D>::new(reg.erase_signatures());
1316                    if n > 1 || !registrations.insert(erased.hash()) {
1317                        return Err(MalformedTransaction::RepeatedDustRegistration {
1318                            registration: Box::new((*erased).clone()),
1319                        });
1320                    }
1321                }
1322            }
1323        }
1324        self.committee_signatures_check()
1325    }
1326
1327    // Each signature is verified once per path to it, so sharing would let
1328    // verification work outgrow the bytes paying for it.
1329    fn committee_signatures_check(&self) -> Result<(), MalformedTransaction<D>> {
1330        let intents: Vec<_> = self.intents.iter().map(|entry| entry.1.clone()).collect();
1331        let actions = storage::storage::Array::distinct_values_across(
1332            intents.iter().map(|i| (&i.actions, 1)),
1333        );
1334        let signatures = storage::storage::Array::distinct_values_across(
1335            actions.iter().filter_map(|(action, n)| match &**action {
1336                ContractAction::Maintain(upd) => Some((&upd.signatures, *n)),
1337                _ => None,
1338            }),
1339        );
1340        let mut seen = BTreeSet::new();
1341        for (sig, n) in signatures {
1342            if n > 1 || !seen.insert(sig.1.clone()) {
1343                return Err(MalformedTransaction::RepeatedCommitteeSignature {
1344                    signature: sig.1.clone(),
1345                });
1346            }
1347        }
1348        Ok(())
1349    }
1350}
1351
1352impl<
1353    S: SignatureKind<D>,
1354    P: ProofKind<D>,
1355    B: Storable<D> + Serializable + PedersenDowngradeable<D> + BindingKind<S, P, D>,
1356    D: DB,
1357> StandardTransaction<S, P, B, D>
1358{
1359    pub fn sequencing_check(&self) -> Result<(), MalformedTransaction<D>> {
1360        let mut adjacencies: std::collections::BTreeMap<CallNode, Vec<CallNode>> =
1361            std::collections::BTreeMap::new();
1362
1363        // ALL guaranteed calls
1364        let mut guaranteed_calls: BTreeSet<CallNode> = BTreeSet::new();
1365
1366        // ALL fallible calls
1367        let mut fallible_calls: BTreeSet<CallNode> = BTreeSet::new();
1368
1369        let mut intents_sorted: Vec<(u16, Intent<_, _, _, _>)> = self
1370            .intents
1371            .iter()
1372            .map(|sid_x_intent| (*sid_x_intent.0, sid_x_intent.1.deref().clone()))
1373            .collect();
1374
1375        // Our checks demand sorted `segment_id`s
1376        intents_sorted.sort_by_key(|&(sid, _)| sid);
1377
1378        // This map essentially keeps track of which intents share top level calls to the same address
1379        // Note that the `ContractAddress` in the key == the `ContractAddress` in the value
1380        // To be super clear, this is more or less a map from ContractAddress to intents (via segment_id) which contain that ContractAddress
1381        let mut calls_by_address: std::collections::BTreeMap<ContractAddress, Vec<CallNode>> =
1382            std::collections::BTreeMap::new();
1383
1384        for (segment_id, intent) in intents_sorted {
1385            let calls_in_intent = as_indexed(intent.calls());
1386
1387            // A mapping from (address, entry_point, communication_commitment) to that call's position within this intent
1388            // This is so we can easily check that the calling order is valid (sequential) in the next step
1389            let mut call_lookup: std::collections::BTreeMap<
1390                (ContractAddress, HashOutput, Fr),
1391                Vec<u32>,
1392            > = std::collections::BTreeMap::new();
1393            for (cid, call) in &calls_in_intent {
1394                call_lookup
1395                    .entry((
1396                        call.address,
1397                        call.entry_point.ep_hash(),
1398                        call.communication_commitment,
1399                    ))
1400                    .or_default()
1401                    .push(*cid);
1402            }
1403
1404            // If a calls b and c, and the sequence ID of b precedes
1405            // that of c, then b must precede c in the intent.
1406            for (cid1, call1) in &calls_in_intent {
1407                let sequenced_sub_calls = call_sequencing_check(*cid1, *call1, &call_lookup)?;
1408                sequencing_correlation_check(call1.address, sequenced_sub_calls)?;
1409            }
1410
1411            let callers_for_addr = relate_nodes(
1412                &mut guaranteed_calls,
1413                &mut fallible_calls,
1414                &mut calls_by_address,
1415                &mut adjacencies,
1416                segment_id,
1417                &calls_in_intent,
1418            )?;
1419            sequencing_context_check(
1420                &mut adjacencies,
1421                segment_id,
1422                calls_in_intent,
1423                callers_for_addr,
1424            )?;
1425        }
1426
1427        // Enforce causality requirements
1428        causality_check(&guaranteed_calls, &fallible_calls, adjacencies)
1429    }
1430
1431    fn balancing_check(
1432        &self,
1433        strictness: WellFormedStrictness,
1434        fees: u128,
1435    ) -> Result<(), MalformedTransaction<D>> {
1436        for ((token_type, segment), bal) in self.balance(Some(fees))?.into_iter() {
1437            if bal < 0 && strictness.enforce_balancing {
1438                return Err(MalformedTransaction::<D>::BalanceCheckOverspend {
1439                    token_type,
1440                    segment,
1441                    overspent_value: bal,
1442                });
1443            }
1444        }
1445
1446        Ok(())
1447    }
1448
1449    fn pedersen_check(&self) -> Result<(), MalformedTransaction<D>> {
1450        let comm_parts: Vec<Pedersen> = self
1451            .intents()
1452            .map(|(_, intent)| intent.binding_commitment.downgrade())
1453            .chain(
1454                self.guaranteed_coins
1455                    .iter()
1456                    .map(|sp_offer| sp_offer.deref().clone())
1457                    .chain(self.fallible_coins.values())
1458                    .flat_map(|offer| {
1459                        offer
1460                            .inputs
1461                            .iter()
1462                            .map(|inp| inp.value_commitment)
1463                            .chain(offer.outputs.iter().map(|out| -out.value_commitment))
1464                            .chain(
1465                                offer
1466                                    .transient
1467                                    .iter()
1468                                    .map(|trans| trans.value_commitment_input),
1469                            )
1470                            .chain(
1471                                offer
1472                                    .transient
1473                                    .iter()
1474                                    .map(|trans| -trans.value_commitment_output),
1475                            )
1476                            .collect::<Vec<_>>()
1477                    }),
1478            )
1479            .collect();
1480        let comm = comm_parts
1481            .into_iter()
1482            .fold(EmbeddedGroupAffine::identity(), |a, b| a + b.0);
1483        let expected = self
1484            .balance_maybe_deltas_only(None, true)?
1485            .into_iter()
1486            .filter_map(|((tt, segment), value)| match tt {
1487                TokenType::Shielded(tt) => {
1488                    Some(hash_to_curve(&(tt, segment)).mul(EmbeddedFr::from(value)))
1489                }
1490                _ => None,
1491            })
1492            .fold(
1493                EmbeddedGroupAffine::generator() * self.binding_randomness,
1494                |a, b| a + b,
1495            );
1496
1497        if comm != expected {
1498            return Err(MalformedTransaction::PedersenCheckFailure {
1499                expected: Box::new(expected),
1500                calculated: Box::new(comm),
1501            });
1502        };
1503
1504        Ok(())
1505    }
1506
1507    #[allow(clippy::type_complexity)]
1508    fn effects_check(&self) -> Result<(), MalformedTransaction<D>> {
1509        // We have multisets for the following:
1510        // - Claimed nullifiers (per segment ID)
1511        // - Claimed contract calls (per segment ID)
1512        // - Claimed shielded spends (per segment ID)
1513        // - Claimed shielded receives (per segment ID)
1514        // - Claimed unshielded spends (per segment ID)
1515
1516        // transcripts associate with both the their intent segment, and their
1517        // logical segment (0 for guarnateed transcripts), as the matching uses
1518        // the former for calls, and the latter for zswap.
1519        let calls: Vec<(u16, ContractCall<P, D>)> = self
1520            .intents
1521            .iter()
1522            .flat_map(|seg_x_intent| {
1523                seg_x_intent
1524                    .1
1525                    .deref()
1526                    .clone()
1527                    .actions
1528                    .iter_deref()
1529                    .filter_map(move |action| match action {
1530                        ContractAction::Call(call) => {
1531                            Some((*seg_x_intent.0.deref(), (**call).clone()))
1532                        }
1533                        _ => None,
1534                    })
1535                    .collect::<Vec<_>>()
1536            })
1537            .collect();
1538        // Vector of tuple of:
1539        // - Physical segment ID (which intent the transcript is in)
1540        // - Logical segment ID (which segment the transcript is executing with)
1541        // - Transcript
1542        // - Contract address
1543        let transcripts: Vec<_> = calls
1544            .iter()
1545            .flat_map(|(segment, call)| {
1546                call.guaranteed_transcript
1547                    .iter()
1548                    .map(move |t| (segment, &0, t, call.address))
1549                    .chain(
1550                        call.fallible_transcript
1551                            .iter()
1552                            .map(move |t| (segment, segment, t, call.address)),
1553                    )
1554            })
1555            .collect();
1556        let offers: std::collections::BTreeMap<_, _> = self
1557            .guaranteed_coins
1558            .iter()
1559            .map(|sp| (0, sp.deref().clone()))
1560            .chain(
1561                self.fallible_coins
1562                    .iter()
1563                    .map(|seg_x_offer| (*seg_x_offer.0.deref(), seg_x_offer.1.deref().clone())),
1564            )
1565            .collect();
1566        let commitments: MultiSet<(u16, Commitment, ContractAddress)> =
1567            offers
1568                .iter()
1569                .flat_map(|(segment, offer)| {
1570                    offer
1571                        .outputs
1572                        .iter()
1573                        .filter_map(|o| o.contract_address.clone().map(|addr| (o.coin_com, addr)))
1574                        .chain(offer.transient.iter().filter_map(|t| {
1575                            t.contract_address.clone().map(|addr| (t.coin_com, addr))
1576                        }))
1577                        .map(|(com, addr)| (*segment, com, *addr.deref()))
1578                })
1579                .collect();
1580        let nullifiers: MultiSet<(u16, Nullifier, ContractAddress)> =
1581            offers
1582                .iter()
1583                .flat_map(|(segment, offer)| {
1584                    offer
1585                        .inputs
1586                        .iter()
1587                        .flat_map(|i| i.contract_address.clone().map(|addr| (i.nullifier, addr)))
1588                        .chain(offer.transient.iter().flat_map(|t| {
1589                            t.contract_address.clone().map(|addr| (t.nullifier, addr))
1590                        }))
1591                        .map(|(nullifier, addr)| (*segment, nullifier, *addr.deref()))
1592                })
1593                .collect();
1594        let claimed_nullifiers: MultiSet<(u16, Nullifier, ContractAddress)> = transcripts
1595            .iter()
1596            .flat_map(|(_, segment, t, addr)| {
1597                t.effects
1598                    .claimed_nullifiers
1599                    .iter()
1600                    .map(|n| (**segment, *(*n).deref(), *addr))
1601            })
1602            .collect();
1603        // All contract-associated nullifiers must be claimed by exactly one
1604        // instance of the same contract in the same segment.
1605        if nullifiers != claimed_nullifiers {
1606            return Err(MalformedTransaction::EffectsCheckFailure(
1607                EffectsCheckError::NullifiersNEClaimedNullifiers {
1608                    nullifiers: nullifiers.into_iter().map(|(v, _)| v).collect(),
1609                    claimed_nullifiers: claimed_nullifiers.into_iter().map(|(v, _)| v).collect(),
1610                },
1611            ));
1612        }
1613        let claimed_shielded_receives: MultiSet<(u16, Commitment, ContractAddress)> = transcripts
1614            .iter()
1615            .flat_map(|(_, segment, t, addr)| {
1616                (*t).deref()
1617                    .effects
1618                    .claimed_shielded_receives
1619                    .iter()
1620                    .map(|c| (**segment, *(*c).deref(), *addr))
1621            })
1622            .collect();
1623        // All contract-associated commitments must be claimed by exactly one
1624        // instance of the same contract in the same segment.
1625        if commitments != claimed_shielded_receives {
1626            return Err(MalformedTransaction::EffectsCheckFailure(
1627                EffectsCheckError::CommitmentsNEClaimedShieldedReceives {
1628                    commitments: commitments.into_iter().map(|(v, _)| v).collect(),
1629                    claimed_shielded_receives: claimed_shielded_receives
1630                        .into_iter()
1631                        .map(|(v, _)| v)
1632                        .collect(),
1633                },
1634            ));
1635        }
1636        let claimed_shielded_spends: MultiSet<(u16, Commitment)> = transcripts
1637            .iter()
1638            .flat_map(|(_, segment, t, _addr)| {
1639                (*t).deref()
1640                    .effects
1641                    .claimed_shielded_spends
1642                    .iter()
1643                    .map(|c| (**segment, *(*c).deref()))
1644            })
1645            .collect();
1646
1647        let duplicate_spends: Vec<((u16, Commitment), usize)> = claimed_shielded_spends
1648            .clone()
1649            .into_iter()
1650            .filter(|(_, count)| count > &1)
1651            .collect();
1652
1653        if !(duplicate_spends.is_empty()) {
1654            return Err(MalformedTransaction::EffectsCheckFailure(
1655                EffectsCheckError::ClaimedUnshieldedSpendsUniquenessFailure(duplicate_spends),
1656            ));
1657        }
1658
1659        let all_commitments: MultiSet<(u16, Commitment)> = offers
1660            .iter()
1661            .flat_map(|(segment, offer)| {
1662                offer
1663                    .outputs
1664                    .iter()
1665                    .map(|o| o.coin_com)
1666                    .chain(offer.transient.iter().map(|t| t.coin_com))
1667                    .map(|c| (*segment, c))
1668            })
1669            .collect();
1670        // Any claimed shielded outputs must exist, and may not be claimed by
1671        // another contract.
1672        // WG: @Thomas: Is it actually a multi-set subset check that we want here?
1673        // TK: This is probably fine. `claimed_shielded_spends` is known to be a plain set at this
1674        // point, `all_commitments` technically isn't, but that gets checked during application, so
1675        // it's not too big of a deal.
1676        if !(all_commitments.has_subset(&claimed_shielded_spends)) {
1677            return Err(MalformedTransaction::EffectsCheckFailure(
1678                EffectsCheckError::AllCommitmentsSubsetCheckFailure(SubsetCheckFailure {
1679                    subset: claimed_shielded_spends
1680                        .into_iter()
1681                        .map(|(v, _len)| v)
1682                        .collect(),
1683                    superset: all_commitments.into_iter().map(|(v, _len)| v).collect(),
1684                }),
1685            ));
1686        }
1687        let claimed_calls: MultiSet<(u16, (ContractAddress, HashOutput, Fr))> = transcripts
1688            .iter()
1689            .flat_map(|(segment, _, t, _)| {
1690                t.effects.claimed_contract_calls.iter().map(|call| {
1691                    let (_seq, addr, hash, fr) = &call.into_inner();
1692                    (**segment, (*addr, *hash, *fr))
1693                })
1694            })
1695            .collect();
1696
1697        let duplicate_claimed_calls: Vec<((u16, (ContractAddress, HashOutput, Fr)), usize)> =
1698            claimed_calls
1699                .clone()
1700                .into_iter()
1701                .filter(|(_, count)| count > &1)
1702                .collect();
1703
1704        if !(duplicate_claimed_calls.is_empty()) {
1705            return Err(MalformedTransaction::EffectsCheckFailure(
1706                EffectsCheckError::ClaimedCallsUniquenessFailure(duplicate_claimed_calls),
1707            ));
1708        }
1709
1710        let real_calls: MultiSet<(u16, (ContractAddress, HashOutput, Fr))> = calls
1711            .iter()
1712            .map(|(segment, call)| {
1713                (
1714                    *segment,
1715                    (
1716                        call.address,
1717                        call.entry_point.ep_hash(),
1718                        call.communication_commitment,
1719                    ),
1720                )
1721            })
1722            .collect();
1723        // Any claimed call must also exist within the same segment
1724        if !(real_calls.has_subset(&claimed_calls)) {
1725            return Err(MalformedTransaction::EffectsCheckFailure(
1726                EffectsCheckError::RealCallsSubsetCheckFailure(SubsetCheckFailure {
1727                    subset: claimed_calls.into_iter().map(|(v, _len)| v).collect(),
1728                    superset: real_calls.into_iter().map(|(v, _len)| v).collect(),
1729                }),
1730            ));
1731        }
1732        let claimed_unshielded_spends: MultiSet<((u16, bool), ((TokenType, PublicAddress), u128))> =
1733            transcripts
1734                .iter()
1735                .flat_map(|(intent_seg, logical_seg, t, _)| {
1736                    t.effects.claimed_unshielded_spends.iter().map(|sp| {
1737                        let (sp, i) = sp.deref();
1738                        (
1739                            (**intent_seg, **logical_seg == 0),
1740                            ((sp.deref().0, sp.deref().1), *(*i).deref()),
1741                        )
1742                    })
1743                })
1744                .collect();
1745        let real_unshielded_spends: MultiSet<((u16, bool), ((TokenType, PublicAddress), u128))> =
1746            transcripts
1747                .iter()
1748                .flat_map(|(intent_seg, logical_seg, t, addr)| {
1749                    t.effects.unshielded_inputs.iter().map(move |sp| {
1750                        (
1751                            (**intent_seg, **logical_seg == 0),
1752                            (
1753                                (*sp.deref().0.deref(), PublicAddress::Contract(*addr)),
1754                                *sp.deref().1.deref(),
1755                            ),
1756                        )
1757                    })
1758                })
1759                .chain(self.intents.iter().flat_map(|sp| {
1760                    let intent = &sp.clone().1;
1761                    let segment = *sp.0;
1762                    let guaranteed_outputs = intent.guaranteed_outputs();
1763                    let fallible_outputs = intent.fallible_outputs();
1764                    guaranteed_outputs
1765                        .iter()
1766                        .map(|o| (true, o))
1767                        .chain(fallible_outputs.iter().map(|o| (false, o)))
1768                        .map(move |(guaranteed, output)| {
1769                            (
1770                                (segment, guaranteed),
1771                                (
1772                                    (
1773                                        TokenType::Unshielded(output.type_),
1774                                        PublicAddress::User(output.owner),
1775                                    ),
1776                                    output.value,
1777                                ),
1778                            )
1779                        })
1780                        .collect::<Vec<_>>()
1781                }))
1782                .collect();
1783
1784        if !(real_unshielded_spends.has_subset(&claimed_unshielded_spends)) {
1785            return Err(MalformedTransaction::EffectsCheckFailure(
1786                EffectsCheckError::RealUnshieldedSpendsSubsetCheckFailure(SubsetCheckFailure {
1787                    subset: claimed_unshielded_spends
1788                        .into_iter()
1789                        .map(|(v, _)| v)
1790                        .collect(),
1791                    superset: real_unshielded_spends.into_iter().map(|(v, _)| v).collect(),
1792                }),
1793            ));
1794        }
1795        Ok(())
1796    }
1797
1798    fn ttl_check_weak(
1799        &self,
1800        tblock: Timestamp,
1801        global_ttl: Duration,
1802    ) -> Result<(), TransactionApplicationError> {
1803        for (_, intent) in self.intents() {
1804            if intent.ttl < tblock {
1805                Err(TransactionApplicationError::IntentTtlExpired(
1806                    intent.ttl, tblock,
1807                ))?;
1808            }
1809
1810            if intent.ttl > tblock + global_ttl {
1811                Err(TransactionApplicationError::IntentTtlTooFarInFuture(
1812                    intent.ttl,
1813                    tblock + global_ttl,
1814                ))?;
1815            }
1816        }
1817
1818        Ok(())
1819    }
1820}
1821
1822fn as_indexed<I, V>(v: I) -> std::collections::BTreeMap<u32, V>
1823where
1824    I: Iterator<Item = V>,
1825{
1826    v.enumerate()
1827        .map(|(i, v)| (i as u32, v))
1828        .collect::<std::collections::BTreeMap<u32, V>>()
1829}
1830
1831impl<D: DB> ContractDeploy<D> {
1832    pub(crate) fn well_formed(
1833        &self,
1834        ref_state: &impl StateReference<D>,
1835    ) -> Result<(), MalformedTransaction<D>> {
1836        let operations = self.initial_state.operations.size() as u64;
1837        if operations > MAX_CONTRACT_OPERATIONS {
1838            return Err(MalformedTransaction::MalformedContractDeploy(
1839                MalformedContractDeploy::TooManyOperations {
1840                    operations,
1841                    limit: MAX_CONTRACT_OPERATIONS,
1842                },
1843            ));
1844        }
1845        self.initial_state.well_formed(self.address())?;
1846
1847        // Or we could change the types. Current (pre-this-ticket) ContractState could be renamed to
1848        // `DeployContractState`, and the new version with `balance` could be called ContractState
1849        // `ContractDeploy` would contain `DeployContractState`. Then, this check isn't required.
1850        if self.initial_state.balance.iter().any(|bal| *bal.1 > 0) {
1851            let mut err_data = std::collections::BTreeMap::new();
1852            for val in self.initial_state.balance.clone().iter() {
1853                err_data.insert(*val.0, *val.1);
1854            }
1855            return Err(MalformedTransaction::<D>::MalformedContractDeploy(
1856                MalformedContractDeploy::NonZeroBalance(err_data),
1857            ));
1858        }
1859        let rechecked_state = ChargedState::new((*self.initial_state.data.get()).clone());
1860        if rechecked_state != self.initial_state.data {
1861            return Err(MalformedTransaction::<D>::MalformedContractDeploy(
1862                MalformedContractDeploy::IncorrectChargedState,
1863            ));
1864        }
1865        ref_state.param_check(false, |params| {
1866            let limit = params.limits.max_contract_metadata_size;
1867            if let Err(e) = check_entry_point_metadata_sizes(&self.initial_state, limit) {
1868                return Err(MalformedTransaction::MalformedContractDeploy(match e {
1869                    MetadataSizeError::EntryPoint(entry_point, size) => {
1870                        MalformedContractDeploy::MetadataTooLarge {
1871                            entry_point,
1872                            size,
1873                            limit,
1874                        }
1875                    }
1876                    MetadataSizeError::Authority(size) => {
1877                        MalformedContractDeploy::AuthorityMetadataTooLarge { size, limit }
1878                    }
1879                }));
1880            }
1881            Ok(())
1882        })?;
1883        Ok(())
1884    }
1885}
1886
1887impl<P: ProofKind<D>, D: DB> ContractAction<P, D> {
1888    fn well_formed(
1889        &self,
1890        ref_state: &impl StateReference<D>,
1891        strictness: WellFormedStrictness,
1892        parent: &ErasedIntent<D>,
1893    ) -> Result<(), MalformedTransaction<D>> {
1894        match self {
1895            ContractAction::Call(call) => call.well_formed(ref_state, strictness, parent),
1896            ContractAction::Deploy(deploy) => deploy.well_formed(ref_state),
1897            ContractAction::Maintain(upd) => upd.well_formed(ref_state, strictness),
1898        }
1899    }
1900}
1901
1902impl<D: DB> MaintenanceUpdate<D> {
1903    pub(crate) fn well_formed(
1904        &self,
1905        ref_state: &impl StateReference<D>,
1906        strictness: WellFormedStrictness,
1907    ) -> Result<(), MalformedTransaction<D>> {
1908        ref_state.maintenance_check(self.address, |authority| {
1909            let data = self.data_to_sign();
1910            // Ensure ordering, and that no party signed two votes
1911            if !Vec::from(&self.signatures)
1912                .windows(2)
1913                .all(|xs| xs[0].0 < xs[1].0)
1914            {
1915                return Err(MalformedTransaction::NotNormalized);
1916            }
1917            // Ensure that any new committee uses an incremented counter
1918            if self
1919                .updates
1920                .iter_deref()
1921                .filter_map(|up| match up {
1922                    SingleUpdate::ReplaceAuthority(new_auth) => Some(new_auth),
1923                    _ => None,
1924                })
1925                .any(|auth| auth.counter != self.counter.saturating_add(1))
1926            {
1927                return Err(MalformedTransaction::NotNormalized);
1928            }
1929            for (idx, sig) in self.signatures.iter().map(|x| x.into_inner()) {
1930                let vk = authority.committee.get(idx as usize).ok_or(
1931                    MalformedTransaction::KeyNotInCommittee {
1932                        address: self.address,
1933                        key_id: idx as usize,
1934                    },
1935                )?;
1936                if strictness.verify_signatures && !vk.verify(&data, &sig) {
1937                    return Err(MalformedTransaction::InvalidCommitteeSignature {
1938                        address: self.address,
1939                        key_id: idx as usize,
1940                    });
1941                }
1942            }
1943            if self.signatures.len() < authority.threshold as usize {
1944                return Err(MalformedTransaction::ThresholdMissed {
1945                    address: self.address,
1946                    signatures: self.signatures.len(),
1947                    threshold: authority.threshold as usize,
1948                });
1949            }
1950            Ok(())
1951        })
1952    }
1953}
1954
1955/// Re-exported from `onchain-runtime`, so that consumers outside the ledger can
1956/// apply the same bound before materializing a call's public inputs. Fee
1957/// calculation rejects transcripts far below this bound long before it is
1958/// reached (see [`ContractCall::public_inputs_len`]); in the ledger it exists to
1959/// bound the allocation on paths where fee enforcement is disabled.
1960pub use onchain_runtime::transcript::MAX_CALL_PUBLIC_INPUTS;
1961
1962impl<P: ProofKind<D>, D: DB> ContractCall<P, D> {
1963    pub(crate) fn well_formed(
1964        &self,
1965        ref_state: &impl StateReference<D>,
1966        strictness: WellFormedStrictness,
1967        parent: &ErasedIntent<D>,
1968    ) -> Result<(), MalformedTransaction<D>> {
1969        // Checked before anything materializes the public inputs below.
1970        self.public_inputs_len_check()?;
1971        if let Some(fallible) = &self.fallible_transcript
1972            && fallible.program.get(0) != Some(&Op::Ckpt)
1973            && self.guaranteed_transcript.is_some()
1974        {
1975            return Err(MalformedTransaction::FallibleWithoutCheckpoint);
1976        }
1977        for transcript in [
1978            self.guaranteed_transcript.as_ref(),
1979            self.fallible_transcript.as_ref(),
1980        ]
1981        .into_iter()
1982        .flatten()
1983        {
1984            // Dust is not transferable, so contracts may neither hold nor release it. Otherwise
1985            // the Dust balance credited by a registration's `allow_fee_payment` could be absorbed
1986            // by a contract instead of paying fees, while the registration still mints the full
1987            // entitlement to the registrant.
1988            if transcript
1989                .effects
1990                .unshielded_inputs
1991                .contains_key(&TokenType::Dust)
1992                || transcript
1993                    .effects
1994                    .unshielded_outputs
1995                    .contains_key(&TokenType::Dust)
1996            {
1997                return Err(MalformedTransaction::ContractDustTransfer {
1998                    address: self.address,
1999                });
2000            }
2001            let program = Vec::from(&transcript.program);
2002            // `noop 0` contributes nothing to the proof's public inputs, but still shifts the
2003            // targets of `branch` and `jmp`, which count operations.
2004            if program.iter().any(|op| matches!(op, Op::Noop { n: 0 })) {
2005                return Err(MalformedTransaction::NotNormalized);
2006            }
2007            for window in program.windows(2) {
2008                if let (Op::Noop { .. }, Op::Noop { .. }) = (&window[0], &window[1]) {
2009                    return Err(MalformedTransaction::NotNormalized);
2010                }
2011            }
2012        }
2013
2014        // Declared gas is the VM's execution ceiling, and is priced at face value. Bound it
2015        // by the block limits, so that no transcript can declare more work than could ever
2016        // fit into a block, and cannot push fee arithmetic into overflow.
2017        if strictness.enforce_limits {
2018            ref_state.param_check(true, |params| {
2019                let limits = &params.limits.block_limits;
2020                for transcript in [
2021                    self.guaranteed_transcript.as_ref(),
2022                    self.fallible_transcript.as_ref(),
2023                ]
2024                .into_iter()
2025                .flatten()
2026                {
2027                    if transcript.gas.compute_time > limits.compute_time
2028                        || transcript.gas.read_time > limits.read_time
2029                    {
2030                        return Err(MalformedTransaction::TranscriptGasExceedsBlockLimits {
2031                            address: self.address,
2032                            declared_compute_time: transcript.gas.compute_time,
2033                            declared_read_time: transcript.gas.read_time,
2034                            compute_time_limit: limits.compute_time,
2035                            read_time_limit: limits.read_time,
2036                        });
2037                    }
2038                }
2039                Ok(())
2040            })?;
2041        }
2042
2043        if strictness.verify_contract_proofs {
2044            ref_state.op_check(self.address, &self.entry_point, |op| {
2045                let gt = self
2046                    .guaranteed_transcript
2047                    .clone()
2048                    .map(|x| x.deref().clone());
2049
2050                if op.v2.is_some() {
2051                    if gt.is_some()
2052                        && !matches!(&gt, Some(Transcript { version: Some(version), ..}) if version.major == 2 && version.minor <= 3)
2053                    {
2054                        return Err(MalformedTransaction::GuaranteedTranscriptVersion {
2055                            op_version: "V2".to_string(),
2056                        });
2057                    }
2058
2059                    let ft = self.fallible_transcript.clone().map(|x| x.deref().clone());
2060
2061                    if ft.is_some()
2062                        && !matches!(&ft, Some(Transcript { version: Some(version), ..}) if version.major == 2 && version.minor <= 3)
2063                    {
2064                        return Err(MalformedTransaction::FallibleTranscriptVersion {
2065                            op_version: "V2".to_string(),
2066                        });
2067                    }
2068                }
2069                P::proof_verify(
2070                    op,
2071                    &self.proof,
2072                    self.public_inputs(parent.binding_commitment)?,
2073                    self,
2074                    strictness.proof_verification_mode
2075                )?;
2076                trace!("call valid");
2077                Ok(())
2078            })?;
2079        }
2080        Ok(())
2081    }
2082
2083    /// Builds the public input vector this call's proof will be validated against.
2084    ///
2085    /// NOTE: The proof should receive the following inputs for binding purposes:
2086    ///  - The contract address
2087    ///  - The contract entry point
2088    ///  - Both transcript parts's declared gas costs, and effects
2089    ///  - The count of instructions in the guaranteed transcript
2090    ///  - The parent ContractCalls's `binding_commitment.commitment`.
2091    ///
2092    /// These need to be *truely* binding (see note at the bottom of this file!)
2093    ///
2094    /// In addition, it should receive
2095    ///  - The communication commitment
2096    ///  - The transcript
2097    ///
2098    /// Fails without allocating if the call declares more than
2099    /// [`MAX_CALL_PUBLIC_INPUTS`] public inputs: `Op::Noop { n }` lets a 9-byte
2100    /// op name an arbitrarily large statement, so this must not trust callers
2101    /// to have checked well-formedness first.
2102    pub fn public_inputs(&self, binding_com: Pedersen) -> Result<Vec<Fr>, MalformedTransaction<D>> {
2103        self.public_inputs_len_check()?;
2104        let mut res = vec![self.binding_input(binding_com)];
2105        res.push(self.communication_commitment);
2106        if let Some(guaranteed) = self.guaranteed_transcript.as_ref() {
2107            for op in guaranteed.program.iter() {
2108                op.field_repr(&mut res);
2109            }
2110        }
2111        if let Some(fallible) = self.fallible_transcript.as_ref() {
2112            for op in fallible.program.iter() {
2113                op.field_repr(&mut res);
2114            }
2115        }
2116        Ok(res)
2117    }
2118
2119    /// The number of field elements [`Self::public_inputs`] would produce,
2120    /// computed without materializing them. Each transcript counts at least
2121    /// its program length, so programs padded with `noop 0` are bounded too.
2122    pub fn public_inputs_len(&self) -> usize {
2123        self.public_inputs_len_memoized(&mut DagMemo::new())
2124    }
2125
2126    /// As [`Self::public_inputs_len`], visiting each distinct op and pushed
2127    /// node once across every call sharing `memo`.
2128    pub fn public_inputs_len_memoized(&self, memo: &mut DagMemo<usize, D>) -> usize {
2129        self.guaranteed_transcript
2130            .iter()
2131            .chain(self.fallible_transcript.iter())
2132            // Only the ill-formed `noop 0` adds no input, so no valid count changes.
2133            .map(|t| t.public_inputs_len_memoized(memo).max(t.program.len()))
2134            // The binding input and the communication commitment.
2135            .fold(2, usize::saturating_add)
2136    }
2137
2138    fn public_inputs_len_check(&self) -> Result<(), MalformedTransaction<D>> {
2139        let public_inputs = self.public_inputs_len();
2140        if public_inputs > MAX_CALL_PUBLIC_INPUTS {
2141            return Err(MalformedTransaction::TooManyPublicInputs {
2142                address: self.address,
2143                operation: self.entry_point.clone(),
2144                public_inputs,
2145                limit: MAX_CALL_PUBLIC_INPUTS,
2146            });
2147        }
2148        Ok(())
2149    }
2150
2151    pub(crate) fn binding_input(&self, binding_com: Pedersen) -> Fr {
2152        let mut binding_input = Vec::new();
2153
2154        binding_input.extend(b"midnight:binding-input[v1]");
2155        let _ = Serializable::serialize(&self.address, &mut binding_input);
2156        let _ = Serializable::serialize(&self.entry_point, &mut binding_input);
2157        let _ = Serializable::serialize(
2158            &self
2159                .guaranteed_transcript
2160                .as_ref()
2161                .map(|t| t.gas)
2162                .unwrap_or_default(),
2163            &mut binding_input,
2164        );
2165
2166        if let Some(t) = self.guaranteed_transcript.as_ref() {
2167            let _ = Serializable::serialize(&t.effects, &mut binding_input);
2168        } else {
2169            // Backwards-compatible with `Effects::default` serialization, as this may be unstable.
2170            binding_input.extend(vec![0u8; 20]);
2171        }
2172        if let Some(t) = self.fallible_transcript.as_ref() {
2173            let _ = Serializable::serialize(&Some(t.gas), &mut binding_input);
2174            // Discriminant for `Some`.
2175            binding_input.push(1);
2176
2177            let _ = Serializable::serialize(&t.effects, &mut binding_input);
2178        } else {
2179            // (None, None)
2180            binding_input.extend(&[0, 0]);
2181        }
2182        let len = self
2183            .guaranteed_transcript
2184            .as_ref()
2185            .map(|t| t.program.len() as u64)
2186            .unwrap_or_default();
2187        let _ = Serializable::serialize(&len, &mut binding_input);
2188        let _ = Serializable::serialize(&Into::<Pedersen>::into(binding_com), &mut binding_input);
2189        let mut hasher = Sha256::new();
2190        hasher.update(&binding_input[..]);
2191        Fr::from_le_bytes(&hasher.finalize()[..31])
2192            .expect("Trimmed persistent hash should fall in Fr")
2193    }
2194}
2195
2196trait ContractMaintenanceVerifyingKeyExt {
2197    fn verify(&self, data: &[u8], sig: &Signature) -> bool;
2198}
2199
2200impl ContractMaintenanceVerifyingKeyExt for ContractMaintenanceVerifyingKey {
2201    fn verify(&self, msg: &[u8], sig: &Signature) -> bool {
2202        match (self, sig) {
2203            (ContractMaintenanceVerifyingKey::Schnorr(vk), Signature::Schnorr(sig)) => {
2204                vk.verify(msg, sig)
2205            }
2206            (ContractMaintenanceVerifyingKey::Schnorr(_), _) => false,
2207            (ContractMaintenanceVerifyingKey::ECDSA(vk), Signature::ECDSA(sig)) => {
2208                vk.verify(msg, sig)
2209            }
2210            (ContractMaintenanceVerifyingKey::ECDSA(_), _) => false,
2211        }
2212    }
2213}
2214
2215#[cfg(test)]
2216mod sparse_unshielded_signature_tests {
2217    use super::*;
2218    use crate::structure::{SigningKey, UtxoSpend};
2219    use coin_structure::coin::NIGHT;
2220    use rand::Rng;
2221    use rand::rngs::OsRng;
2222    use storage::Storable;
2223    use storage::arena::Sp;
2224    use storage::db::InMemoryDB;
2225    use storage::merkle_patricia_trie::{MerklePatriciaTrie, Node};
2226    use storage::storable::SizeAnn;
2227
2228    fn sparse_len_two_array<T: Storable<InMemoryDB> + 'static>(
2229        visible_at_zero: T,
2230        hidden_duplicate: T,
2231    ) -> storage::storage::Array<T, InMemoryDB> {
2232        let hidden_duplicate: Node<T, InMemoryDB> = Node::Leaf {
2233            ann: SizeAnn(1),
2234            value: Sp::new(hidden_duplicate),
2235        };
2236        let malformed_root = Node::MidBranchLeaf {
2237            ann: SizeAnn(2),
2238            value: Sp::new(visible_at_zero),
2239            child: Sp::new(hidden_duplicate),
2240        };
2241        storage::storage::Array(Sp::new(MerklePatriciaTrie(Sp::new(malformed_root))))
2242    }
2243
2244    /// Defence-in-depth: `well_formed` rejects a sparse signature array even
2245    /// when it is constructed directly in-process (bypassing the
2246    /// deserialization invariant). Because every input index must resolve to a
2247    /// signature via `get`, the victim input at index 1 — which has none — is
2248    /// no longer silently skipped by `zip`.
2249    #[test]
2250    fn sparse_signature_offer_rejected_by_well_formed() {
2251        let mut rng = OsRng;
2252        let signer = SigningKey::Schnorr(base_crypto::schnorr::SigningKey::sample(rng));
2253        let victim = SigningKey::Schnorr(base_crypto::schnorr::SigningKey::sample(rng));
2254
2255        let parent: ErasedIntent<InMemoryDB> = Intent {
2256            guaranteed_unshielded_offer: None,
2257            fallible_unshielded_offer: None,
2258            actions: storage::storage::Array::new(),
2259            dust_actions: None,
2260            ttl: Timestamp::from_secs(0),
2261            binding_commitment: Default::default(),
2262        };
2263        let msg = parent.data_to_sign(1);
2264
2265        let input_0 = UtxoSpend {
2266            value: 1,
2267            owner: signer.verifying_key(),
2268            type_: NIGHT,
2269            intent_hash: rng.r#gen(),
2270            output_no: 0,
2271        };
2272        let input_1 = UtxoSpend {
2273            value: 2,
2274            owner: victim.verifying_key(),
2275            type_: NIGHT,
2276            intent_hash: rng.r#gen(),
2277            output_no: 0,
2278        };
2279        let sig_0 = signer.sign(&mut rng, &msg);
2280
2281        let offer: UnshieldedOffer<Signature, InMemoryDB> = UnshieldedOffer {
2282            inputs: vec![input_0, input_1].into(),
2283            outputs: vec![].into(),
2284            signatures: sparse_len_two_array(sig_0, Signature::default()),
2285        };
2286
2287        // The signature array really is malformed: it reports length 2 but
2288        // only exposes one signature on iteration.
2289        assert_eq!(offer.signatures.len(), 2);
2290        assert_eq!(offer.signatures.iter_deref().count(), 1);
2291
2292        // Structural checks pass, but the signature closure must now reject it.
2293        let check = offer.well_formed(1, &parent).unwrap();
2294        let err = check().expect_err("sparse signature array must be rejected");
2295        assert!(matches!(
2296            err,
2297            MalformedTransaction::IntentSignatureVerificationFailure
2298        ));
2299    }
2300
2301    /// Root-cause fix: the malformed offer is rejected at (untrusted) wire
2302    /// deserialization. `IrLoader` (`CHECK_INVARIANTS = true`) now routes each
2303    /// node through `Node::check_invariant`, which rejects the sparse
2304    /// `MidBranchLeaf` shape (its child is a `Leaf`, not a `Branch`/`Extension`)
2305    /// before the offer can ever reach `well_formed`.
2306    #[test]
2307    fn malformed_sparse_signature_array_rejected_on_deserialize() {
2308        let mut rng = OsRng;
2309        let signer = SigningKey::Schnorr(base_crypto::schnorr::SigningKey::sample(rng));
2310        let victim = SigningKey::Schnorr(base_crypto::schnorr::SigningKey::sample(rng));
2311
2312        let parent: ErasedIntent<InMemoryDB> = Intent {
2313            guaranteed_unshielded_offer: None,
2314            fallible_unshielded_offer: None,
2315            actions: storage::storage::Array::new(),
2316            dust_actions: None,
2317            ttl: Timestamp::from_secs(0),
2318            binding_commitment: Default::default(),
2319        };
2320        let msg = parent.data_to_sign(1);
2321
2322        let input_0 = UtxoSpend {
2323            value: 1,
2324            owner: signer.verifying_key(),
2325            type_: NIGHT,
2326            intent_hash: rng.r#gen(),
2327            output_no: 0,
2328        };
2329        let input_1 = UtxoSpend {
2330            value: 2,
2331            owner: victim.verifying_key(),
2332            type_: NIGHT,
2333            intent_hash: rng.r#gen(),
2334            output_no: 0,
2335        };
2336        let sig_0 = signer.sign(&mut rng, &msg);
2337
2338        let offer: UnshieldedOffer<Signature, InMemoryDB> = UnshieldedOffer {
2339            inputs: vec![input_0, input_1].into(),
2340            outputs: vec![].into(),
2341            signatures: sparse_len_two_array(sig_0, Signature::default()),
2342        };
2343
2344        // Serialize the offer to the tagged wire format a peer would send.
2345        let mut bytes = Vec::new();
2346        serialize::tagged_serialize(&offer, &mut bytes).expect("offer should serialize");
2347
2348        // Deserialize as an untrusted peer's bytes. The tightened node
2349        // invariant must reject the malformed sparse array.
2350        let result: std::io::Result<UnshieldedOffer<Signature, InMemoryDB>> =
2351            serialize::tagged_deserialize(&bytes[..]);
2352        let err = result.expect_err("malformed offer must be rejected on deserialization");
2353        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
2354    }
2355
2356    /// Regression guard: a legitimately-constructed dense signatures array
2357    /// still round-trips through the same untrusted wire path and validates,
2358    /// confirming the tightened invariant does not reject well-formed data and
2359    /// that the `well_formed` change still accepts fully-signed offers.
2360    #[test]
2361    fn dense_signature_array_round_trips_and_validates() {
2362        let mut rng = OsRng;
2363        let signer_0 = SigningKey::Schnorr(base_crypto::schnorr::SigningKey::sample(rng));
2364        let signer_1 = SigningKey::Schnorr(base_crypto::schnorr::SigningKey::sample(rng));
2365
2366        let parent: ErasedIntent<InMemoryDB> = Intent {
2367            guaranteed_unshielded_offer: None,
2368            fallible_unshielded_offer: None,
2369            actions: storage::storage::Array::new(),
2370            dust_actions: None,
2371            ttl: Timestamp::from_secs(0),
2372            binding_commitment: Default::default(),
2373        };
2374        let msg = parent.data_to_sign(1);
2375
2376        // `input_0` sorts before `input_1` (lower value), satisfying the
2377        // sorted-inputs requirement.
2378        let input_0 = UtxoSpend {
2379            value: 1,
2380            owner: signer_0.verifying_key(),
2381            type_: NIGHT,
2382            intent_hash: rng.r#gen(),
2383            output_no: 0,
2384        };
2385        let input_1 = UtxoSpend {
2386            value: 2,
2387            owner: signer_1.verifying_key(),
2388            type_: NIGHT,
2389            intent_hash: rng.r#gen(),
2390            output_no: 0,
2391        };
2392        let sig_0 = signer_0.sign(&mut rng, &msg);
2393        let sig_1 = signer_1.sign(&mut rng, &msg);
2394
2395        let offer: UnshieldedOffer<Signature, InMemoryDB> = UnshieldedOffer {
2396            inputs: vec![input_0, input_1].into(),
2397            outputs: vec![].into(),
2398            // Canonical, dense construction from a slice.
2399            signatures: vec![sig_0, sig_1].into(),
2400        };
2401
2402        let mut bytes = Vec::new();
2403        serialize::tagged_serialize(&offer, &mut bytes).expect("offer should serialize");
2404        let offer: UnshieldedOffer<Signature, InMemoryDB> =
2405            serialize::tagged_deserialize(&bytes[..])
2406                .expect("well-formed dense offer must deserialize");
2407
2408        assert_eq!(offer.inputs.len(), 2);
2409        assert_eq!(offer.inputs.iter_deref().count(), 2);
2410        assert_eq!(offer.signatures.len(), 2);
2411        assert_eq!(offer.signatures.iter_deref().count(), 2);
2412
2413        let check = offer.well_formed(1, &parent).unwrap();
2414        assert!(check().is_ok());
2415    }
2416}
2417
2418#[cfg(test)]
2419mod well_formed_tests {
2420    use super::*;
2421    use coin_structure::contract::ContractAddress;
2422    use onchain_runtime::context::Effects;
2423    use onchain_runtime::result_mode::ResultModeVerify;
2424    use onchain_runtime::state::EntryPointBuf;
2425    use onchain_runtime::transcript::Transcript;
2426    use storage::{arena::Sp, db::InMemoryDB};
2427    use transient_crypto::curve::Fr;
2428
2429    #[test]
2430    fn contract_call_rejects_zero_length_noop() {
2431        let parent: ErasedIntent<InMemoryDB> = Intent {
2432            guaranteed_unshielded_offer: None,
2433            fallible_unshielded_offer: None,
2434            actions: storage::storage::Array::new(),
2435            dust_actions: None,
2436            ttl: Timestamp::from_secs(0),
2437            binding_commitment: Default::default(),
2438        };
2439        let state = LedgerState::<InMemoryDB>::new("local-test");
2440        let strictness = WellFormedStrictness {
2441            verify_contract_proofs: false,
2442            .. WellFormedStrictness::default()
2443        };
2444        let call_with = |program: Vec<Op<ResultModeVerify, InMemoryDB>>| ContractCall::<
2445            (),
2446            InMemoryDB,
2447        > {
2448            address: ContractAddress::default(),
2449            entry_point: EntryPointBuf(b"count".to_vec()),
2450            guaranteed_transcript: None,
2451            fallible_transcript: Some(Sp::new(Transcript {
2452                gas: Default::default(),
2453                effects: Default::default(),
2454                program: program.into(),
2455                version: None,
2456            })),
2457            communication_commitment: Fr::from(0u64),
2458            proof: (),
2459        };
2460
2461        assert!(
2462            call_with(vec![Op::Noop { n: 1 }])
2463                .well_formed(&state, strictness, &parent)
2464                .is_ok()
2465        );
2466        assert!(matches!(
2467            call_with(vec![Op::Noop { n: 0 }]).well_formed(&state, strictness, &parent),
2468            Err(MalformedTransaction::NotNormalized)
2469        ));
2470    }
2471
2472    #[test]
2473    fn contract_call_with_shared_push_is_rejected_quickly() {
2474        use onchain_runtime::state::{AlignedValueChecked, StateValue};
2475        use std::time::Duration;
2476        use storage::test::assert_completes_within;
2477
2478        // Each level is a 16-wide array whose entries all share one child, so
2479        // the value stays a few hundred bytes while its tree has 16^12 leaves.
2480        let value = (0..12).fold(
2481            StateValue::<InMemoryDB, AlignedValueChecked>::Null,
2482            |v, _| StateValue::Array(vec![v; 16].into()),
2483        );
2484        let res = assert_completes_within(Duration::from_secs(10), move || {
2485            let parent: ErasedIntent<InMemoryDB> = Intent {
2486                guaranteed_unshielded_offer: None,
2487                fallible_unshielded_offer: None,
2488                actions: storage::storage::Array::new(),
2489                dust_actions: None,
2490                ttl: Timestamp::from_secs(0),
2491                binding_commitment: Default::default(),
2492            };
2493            let state = LedgerState::<InMemoryDB>::new("local-test");
2494            let strictness = WellFormedStrictness {
2495                verify_contract_proofs: false,
2496                ..WellFormedStrictness::default()
2497            };
2498            let call = ContractCall::<(), InMemoryDB> {
2499                address: ContractAddress::default(),
2500                entry_point: EntryPointBuf(b"count".to_vec()),
2501                guaranteed_transcript: None,
2502                fallible_transcript: Some(Sp::new(Transcript {
2503                    gas: Default::default(),
2504                    effects: Default::default(),
2505                    program: vec![Op::Push {
2506                        storage: false,
2507                        value,
2508                    }]
2509                    .into(),
2510                    version: None,
2511                })),
2512                communication_commitment: Fr::from(0u64),
2513                proof: (),
2514            };
2515            call.well_formed(&state, strictness, &parent)
2516        });
2517        assert!(
2518            matches!(res, Err(MalformedTransaction::TooManyPublicInputs { .. })),
2519            "{res:?}"
2520        );
2521    }
2522
2523    #[test]
2524    fn contract_call_rejects_dust_transfer() {
2525        let parent: ErasedIntent<InMemoryDB> = Intent {
2526            guaranteed_unshielded_offer: None,
2527            fallible_unshielded_offer: None,
2528            actions: storage::storage::Array::new(),
2529            dust_actions: None,
2530            ttl: Timestamp::from_secs(0),
2531            binding_commitment: Default::default(),
2532        };
2533        let state = LedgerState::<InMemoryDB>::new("local-test");
2534        let strictness = WellFormedStrictness {
2535            verify_contract_proofs: false,
2536            ..WellFormedStrictness::default()
2537        };
2538        let call_with = |effects: Effects<InMemoryDB>, guaranteed: bool| {
2539            let transcript = Some(Sp::new(Transcript {
2540                gas: Default::default(),
2541                effects,
2542                program: vec![Op::Noop { n: 1 }].into(),
2543                version: None,
2544            }));
2545            let (guaranteed_transcript, fallible_transcript) = if guaranteed {
2546                (transcript, None)
2547            } else {
2548                (None, transcript)
2549            };
2550            ContractCall::<(), InMemoryDB> {
2551                address: ContractAddress::default(),
2552                entry_point: EntryPointBuf(b"count".to_vec()),
2553                guaranteed_transcript,
2554                fallible_transcript,
2555                communication_commitment: Fr::from(0u64),
2556                proof: (),
2557            }
2558        };
2559        let night = TokenType::Unshielded(coin_structure::coin::NIGHT);
2560        let inputs = |tt| Effects {
2561            unshielded_inputs: storage::storage::HashMap::new().insert(tt, 5),
2562            ..Default::default()
2563        };
2564        let outputs = |tt| Effects {
2565            unshielded_outputs: storage::storage::HashMap::new().insert(tt, 5),
2566            ..Default::default()
2567        };
2568
2569        for guaranteed in [true, false] {
2570            // Non-Dust token transfers remain allowed.
2571            assert!(
2572                call_with(inputs(night), guaranteed)
2573                    .well_formed(&state, strictness, &parent)
2574                    .is_ok()
2575            );
2576            assert!(
2577                call_with(outputs(night), guaranteed)
2578                    .well_formed(&state, strictness, &parent)
2579                    .is_ok()
2580            );
2581            // Contracts may neither receive nor send Dust.
2582            for effects in [inputs(TokenType::Dust), outputs(TokenType::Dust)] {
2583                assert!(matches!(
2584                    call_with(effects, guaranteed).well_formed(&state, strictness, &parent),
2585                    Err(MalformedTransaction::ContractDustTransfer { .. })
2586                ));
2587            }
2588        }
2589    }
2590}
2591
2592#[cfg(test)]
2593mod disjoint_tests {
2594    //! `disjoint_check` rejects exactly what the per-entry checks it replaces
2595    //! rejected, plus registrations and committee signatures reached twice,
2596    //! however entries are shared.
2597
2598    use super::*;
2599    use crate::structure::tests::transactions::{Entries, Recipe, build, recipe, transaction};
2600    use base_crypto::hash::HashOutput;
2601    use proptest::prelude::*;
2602    use std::sync::Arc;
2603    use storage::db::InMemoryDB;
2604    use storage::storage::{Array, HashMap};
2605    use zswap::{Input, Offer, Output, Transient};
2606
2607    type D = InMemoryDB;
2608    type Stx = StandardTransaction<(), (), Pedersen, D>;
2609
2610    /// Per offer, its inputs, outputs and transients, and how it shares the
2611    /// previous offer's inputs: 0 not at all, 1 the same array, 2 that array plus
2612    /// one more entry.
2613    type ShieldedRecipe = Vec<(Entries, Entries, Entries, u8)>;
2614
2615    fn shielded() -> impl Strategy<Value = ShieldedRecipe> {
2616        let entries = || prop::collection::vec((0u8..6, 0u8..4), 0..4);
2617        prop::collection::vec((entries(), entries(), entries(), 0u8..3), 0..4)
2618    }
2619
2620    fn input(kind: u8) -> Input<(), D> {
2621        Input {
2622            nullifier: Nullifier(HashOutput([kind; 32])),
2623            value_commitment: Default::default(),
2624            contract_address: None,
2625            merkle_tree_root: Default::default(),
2626            proof: Arc::new(()),
2627        }
2628    }
2629
2630    fn offers(r: &[(Entries, Entries, Entries, u8)]) -> Vec<Offer<(), D>> {
2631        let mut out: Vec<Offer<(), D>> = Vec::new();
2632        for (inputs, outputs, transients, sharing) in r {
2633            let mut inputs: Array<_, D> = build(inputs, input).into();
2634            if let (Some(prev), 1 | 2) = (out.last(), sharing) {
2635                inputs = prev.inputs.clone();
2636                if *sharing == 2 {
2637                    inputs = inputs.push(input(7));
2638                }
2639            }
2640            let outputs = build(outputs, |kind| Output {
2641                coin_com: Commitment(HashOutput([kind; 32])),
2642                value_commitment: Default::default(),
2643                contract_address: None,
2644                ciphertext: None,
2645                proof: Arc::new(()),
2646            });
2647            // Transients of kinds 2j and 2j + 1 share their input but not their
2648            // output, so input collisions are not always output collisions.
2649            let transient = build(transients, |kind| Transient {
2650                nullifier: Nullifier(HashOutput([kind / 2; 32])),
2651                coin_com: Commitment(HashOutput([kind / 2; 32])),
2652                value_commitment_input: Default::default(),
2653                value_commitment_output: match kind % 2 {
2654                    0 => Default::default(),
2655                    _ => Pedersen(EmbeddedGroupAffine::generator()),
2656                },
2657                contract_address: None,
2658                ciphertext: None,
2659                proof_input: Arc::new(()),
2660                proof_output: Arc::new(()),
2661            });
2662            out.push(Offer {
2663                inputs,
2664                outputs: outputs.into(),
2665                transient: transient.into(),
2666                deltas: Array::new(),
2667            });
2668        }
2669        out
2670    }
2671
2672    #[derive(Debug, Clone, Copy)]
2673    enum Intents {
2674        None,
2675        Distinct,
2676        FirstRepeated,
2677    }
2678
2679    /// With `actions_only`, intents keep only their actions, whose committee
2680    /// signatures are otherwise mostly masked by repeated inputs or
2681    /// registrations.
2682    fn standard(
2683        r: &Recipe,
2684        shielded: &ShieldedRecipe,
2685        intents: Intents,
2686        actions_only: bool,
2687    ) -> Stx {
2688        let Transaction::Standard(mut stx) = transaction(r) else {
2689            unreachable!()
2690        };
2691        if let Intents::None = intents {
2692            stx.intents = HashMap::new();
2693        }
2694        if actions_only {
2695            for (segment, mut intent) in stx.intents().collect::<Vec<_>>() {
2696                intent.guaranteed_unshielded_offer = None;
2697                intent.fallible_unshielded_offer = None;
2698                intent.dust_actions = None;
2699                stx.intents = stx.intents.insert(segment, intent);
2700            }
2701        }
2702        let shielded = if actions_only { &[][..] } else { &shielded[..] };
2703        let mut offers = offers(shielded).into_iter();
2704        stx.guaranteed_coins = offers.next().map(Sp::new);
2705        for (segment, offer) in (1u16..).zip(offers) {
2706            stx.fallible_coins = stx.fallible_coins.insert(segment, offer);
2707        }
2708        if let Intents::FirstRepeated = intents {
2709            let first = stx.intents.get(&1).map(|i| (*i).clone()).unwrap();
2710            stx.intents = stx.intents.insert(100, first);
2711        }
2712        stx
2713    }
2714
2715    /// The checks `disjoint_check` replaces, over every entry as reached, plus
2716    /// registration uniqueness by node and committee signature uniqueness.
2717    fn accepts_per_entry(stx: &Stx) -> bool {
2718        let mut shielded_inputs = BTreeSet::new();
2719        let mut shielded_outputs = BTreeSet::new();
2720        let offers = stx
2721            .guaranteed_coins
2722            .iter()
2723            .map(|o| (**o).clone())
2724            .chain(stx.fallible_coins.values());
2725        for offer in offers {
2726            let mut inputs: BTreeSet<_> = offer.inputs.iter_deref().cloned().collect();
2727            inputs.extend(offer.transient.iter_deref().map(Transient::as_input));
2728            let mut outputs: BTreeSet<_> = offer.outputs.iter_deref().cloned().collect();
2729            outputs.extend(offer.transient.iter_deref().map(Transient::as_output));
2730            if !shielded_inputs.is_disjoint(&inputs) || !shielded_outputs.is_disjoint(&outputs) {
2731                return false;
2732            }
2733            shielded_inputs.extend(inputs);
2734            shielded_outputs.extend(outputs);
2735        }
2736        let mut unshielded_inputs = BTreeSet::new();
2737        let mut registrations = Vec::new();
2738        let mut committee_signatures = Vec::new();
2739        for (_, intent) in stx.intents() {
2740            for action in intent.actions.iter_deref() {
2741                if let ContractAction::Maintain(upd) = action {
2742                    committee_signatures
2743                        .extend(upd.signatures.iter_deref().map(|sig| sig.1.clone()));
2744                }
2745            }
2746            let offers = [
2747                intent.guaranteed_unshielded_offer.clone(),
2748                intent.fallible_unshielded_offer.clone(),
2749            ];
2750            for offer in offers.into_iter().flatten() {
2751                let ins = Vec::from(&offer.inputs);
2752                if !no_duplicates(&ins) {
2753                    return false;
2754                }
2755                let ins: BTreeSet<_> = ins.into_iter().collect();
2756                if !unshielded_inputs.is_disjoint(&ins) {
2757                    return false;
2758                }
2759                unshielded_inputs.extend(ins);
2760            }
2761            for dust_actions in intent.dust_actions.iter() {
2762                registrations.extend(dust_actions.registrations.iter().map(|reg| reg.hash()));
2763            }
2764        }
2765        no_duplicates(&registrations) && no_duplicates(&committee_signatures)
2766    }
2767
2768    /// Actions shared by many segments are counted once per distinct node, not
2769    /// walked once per segment.
2770    #[test]
2771    fn actions_shared_by_many_segments_are_checked_quickly() {
2772        let actions: Array<ContractAction<(), D>, D> = (0..4000)
2773            .map(|counter| {
2774                ContractAction::Maintain(MaintenanceUpdate {
2775                    address: Default::default(),
2776                    updates: Array::new(),
2777                    counter,
2778                    signatures: Array::new(),
2779                })
2780            })
2781            .collect();
2782        let intent = Intent::<(), (), Pedersen, D> {
2783            guaranteed_unshielded_offer: None,
2784            fallible_unshielded_offer: None,
2785            actions,
2786            dust_actions: None,
2787            ttl: Timestamp::from_secs(0),
2788            binding_commitment: Default::default(),
2789        };
2790        let stx: Stx = StandardTransaction {
2791            network_id: "local-test".into(),
2792            intents: (1..=4000).fold(HashMap::new(), |m, seg| m.insert(seg, intent.clone())),
2793            guaranteed_coins: None,
2794            fallible_coins: HashMap::new(),
2795            binding_randomness: Default::default(),
2796        };
2797        storage::test::assert_completes_within(std::time::Duration::from_secs(5), move || {
2798            assert!(stx.disjoint_check().is_ok())
2799        });
2800    }
2801
2802    /// Erasing signatures, as pricing a verified transaction does, must not
2803    /// turn an accepted transaction into one with repeats.
2804    #[test]
2805    fn registrations_differing_only_in_signature_repeat() {
2806        use crate::dust::{DustActions, DustRegistration};
2807        use crate::structure::{Signature, SigningKey};
2808        use rand::SeedableRng;
2809        let mut rng = rand::rngs::StdRng::seed_from_u64(0);
2810        let key = SigningKey::Schnorr(base_crypto::schnorr::SigningKey::sample(&mut rng));
2811        let mut stx: StandardTransaction<Signature, (), Pedersen, D> = StandardTransaction {
2812            network_id: String::new(),
2813            intents: HashMap::new(),
2814            guaranteed_coins: None,
2815            fallible_coins: HashMap::new(),
2816            binding_randomness: Default::default(),
2817        };
2818        for segment in [1u16, 2] {
2819            let registration = DustRegistration {
2820                night_key: key.verifying_key(),
2821                dust_address: None,
2822                allow_fee_payment: 0,
2823                signature: Some(Sp::new(key.sign(&mut rng, &segment.to_le_bytes()))),
2824            };
2825            let dust_actions = DustActions {
2826                spends: Array::new(),
2827                registrations: vec![registration].into(),
2828                ctime: Timestamp::from_secs(0),
2829            };
2830            let intent = Intent {
2831                guaranteed_unshielded_offer: None,
2832                fallible_unshielded_offer: None,
2833                actions: Array::new(),
2834                dust_actions: Some(Sp::new(dust_actions)),
2835                ttl: Timestamp::from_secs(0),
2836                binding_commitment: Pedersen::default(),
2837            };
2838            stx.intents = stx.intents.insert(segment, intent);
2839        }
2840        assert!(matches!(
2841            stx.disjoint_check(),
2842            Err(MalformedTransaction::RepeatedDustRegistration { .. })
2843        ));
2844    }
2845
2846    proptest! {
2847        #[test]
2848        fn disjoint_check_matches_per_entry_checks(
2849            r in recipe(),
2850            s in shielded(),
2851            // Intents are usually rejected for their own entries; drop them half
2852            // the time to test the shielded checks alone.
2853            intents in prop_oneof![
2854                2 => Just(Intents::None),
2855                1 => Just(Intents::Distinct),
2856                1 => Just(Intents::FirstRepeated),
2857            ],
2858            actions_only in any::<bool>(),
2859        ) {
2860            let stx = standard(&r, &s, intents, actions_only);
2861            prop_assert_eq!(stx.disjoint_check().is_ok(), accepts_per_entry(&stx));
2862        }
2863    }
2864}
2865
2866#[cfg(feature = "proving")]
2867#[cfg(test)]
2868mod tests {
2869    use super::*;
2870    use base_crypto::hash::HashOutput;
2871    use coin_structure::contract::ContractAddress;
2872    use onchain_runtime::state::EntryPointBuf;
2873    use onchain_runtime::{
2874        context::{ClaimedContractCallsValue, Effects},
2875        transcript::Transcript,
2876    };
2877    use rand::Rng;
2878    use rand::SeedableRng;
2879    use rand::rngs::StdRng;
2880    use storage::{arena::Sp, db::InMemoryDB};
2881    use transient_crypto::curve::Fr;
2882
2883    #[cfg(feature = "proving")]
2884    #[tokio::test]
2885    async fn causality_check_failure() {
2886        let mut rng = StdRng::seed_from_u64(0x42);
2887
2888        let addr_1 = rng.r#gen();
2889        let addr_2 = rng.r#gen();
2890
2891        let cn_1 = CallNode {
2892            segment_id: 1,
2893            addr: addr_1,
2894            call_index: 1,
2895        };
2896        let cn_2 = CallNode {
2897            segment_id: 1,
2898            addr: addr_2,
2899            call_index: 2,
2900        };
2901
2902        let mut guaranteed_calls = std::collections::BTreeSet::new();
2903        guaranteed_calls.insert(cn_1);
2904
2905        let mut fallible_calls = std::collections::BTreeSet::new();
2906        fallible_calls.insert(cn_2);
2907
2908        let mut adjacencies = std::collections::BTreeMap::new();
2909        adjacencies.insert(cn_2, vec![cn_1]);
2910
2911        let res = causality_check::<InMemoryDB>(&guaranteed_calls, &fallible_calls, adjacencies);
2912
2913        match res {
2914            Ok(_) => panic!("Unexpected success"),
2915            Err(MalformedTransaction::SequencingCheckFailure(
2916                SequencingCheckError::CausalityConstraintViolation { .. },
2917            )) => (),
2918            Err(e) => panic!(
2919                "Test failed as expected, but the error was unexpected: {:?}",
2920                e.to_string()
2921            ),
2922        }
2923    }
2924
2925    #[cfg(feature = "proving")]
2926    #[tokio::test]
2927    async fn sequencing_check_failure() {
2928        let mut rng = StdRng::seed_from_u64(0x42);
2929
2930        let addr_1 = rng.r#gen();
2931        let addr_2 = rng.r#gen();
2932
2933        let mut claimed_contract_calls: storage::storage::HashSet<
2934            ClaimedContractCallsValue,
2935            InMemoryDB,
2936        > = storage::storage::HashSet::new();
2937
2938        let claimed_call_pos = 1;
2939        let claimed_call_addr = addr_1;
2940        let claimed_call_hash = rng.r#gen();
2941        let claimed_call_rng = rng.r#gen();
2942
2943        claimed_contract_calls = claimed_contract_calls.insert(ClaimedContractCallsValue(
2944            claimed_call_pos,
2945            claimed_call_addr,
2946            claimed_call_hash,
2947            claimed_call_rng,
2948        ));
2949
2950        let eff = Effects {
2951            claimed_nullifiers: rng.r#gen(),
2952            claimed_shielded_receives: rng.r#gen(),
2953            claimed_shielded_spends: rng.r#gen(),
2954            claimed_contract_calls,
2955            shielded_mints: rng.r#gen(),
2956            unshielded_mints: rng.r#gen(),
2957            unshielded_inputs: rng.r#gen(),
2958            unshielded_outputs: rng.r#gen(),
2959            claimed_unshielded_spends: rng.r#gen(),
2960        };
2961
2962        let transcript = Transcript {
2963            gas: rng.r#gen(),
2964            effects: eff,
2965            program: storage::storage::Array::new(),
2966            version: None,
2967        };
2968
2969        let cc_2: ContractCall<(), InMemoryDB> = ContractCall {
2970            address: addr_2,
2971            entry_point: rng.r#gen(),
2972            guaranteed_transcript: Some(Sp::new(transcript)),
2973            fallible_transcript: None,
2974            communication_commitment: rng.r#gen(),
2975            proof: (),
2976        };
2977
2978        let mut call_lookup: std::collections::BTreeMap<
2979            (ContractAddress, HashOutput, Fr),
2980            Vec<u32>,
2981        > = std::collections::BTreeMap::new();
2982
2983        call_lookup.insert((addr_1, claimed_call_hash, claimed_call_rng), vec![1]);
2984        call_lookup.insert((addr_2, rng.r#gen(), rng.r#gen()), vec![2]);
2985
2986        let res = call_sequencing_check(2, &cc_2, &call_lookup);
2987
2988        match res {
2989            Ok(_) => panic!("Unexpected success"),
2990            Err(MalformedTransaction::SequencingCheckFailure(
2991                SequencingCheckError::CallSequencingViolation { .. },
2992            )) => (),
2993            Err(e) => panic!(
2994                "Test failed as expected, but the error was unexpected: {:?}",
2995                e.to_string()
2996            ),
2997        }
2998    }
2999
3000    #[cfg(feature = "proving")]
3001    #[tokio::test]
3002    async fn sequencing_correlation_check_failure() {
3003        let mut rng = StdRng::seed_from_u64(0x42);
3004
3005        let addr_1 = rng.r#gen();
3006
3007        let sequenced_sub_calls = vec![(1, 2, addr_1), (2, 1, rng.r#gen())];
3008
3009        let res = sequencing_correlation_check::<InMemoryDB>(addr_1, sequenced_sub_calls);
3010
3011        match res {
3012            Ok(_) => panic!("Unexpected success"),
3013            Err(MalformedTransaction::SequencingCheckFailure(
3014                SequencingCheckError::SequencingCorrelationViolation { .. },
3015            )) => (),
3016            Err(e) => panic!(
3017                "Test failed as expected, but the error was unexpected: {:?}",
3018                e.to_string()
3019            ),
3020        }
3021    }
3022
3023    #[cfg(feature = "proving")]
3024    #[tokio::test]
3025    async fn sequencing_context_check_failure_guaranteed_in_fallible() {
3026        let mut rng = StdRng::seed_from_u64(0x42);
3027
3028        let addr_1 = rng.r#gen();
3029        let addr_2 = rng.r#gen();
3030
3031        let cn_1 = CallNode {
3032            segment_id: 1,
3033            addr: addr_1,
3034            call_index: 1,
3035        };
3036        let cn_1_ep: EntryPointBuf = rng.r#gen();
3037        let cn_1_commitment = rng.r#gen();
3038        let cn_2_ep: EntryPointBuf = rng.r#gen();
3039        let cn_2_commitment = rng.r#gen();
3040        let ck_2 = CallKey {
3041            addr: addr_2,
3042            ep_hash: cn_2_ep.ep_hash(),
3043            commitment: cn_2_commitment,
3044        };
3045        let cn_2 = CallNode {
3046            segment_id: 1,
3047            addr: addr_2,
3048            call_index: 2,
3049        };
3050
3051        let mut claimed_contract_calls: storage::storage::HashSet<
3052            ClaimedContractCallsValue,
3053            InMemoryDB,
3054        > = storage::storage::HashSet::new();
3055        claimed_contract_calls = claimed_contract_calls.insert(ClaimedContractCallsValue(
3056            2,
3057            addr_2,
3058            cn_2_ep.ep_hash(),
3059            cn_2_commitment,
3060        ));
3061
3062        let eff_1 = Effects {
3063            claimed_nullifiers: rng.r#gen(),
3064            claimed_shielded_receives: rng.r#gen(),
3065            claimed_shielded_spends: rng.r#gen(),
3066            claimed_contract_calls,
3067            shielded_mints: rng.r#gen(),
3068            unshielded_mints: rng.r#gen(),
3069            unshielded_inputs: rng.r#gen(),
3070            unshielded_outputs: rng.r#gen(),
3071            claimed_unshielded_spends: rng.r#gen(),
3072        };
3073
3074        let transcript_1 = Transcript {
3075            gas: rng.r#gen(),
3076            effects: eff_1,
3077            program: storage::storage::Array::new(),
3078            version: None,
3079        };
3080
3081        let cc_1: ContractCall<(), InMemoryDB> = ContractCall {
3082            address: addr_1,
3083            entry_point: cn_1_ep.clone(),
3084            guaranteed_transcript: None,
3085            fallible_transcript: Some(Sp::new(transcript_1)),
3086            communication_commitment: rng.r#gen(),
3087            proof: (),
3088        };
3089
3090        let eff_2 = Effects {
3091            claimed_nullifiers: rng.r#gen(),
3092            claimed_shielded_receives: rng.r#gen(),
3093            claimed_shielded_spends: rng.r#gen(),
3094            claimed_contract_calls: storage::storage::HashSet::new(),
3095            shielded_mints: rng.r#gen(),
3096            unshielded_mints: rng.r#gen(),
3097            unshielded_inputs: rng.r#gen(),
3098            unshielded_outputs: rng.r#gen(),
3099            claimed_unshielded_spends: rng.r#gen(),
3100        };
3101
3102        let transcript_2 = Transcript {
3103            gas: rng.r#gen(),
3104            effects: eff_2,
3105            program: storage::storage::Array::new(),
3106            version: None,
3107        };
3108
3109        let cc_2: ContractCall<(), InMemoryDB> = ContractCall {
3110            address: addr_2,
3111            entry_point: cn_2_ep.clone(),
3112            guaranteed_transcript: Some(Sp::new(transcript_2)),
3113            fallible_transcript: None,
3114            communication_commitment: cn_2_commitment,
3115            proof: (),
3116        };
3117
3118        let mut call_lookup: std::collections::BTreeMap<
3119            (ContractAddress, HashOutput, Fr),
3120            Vec<i128>,
3121        > = std::collections::BTreeMap::new();
3122
3123        call_lookup.insert((addr_1, cn_1_ep.ep_hash(), cn_1_commitment), vec![1]);
3124        call_lookup.insert((addr_2, cn_2_ep.ep_hash(), cn_2_commitment), vec![2]);
3125
3126        let mut adjacencies = std::collections::BTreeMap::new();
3127        adjacencies.insert(cn_1, vec![cn_2]);
3128
3129        let mut calls_in_intent = std::collections::BTreeMap::new();
3130        calls_in_intent.insert(1, &cc_1);
3131        calls_in_intent.insert(2, &cc_2);
3132        let mut callers_for_addr = std::collections::BTreeMap::new();
3133        callers_for_addr.insert(ck_2, vec![(cn_1, false)]);
3134
3135        let res = sequencing_context_check::<(), InMemoryDB>(
3136            &mut adjacencies,
3137            1,
3138            calls_in_intent,
3139            callers_for_addr,
3140        );
3141
3142        match res {
3143            Ok(_) => panic!("Unexpected success"),
3144            Err(MalformedTransaction::SequencingCheckFailure(
3145                SequencingCheckError::GuaranteedInFallibleContextViolation { .. },
3146            )) => (),
3147            Err(e) => panic!(
3148                "Test failed as expected, but the error was unexpected: {:?}",
3149                e.to_string()
3150            ),
3151        }
3152    }
3153
3154    #[cfg(feature = "proving")]
3155    #[tokio::test]
3156    async fn sequencing_context_check_failure_fallible_in_guaranteed() {
3157        let mut rng = StdRng::seed_from_u64(0x42);
3158
3159        let addr_1 = rng.r#gen();
3160        let addr_2 = rng.r#gen();
3161
3162        let cn_1 = CallNode {
3163            segment_id: 1,
3164            addr: addr_1,
3165            call_index: 1,
3166        };
3167        let cn_1_ep: EntryPointBuf = rng.r#gen();
3168        let cn_1_commitment = rng.r#gen();
3169        let cn_2_ep: EntryPointBuf = rng.r#gen();
3170        let cn_2_commitment = rng.r#gen();
3171        let ck_2 = CallKey {
3172            addr: addr_2,
3173            ep_hash: cn_2_ep.ep_hash(),
3174            commitment: cn_2_commitment,
3175        };
3176        let cn_2 = CallNode {
3177            segment_id: 1,
3178            addr: addr_2,
3179            call_index: 2,
3180        };
3181
3182        let mut claimed_contract_calls: storage::storage::HashSet<
3183            ClaimedContractCallsValue,
3184            InMemoryDB,
3185        > = storage::storage::HashSet::new();
3186        claimed_contract_calls = claimed_contract_calls.insert(ClaimedContractCallsValue(
3187            2,
3188            addr_2,
3189            cn_2_ep.ep_hash(),
3190            cn_2_commitment,
3191        ));
3192
3193        let eff_1 = Effects {
3194            claimed_nullifiers: rng.r#gen(),
3195            claimed_shielded_receives: rng.r#gen(),
3196            claimed_shielded_spends: rng.r#gen(),
3197            claimed_contract_calls,
3198            shielded_mints: rng.r#gen(),
3199            unshielded_mints: rng.r#gen(),
3200            unshielded_inputs: rng.r#gen(),
3201            unshielded_outputs: rng.r#gen(),
3202            claimed_unshielded_spends: rng.r#gen(),
3203        };
3204
3205        let transcript_1 = Transcript {
3206            gas: rng.r#gen(),
3207            effects: eff_1,
3208            program: storage::storage::Array::new(),
3209            version: None,
3210        };
3211
3212        let cc_1: ContractCall<(), InMemoryDB> = ContractCall {
3213            address: addr_1,
3214            entry_point: cn_1_ep.clone(),
3215            guaranteed_transcript: Some(Sp::new(transcript_1)),
3216            fallible_transcript: None,
3217            communication_commitment: rng.r#gen(),
3218            proof: (),
3219        };
3220
3221        let eff_2 = Effects {
3222            claimed_nullifiers: rng.r#gen(),
3223            claimed_shielded_receives: rng.r#gen(),
3224            claimed_shielded_spends: rng.r#gen(),
3225            claimed_contract_calls: storage::storage::HashSet::new(),
3226            shielded_mints: rng.r#gen(),
3227            unshielded_mints: rng.r#gen(),
3228            unshielded_inputs: rng.r#gen(),
3229            unshielded_outputs: rng.r#gen(),
3230            claimed_unshielded_spends: rng.r#gen(),
3231        };
3232
3233        let transcript_2 = Transcript {
3234            gas: rng.r#gen(),
3235            effects: eff_2,
3236            program: storage::storage::Array::new(),
3237            version: None,
3238        };
3239
3240        let cc_2: ContractCall<(), InMemoryDB> = ContractCall {
3241            address: addr_2,
3242            entry_point: cn_2_ep.clone(),
3243            guaranteed_transcript: None,
3244            fallible_transcript: Some(Sp::new(transcript_2)),
3245            communication_commitment: cn_2_commitment,
3246            proof: (),
3247        };
3248
3249        let mut call_lookup: std::collections::BTreeMap<
3250            (ContractAddress, HashOutput, Fr),
3251            Vec<i128>,
3252        > = std::collections::BTreeMap::new();
3253
3254        call_lookup.insert((addr_1, cn_1_ep.ep_hash(), cn_1_commitment), vec![1]);
3255        call_lookup.insert((addr_2, cn_2_ep.ep_hash(), cn_2_commitment), vec![2]);
3256
3257        let mut adjacencies = std::collections::BTreeMap::new();
3258        adjacencies.insert(cn_1, vec![cn_2]);
3259
3260        let mut calls_in_intent = std::collections::BTreeMap::new();
3261        calls_in_intent.insert(1, &cc_1);
3262        calls_in_intent.insert(2, &cc_2);
3263        let mut callers_for_addr = std::collections::BTreeMap::new();
3264        callers_for_addr.insert(ck_2, vec![(cn_1, true)]);
3265
3266        let res = sequencing_context_check::<(), InMemoryDB>(
3267            &mut adjacencies,
3268            1,
3269            calls_in_intent,
3270            callers_for_addr,
3271        );
3272
3273        match res {
3274            Ok(_) => panic!("Unexpected success"),
3275            Err(MalformedTransaction::SequencingCheckFailure(
3276                SequencingCheckError::FallibleInGuaranteedContextViolation { .. },
3277            )) => (),
3278            Err(e) => panic!(
3279                "Test failed as expected, but the error was unexpected: {:?}",
3280                e.to_string()
3281            ),
3282        }
3283    }
3284
3285    /// Regression: as_indexed() previously returned HashMap<u32, V>, so
3286    /// relate_nodes could visit same-address calls in arbitrary order and
3287    /// produce backward precedence edges, triggering spurious
3288    /// CausalityConstraintViolation when guaranteed/fallible calls were mixed.
3289    #[cfg(feature = "proving")]
3290    #[tokio::test]
3291    async fn relate_nodes_same_address_ordering() {
3292        let mut rng = StdRng::seed_from_u64(0x42);
3293        let addr: ContractAddress = rng.r#gen();
3294
3295        let make_transcript = |rng: &mut StdRng| -> Sp<Transcript<InMemoryDB>, InMemoryDB> {
3296            let eff = Effects {
3297                claimed_nullifiers: rng.r#gen(),
3298                claimed_shielded_receives: rng.r#gen(),
3299                claimed_shielded_spends: rng.r#gen(),
3300                claimed_contract_calls: storage::storage::HashSet::new(),
3301                shielded_mints: rng.r#gen(),
3302                unshielded_mints: rng.r#gen(),
3303                unshielded_inputs: rng.r#gen(),
3304                unshielded_outputs: rng.r#gen(),
3305                claimed_unshielded_spends: rng.r#gen(),
3306            };
3307            Sp::new(Transcript {
3308                gas: rng.r#gen(),
3309                effects: eff,
3310                program: storage::storage::Array::new(),
3311                version: None,
3312            })
3313        };
3314
3315        // 6 calls to the same address: 0-3 guaranteed-only, 4-5 fallible-only.
3316        let calls: Vec<ContractCall<(), InMemoryDB>> = (0..6u32)
3317            .map(|i| {
3318                let (gt, ft) = if i < 4 {
3319                    (Some(make_transcript(&mut rng)), None)
3320                } else {
3321                    (None, Some(make_transcript(&mut rng)))
3322                };
3323                ContractCall {
3324                    address: addr,
3325                    entry_point: rng.r#gen(),
3326                    guaranteed_transcript: gt,
3327                    fallible_transcript: ft,
3328                    communication_commitment: rng.r#gen(),
3329                    proof: (),
3330                }
3331            })
3332            .collect();
3333
3334        // Iterate enough times to catch nondeterministic HashMap ordering
3335        let mut backward_edge_found = false;
3336        let mut causality_violation_found = false;
3337
3338        for _ in 0..200 {
3339            let calls_in_intent: std::collections::BTreeMap<u32, &ContractCall<(), InMemoryDB>> =
3340                calls
3341                    .iter()
3342                    .enumerate()
3343                    .map(|(i, c)| (i as u32, c))
3344                    .collect();
3345
3346            let mut guaranteed_calls = BTreeSet::new();
3347            let mut fallible_calls = BTreeSet::new();
3348            let mut calls_by_address = std::collections::BTreeMap::new();
3349            let mut adjacencies = std::collections::BTreeMap::new();
3350
3351            let _callers = relate_nodes::<(), InMemoryDB>(
3352                &mut guaranteed_calls,
3353                &mut fallible_calls,
3354                &mut calls_by_address,
3355                &mut adjacencies,
3356                1,
3357                &calls_in_intent,
3358            )
3359            .unwrap();
3360
3361            // All precedence edges should be forward (lower → higher index)
3362            for (from_node, to_nodes) in &adjacencies {
3363                for to_node in to_nodes {
3364                    if from_node.call_index > to_node.call_index {
3365                        backward_edge_found = true;
3366                    }
3367                }
3368            }
3369
3370            // causality_check should not reject this valid ordering
3371            if causality_check::<InMemoryDB>(&guaranteed_calls, &fallible_calls, adjacencies)
3372                .is_err()
3373            {
3374                causality_violation_found = true;
3375            }
3376
3377            if backward_edge_found && causality_violation_found {
3378                break;
3379            }
3380        }
3381
3382        assert!(
3383            !backward_edge_found,
3384            "'related_nodes' produced backwards edges"
3385        );
3386        assert!(
3387            !causality_violation_found,
3388            "Spurious CausalityConstraintViolation for a valid call ordering"
3389        );
3390    }
3391}