radix_engine/system/
payload_validation.rs

1use crate::errors::RuntimeError;
2use crate::internal_prelude::*;
3use radix_common::constants::*;
4use radix_engine_interface::blueprints::resource::{
5    FUNGIBLE_BUCKET_BLUEPRINT, FUNGIBLE_PROOF_BLUEPRINT, NON_FUNGIBLE_BUCKET_BLUEPRINT,
6    NON_FUNGIBLE_PROOF_BLUEPRINT,
7};
8use sbor::rust::prelude::*;
9use sbor::traversal::TerminalValueRef;
10
11use super::system::SystemService;
12use super::system_callback::*;
13use super::type_info::TypeInfoSubstate;
14
15//=======================================================================================================
16// NOTE:
17// The validation implemented here makes use of a type info lookup to provide tighter validation
18// There is also static validation defined in the `radix-common` repository which is less
19// powerful, does not require this lookup.
20//=======================================================================================================
21
22//==================
23// TRAITS
24//==================
25
26/// We use a trait here so it can be implemented either by the System API (mid-execution) or by off-ledger systems
27pub trait ValidationContext {
28    type Error;
29
30    fn get_node_type_info(&self, node_id: &NodeId) -> Result<TypeInfoForValidation, Self::Error>;
31
32    fn schema_origin(&self) -> &SchemaOrigin;
33
34    fn allow_ownership(&self) -> bool;
35
36    fn allow_non_global_ref(&self) -> bool;
37}
38
39#[derive(Debug, Clone)]
40pub enum SchemaOrigin {
41    Blueprint(BlueprintId),
42    Instance,
43    KeyValueStore,
44}
45
46//==================
47// SYSTEM ADAPTERS
48//==================
49
50pub struct SystemServiceTypeInfoLookup<'s, 'a, Y: SystemBasedKernelApi> {
51    system_service: RefCell<&'s mut SystemService<'a, Y>>,
52    schema_origin: SchemaOrigin,
53    allow_ownership: bool,
54    allow_non_global_ref: bool,
55}
56
57impl<'s, 'a, Y: SystemBasedKernelApi> SystemServiceTypeInfoLookup<'s, 'a, Y> {
58    pub fn new(
59        system_service: &'s mut SystemService<'a, Y>,
60        schema_origin: SchemaOrigin,
61        allow_ownership: bool,
62        allow_non_global_ref: bool,
63    ) -> Self {
64        Self {
65            system_service: system_service.into(),
66            schema_origin,
67            allow_ownership,
68            allow_non_global_ref,
69        }
70    }
71}
72
73impl<'s, 'a, Y: SystemBasedKernelApi> ValidationContext for SystemServiceTypeInfoLookup<'s, 'a, Y> {
74    type Error = RuntimeError;
75
76    fn get_node_type_info(&self, node_id: &NodeId) -> Result<TypeInfoForValidation, RuntimeError> {
77        let type_info = self
78            .system_service
79            .borrow_mut()
80            .get_node_type_info(node_id)?;
81        let mapped = match type_info {
82            TypeInfoSubstate::Object(ObjectInfo {
83                blueprint_info: BlueprintInfo { blueprint_id, .. },
84                ..
85            }) => TypeInfoForValidation::Object {
86                package: blueprint_id.package_address,
87                blueprint: blueprint_id.blueprint_name,
88            },
89            TypeInfoSubstate::KeyValueStore(_) => TypeInfoForValidation::KeyValueStore,
90            TypeInfoSubstate::GlobalAddressReservation(_) => {
91                TypeInfoForValidation::GlobalAddressReservation
92            }
93            TypeInfoSubstate::GlobalAddressPhantom(info) => TypeInfoForValidation::Object {
94                package: info.blueprint_id.package_address,
95                blueprint: info.blueprint_id.blueprint_name,
96            },
97        };
98        Ok(mapped)
99    }
100
101    fn schema_origin(&self) -> &SchemaOrigin {
102        &self.schema_origin
103    }
104
105    fn allow_ownership(&self) -> bool {
106        self.allow_ownership
107    }
108
109    fn allow_non_global_ref(&self) -> bool {
110        self.allow_non_global_ref
111    }
112}
113
114#[derive(Debug, Clone)]
115pub enum TypeInfoForValidation {
116    Object {
117        package: PackageAddress,
118        blueprint: String,
119    },
120    KeyValueStore,
121    GlobalAddressReservation,
122}
123
124impl TypeInfoForValidation {
125    fn matches(&self, expected_package: &PackageAddress, expected_blueprint: &str) -> bool {
126        matches!(
127            self,
128            TypeInfoForValidation::Object { package, blueprint }
129                if package == expected_package && blueprint == expected_blueprint
130        )
131    }
132
133    fn matches_with_origin(
134        &self,
135        expected_package: &Option<PackageAddress>,
136        expected_blueprint: &str,
137        schema_origin: &SchemaOrigin,
138    ) -> bool {
139        match expected_package {
140            Some(package_address) => self.matches(package_address, expected_blueprint),
141            None => match schema_origin {
142                SchemaOrigin::Blueprint(blueprint_id) => {
143                    self.matches(&blueprint_id.package_address, expected_blueprint)
144                }
145                SchemaOrigin::Instance | SchemaOrigin::KeyValueStore => false,
146            },
147        }
148    }
149}
150
151//==================
152// VALIDATION
153//==================
154
155type Lookup<'a, E> = Box<dyn ValidationContext<Error = E> + 'a>;
156
157impl<'a, E: Debug> ValidatableCustomExtension<Lookup<'a, E>> for ScryptoCustomExtension {
158    fn apply_validation_for_custom_value<'de>(
159        schema: &Schema<Self::CustomSchema>,
160        custom_value: &<Self::CustomTraversal as traversal::CustomTraversal>::CustomTerminalValueRef<'de>,
161        type_id: LocalTypeId,
162        context: &Lookup<'a, E>,
163    ) -> Result<(), PayloadValidationError<Self>> {
164        match &custom_value.0 {
165            ScryptoCustomValue::Own(..) => {
166                if !context.allow_ownership() {
167                    return Err(PayloadValidationError::ValidationError(
168                        ValidationError::CustomError("Ownership is not allowed".to_string()),
169                    ));
170                }
171            }
172            ScryptoCustomValue::Reference(reference) => {
173                if !reference.0.is_global() && !context.allow_non_global_ref() {
174                    return Err(PayloadValidationError::ValidationError(
175                        ValidationError::CustomError(
176                            "Non Global Reference is not allowed".to_string(),
177                        ),
178                    ));
179                }
180            }
181            _ => {}
182        }
183
184        match schema
185            .resolve_type_validation(type_id)
186            .ok_or(PayloadValidationError::SchemaInconsistency)?
187        {
188            TypeValidation::None => Ok(()),
189            TypeValidation::Custom(custom_validation) => {
190                apply_custom_validation_to_custom_value(custom_validation, &custom_value.0, context)
191            }
192            _ => Err(PayloadValidationError::SchemaInconsistency),
193        }
194    }
195
196    fn apply_custom_type_validation_for_non_custom_value<'de>(
197        _: &Schema<Self::CustomSchema>,
198        _: &<Self::CustomSchema as CustomSchema>::CustomTypeValidation,
199        _: &TerminalValueRef<'de, Self::CustomTraversal>,
200        _: &Lookup<'a, E>,
201    ) -> Result<(), PayloadValidationError<Self>> {
202        // Non-custom values must have non-custom type kinds...
203        // But custom type validations aren't allowed to combine with non-custom type kinds
204        Err(PayloadValidationError::SchemaInconsistency)
205    }
206}
207
208fn apply_custom_validation_to_custom_value<E: Debug>(
209    custom_validation: &ScryptoCustomTypeValidation,
210    custom_value: &ScryptoCustomValue,
211    lookup: &Lookup<E>,
212) -> Result<(), PayloadValidationError<ScryptoCustomExtension>> {
213    match custom_validation {
214        ScryptoCustomTypeValidation::Reference(reference_validation) => {
215            let ScryptoCustomValue::Reference(reference) = custom_value else {
216                return Err(PayloadValidationError::SchemaInconsistency);
217            };
218            let node_id = reference.0;
219            let type_info = resolve_type_info(&node_id, lookup)?;
220            let is_valid = match &reference_validation {
221                ReferenceValidation::IsGlobal => node_id.is_global(),
222                ReferenceValidation::IsGlobalPackage => node_id.is_global_package(),
223                ReferenceValidation::IsGlobalComponent => node_id.is_global_component(),
224                ReferenceValidation::IsGlobalResourceManager => {
225                    node_id.is_global_resource_manager()
226                }
227                ReferenceValidation::IsGlobalTyped(expected_package, expected_blueprint) => {
228                    node_id.is_global()
229                        && type_info.matches_with_origin(
230                            expected_package,
231                            expected_blueprint,
232                            lookup.schema_origin(),
233                        )
234                }
235                ReferenceValidation::IsInternal => node_id.is_internal(),
236                ReferenceValidation::IsInternalTyped(expected_package, expected_blueprint) => {
237                    node_id.is_internal()
238                        && type_info.matches_with_origin(
239                            expected_package,
240                            expected_blueprint,
241                            lookup.schema_origin(),
242                        )
243                }
244            };
245            if !is_valid {
246                return Err(PayloadValidationError::ValidationError(
247                    ValidationError::CustomError(format!(
248                        "Expected = Reference<{:?}>, actual node: {:?}, resolved type info: {:?}",
249                        reference_validation, node_id, type_info
250                    )),
251                ));
252            }
253        }
254        ScryptoCustomTypeValidation::Own(own_validation) => {
255            let ScryptoCustomValue::Own(own) = custom_value else {
256                return Err(PayloadValidationError::SchemaInconsistency);
257            };
258
259            let node_id = own.0;
260            let type_info = resolve_type_info(&node_id, lookup)?;
261            let is_valid = match own_validation {
262                OwnValidation::IsBucket => {
263                    type_info.matches(&RESOURCE_PACKAGE, FUNGIBLE_BUCKET_BLUEPRINT)
264                        || type_info.matches(&RESOURCE_PACKAGE, NON_FUNGIBLE_BUCKET_BLUEPRINT)
265                }
266                OwnValidation::IsProof => {
267                    type_info.matches(&RESOURCE_PACKAGE, FUNGIBLE_PROOF_BLUEPRINT)
268                        || type_info.matches(&RESOURCE_PACKAGE, NON_FUNGIBLE_PROOF_BLUEPRINT)
269                }
270                OwnValidation::IsVault => node_id.is_internal_vault(),
271                OwnValidation::IsKeyValueStore => node_id.is_internal_kv_store(),
272                OwnValidation::IsGlobalAddressReservation => {
273                    matches!(type_info, TypeInfoForValidation::GlobalAddressReservation)
274                }
275                OwnValidation::IsTypedObject(expected_package, expected_blueprint) => type_info
276                    .matches_with_origin(
277                        expected_package,
278                        expected_blueprint,
279                        lookup.schema_origin(),
280                    ),
281            };
282            if !is_valid {
283                return Err(PayloadValidationError::ValidationError(
284                    ValidationError::CustomError(format!(
285                        "Expected = Own<{:?}>, actual node: {:?}, resolved type info: {:?}",
286                        own_validation, node_id, type_info
287                    )),
288                ));
289            }
290        }
291    };
292    Ok(())
293}
294
295fn resolve_type_info<E: Debug>(
296    node_id: &NodeId,
297    lookup: &Lookup<E>,
298) -> Result<TypeInfoForValidation, PayloadValidationError<ScryptoCustomExtension>> {
299    lookup.get_node_type_info(node_id).map_err(|e| {
300        PayloadValidationError::ValidationError(ValidationError::CustomError(format!("{:?}", e)))
301    })
302}