Skip to main content

grillo_verifier/
frame_v2.rs

1//! Concrete Effect ABI v0.2 invocation evidence and fail-closed binding.
2//!
3//! `InvocationFrameV2` is caller-supplied evidence. Its provenance is only a
4//! label and is never promoted to authenticated execution by this crate.
5//! `BoundInvocationV2` has private fields and can only be constructed after
6//! identity, discriminator, account grammar, unique-state, alias, and CPI
7//! envelope validation.
8
9use core::fmt;
10
11use grillo_manifest::{
12    sha256, AddressConstraintV2, CpiEnvelopeV2, CpiPolicyV2, DeploymentBindingV2,
13    DuplicatePolicyV2, EffectContractV2, InstructionEffectContractV2, PrivilegeRequirementV2,
14};
15
16/// Runtime-informed defensive verifier limits. Binding fails closed when a
17/// frame exceeds them; a larger trace is never mislabeled as a violation.
18pub const MAX_INVOCATION_PATH_DEPTH_V2: usize = 8;
19pub const MAX_INVOCATION_NODES_V2: usize = 64;
20pub const MAX_INSTRUCTION_DATA_BYTES_V2: usize = 10_240;
21pub const MAX_ACCOUNTS_PER_FRAME_V2: usize = 256;
22pub const MAX_ACCOUNT_DATA_BYTES_V2: usize = 10 * 1024 * 1024;
23pub const MAX_LOADED_ACCOUNT_DATA_BYTES_V2: usize = 64 * 1024 * 1024;
24/// Off-chain labels are not SVM account data, but must also be bounded before
25/// the recursive commitment encoder allocates and the binder clones a frame.
26pub const MAX_PROVENANCE_TEXT_BYTES_V2: usize = 4096;
27
28/// Cluster identity for replay separation.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct NetworkIdentityV2 {
31    pub genesis_hash: [u8; 32],
32}
33
34/// Transaction and exact call-tree location.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct TransactionIdentityV2 {
37    pub signature: [u8; 64],
38    pub message_hash: [u8; 32],
39    pub bank_slot: u64,
40    pub outer_instruction_index: u16,
41    /// Child ordinals from the outer instruction to this frame.
42    pub invocation_path: Vec<u16>,
43}
44
45/// Concrete loader/deployment identity observed for one invocation.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct DeploymentIdentityV2 {
48    pub program_id: [u8; 32],
49    pub loader_id: [u8; 32],
50    pub executable_digest: [u8; 32],
51    pub programdata_address: Option<[u8; 32]>,
52    pub deployment_slot: Option<u64>,
53    pub manifest_commitment: [u8; 32],
54}
55
56/// Effective account meta at one invocation position.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct InvocationAccountRefV2 {
59    pub position: u16,
60    pub transaction_index: u16,
61    pub pubkey: [u8; 32],
62    pub signer: bool,
63    pub writable: bool,
64}
65
66/// Logical loaded-state observation. Absence is explicit and is never
67/// inferred from zero lamports or System ownership.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub enum AccountStateV2 {
70    Absent,
71    Present {
72        lamports: u64,
73        owner: [u8; 32],
74        executable: bool,
75        data: Vec<u8>,
76    },
77}
78
79impl AccountStateV2 {
80    pub fn is_present(&self) -> bool {
81        matches!(self, Self::Present { .. })
82    }
83
84    pub fn lamports(&self) -> u64 {
85        match self {
86            Self::Absent => 0,
87            Self::Present { lamports, .. } => *lamports,
88        }
89    }
90
91    pub fn data_len(&self) -> usize {
92        match self {
93            Self::Absent => 0,
94            Self::Present { data, .. } => data.len(),
95        }
96    }
97}
98
99/// Pre/post state for one unique pubkey.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct AccountTransitionV2 {
102    pub pubkey: [u8; 32],
103    pub pre: AccountStateV2,
104    pub post: AccountStateV2,
105}
106
107/// Dimensions claimed present in this evidence object.
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct EvidenceCompletenessV2 {
110    pub accounts: bool,
111    pub data: bool,
112    pub lamports: bool,
113    pub owner: bool,
114    pub data_length: bool,
115    pub presence: bool,
116    pub executable: bool,
117    pub cpi: bool,
118    pub touch: bool,
119}
120
121impl EvidenceCompletenessV2 {
122    pub fn all_state_dimensions(self) -> bool {
123        self.accounts
124            && self.data
125            && self.lamports
126            && self.owner
127            && self.data_length
128            && self.presence
129            && self.executable
130    }
131}
132
133/// Boundary at which pre/post state was observed.
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
135pub enum ObservationBoundaryV2 {
136    InvocationEntryExit,
137    TransactionPrePost,
138    Unknown,
139}
140
141/// Untrusted provenance label retained in evidence and verdicts.
142#[derive(Clone, Debug, PartialEq, Eq)]
143pub enum EvidenceProvenanceV2 {
144    Fixture,
145    RpcObserved {
146        endpoint: String,
147    },
148    ReplayClaimed {
149        source: String,
150    },
151    ProviderClaimed {
152        provider: [u8; 32],
153        signature: [u8; 64],
154    },
155}
156
157/// This pure verifier performs no signature, ledger, or replay validation.
158#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub enum UnverifiedAuthenticityV2 {
160    Unauthenticated,
161}
162
163/// Optional attributed touch carrier. The digest is committed, but this
164/// first slice does not treat it as independently authenticated.
165#[derive(Clone, Debug, PartialEq, Eq)]
166pub struct TouchEvidenceV2 {
167    pub complete: bool,
168    pub digest: Option<[u8; 32]>,
169}
170
171/// Whether an invocation's effects survived its observed execution boundary.
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum InvocationOutcomeV2 {
174    /// The invocation returned successfully and its effects survived.
175    Succeeded,
176    /// The invocation returned an error, so its effects were discarded.
177    Failed,
178    /// The invocation returned but its effects were discarded by rollback.
179    RolledBack,
180}
181
182/// Full concrete evidence for one invocation plus its ordered CPI children.
183#[derive(Clone, Debug, PartialEq, Eq)]
184pub struct InvocationFrameV2 {
185    pub network: NetworkIdentityV2,
186    pub transaction: TransactionIdentityV2,
187    pub deployment: DeploymentIdentityV2,
188    pub instruction_data: Vec<u8>,
189    pub accounts: Vec<InvocationAccountRefV2>,
190    /// Exactly one entry per unique account pubkey when `evidence.accounts`.
191    pub states: Vec<AccountTransitionV2>,
192    pub touch: TouchEvidenceV2,
193    pub children: Vec<InvocationFrameV2>,
194    pub outcome: InvocationOutcomeV2,
195    pub boundary: ObservationBoundaryV2,
196    pub evidence: EvidenceCompletenessV2,
197    pub provenance: EvidenceProvenanceV2,
198}
199
200impl InvocationFrameV2 {
201    /// Stable digest over all frame fields. This commits caller-supplied
202    /// provenance but does not authenticate it.
203    ///
204    /// This infallible low-level helper assumes a locally constructed or
205    /// already shape-checked frame. Untrusted frames should be passed directly
206    /// to [`bind_invocation_v2`], which enforces depth, node, and byte quotas
207    /// before invoking the recursive encoder.
208    pub fn commitment(&self) -> [u8; 32] {
209        let mut out = Vec::new();
210        out.extend_from_slice(b"grillo.invocation-frame.v0.2.c1");
211        encode_frame(&mut out, self);
212        sha256(&out)
213    }
214}
215
216/// Concrete resolved role after expanding the remaining-account grammar.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct ResolvedAccountRoleV2 {
219    name: String,
220    position: u16,
221    pubkey: [u8; 32],
222    contract: grillo_manifest::AccountRoleContractV2,
223}
224
225impl ResolvedAccountRoleV2 {
226    pub fn name(&self) -> &str {
227        &self.name
228    }
229
230    pub fn position(&self) -> u16 {
231        self.position
232    }
233
234    pub fn pubkey(&self) -> [u8; 32] {
235        self.pubkey
236    }
237
238    pub fn contract(&self) -> &grillo_manifest::AccountRoleContractV2 {
239        &self.contract
240    }
241}
242
243/// Immutable, validated binding of a concrete frame to a v0.2 contract.
244#[derive(Clone, Debug)]
245pub struct BoundInvocationV2 {
246    contract_commitment: [u8; 32],
247    frame_commitment: [u8; 32],
248    commitment: [u8; 32],
249    instruction: InstructionEffectContractV2,
250    frame: InvocationFrameV2,
251    roles: Vec<ResolvedAccountRoleV2>,
252}
253
254impl BoundInvocationV2 {
255    pub fn contract_commitment(&self) -> [u8; 32] {
256        self.contract_commitment
257    }
258
259    pub fn frame_commitment(&self) -> [u8; 32] {
260        self.frame_commitment
261    }
262
263    pub fn commitment(&self) -> [u8; 32] {
264        self.commitment
265    }
266
267    pub fn instruction_name(&self) -> &str {
268        &self.instruction.name
269    }
270
271    pub fn roles(&self) -> &[ResolvedAccountRoleV2] {
272        &self.roles
273    }
274
275    pub fn provenance(&self) -> &EvidenceProvenanceV2 {
276        &self.frame.provenance
277    }
278
279    pub fn authenticity(&self) -> UnverifiedAuthenticityV2 {
280        UnverifiedAuthenticityV2::Unauthenticated
281    }
282
283    pub(crate) fn instruction(&self) -> &InstructionEffectContractV2 {
284        &self.instruction
285    }
286
287    pub(crate) fn frame(&self) -> &InvocationFrameV2 {
288        &self.frame
289    }
290}
291
292/// Why an untrusted frame could not be bound to a contract.
293#[derive(Clone, Debug, PartialEq, Eq)]
294pub enum BindErrorV2 {
295    InvalidContract(String),
296    InstructionNotFound,
297    DeploymentMismatch {
298        field: &'static str,
299    },
300    ManifestCommitmentMismatch,
301    AccountCount {
302        expected: usize,
303        actual: usize,
304    },
305    AccountPosition {
306        expected: u16,
307        actual: u16,
308    },
309    TransactionAccountMismatch {
310        first: u16,
311        second: u16,
312    },
313    DeploymentSlotAfterInvocation {
314        deployment_slot: u64,
315        bank_slot: u64,
316    },
317    FrameLimitExceeded {
318        resource: &'static str,
319        max: usize,
320        actual: usize,
321    },
322    PrivilegeMismatch {
323        position: u16,
324        privilege: &'static str,
325    },
326    AddressMismatch {
327        position: u16,
328    },
329    DuplicateAccount {
330        first: u16,
331        second: u16,
332    },
333    DuplicateState {
334        pubkey: [u8; 32],
335    },
336    MissingState {
337        pubkey: [u8; 32],
338    },
339    ExtraState {
340        pubkey: [u8; 32],
341    },
342    ForbiddenCpi,
343    UndeclaredCpi {
344        child_index: usize,
345    },
346    CpiCount {
347        envelope: String,
348        min: u16,
349        max: u16,
350        actual: usize,
351    },
352    CpiAccountMismatch {
353        child_index: usize,
354        child_position: u16,
355    },
356    CpiContextMismatch {
357        child_index: usize,
358        field: &'static str,
359    },
360    CpiAccountNotVisible {
361        child_index: usize,
362        child_position: u16,
363    },
364    CpiPrivilegeEscalation {
365        child_index: usize,
366        child_position: u16,
367        privilege: &'static str,
368    },
369    CpiRollbackForbidden {
370        child_index: usize,
371    },
372    IncompleteRollbackEvidence {
373        child_index: usize,
374    },
375    RolledBackMutation {
376        child_index: usize,
377        pubkey: [u8; 32],
378    },
379    InvalidFrame(String),
380}
381
382impl fmt::Display for BindErrorV2 {
383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384        write!(f, "Effect ABI v0.2 frame bind failed: {self:?}")
385    }
386}
387
388impl std::error::Error for BindErrorV2 {}
389
390/// Validate and bind one concrete frame. Provenance is copied verbatim and
391/// authenticity remains `Unauthenticated` regardless of its label.
392pub fn bind_invocation_v2(
393    contract: &EffectContractV2,
394    frame: &InvocationFrameV2,
395) -> Result<BoundInvocationV2, BindErrorV2> {
396    contract
397        .validate()
398        .map_err(|error| BindErrorV2::InvalidContract(error.to_string()))?;
399    let mut usage = FrameShapeUsage::default();
400    validate_frame_shape(frame, None, None, &mut usage)?;
401
402    let contract_commitment = contract
403        .commitment()
404        .map_err(|error| BindErrorV2::InvalidContract(error.to_string()))?;
405    if frame.deployment.manifest_commitment != contract_commitment {
406        return Err(BindErrorV2::ManifestCommitmentMismatch);
407    }
408    match &contract.deployment {
409        DeploymentBindingV2::ExactDeployment {
410            program_id,
411            loader_id,
412            executable_digest,
413        } => {
414            if &frame.deployment.program_id != program_id {
415                return Err(BindErrorV2::DeploymentMismatch {
416                    field: "program_id",
417                });
418            }
419            if &frame.deployment.loader_id != loader_id {
420                return Err(BindErrorV2::DeploymentMismatch { field: "loader_id" });
421            }
422            if &frame.deployment.executable_digest != executable_digest {
423                return Err(BindErrorV2::DeploymentMismatch {
424                    field: "executable_digest",
425                });
426            }
427        }
428        DeploymentBindingV2::ExactArtifact { executable_digest } => {
429            if &frame.deployment.executable_digest != executable_digest {
430                return Err(BindErrorV2::DeploymentMismatch {
431                    field: "executable_digest",
432                });
433            }
434        }
435    }
436
437    let instruction = contract
438        .instruction_for_data(&frame.instruction_data)
439        .ok_or(BindErrorV2::InstructionNotFound)?;
440    let expanded = instruction.expanded_roles();
441    if frame.accounts.len() != expanded.len() {
442        return Err(BindErrorV2::AccountCount {
443            expected: expanded.len(),
444            actual: frame.accounts.len(),
445        });
446    }
447
448    let mut roles = Vec::with_capacity(expanded.len());
449    for (index, ((name, role), account)) in expanded.iter().zip(&frame.accounts).enumerate() {
450        validate_privilege(role.signer, account.signer, account.position, "signer")?;
451        validate_privilege(
452            role.writable,
453            account.writable,
454            account.position,
455            "writable",
456        )?;
457        let address_ok = match &role.address {
458            AddressConstraintV2::Any => true,
459            AddressConstraintV2::Exact { address } => account.pubkey == *address,
460            AddressConstraintV2::ProgramId => account.pubkey == frame.deployment.program_id,
461        };
462        if !address_ok {
463            return Err(BindErrorV2::AddressMismatch {
464                position: index as u16,
465            });
466        }
467        roles.push(ResolvedAccountRoleV2 {
468            name: name.clone(),
469            position: index as u16,
470            pubkey: account.pubkey,
471            contract: role.clone(),
472        });
473    }
474
475    validate_aliases(instruction, &frame.accounts)?;
476    validate_cpi_policy(instruction, frame)?;
477
478    let frame_commitment = frame.commitment();
479    let mut bound_bytes = Vec::new();
480    bound_bytes.extend_from_slice(b"grillo.bound-invocation.v0.2.c1");
481    bound_bytes.extend_from_slice(&contract_commitment);
482    bound_bytes.extend_from_slice(&frame_commitment);
483    encode_bytes(&mut bound_bytes, instruction.name.as_bytes());
484    encode_bytes(&mut bound_bytes, &instruction.discriminator);
485    encode_len(&mut bound_bytes, roles.len());
486    for role in &roles {
487        encode_bytes(&mut bound_bytes, role.name.as_bytes());
488        bound_bytes.extend_from_slice(&role.position.to_le_bytes());
489        bound_bytes.extend_from_slice(&role.pubkey);
490    }
491    let commitment = sha256(&bound_bytes);
492
493    Ok(BoundInvocationV2 {
494        contract_commitment,
495        frame_commitment,
496        commitment,
497        instruction: instruction.clone(),
498        frame: frame.clone(),
499        roles,
500    })
501}
502
503fn validate_frame_shape(
504    frame: &InvocationFrameV2,
505    child_index: Option<usize>,
506    parent: Option<&InvocationFrameV2>,
507    usage: &mut FrameShapeUsage,
508) -> Result<(), BindErrorV2> {
509    usage.nodes = usage.nodes.saturating_add(1);
510    check_frame_limit("invocation nodes", MAX_INVOCATION_NODES_V2, usage.nodes)?;
511    check_frame_limit(
512        "invocation path depth",
513        MAX_INVOCATION_PATH_DEPTH_V2,
514        frame.transaction.invocation_path.len(),
515    )?;
516    check_frame_limit(
517        "instruction data bytes",
518        MAX_INSTRUCTION_DATA_BYTES_V2,
519        frame.instruction_data.len(),
520    )?;
521    let provenance_text_len = match &frame.provenance {
522        EvidenceProvenanceV2::RpcObserved { endpoint } => endpoint.len(),
523        EvidenceProvenanceV2::ReplayClaimed { source } => source.len(),
524        EvidenceProvenanceV2::Fixture | EvidenceProvenanceV2::ProviderClaimed { .. } => 0,
525    };
526    check_frame_limit(
527        "provenance text bytes",
528        MAX_PROVENANCE_TEXT_BYTES_V2,
529        provenance_text_len,
530    )?;
531    check_frame_limit(
532        "accounts per frame",
533        MAX_ACCOUNTS_PER_FRAME_V2,
534        frame.accounts.len(),
535    )?;
536    if let Some(deployment_slot) = frame.deployment.deployment_slot {
537        if deployment_slot > frame.transaction.bank_slot {
538            return Err(BindErrorV2::DeploymentSlotAfterInvocation {
539                deployment_slot,
540                bank_slot: frame.transaction.bank_slot,
541            });
542        }
543    }
544    for (index, account) in frame.accounts.iter().enumerate() {
545        if account.position as usize != index {
546            return Err(BindErrorV2::AccountPosition {
547                expected: index as u16,
548                actual: account.position,
549            });
550        }
551    }
552    for (index, left) in frame.accounts.iter().enumerate() {
553        for right in &frame.accounts[index + 1..] {
554            let index_reused_for_another_key =
555                left.transaction_index == right.transaction_index && left.pubkey != right.pubkey;
556            let key_reused_at_another_index =
557                left.pubkey == right.pubkey && left.transaction_index != right.transaction_index;
558            if index_reused_for_another_key || key_reused_at_another_index {
559                return Err(BindErrorV2::TransactionAccountMismatch {
560                    first: left.position,
561                    second: right.position,
562                });
563            }
564        }
565    }
566    if let (Some(parent), Some(child_index)) = (parent, child_index) {
567        validate_child_context(parent, frame, child_index)?;
568    }
569    for (index, state) in frame.states.iter().enumerate() {
570        charge_state_data(
571            &mut usage.pre_state_data_bytes,
572            &state.pre,
573            "pre-state data bytes",
574        )?;
575        charge_state_data(
576            &mut usage.post_state_data_bytes,
577            &state.post,
578            "post-state data bytes",
579        )?;
580        if frame.states[index + 1..]
581            .iter()
582            .any(|other| other.pubkey == state.pubkey)
583        {
584            return Err(BindErrorV2::DuplicateState {
585                pubkey: state.pubkey,
586            });
587        }
588        if !frame
589            .accounts
590            .iter()
591            .any(|account| account.pubkey == state.pubkey)
592        {
593            return Err(BindErrorV2::ExtraState {
594                pubkey: state.pubkey,
595            });
596        }
597    }
598    if frame.evidence.accounts {
599        for account in &frame.accounts {
600            if !frame
601                .states
602                .iter()
603                .any(|state| state.pubkey == account.pubkey)
604            {
605                return Err(BindErrorV2::MissingState {
606                    pubkey: account.pubkey,
607                });
608            }
609        }
610    }
611    // A failed CPI and an explicitly rolled-back CPI have the same effective
612    // state invariant: neither may leave a mutation behind. Keep the two
613    // outcome labels for provenance, but bind both fail closed.
614    if frame.outcome != InvocationOutcomeV2::Succeeded {
615        let index = child_index.unwrap_or(0);
616        if !frame.evidence.all_state_dimensions() {
617            return Err(BindErrorV2::IncompleteRollbackEvidence { child_index: index });
618        }
619        for state in &frame.states {
620            if state.pre != state.post {
621                return Err(BindErrorV2::RolledBackMutation {
622                    child_index: index,
623                    pubkey: state.pubkey,
624                });
625            }
626        }
627    }
628    for (index, child) in frame.children.iter().enumerate() {
629        validate_frame_shape(child, Some(index), Some(frame), usage)?;
630    }
631    Ok(())
632}
633
634#[derive(Default)]
635struct FrameShapeUsage {
636    nodes: usize,
637    pre_state_data_bytes: usize,
638    post_state_data_bytes: usize,
639}
640
641fn check_frame_limit(resource: &'static str, max: usize, actual: usize) -> Result<(), BindErrorV2> {
642    if actual <= max {
643        Ok(())
644    } else {
645        Err(BindErrorV2::FrameLimitExceeded {
646            resource,
647            max,
648            actual,
649        })
650    }
651}
652
653fn charge_state_data(
654    total: &mut usize,
655    state: &AccountStateV2,
656    resource: &'static str,
657) -> Result<(), BindErrorV2> {
658    let len = state.data_len();
659    check_frame_limit("account data bytes", MAX_ACCOUNT_DATA_BYTES_V2, len)?;
660    *total = total.saturating_add(len);
661    check_frame_limit(resource, MAX_LOADED_ACCOUNT_DATA_BYTES_V2, *total)
662}
663
664fn validate_child_context(
665    parent: &InvocationFrameV2,
666    child: &InvocationFrameV2,
667    child_index: usize,
668) -> Result<(), BindErrorV2> {
669    if child.boundary != ObservationBoundaryV2::InvocationEntryExit {
670        return Err(BindErrorV2::CpiContextMismatch {
671            child_index,
672            field: "observation_boundary",
673        });
674    }
675    let context_matches = [
676        (
677            "genesis_hash",
678            parent.network.genesis_hash == child.network.genesis_hash,
679        ),
680        (
681            "signature",
682            parent.transaction.signature == child.transaction.signature,
683        ),
684        (
685            "message_hash",
686            parent.transaction.message_hash == child.transaction.message_hash,
687        ),
688        (
689            "bank_slot",
690            parent.transaction.bank_slot == child.transaction.bank_slot,
691        ),
692        (
693            "outer_instruction_index",
694            parent.transaction.outer_instruction_index == child.transaction.outer_instruction_index,
695        ),
696    ];
697    for (field, matches) in context_matches {
698        if !matches {
699            return Err(BindErrorV2::CpiContextMismatch { child_index, field });
700        }
701    }
702
703    let ordinal = u16::try_from(child_index)
704        .map_err(|_| BindErrorV2::InvalidFrame("CPI child ordinal exceeds u16::MAX".to_string()))?;
705    let mut expected_path = parent.transaction.invocation_path.clone();
706    expected_path.push(ordinal);
707    if child.transaction.invocation_path != expected_path {
708        return Err(BindErrorV2::CpiContextMismatch {
709            child_index,
710            field: "invocation_path",
711        });
712    }
713
714    for child_account in &child.accounts {
715        let visible_parent_accounts: Vec<&InvocationAccountRefV2> = parent
716            .accounts
717            .iter()
718            .filter(|parent_account| {
719                parent_account.transaction_index == child_account.transaction_index
720                    && parent_account.pubkey == child_account.pubkey
721            })
722            .collect();
723        if visible_parent_accounts.is_empty() {
724            return Err(BindErrorV2::CpiAccountNotVisible {
725                child_index,
726                child_position: child_account.position,
727            });
728        }
729        if child_account.writable
730            && !visible_parent_accounts
731                .iter()
732                .any(|parent_account| parent_account.writable)
733        {
734            return Err(BindErrorV2::CpiPrivilegeEscalation {
735                child_index,
736                child_position: child_account.position,
737                privilege: "writable",
738            });
739        }
740        // A CPI signer may be elevated by invoke_signed for a PDA. Without a
741        // captured signer-seed proof, treating that elevation as impossible
742        // would reject valid call trees, so only writable escalation is
743        // checked here.
744    }
745    Ok(())
746}
747
748fn validate_privilege(
749    requirement: PrivilegeRequirementV2,
750    actual: bool,
751    position: u16,
752    privilege: &'static str,
753) -> Result<(), BindErrorV2> {
754    let valid = match requirement {
755        PrivilegeRequirementV2::Required => actual,
756        PrivilegeRequirementV2::Forbidden => !actual,
757        PrivilegeRequirementV2::Allowed => true,
758    };
759    if valid {
760        Ok(())
761    } else {
762        Err(BindErrorV2::PrivilegeMismatch {
763            position,
764            privilege,
765        })
766    }
767}
768
769fn validate_aliases(
770    instruction: &InstructionEffectContractV2,
771    accounts: &[InvocationAccountRefV2],
772) -> Result<(), BindErrorV2> {
773    let policy = instruction.remaining_accounts.duplicate_policy;
774    for (index, left) in accounts.iter().enumerate() {
775        for right in &accounts[index + 1..] {
776            if left.pubkey != right.pubkey {
777                continue;
778            }
779            let reject = match policy {
780                DuplicatePolicyV2::DenyAll => true,
781                DuplicatePolicyV2::DenyWritable => left.writable || right.writable,
782                DuplicatePolicyV2::Allow => false,
783            };
784            if reject {
785                return Err(BindErrorV2::DuplicateAccount {
786                    first: left.position,
787                    second: right.position,
788                });
789            }
790        }
791    }
792    Ok(())
793}
794
795fn validate_cpi_policy(
796    instruction: &InstructionEffectContractV2,
797    frame: &InvocationFrameV2,
798) -> Result<(), BindErrorV2> {
799    match &instruction.cpi {
800        CpiPolicyV2::Forbidden => {
801            if frame.children.is_empty() {
802                Ok(())
803            } else {
804                Err(BindErrorV2::ForbiddenCpi)
805            }
806        }
807        CpiPolicyV2::Declared { calls, .. } => {
808            let mut counts = vec![0usize; calls.len()];
809            for (child_index, child) in frame.children.iter().enumerate() {
810                let Some((call_index, call)) = calls.iter().enumerate().find(|(_, call)| {
811                    child.deployment.program_id == call.program_id
812                        && child.instruction_data.starts_with(&call.discriminator)
813                }) else {
814                    return Err(BindErrorV2::UndeclaredCpi { child_index });
815                };
816                if child.deployment.loader_id != call.loader_id
817                    || child.deployment.executable_digest != call.executable_digest
818                {
819                    return Err(BindErrorV2::UndeclaredCpi { child_index });
820                }
821                counts[call_index] += 1;
822                validate_cpi_child(frame, child, child_index, call)?;
823            }
824            for (index, call) in calls.iter().enumerate() {
825                let actual = counts[index];
826                let below_min = frame.evidence.cpi && actual < usize::from(call.min_calls);
827                if below_min || actual > usize::from(call.max_calls) {
828                    return Err(BindErrorV2::CpiCount {
829                        envelope: call.id.clone(),
830                        min: call.min_calls,
831                        max: call.max_calls,
832                        actual,
833                    });
834                }
835            }
836            Ok(())
837        }
838    }
839}
840
841fn validate_cpi_child(
842    parent: &InvocationFrameV2,
843    child: &InvocationFrameV2,
844    child_index: usize,
845    call: &CpiEnvelopeV2,
846) -> Result<(), BindErrorV2> {
847    if child.outcome != InvocationOutcomeV2::Succeeded && !call.allow_rollback {
848        return Err(BindErrorV2::CpiRollbackForbidden { child_index });
849    }
850    if !call.allow_extra_accounts && child.accounts.len() != call.accounts.len() {
851        return Err(BindErrorV2::CpiAccountMismatch {
852            child_index,
853            child_position: child.accounts.len() as u16,
854        });
855    }
856    for binding in &call.accounts {
857        let Some(child_account) = child.accounts.get(binding.child_position as usize) else {
858            return Err(BindErrorV2::CpiAccountMismatch {
859                child_index,
860                child_position: binding.child_position,
861            });
862        };
863        let Some(parent_account) = parent.accounts.get(binding.parent_position as usize) else {
864            return Err(BindErrorV2::CpiAccountMismatch {
865                child_index,
866                child_position: binding.child_position,
867            });
868        };
869        if child_account.pubkey != parent_account.pubkey
870            || validate_privilege(
871                binding.signer,
872                child_account.signer,
873                child_account.position,
874                "child signer",
875            )
876            .is_err()
877            || validate_privilege(
878                binding.writable,
879                child_account.writable,
880                child_account.position,
881                "child writable",
882            )
883            .is_err()
884        {
885            return Err(BindErrorV2::CpiAccountMismatch {
886                child_index,
887                child_position: binding.child_position,
888            });
889        }
890    }
891    Ok(())
892}
893
894fn encode_frame(out: &mut Vec<u8>, frame: &InvocationFrameV2) {
895    out.extend_from_slice(&frame.network.genesis_hash);
896    out.extend_from_slice(&frame.transaction.signature);
897    out.extend_from_slice(&frame.transaction.message_hash);
898    out.extend_from_slice(&frame.transaction.bank_slot.to_le_bytes());
899    out.extend_from_slice(&frame.transaction.outer_instruction_index.to_le_bytes());
900    encode_len(out, frame.transaction.invocation_path.len());
901    for ordinal in &frame.transaction.invocation_path {
902        out.extend_from_slice(&ordinal.to_le_bytes());
903    }
904    encode_deployment(out, &frame.deployment);
905    encode_bytes(out, &frame.instruction_data);
906    encode_len(out, frame.accounts.len());
907    for account in &frame.accounts {
908        out.extend_from_slice(&account.position.to_le_bytes());
909        out.extend_from_slice(&account.transaction_index.to_le_bytes());
910        out.extend_from_slice(&account.pubkey);
911        out.push(account.signer as u8);
912        out.push(account.writable as u8);
913    }
914    encode_len(out, frame.states.len());
915    for state in &frame.states {
916        out.extend_from_slice(&state.pubkey);
917        encode_state(out, &state.pre);
918        encode_state(out, &state.post);
919    }
920    out.push(frame.touch.complete as u8);
921    encode_option_32(out, frame.touch.digest);
922    encode_len(out, frame.children.len());
923    for child in &frame.children {
924        encode_frame(out, child);
925    }
926    out.push(match frame.outcome {
927        InvocationOutcomeV2::Succeeded => 0,
928        InvocationOutcomeV2::Failed => 1,
929        InvocationOutcomeV2::RolledBack => 2,
930    });
931    out.push(match frame.boundary {
932        ObservationBoundaryV2::InvocationEntryExit => 0,
933        ObservationBoundaryV2::TransactionPrePost => 1,
934        ObservationBoundaryV2::Unknown => 2,
935    });
936    out.extend_from_slice(&[
937        frame.evidence.accounts as u8,
938        frame.evidence.data as u8,
939        frame.evidence.lamports as u8,
940        frame.evidence.owner as u8,
941        frame.evidence.data_length as u8,
942        frame.evidence.presence as u8,
943        frame.evidence.executable as u8,
944        frame.evidence.cpi as u8,
945        frame.evidence.touch as u8,
946    ]);
947    match &frame.provenance {
948        EvidenceProvenanceV2::Fixture => out.push(0),
949        EvidenceProvenanceV2::RpcObserved { endpoint } => {
950            out.push(1);
951            encode_bytes(out, endpoint.as_bytes());
952        }
953        EvidenceProvenanceV2::ReplayClaimed { source } => {
954            out.push(2);
955            encode_bytes(out, source.as_bytes());
956        }
957        EvidenceProvenanceV2::ProviderClaimed {
958            provider,
959            signature,
960        } => {
961            out.push(3);
962            out.extend_from_slice(provider);
963            out.extend_from_slice(signature);
964        }
965    }
966}
967
968fn encode_deployment(out: &mut Vec<u8>, deployment: &DeploymentIdentityV2) {
969    out.extend_from_slice(&deployment.program_id);
970    out.extend_from_slice(&deployment.loader_id);
971    out.extend_from_slice(&deployment.executable_digest);
972    encode_option_32(out, deployment.programdata_address);
973    match deployment.deployment_slot {
974        Some(slot) => {
975            out.push(1);
976            out.extend_from_slice(&slot.to_le_bytes());
977        }
978        None => out.push(0),
979    }
980    out.extend_from_slice(&deployment.manifest_commitment);
981}
982
983fn encode_state(out: &mut Vec<u8>, state: &AccountStateV2) {
984    match state {
985        AccountStateV2::Absent => out.push(0),
986        AccountStateV2::Present {
987            lamports,
988            owner,
989            executable,
990            data,
991        } => {
992            out.push(1);
993            out.extend_from_slice(&lamports.to_le_bytes());
994            out.extend_from_slice(owner);
995            out.push(*executable as u8);
996            encode_bytes(out, data);
997        }
998    }
999}
1000
1001fn encode_option_32(out: &mut Vec<u8>, value: Option<[u8; 32]>) {
1002    match value {
1003        Some(value) => {
1004            out.push(1);
1005            out.extend_from_slice(&value);
1006        }
1007        None => out.push(0),
1008    }
1009}
1010
1011fn encode_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
1012    encode_len(out, bytes.len());
1013    out.extend_from_slice(bytes);
1014}
1015
1016fn encode_len(out: &mut Vec<u8>, value: usize) {
1017    out.extend_from_slice(&(value as u32).to_le_bytes());
1018}