Skip to main content

grillo_manifest/
resolve.rs

1//! Invocation resolution for parametric mutation contracts.
2//!
3//! A Hopper manifest publishes conservative static write ranges plus exact-cell
4//! rules selected by instruction arguments.  This module binds those rules to
5//! the REAL wire payload and produces the effective authorization set:
6//!
7//! ```text
8//! selected cells U (static authorized bytes - every governed envelope)
9//! ```
10//!
11//! Resolution is deliberately fail-closed.  Malformed descriptors, missing or
12//! truncated arguments, overlapping envelopes, selectors outside their cell
13//! count, and envelopes not covered by the static contract are all errors.
14
15use core::fmt;
16
17use crate::manifest::{
18    ArgContract, ArgEncodingContract, InstructionContract, MutationContractView,
19    ParametricRangeContract, RangeContract,
20};
21use crate::sha256::sha256;
22
23/// One selector value bound from an invocation.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct ResolvedSelector {
26    /// Compact selector index used by Hopper's runtime write policy.
27    pub argument_index: u8,
28    /// Stable instruction-argument name.
29    pub name: String,
30    /// Decoded unsigned selector value.
31    pub value: u32,
32}
33
34/// A concrete instruction effect contract after all parametric rules have
35/// been bound to invocation arguments.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct ResolvedInstructionContract {
38    /// Instruction name.
39    name: String,
40    /// One-byte manifest tag.
41    tag: u8,
42    /// Whether the data write set is complete.
43    strict_writes: bool,
44    /// Whether the lamport dimension is complete.
45    mutation_complete: bool,
46    /// Effective, invocation-specific authorized byte ranges.
47    authorized: Vec<RangeContract>,
48    /// Accounts permitted to mutate lamports.
49    lamport_accounts: Vec<u8>,
50    /// Concrete selector values that produced this contract.
51    selectors: Vec<ResolvedSelector>,
52    /// Commitment to the unresolved instruction contract, including all
53    /// parametric rules and wire argument descriptors.
54    source_commitment: [u8; 32],
55}
56
57impl MutationContractView for ResolvedInstructionContract {
58    fn strict_writes(&self) -> bool {
59        self.strict_writes
60    }
61
62    fn mutation_complete(&self) -> bool {
63        self.mutation_complete
64    }
65
66    fn authorized_ranges(&self) -> &[RangeContract] {
67        &self.authorized
68    }
69
70    fn lamport_accounts(&self) -> &[u8] {
71        &self.lamport_accounts
72    }
73}
74
75impl ResolvedInstructionContract {
76    /// Instruction name pinned by the source contract.
77    pub fn name(&self) -> &str {
78        &self.name
79    }
80
81    /// One-byte manifest tag pinned by the source contract.
82    pub fn tag(&self) -> u8 {
83        self.tag
84    }
85
86    /// Whether the data write set is complete.
87    pub fn strict_writes(&self) -> bool {
88        self.strict_writes
89    }
90
91    /// Whether the lamport permission set is complete.
92    pub fn mutation_complete(&self) -> bool {
93        self.mutation_complete
94    }
95
96    /// Effective invocation-specific authorized ranges.
97    pub fn authorized_ranges(&self) -> &[RangeContract] {
98        &self.authorized
99    }
100
101    /// Accounts permitted to mutate lamports.
102    pub fn lamport_accounts(&self) -> &[u8] {
103        &self.lamport_accounts
104    }
105
106    /// Selector values used to resolve this invocation.
107    pub fn selectors(&self) -> &[ResolvedSelector] {
108        &self.selectors
109    }
110
111    /// Commitment to the unresolved source contract.
112    pub fn source_commitment(&self) -> [u8; 32] {
113        self.source_commitment
114    }
115
116    /// Stable SHA-256 certificate for this concrete invocation effect.
117    ///
118    /// The source commitment pins the published rule set.  The selector list
119    /// and resolved ranges pin the invocation-specific result, so changing a
120    /// slot or any exact-cell rule changes this digest.
121    pub fn commitment(&self) -> [u8; 32] {
122        let mut bytes = Vec::new();
123        bytes.extend_from_slice(b"grillo.resolved-effect.v2");
124        bytes.extend_from_slice(&self.source_commitment);
125        bytes.extend_from_slice(&(self.name.len() as u32).to_le_bytes());
126        bytes.extend_from_slice(self.name.as_bytes());
127        bytes.push(self.tag);
128        bytes.push(self.strict_writes as u8);
129        bytes.push(self.mutation_complete as u8);
130        bytes.extend_from_slice(&(self.lamport_accounts.len() as u32).to_le_bytes());
131        bytes.extend_from_slice(&self.lamport_accounts);
132        bytes.extend_from_slice(&(self.selectors.len() as u32).to_le_bytes());
133        for selector in &self.selectors {
134            bytes.push(selector.argument_index);
135            bytes.extend_from_slice(&(selector.name.len() as u32).to_le_bytes());
136            bytes.extend_from_slice(selector.name.as_bytes());
137            bytes.extend_from_slice(&selector.value.to_le_bytes());
138        }
139        bytes.extend_from_slice(&(self.authorized.len() as u32).to_le_bytes());
140        for range in &self.authorized {
141            bytes.push(range.account_index);
142            bytes.extend_from_slice(&range.offset.to_le_bytes());
143            bytes.extend_from_slice(&range.size.to_le_bytes());
144        }
145        sha256(&bytes)
146    }
147
148    /// Effective ranges for one positional instruction account.
149    pub fn authorized_for(&self, account_index: u8) -> impl Iterator<Item = &RangeContract> {
150        self.authorized
151            .iter()
152            .filter(move |range| range.account_index == account_index)
153    }
154}
155
156/// Why an invocation-specific effect contract could not be resolved.
157#[derive(Clone, Debug, PartialEq, Eq)]
158pub enum ResolveError {
159    /// A parametric selector has no matching argument descriptor.
160    MissingArgumentDescriptor { argument: String },
161    /// The instruction payload ended while decoding an argument.
162    TruncatedArgument { argument: String },
163    /// An argument descriptor is internally inconsistent.
164    InvalidArgumentDescriptor {
165        argument: String,
166        reason: &'static str,
167    },
168    /// Exact-cell selectors are intentionally restricted to fixed unsigned
169    /// integer wire types so off-chain and on-chain casts cannot diverge.
170    UnsupportedSelectorType { argument: String, ty: String },
171    /// A decoded selector is outside the declared cell count.
172    SelectorOutOfRange {
173        argument: String,
174        value: u32,
175        count: u32,
176    },
177    /// A parametric rule is malformed or overflows its offset arithmetic.
178    InvalidRule {
179        segment: String,
180        reason: &'static str,
181    },
182    /// Two rules on the same account govern overlapping envelopes.  Hopper's
183    /// runtime gives the first rule precedence, so accepting a set union here
184    /// would be unsound.
185    OverlappingRules {
186        first_segment: String,
187        second_segment: String,
188    },
189    /// A rule could broaden authority beyond the conservative static set.
190    EnvelopeNotStaticallyAuthorized { account_index: u8, segment: String },
191    /// Caller supplied fewer already-decoded compact selectors than the rule
192    /// references.
193    MissingSelectorValue {
194        argument: String,
195        argument_index: u8,
196    },
197    /// Two rules disagree about the name/index identity of one selector.
198    InconsistentSelectorIdentity {
199        argument: String,
200        argument_index: u8,
201    },
202}
203
204impl fmt::Display for ResolveError {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        match self {
207            Self::MissingArgumentDescriptor { argument } => {
208                write!(f, "no wire descriptor for parametric argument `{argument}`")
209            }
210            Self::TruncatedArgument { argument } => {
211                write!(f, "instruction payload is truncated at argument `{argument}`")
212            }
213            Self::InvalidArgumentDescriptor { argument, reason } => {
214                write!(f, "invalid descriptor for argument `{argument}`: {reason}")
215            }
216            Self::UnsupportedSelectorType { argument, ty } => write!(
217                f,
218                "parametric argument `{argument}` has unsupported type `{ty}`; expected u8, u16, or u32"
219            ),
220            Self::SelectorOutOfRange {
221                argument,
222                value,
223                count,
224            } => write!(
225                f,
226                "parametric argument `{argument}` selects cell {value}, but count is {count}"
227            ),
228            Self::InvalidRule { segment, reason } => {
229                write!(f, "invalid parametric rule for `{segment}`: {reason}")
230            }
231            Self::OverlappingRules {
232                first_segment,
233                second_segment,
234            } => write!(
235                f,
236                "parametric envelopes `{first_segment}` and `{second_segment}` overlap"
237            ),
238            Self::EnvelopeNotStaticallyAuthorized {
239                account_index,
240                segment,
241            } => write!(
242                f,
243                "parametric envelope `{segment}` on account {account_index} is not covered by the static contract"
244            ),
245            Self::MissingSelectorValue {
246                argument,
247                argument_index,
248            } => write!(
249                f,
250                "missing selector {argument_index} for parametric argument `{argument}`"
251            ),
252            Self::InconsistentSelectorIdentity {
253                argument,
254                argument_index,
255            } => write!(
256                f,
257                "parametric selector {argument_index} and name `{argument}` are inconsistent across rules"
258            ),
259        }
260    }
261}
262
263impl std::error::Error for ResolveError {}
264
265impl InstructionContract {
266    /// Resolve exact-cell effects from the actual instruction **argument
267    /// payload** (the bytes after the instruction discriminator).
268    ///
269    /// Hopper manifests currently expose a one-byte `tag`, not the complete
270    /// discriminator byte string used by imported multi-byte ABIs.  Accepting
271    /// the post-discriminator payload keeps this API exact for both cases: the
272    /// transaction/IDL decoder that selected this instruction also knows the
273    /// discriminator length and passes the remaining bytes here.
274    pub fn resolve_effects(
275        &self,
276        argument_payload: &[u8],
277    ) -> Result<ResolvedInstructionContract, ResolveError> {
278        let named = decode_selector_values(&self.args, &self.parametric, argument_payload)?;
279        self.resolve_with(|rule| {
280            named
281                .iter()
282                .find(|(name, _)| name == &rule.argument_name)
283                .map(|(_, value)| *value)
284        })
285    }
286
287    /// Resolve from selector values already decoded in Hopper's compact
288    /// parametric-index order.
289    ///
290    /// This is useful for SVM integrations that already decoded handler args;
291    /// independent transaction verifiers should prefer [`Self::resolve_effects`]
292    /// so the certificate is bound directly to wire bytes.
293    pub fn resolve_effects_with_selectors(
294        &self,
295        selectors: &[u32],
296    ) -> Result<ResolvedInstructionContract, ResolveError> {
297        self.resolve_with(|rule| selectors.get(rule.argument_index as usize).copied())
298    }
299
300    fn resolve_with(
301        &self,
302        mut selector_for: impl FnMut(&ParametricRangeContract) -> Option<u32>,
303    ) -> Result<ResolvedInstructionContract, ResolveError> {
304        validate_rules(self)?;
305
306        let mut effective = self.authorized.clone();
307        let mut selected_ranges = Vec::with_capacity(self.parametric.len());
308        let mut selectors: Vec<ResolvedSelector> = Vec::new();
309
310        for rule in &self.parametric {
311            let value = selector_for(rule).ok_or_else(|| ResolveError::MissingSelectorValue {
312                argument: rule.argument_name.clone(),
313                argument_index: rule.argument_index,
314            })?;
315            let selected =
316                rule.selected_range(value)
317                    .ok_or_else(|| ResolveError::SelectorOutOfRange {
318                        argument: rule.argument_name.clone(),
319                        value,
320                        count: rule.count,
321                    })?;
322
323            if let Some(existing) = selectors.iter().find(|selector| {
324                selector.argument_index == rule.argument_index
325                    || selector.name == rule.argument_name
326            }) {
327                if existing.argument_index != rule.argument_index
328                    || existing.name != rule.argument_name
329                    || existing.value != value
330                {
331                    return Err(ResolveError::InconsistentSelectorIdentity {
332                        argument: rule.argument_name.clone(),
333                        argument_index: rule.argument_index,
334                    });
335                }
336            } else {
337                selectors.push(ResolvedSelector {
338                    argument_index: rule.argument_index,
339                    name: rule.argument_name.clone(),
340                    value,
341                });
342            }
343            selected_ranges.push(selected);
344        }
345
346        // Parametric rules take authority over every byte in their envelopes;
347        // remove those bytes from every static grant before adding only the
348        // selected cells back.
349        for rule in &self.parametric {
350            let envelope_end = rule
351                .envelope_end()
352                .ok_or_else(|| ResolveError::InvalidRule {
353                    segment: rule.segment_name.clone(),
354                    reason: "column envelope overflows",
355                })?;
356            let mut next = Vec::with_capacity(effective.len() + 1);
357            for range in effective {
358                subtract_envelope(
359                    &range,
360                    rule.account_index,
361                    rule.base_offset as u64,
362                    envelope_end,
363                    &mut next,
364                );
365            }
366            effective = next;
367        }
368        effective.extend(selected_ranges);
369        effective.sort_by_key(|range| (range.account_index, range.offset, range.size));
370        selectors.sort_by_key(|selector| selector.argument_index);
371
372        Ok(ResolvedInstructionContract {
373            name: self.name.clone(),
374            tag: self.tag,
375            strict_writes: self.strict_writes,
376            mutation_complete: self.mutation_complete,
377            authorized: effective,
378            lamport_accounts: self.lamport_accounts.clone(),
379            selectors,
380            source_commitment: self.commitment(),
381        })
382    }
383}
384
385fn validate_rules(contract: &InstructionContract) -> Result<(), ResolveError> {
386    for rule in &contract.parametric {
387        if rule.count == 0 {
388            return Err(ResolveError::InvalidRule {
389                segment: rule.segment_name.clone(),
390                reason: "cell count is zero",
391            });
392        }
393        if rule.cell_size == 0 {
394            return Err(ResolveError::InvalidRule {
395                segment: rule.segment_name.clone(),
396                reason: "cell size is zero",
397            });
398        }
399        if rule.count > 1 && rule.stride < rule.cell_size {
400            return Err(ResolveError::InvalidRule {
401                segment: rule.segment_name.clone(),
402                reason: "cell stride is smaller than cell size",
403            });
404        }
405        let end = rule
406            .envelope_end()
407            .ok_or_else(|| ResolveError::InvalidRule {
408                segment: rule.segment_name.clone(),
409                reason: "column envelope overflows",
410            })?;
411        if end > u32::MAX as u64 {
412            return Err(ResolveError::InvalidRule {
413                segment: rule.segment_name.clone(),
414                reason: "column envelope exceeds the u32 account address space",
415            });
416        }
417        let static_cover: Vec<(u64, u64)> = contract
418            .authorized
419            .iter()
420            .filter(|range| range.account_index == rule.account_index)
421            .map(|range| (range.offset as u64, range.end()))
422            .collect();
423        if first_gap(rule.base_offset as u64, end, &static_cover).is_some() {
424            return Err(ResolveError::EnvelopeNotStaticallyAuthorized {
425                account_index: rule.account_index,
426                segment: rule.segment_name.clone(),
427            });
428        }
429    }
430
431    for left_index in 0..contract.parametric.len() {
432        let left = &contract.parametric[left_index];
433        let left_end = left
434            .envelope_end()
435            .ok_or_else(|| ResolveError::InvalidRule {
436                segment: left.segment_name.clone(),
437                reason: "column envelope overflows",
438            })?;
439        for right in &contract.parametric[left_index + 1..] {
440            if left.account_index != right.account_index {
441                continue;
442            }
443            let right_end = right
444                .envelope_end()
445                .ok_or_else(|| ResolveError::InvalidRule {
446                    segment: right.segment_name.clone(),
447                    reason: "column envelope overflows",
448                })?;
449            if (left.base_offset as u64) < right_end && (right.base_offset as u64) < left_end {
450                return Err(ResolveError::OverlappingRules {
451                    first_segment: left.segment_name.clone(),
452                    second_segment: right.segment_name.clone(),
453                });
454            }
455        }
456    }
457
458    // One compact runtime selector index must name exactly one wire arg, and
459    // one wire arg must map to exactly one compact index.
460    for (index, left) in contract.parametric.iter().enumerate() {
461        for right in &contract.parametric[index + 1..] {
462            if (left.argument_index == right.argument_index)
463                != (left.argument_name == right.argument_name)
464            {
465                return Err(ResolveError::InconsistentSelectorIdentity {
466                    argument: right.argument_name.clone(),
467                    argument_index: right.argument_index,
468                });
469            }
470        }
471    }
472    Ok(())
473}
474
475fn decode_selector_values(
476    args: &[ArgContract],
477    rules: &[ParametricRangeContract],
478    payload: &[u8],
479) -> Result<Vec<(String, u32)>, ResolveError> {
480    for (index, left) in args.iter().enumerate() {
481        if args[index + 1..]
482            .iter()
483            .any(|right| right.name == left.name)
484        {
485            return Err(ResolveError::InvalidArgumentDescriptor {
486                argument: left.name.clone(),
487                reason: "duplicate argument name",
488            });
489        }
490    }
491
492    for rule in rules {
493        if !args.iter().any(|arg| arg.name == rule.argument_name) {
494            return Err(ResolveError::MissingArgumentDescriptor {
495                argument: rule.argument_name.clone(),
496            });
497        }
498    }
499
500    let mut selector_names: Vec<&str> = Vec::new();
501    for rule in rules {
502        if !selector_names.contains(&rule.argument_name.as_str()) {
503            selector_names.push(&rule.argument_name);
504        }
505    }
506
507    let mut cursor = 0usize;
508    let mut decoded = Vec::new();
509    for arg in args {
510        // Everything after the final selector is irrelevant to effect
511        // resolution.  Stopping here also avoids pretending we can skip an
512        // arbitrary bounded-vector element codec from max-size metadata.
513        if decoded.len() == selector_names.len() {
514            break;
515        }
516        let selected = rules.iter().any(|rule| rule.argument_name == arg.name);
517        match arg.encoding {
518            ArgEncodingContract::Fixed => {
519                if arg.size == 0 {
520                    return Err(ResolveError::InvalidArgumentDescriptor {
521                        argument: arg.name.clone(),
522                        reason:
523                            "cannot locate a selector after a zero-width or unknown fixed encoding",
524                    });
525                }
526                let end = cursor.checked_add(arg.size as usize).ok_or_else(|| {
527                    ResolveError::InvalidArgumentDescriptor {
528                        argument: arg.name.clone(),
529                        reason: "fixed size overflows",
530                    }
531                })?;
532                let bytes =
533                    payload
534                        .get(cursor..end)
535                        .ok_or_else(|| ResolveError::TruncatedArgument {
536                            argument: arg.name.clone(),
537                        })?;
538                if selected {
539                    let value = decode_unsigned_selector(arg, bytes)?;
540                    decoded.push((arg.name.clone(), value));
541                }
542                cursor = end;
543            }
544            ArgEncodingContract::BoundedVec => {
545                if selected {
546                    return Err(ResolveError::UnsupportedSelectorType {
547                        argument: arg.name.clone(),
548                        ty: arg.canonical_type.clone(),
549                    });
550                }
551                // `elementSize` is a MAX encoded size, not necessarily an
552                // exact stride (nested bounded codecs may consume less).  The
553                // current manifest cannot locate a later selector soundly, so
554                // fail closed instead of advancing by `len * elementSize`.
555                return Err(ResolveError::InvalidArgumentDescriptor {
556                    argument: arg.name.clone(),
557                    reason: "cannot locate a later selector after boundedVec without an exact element encoding",
558                });
559            }
560            ArgEncodingContract::BoundedString => {
561                if selected {
562                    return Err(ResolveError::UnsupportedSelectorType {
563                        argument: arg.name.clone(),
564                        ty: arg.canonical_type.clone(),
565                    });
566                }
567                let (len, after_len) = read_u16_len(payload, cursor, &arg.name)?;
568                let max_len =
569                    arg.max_len
570                        .ok_or_else(|| ResolveError::InvalidArgumentDescriptor {
571                            argument: arg.name.clone(),
572                            reason: "bounded string has no maxLen",
573                        })?;
574                if len > max_len {
575                    return Err(ResolveError::InvalidArgumentDescriptor {
576                        argument: arg.name.clone(),
577                        reason: "bounded string length exceeds maxLen",
578                    });
579                }
580                cursor = after_len.checked_add(len as usize).ok_or_else(|| {
581                    ResolveError::InvalidArgumentDescriptor {
582                        argument: arg.name.clone(),
583                        reason: "bounded string length overflows",
584                    }
585                })?;
586                if cursor > payload.len() {
587                    return Err(ResolveError::TruncatedArgument {
588                        argument: arg.name.clone(),
589                    });
590                }
591            }
592        }
593    }
594    Ok(decoded)
595}
596
597fn decode_unsigned_selector(arg: &ArgContract, bytes: &[u8]) -> Result<u32, ResolveError> {
598    match (arg.canonical_type.as_str(), bytes) {
599        ("u8", [value]) => Ok(*value as u32),
600        ("u16", [a, b]) => Ok(u16::from_le_bytes([*a, *b]) as u32),
601        ("u32", [a, b, c, d]) => Ok(u32::from_le_bytes([*a, *b, *c, *d])),
602        _ => Err(ResolveError::UnsupportedSelectorType {
603            argument: arg.name.clone(),
604            ty: arg.canonical_type.clone(),
605        }),
606    }
607}
608
609fn read_u16_len(
610    payload: &[u8],
611    cursor: usize,
612    argument: &str,
613) -> Result<(u16, usize), ResolveError> {
614    let bytes = payload
615        .get(cursor..cursor.saturating_add(2))
616        .ok_or_else(|| ResolveError::TruncatedArgument {
617            argument: argument.to_string(),
618        })?;
619    Ok((u16::from_le_bytes([bytes[0], bytes[1]]), cursor + 2))
620}
621
622fn subtract_envelope(
623    range: &RangeContract,
624    account_index: u8,
625    envelope_start: u64,
626    envelope_end: u64,
627    out: &mut Vec<RangeContract>,
628) {
629    if range.account_index != account_index
630        || range.end() <= envelope_start
631        || range.offset as u64 >= envelope_end
632    {
633        out.push(*range);
634        return;
635    }
636
637    let range_start = range.offset as u64;
638    let range_end = range.end();
639    if range_start < envelope_start {
640        out.push(RangeContract {
641            account_index,
642            offset: range.offset,
643            size: (envelope_start - range_start) as u32,
644        });
645    }
646    if range_end > envelope_end {
647        out.push(RangeContract {
648            account_index,
649            offset: envelope_end as u32,
650            size: (range_end - envelope_end) as u32,
651        });
652    }
653}
654
655fn first_gap(start: u64, end: u64, cover: &[(u64, u64)]) -> Option<u64> {
656    let mut cursor = start;
657    while cursor < end {
658        let mut furthest = cursor;
659        for &(cover_start, cover_end) in cover {
660            if cover_start <= cursor && cursor < cover_end && cover_end > furthest {
661                furthest = cover_end;
662            }
663        }
664        if furthest == cursor {
665            return Some(cursor);
666        }
667        cursor = furthest;
668    }
669    None
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675    use crate::manifest::{AccountRole, ArgContract, ArgEncodingContract};
676
677    fn contract() -> InstructionContract {
678        InstructionContract {
679            name: "settle".to_string(),
680            tag: 7,
681            strict_writes: true,
682            mutation_complete: false,
683            authorized: vec![RangeContract {
684                account_index: 1,
685                offset: 90,
686                size: 60,
687            }],
688            parametric: vec![ParametricRangeContract {
689                account_index: 1,
690                base_offset: 100,
691                stride: 4,
692                cell_size: 4,
693                count: 10,
694                argument_index: 0,
695                argument_name: "slot".to_string(),
696                segment_name: "statuses".to_string(),
697            }],
698            lamport_accounts: vec![],
699            args: vec![ArgContract {
700                name: "slot".to_string(),
701                canonical_type: "u16".to_string(),
702                size: 2,
703                encoding: ArgEncodingContract::Fixed,
704                max_len: None,
705                element_size: None,
706            }],
707            accounts: vec![AccountRole {
708                name: "shard".to_string(),
709                writable: true,
710                signer: false,
711            }],
712        }
713    }
714
715    #[test]
716    fn payload_resolves_static_minus_envelope_plus_selected_cell() {
717        let resolved = contract().resolve_effects(&3u16.to_le_bytes()).unwrap();
718        assert_eq!(
719            resolved.authorized_ranges(),
720            vec![
721                RangeContract {
722                    account_index: 1,
723                    offset: 90,
724                    size: 10,
725                },
726                RangeContract {
727                    account_index: 1,
728                    offset: 112,
729                    size: 4,
730                },
731                RangeContract {
732                    account_index: 1,
733                    offset: 140,
734                    size: 10,
735                },
736            ]
737        );
738        assert!(resolved
739            .authorized_ranges()
740            .iter()
741            .any(|r| r.contains_byte(112)));
742        assert!(!resolved
743            .authorized_ranges()
744            .iter()
745            .any(|r| r.contains_byte(116)));
746    }
747
748    #[test]
749    fn selector_changes_resolved_commitment() {
750        let a = contract().resolve_effects(&3u16.to_le_bytes()).unwrap();
751        let b = contract().resolve_effects(&4u16.to_le_bytes()).unwrap();
752        assert_ne!(a.commitment(), b.commitment());
753    }
754
755    #[test]
756    fn every_verifier_relevant_resolved_field_is_committed() {
757        let resolved = contract().resolve_effects(&3u16.to_le_bytes()).unwrap();
758        let baseline = resolved.commitment();
759
760        let mut altered = resolved.clone();
761        altered.mutation_complete = true;
762        altered.lamport_accounts.push(1);
763        assert_ne!(baseline, altered.commitment());
764
765        let mut altered = resolved.clone();
766        altered.strict_writes = false;
767        assert_ne!(baseline, altered.commitment());
768    }
769
770    #[test]
771    fn malformed_selector_payload_fails_closed() {
772        assert!(matches!(
773            contract().resolve_effects(&[3]),
774            Err(ResolveError::TruncatedArgument { .. })
775        ));
776        assert!(matches!(
777            contract().resolve_effects(&10u16.to_le_bytes()),
778            Err(ResolveError::SelectorOutOfRange { .. })
779        ));
780    }
781
782    #[test]
783    fn overlapping_envelopes_are_rejected() {
784        let mut c = contract();
785        let mut second = c.parametric[0].clone();
786        second.base_offset = 108;
787        second.segment_name = "revisions".to_string();
788        c.parametric.push(second);
789        assert!(matches!(
790            c.resolve_effects(&3u16.to_le_bytes()),
791            Err(ResolveError::OverlappingRules { .. })
792        ));
793    }
794
795    #[test]
796    fn envelope_must_be_statically_declared() {
797        let mut c = contract();
798        c.authorized[0] = RangeContract {
799            account_index: 1,
800            offset: 0,
801            size: 50,
802        };
803        assert!(matches!(
804            c.resolve_effects(&3u16.to_le_bytes()),
805            Err(ResolveError::EnvelopeNotStaticallyAuthorized { .. })
806        ));
807    }
808
809    #[test]
810    fn bounded_vector_before_selector_fails_closed_without_exact_element_shape() {
811        let mut c = contract();
812        c.args.insert(
813            0,
814            ArgContract {
815                name: "route".to_string(),
816                canonical_type: "HopperVec<u8, 8>".to_string(),
817                size: 10,
818                encoding: ArgEncodingContract::BoundedVec,
819                max_len: Some(8),
820                element_size: Some(1),
821            },
822        );
823        let payload = [2, 0, 0xaa, 0xbb, 4, 0];
824        assert!(matches!(
825            c.resolve_effects(&payload),
826            Err(ResolveError::InvalidArgumentDescriptor { .. })
827        ));
828    }
829
830    #[test]
831    fn unknown_fixed_argument_before_selector_fails_closed() {
832        let mut c = contract();
833        c.args.insert(
834            0,
835            ArgContract {
836                name: "custom".to_string(),
837                canonical_type: "CustomCodec".to_string(),
838                size: 0,
839                encoding: ArgEncodingContract::Fixed,
840                max_len: None,
841                element_size: None,
842            },
843        );
844        assert!(matches!(
845            c.resolve_effects(&[0xaa, 3, 0]),
846            Err(ResolveError::InvalidArgumentDescriptor { argument, .. })
847                if argument == "custom"
848        ));
849    }
850
851    #[test]
852    fn duplicate_argument_names_fail_closed() {
853        let mut c = contract();
854        c.args.insert(0, c.args[0].clone());
855        assert!(matches!(
856            c.resolve_effects(&[3, 0, 3, 0]),
857            Err(ResolveError::InvalidArgumentDescriptor { reason, .. })
858                if reason == "duplicate argument name"
859        ));
860    }
861}