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(format!("Ownership is not allowed")),
169                    ));
170                }
171            }
172            ScryptoCustomValue::Reference(reference) => {
173                if !reference.0.is_global() {
174                    if !context.allow_non_global_ref() {
175                        return Err(PayloadValidationError::ValidationError(
176                            ValidationError::CustomError(format!(
177                                "Non Global Reference is not allowed"
178                            )),
179                        ));
180                    }
181                }
182            }
183            _ => {}
184        }
185
186        match schema
187            .resolve_type_validation(type_id)
188            .ok_or(PayloadValidationError::SchemaInconsistency)?
189        {
190            TypeValidation::None => Ok(()),
191            TypeValidation::Custom(custom_validation) => {
192                apply_custom_validation_to_custom_value(custom_validation, &custom_value.0, context)
193            }
194            _ => Err(PayloadValidationError::SchemaInconsistency),
195        }
196    }
197
198    fn apply_custom_type_validation_for_non_custom_value<'de>(
199        _: &Schema<Self::CustomSchema>,
200        _: &<Self::CustomSchema as CustomSchema>::CustomTypeValidation,
201        _: &TerminalValueRef<'de, Self::CustomTraversal>,
202        _: &Lookup<'a, E>,
203    ) -> Result<(), PayloadValidationError<Self>> {
204        // Non-custom values must have non-custom type kinds...
205        // But custom type validations aren't allowed to combine with non-custom type kinds
206        Err(PayloadValidationError::SchemaInconsistency)
207    }
208}
209
210fn apply_custom_validation_to_custom_value<E: Debug>(
211    custom_validation: &ScryptoCustomTypeValidation,
212    custom_value: &ScryptoCustomValue,
213    lookup: &Lookup<E>,
214) -> Result<(), PayloadValidationError<ScryptoCustomExtension>> {
215    match custom_validation {
216        ScryptoCustomTypeValidation::Reference(reference_validation) => {
217            let ScryptoCustomValue::Reference(reference) = custom_value else {
218                return Err(PayloadValidationError::SchemaInconsistency);
219            };
220            let node_id = reference.0;
221            let type_info = resolve_type_info(&node_id, lookup)?;
222            let is_valid = match &reference_validation {
223                ReferenceValidation::IsGlobal => node_id.is_global(),
224                ReferenceValidation::IsGlobalPackage => node_id.is_global_package(),
225                ReferenceValidation::IsGlobalComponent => node_id.is_global_component(),
226                ReferenceValidation::IsGlobalResourceManager => {
227                    node_id.is_global_resource_manager()
228                }
229                ReferenceValidation::IsGlobalTyped(expected_package, expected_blueprint) => {
230                    node_id.is_global()
231                        && type_info.matches_with_origin(
232                            expected_package,
233                            expected_blueprint,
234                            lookup.schema_origin(),
235                        )
236                }
237                ReferenceValidation::IsInternal => node_id.is_internal(),
238                ReferenceValidation::IsInternalTyped(expected_package, expected_blueprint) => {
239                    node_id.is_internal()
240                        && type_info.matches_with_origin(
241                            expected_package,
242                            expected_blueprint,
243                            lookup.schema_origin(),
244                        )
245                }
246            };
247            if !is_valid {
248                return Err(PayloadValidationError::ValidationError(
249                    ValidationError::CustomError(format!(
250                        "Expected = Reference<{:?}>, actual node: {:?}, resolved type info: {:?}",
251                        reference_validation, node_id, type_info
252                    )),
253                ));
254            }
255        }
256        ScryptoCustomTypeValidation::Own(own_validation) => {
257            let ScryptoCustomValue::Own(own) = custom_value else {
258                return Err(PayloadValidationError::SchemaInconsistency);
259            };
260
261            let node_id = own.0;
262            let type_info = resolve_type_info(&node_id, lookup)?;
263            let is_valid = match own_validation {
264                OwnValidation::IsBucket => {
265                    type_info.matches(&RESOURCE_PACKAGE, FUNGIBLE_BUCKET_BLUEPRINT)
266                        || type_info.matches(&RESOURCE_PACKAGE, NON_FUNGIBLE_BUCKET_BLUEPRINT)
267                }
268                OwnValidation::IsProof => {
269                    type_info.matches(&RESOURCE_PACKAGE, FUNGIBLE_PROOF_BLUEPRINT)
270                        || type_info.matches(&RESOURCE_PACKAGE, NON_FUNGIBLE_PROOF_BLUEPRINT)
271                }
272                OwnValidation::IsVault => node_id.is_internal_vault(),
273                OwnValidation::IsKeyValueStore => node_id.is_internal_kv_store(),
274                OwnValidation::IsGlobalAddressReservation => {
275                    matches!(type_info, TypeInfoForValidation::GlobalAddressReservation)
276                }
277                OwnValidation::IsTypedObject(expected_package, expected_blueprint) => type_info
278                    .matches_with_origin(
279                        expected_package,
280                        expected_blueprint,
281                        lookup.schema_origin(),
282                    ),
283            };
284            if !is_valid {
285                return Err(PayloadValidationError::ValidationError(
286                    ValidationError::CustomError(format!(
287                        "Expected = Own<{:?}>, actual node: {:?}, resolved type info: {:?}",
288                        own_validation, node_id, type_info
289                    )),
290                ));
291            }
292        }
293    };
294    Ok(())
295}
296
297fn resolve_type_info<E: Debug>(
298    node_id: &NodeId,
299    lookup: &Lookup<E>,
300) -> Result<TypeInfoForValidation, PayloadValidationError<ScryptoCustomExtension>> {
301    lookup.get_node_type_info(node_id).map_err(|e| {
302        PayloadValidationError::ValidationError(ValidationError::CustomError(format!("{:?}", e)))
303    })
304}