Skip to main content

fogo_paymaster/constraint/
mod.rs

1use anchor_lang::AnchorDeserialize;
2use axum::http::StatusCode;
3use fogo_sessions_sdk::tollbooth::TOLLBOOTH_PROGRAM_ID;
4use intent_transfer::bridge::processor::bridge_ntt_tokens::{SignedQuote, H160};
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use serde_with::{serde_as, DisplayFromStr};
7use solana_program::keccak;
8use solana_pubkey::{ParsePubkeyError, Pubkey};
9use std::fmt::Display;
10use std::ops::Deref;
11use std::str::FromStr;
12
13use crate::rpc::ChainIndex;
14use crate::serde::{deserialize_pubkey_vec, serialize_pubkey_vec};
15use transaction::{InstructionWithIndex, TransactionToValidate};
16
17mod fee;
18mod gas;
19mod templates;
20
21pub mod config;
22pub use templates::insert_session_management_variations;
23pub mod transaction;
24
25pub enum ParsedTransactionVariation {
26    V0(VariationProgramWhitelist),
27    V1(ParsedVariationOrderedInstructionConstraints),
28}
29
30impl ParsedTransactionVariation {
31    pub fn name(&self) -> &str {
32        match self {
33            ParsedTransactionVariation::V0(v) => &v.name,
34            ParsedTransactionVariation::V1(v) => &v.name,
35        }
36    }
37
38    pub fn swap_into_fogo(&self) -> &[MintSwapRate] {
39        match self {
40            ParsedTransactionVariation::V0(_) => &[],
41            ParsedTransactionVariation::V1(v) => &v.swap_into_fogo,
42        }
43    }
44}
45
46#[derive(Serialize, Deserialize)]
47#[serde_as]
48pub struct VariationProgramWhitelist {
49    pub name: String,
50
51    #[serde(
52        deserialize_with = "deserialize_pubkey_vec",
53        serialize_with = "serialize_pubkey_vec"
54    )]
55    pub whitelisted_programs: Vec<Pubkey>,
56}
57
58impl VariationProgramWhitelist {
59    pub fn validate_transaction(
60        &self,
61        transaction: &TransactionToValidate<'_>,
62    ) -> Result<(), (StatusCode, String)> {
63        for instruction in transaction.message.instructions() {
64            let program_id = instruction.program_id(transaction.message.static_account_keys());
65            if !self.whitelisted_programs.contains(program_id) {
66                return Err((
67                    StatusCode::BAD_REQUEST,
68                    format!(
69                        "Transaction contains unauthorized program ID {program_id} for variation {}",
70                        self.name
71                    ),
72                ));
73            }
74        }
75        Ok(())
76    }
77}
78
79pub struct ParsedVariationOrderedInstructionConstraints {
80    pub name: String,
81    pub instructions: Vec<ParsedInstructionConstraint>,
82    pub max_gas_spend: u64,
83    pub paymaster_fee_lamports: Option<u64>,
84    pub swap_into_fogo: Vec<MintSwapRate>,
85}
86#[serde_as]
87#[derive(Clone, Serialize)]
88pub struct MintSwapRate {
89    #[serde_as(as = "DisplayFromStr")]
90    mint: Pubkey,
91    rate: f64,
92}
93
94impl MintSwapRate {
95    pub fn new(mint: Pubkey, rate: f64) -> Self {
96        Self {
97            mint,
98            rate: rate.clamp(0.0, 1.0),
99        }
100    }
101
102    pub fn mint(&self) -> Pubkey {
103        self.mint
104    }
105
106    pub fn rate(&self) -> f64 {
107        self.rate
108    }
109}
110
111#[serde_as]
112#[derive(Deserialize)]
113struct MintSwapRateRaw {
114    #[serde_as(as = "DisplayFromStr")]
115    mint: Pubkey,
116    rate: f64,
117}
118
119impl<'de> serde::Deserialize<'de> for MintSwapRate {
120    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
121    where
122        D: Deserializer<'de>,
123    {
124        let raw = MintSwapRateRaw::deserialize(deserializer)?;
125        Ok(MintSwapRate::new(raw.mint, raw.rate))
126    }
127}
128
129#[derive(Clone)]
130pub struct ContextualDomainKeys {
131    pub domain_registry: Pubkey,
132    pub sponsor: Pubkey,
133}
134
135impl ParsedVariationOrderedInstructionConstraints {
136    pub async fn validate_transaction(
137        &self,
138        transaction: &TransactionToValidate<'_>,
139        contextual_domain_keys: &ContextualDomainKeys,
140        chain_index: &ChainIndex,
141    ) -> Result<(), (StatusCode, String)> {
142        self.validate_compute_units(transaction)?;
143        self.validate_paymaster_fees(transaction)
144            .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
145        self.validate_instruction_constraints(transaction, contextual_domain_keys, chain_index)
146            .await
147    }
148
149    pub fn validate_compute_units(
150        &self,
151        transaction: &TransactionToValidate<'_>,
152    ) -> Result<(), (StatusCode, String)> {
153        if transaction.gas_spend > self.max_gas_spend {
154            return Err((
155                StatusCode::BAD_REQUEST,
156                format!(
157                    "Transaction gas spend {} exceeds maximum allowed {}",
158                    transaction.gas_spend, self.max_gas_spend
159                ),
160            ));
161        }
162        Ok(())
163    }
164
165    pub fn validate_paymaster_fees(
166        &self,
167        transaction: &TransactionToValidate<'_>,
168    ) -> anyhow::Result<()> {
169        anyhow::ensure!(
170            transaction.total_fee_lamports >= self.paymaster_fee_lamports.unwrap_or(0),
171            "Paymaster fee is not sufficient"
172        );
173
174        Ok(())
175    }
176
177    pub async fn validate_instruction_constraints(
178        &self,
179        transaction: &TransactionToValidate<'_>,
180        contextual_domain_keys: &ContextualDomainKeys,
181        chain_index: &ChainIndex,
182    ) -> Result<(), (StatusCode, String)> {
183        let mut substantive_instructions_iterator =
184            transaction.substantive_instructions.iter().peekable();
185
186        // Note: this validation algorithm is technically incorrect, because of optional constraints.
187        // E.g. instruction i might match against both constraint j and constraint j+1; if constraint j
188        // is optional, it might be possible that matching against j leads to failure due to later
189        // constraints failing while matching against j+1 would result in a valid transaction match.
190        // Technically, the correct way to validate this is via branching (efficiently via DP), but given
191        // the expected variation space and a desire to avoid complexity, we use this greedy approach.
192        for (constraint_index, constraint) in self.instructions.iter().enumerate() {
193            let constraint_validation_result = {
194                if let Some(instruction_with_index) = substantive_instructions_iterator.peek() {
195                    constraint
196                        .validate_instruction(
197                            transaction,
198                            instruction_with_index,
199                            contextual_domain_keys,
200                            &self.name,
201                            chain_index,
202                        )
203                        .await
204                } else {
205                    Err((
206                    StatusCode::BAD_REQUEST,
207                    format!(
208                        "Ran out of instructions while validating constraint {constraint_index} for variation {}",
209                        self.name
210                    ),
211                ))
212                }
213            };
214
215            match constraint_validation_result {
216                Ok(_) => {
217                    substantive_instructions_iterator.next();
218                }
219                Err(e) if constraint.required => {
220                    return Err(e);
221                }
222                Err(_) => {}
223            }
224        }
225
226        if let Some(InstructionWithIndex {
227            index,
228            instruction: _,
229        }) = substantive_instructions_iterator.peek()
230        {
231            return Err((
232                StatusCode::BAD_REQUEST,
233                format!(
234                    "Ran out of constraints while validating instruction {index} for variation {}",
235                    self.name
236                ),
237            ));
238        }
239
240        Ok(())
241    }
242}
243
244const NON_SUBSTANTIVE_PROGRAM_IDS: [Pubkey; 2] =
245    [solana_compute_budget_interface::id(), TOLLBOOTH_PROGRAM_ID];
246pub struct SubstantiveProgramId(Pubkey);
247
248impl Deref for SubstantiveProgramId {
249    type Target = Pubkey;
250    fn deref(&self) -> &Self::Target {
251        &self.0
252    }
253}
254
255impl Display for SubstantiveProgramId {
256    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        self.0.fmt(f)
258    }
259}
260
261pub enum ParseSubstantiveProgramIdError {
262    NonSubstantiveProgramId(Pubkey),
263    ParsePubkeyError(ParsePubkeyError),
264}
265
266impl From<ParsePubkeyError> for ParseSubstantiveProgramIdError {
267    fn from(error: ParsePubkeyError) -> Self {
268        ParseSubstantiveProgramIdError::ParsePubkeyError(error)
269    }
270}
271
272impl Display for ParseSubstantiveProgramIdError {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        match self {
275            ParseSubstantiveProgramIdError::NonSubstantiveProgramId(pubkey) => f.write_str(
276                format!("The program ID {pubkey} is not allowed to be used in V1 constraints")
277                    .as_str(),
278            ),
279            ParseSubstantiveProgramIdError::ParsePubkeyError(error) => error.fmt(f),
280        }
281    }
282}
283
284impl FromStr for SubstantiveProgramId {
285    type Err = ParseSubstantiveProgramIdError;
286    fn from_str(s: &str) -> Result<Self, Self::Err> {
287        let pubkey = Pubkey::from_str(s)?;
288        if NON_SUBSTANTIVE_PROGRAM_IDS.contains(&pubkey) {
289            return Err(ParseSubstantiveProgramIdError::NonSubstantiveProgramId(
290                pubkey,
291            ));
292        }
293        Ok(SubstantiveProgramId(pubkey))
294    }
295}
296
297pub struct ParsedInstructionConstraint {
298    pub program: SubstantiveProgramId,
299    pub accounts: Vec<AccountConstraint>,
300    pub data: Vec<ParsedDataConstraint>,
301    pub required: bool,
302}
303
304impl ParsedInstructionConstraint {
305    async fn validate_instruction(
306        &self,
307        transaction: &TransactionToValidate<'_>,
308        instruction_with_index: &InstructionWithIndex<'_>,
309        contextual_domain_keys: &ContextualDomainKeys,
310        variation_name: &str,
311        chain_index: &ChainIndex,
312    ) -> Result<(), (StatusCode, String)> {
313        let static_accounts = transaction.message.static_account_keys();
314        let signatures = &transaction.signatures;
315
316        let program_id = instruction_with_index
317            .instruction
318            .program_id(static_accounts);
319        if program_id != self.program.deref() {
320            return Err((
321                StatusCode::BAD_REQUEST,
322                format!(
323                    "Transaction instruction {} program ID {program_id} does not match expected ID {} for variation {variation_name}",
324                    instruction_with_index.index,
325                    self.program,
326                ),
327            ));
328        }
329
330        for account_constraint in &self.accounts {
331            let account_pubkey = chain_index
332                .resolve_instruction_account_pubkey(
333                    transaction.message,
334                    instruction_with_index,
335                    account_constraint.index.into(),
336                )
337                .await?;
338
339            let signers = static_accounts
340                .iter()
341                .take(signatures.len())
342                .cloned()
343                .collect::<Vec<_>>();
344            account_constraint
345                .check_account(
346                    &account_pubkey,
347                    signers,
348                    contextual_domain_keys,
349                    instruction_with_index.index,
350                )
351                .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
352        }
353
354        for data_constraint in &self.data {
355            data_constraint
356                .check_data(instruction_with_index)
357                .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
358        }
359
360        Ok(())
361    }
362}
363
364#[derive(Serialize, Deserialize)]
365pub struct AccountConstraint {
366    pub index: u16,
367    #[serde(default)]
368    pub include: Vec<ContextualPubkey>,
369    #[serde(default)]
370    pub exclude: Vec<ContextualPubkey>,
371}
372
373impl AccountConstraint {
374    fn check_account(
375        &self,
376        account: &Pubkey,
377        signers: Vec<Pubkey>,
378        contextual_domain_keys: &ContextualDomainKeys,
379        instruction_index: usize,
380    ) -> anyhow::Result<()> {
381        // excludes are AND-gated: all excludes must be satisfied
382        self.exclude.iter().try_for_each(|excluded| {
383            excluded.matches_account(
384                account,
385                &signers,
386                contextual_domain_keys,
387                false,
388                instruction_index,
389            )
390        })?;
391
392        // includes are OR-gated: at least one include must be satisfied
393        if !self.include.is_empty() {
394            let matches_any = self.include.iter().any(|included| {
395                included
396                    .matches_account(
397                        account,
398                        &signers,
399                        contextual_domain_keys,
400                        true,
401                        instruction_index,
402                    )
403                    .is_ok()
404            });
405
406            if !matches_any {
407                anyhow::bail!("Instruction {instruction_index}: Account {account} does not match any include constraints");
408            }
409        }
410
411        Ok(())
412    }
413}
414
415#[serde_as]
416#[derive(Serialize, Deserialize)]
417pub enum ContextualPubkey {
418    Explicit {
419        #[serde_as(as = "DisplayFromStr")]
420        pubkey: Pubkey,
421    },
422    Sponsor,
423    NonFeePayerSigner,
424    DomainRegistry,
425}
426
427impl ContextualPubkey {
428    fn matches_account(
429        &self,
430        account: &Pubkey,
431        signers: &[Pubkey],
432        contextual_domain_keys: &ContextualDomainKeys,
433        expect_include: bool,
434        instruction_index: usize,
435    ) -> anyhow::Result<()> {
436        match self {
437            ContextualPubkey::Explicit { pubkey } => {
438                if expect_include == (account == pubkey) {
439                    Ok(())
440                } else {
441                    Err(anyhow::anyhow!(if expect_include {
442                        format!("Instruction {instruction_index}: Account {account} is not explicitly included")
443                    } else {
444                        format!("Instruction {instruction_index}: Account {account} is explicitly excluded")
445                    },))
446                }
447            }
448
449            ContextualPubkey::NonFeePayerSigner => {
450                if expect_include == (signers.iter().skip(1).any(|s| s == account)) {
451                    Ok(())
452                } else {
453                    Err(anyhow::anyhow!(if expect_include {
454                        format!("Instruction {instruction_index}: Account {account} is not a non-fee-payer signer")
455                    } else {
456                        format!("Instruction {instruction_index}: Account {account} should be excluded as a non-fee-payer signer")
457                    },))
458                }
459            }
460
461            ContextualPubkey::Sponsor => {
462                if expect_include == (*account == contextual_domain_keys.sponsor) {
463                    Ok(())
464                } else {
465                    Err(anyhow::anyhow!(if expect_include {
466                        format!("Instruction {instruction_index}: Account {account} is not the sponsor account")
467                    } else {
468                        format!("Instruction {instruction_index}: Account {account} should be excluded as the sponsor account")
469                    },))
470                }
471            }
472
473            ContextualPubkey::DomainRegistry => {
474                if expect_include == (*account == contextual_domain_keys.domain_registry) {
475                    Ok(())
476                } else {
477                    Err(anyhow::anyhow!(if expect_include {
478                        format!("Instruction {instruction_index}: Account {account} is not the domain registry account")
479                    } else {
480                        format!("Instruction {instruction_index}: Account {account} should be excluded as the domain registry account")
481                    },))
482                }
483            }
484        }
485    }
486}
487
488pub struct ParsedDataConstraint {
489    pub start_byte: u16,
490    pub constraint: ParsedDataConstraintSpecification,
491}
492
493impl ParsedDataConstraint {
494    fn check_data(
495        &self,
496        InstructionWithIndex {
497            index: instruction_index,
498            instruction,
499        }: &InstructionWithIndex<'_>,
500    ) -> anyhow::Result<()> {
501        let length = self.constraint.byte_length();
502        let end_byte = length + usize::from(self.start_byte);
503        if end_byte > instruction.data.len() {
504            anyhow::bail!(
505                "Instruction {instruction_index}: Data constraint byte range {}-{} is out of bounds for data length {}",
506                self.start_byte,
507                end_byte - 1,
508                instruction.data.len()
509            );
510        }
511
512        let mut data_to_analyze = instruction
513            .data
514            .get(usize::from(self.start_byte)..end_byte)
515            .expect("We checked instruction.data.length is greater than end_byte");
516        let check_result = match &self.constraint {
517            ParsedDataConstraintSpecification::Bool(constraint) => {
518                let value = *data_to_analyze
519                    .first()
520                    .expect("data_to_analyze has length 1 if data_type is Bool")
521                    != 0;
522                constraint.check(value)
523            }
524            ParsedDataConstraintSpecification::U8(constraint) => {
525                let value = *data_to_analyze
526                    .first()
527                    .expect("data_to_analyze has length 1 if data_type is U8");
528                constraint.check(value)
529            }
530            ParsedDataConstraintSpecification::U16(constraint) => {
531                let value = u16::from_le_bytes((*data_to_analyze).try_into().map_err(|_| {
532                    anyhow::anyhow!(
533                        "Data constraint expects 2 bytes for U16, found {} bytes",
534                        data_to_analyze.len()
535                    )
536                })?);
537                constraint.check(value)
538            }
539            ParsedDataConstraintSpecification::U32(constraint) => {
540                let value = u32::from_le_bytes((*data_to_analyze).try_into().map_err(|_| {
541                    anyhow::anyhow!(
542                        "Data constraint expects 4 bytes for U32, found {} bytes",
543                        data_to_analyze.len()
544                    )
545                })?);
546                constraint.check(value)
547            }
548            ParsedDataConstraintSpecification::U64(constraint) => {
549                let value = u64::from_le_bytes((*data_to_analyze).try_into().map_err(|_| {
550                    anyhow::anyhow!(
551                        "Data constraint expects 8 bytes for U64, found {} bytes",
552                        data_to_analyze.len()
553                    )
554                })?);
555                constraint.check(value)
556            }
557            ParsedDataConstraintSpecification::Pubkey(constraint) => {
558                let value =
559                    Pubkey::new_from_array((*data_to_analyze).try_into().map_err(|_| {
560                        anyhow::anyhow!(
561                            "Data constraint expects 32 bytes for Pubkey, found {} bytes",
562                            data_to_analyze.len()
563                        )
564                    })?);
565                constraint.check(value)
566            }
567            ParsedDataConstraintSpecification::Bytes(constraint) => {
568                constraint.check(data_to_analyze)
569            }
570            ParsedDataConstraintSpecification::NttSignedQuoter(constraint) => {
571                let signed_quote = SignedQuote::deserialize(&mut data_to_analyze)
572                    .map_err(|e| anyhow::anyhow!("Failed to deserialize NTT SignedQuote: {e}"))?;
573                let recovered_quoter = recover_signer_pubkey(signed_quote)?;
574                constraint.check(NttSignedQuoter(recovered_quoter))
575            }
576        };
577        check_result.map_err(|err| {
578            anyhow::anyhow!("Instruction {instruction_index}: Data constraint not satisfied: {err}")
579        })?;
580
581        Ok(())
582    }
583}
584
585pub enum ParsedDataConstraintSpecification {
586    U8(IntegerConstraint<u8>),
587    U16(IntegerConstraint<u16>),
588    U32(IntegerConstraint<u32>),
589    U64(IntegerConstraint<u64>),
590    Bool(ScalarConstraint<bool>),
591    Pubkey(ScalarConstraint<Pubkey>),
592    Bytes(BytesConstraint),
593    NttSignedQuoter(ScalarConstraint<NttSignedQuoter>),
594}
595
596impl ParsedDataConstraintSpecification {
597    fn byte_length(&self) -> usize {
598        match self {
599            ParsedDataConstraintSpecification::U8(_) => 1,
600            ParsedDataConstraintSpecification::U16(_) => 2,
601            ParsedDataConstraintSpecification::U32(_) => 4,
602            ParsedDataConstraintSpecification::U64(_) => 8,
603            ParsedDataConstraintSpecification::Bool(_) => 1,
604            ParsedDataConstraintSpecification::Pubkey(_) => 32,
605            ParsedDataConstraintSpecification::Bytes(BytesConstraint::EqualTo {
606                length, ..
607            })
608            | ParsedDataConstraintSpecification::Bytes(BytesConstraint::Neq { length, .. }) => {
609                *length
610            }
611            ParsedDataConstraintSpecification::NttSignedQuoter(_) => 165,
612        }
613    }
614}
615
616pub enum IntegerConstraint<T> {
617    LessThan(T),
618    GreaterThan(T),
619    EqualTo(Vec<T>),
620    Neq(Vec<T>),
621}
622
623pub enum ScalarConstraint<T> {
624    EqualTo(Vec<T>),
625    Neq(Vec<T>),
626}
627
628pub enum BytesConstraint {
629    EqualTo { length: usize, values: Vec<Vec<u8>> },
630    Neq { length: usize, values: Vec<Vec<u8>> },
631}
632
633fn recover_signer_pubkey(signed_quote: SignedQuote) -> anyhow::Result<H160> {
634    let message_body = signed_quote
635        .try_get_message_body()
636        .map_err(|e| anyhow::anyhow!("Failed to extract message from signed quote: {e}"))?;
637
638    let message = libsecp256k1::Message::parse(&keccak::hash(&message_body).0);
639
640    let (signature, recovery_index) = signed_quote.try_get_signature_components().map_err(|e| {
641        anyhow::anyhow!("Failed to extract signature components from signed quote: {e}")
642    })?;
643    let sig = libsecp256k1::Signature::parse_standard_slice(signature)
644        .map_err(|e| anyhow::anyhow!("Invalid signature: {e}"))?;
645    let recovery_id = libsecp256k1::RecoveryId::parse_rpc(recovery_index)
646        .map_err(|e| anyhow::anyhow!("Invalid recovery index in signature: {e}"))?;
647
648    let secp_pubkey = libsecp256k1::recover(&message, &sig, &recovery_id)
649        .map_err(|e| anyhow::anyhow!("Failed to recover secp256k1 public key: {e}"))?;
650    let secp_pubkey_serialized = secp_pubkey.serialize();
651    let pubkey_hashed = keccak::hash(
652        secp_pubkey_serialized
653            .get(1..)
654            .expect("Serialized key should be 65 bytes"),
655    );
656    let evm_address = pubkey_hashed
657        .0
658        .get(12..)
659        .expect("Hash should be 32 bytes")
660        .try_into()
661        .expect("Slice of 20 bytes should convert to H160");
662
663    if evm_address != signed_quote.header.quoter_address {
664        anyhow::bail!("Recovered quoter address does not match stated quoter address");
665    };
666
667    Ok(evm_address)
668}
669
670#[derive(Clone, Copy, PartialEq, Eq)]
671pub struct NttSignedQuoter([u8; 20]);
672
673impl Serialize for NttSignedQuoter {
674    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
675    where
676        S: Serializer,
677    {
678        serializer.serialize_str(&format!("0x{}", hex::encode(self.0)))
679    }
680}
681
682impl<'de> Deserialize<'de> for NttSignedQuoter {
683    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
684    where
685        D: Deserializer<'de>,
686    {
687        let s = <String as serde::Deserialize>::deserialize(deserializer)?;
688        let hex_part = s.strip_prefix("0x").unwrap_or(&s);
689        let bytes = hex::decode(hex_part)
690            .map_err(|e| serde::de::Error::custom(format!("Invalid hex string {hex_part}: {e}")))?;
691        let arr: [u8; 20] = bytes.try_into().map_err(|_| {
692            serde::de::Error::custom(
693                "Failed to convert bytes to H160 address: invalid byte array length",
694            )
695        })?;
696        Ok(NttSignedQuoter(arr))
697    }
698}
699
700impl<T: PartialOrd + PartialEq> IntegerConstraint<T> {
701    fn check(&self, value: T) -> anyhow::Result<()> {
702        match self {
703            IntegerConstraint::LessThan(expected) => {
704                if value < *expected {
705                    Ok(())
706                } else {
707                    anyhow::bail!("Constraint not met")
708                }
709            }
710            IntegerConstraint::GreaterThan(expected) => {
711                if value > *expected {
712                    Ok(())
713                } else {
714                    anyhow::bail!("Constraint not met")
715                }
716            }
717            IntegerConstraint::EqualTo(values) => check_equal_to(values, |v| v == &value),
718            IntegerConstraint::Neq(values) => check_neq(values, |v| v == &value),
719        }
720    }
721}
722
723impl<T: PartialEq> ScalarConstraint<T> {
724    fn check(&self, value: T) -> anyhow::Result<()> {
725        match self {
726            ScalarConstraint::EqualTo(values) => check_equal_to(values, |v| v == &value),
727            ScalarConstraint::Neq(values) => check_neq(values, |v| v == &value),
728        }
729    }
730}
731
732impl BytesConstraint {
733    fn check(&self, value: &[u8]) -> anyhow::Result<()> {
734        match self {
735            BytesConstraint::EqualTo { values, .. } => {
736                check_equal_to(values, |v| v.as_slice() == value)
737            }
738            BytesConstraint::Neq { values, .. } => check_neq(values, |v| v.as_slice() == value),
739        }
740    }
741}
742
743fn check_equal_to<T, F>(values: &[T], matches: F) -> anyhow::Result<()>
744where
745    F: Fn(&T) -> bool,
746{
747    if values.iter().any(matches) {
748        Ok(())
749    } else {
750        anyhow::bail!("No matching value found")
751    }
752}
753
754fn check_neq<T, F>(values: &[T], matches: F) -> anyhow::Result<()>
755where
756    F: Fn(&T) -> bool,
757{
758    if values.iter().any(matches) {
759        anyhow::bail!("Value matches an excluded value")
760    } else {
761        Ok(())
762    }
763}