1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use crate::blueprints::resource::*;
use crate::types::*;
use crate::*;
use radix_engine_common::data::manifest::model::ManifestAddressReservation;
use radix_engine_common::data::manifest::model::ManifestBlobRef;
use radix_engine_interface::api::node_modules::metadata::MetadataInit;
use sbor::basic_well_known_types::ANY_TYPE;
use sbor::rust::prelude::*;
use sbor::LocalTypeId;
use scrypto_schema::TypeRef;
use scrypto_schema::{BlueprintCollectionSchema, BlueprintKeyValueSchema, FunctionSchemaInit};
use scrypto_schema::{BlueprintFunctionsSchemaInit, ReceiverInfo};
use scrypto_schema::{BlueprintSchemaInit, BlueprintStateSchemaInit, FieldSchema};

pub const PACKAGE_BLUEPRINT: &str = "Package";

pub const PACKAGE_PUBLISH_WASM_IDENT: &str = "publish_wasm";

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestSbor)]
pub struct PackagePublishWasmInput {
    pub definition: PackageDefinition,
    pub code: Vec<u8>,
    pub metadata: MetadataInit,
}

#[derive(Debug, Clone, Eq, PartialEq, ManifestSbor)]
pub struct PackagePublishWasmManifestInput {
    pub definition: PackageDefinition,
    pub code: ManifestBlobRef,
    pub metadata: MetadataInit,
}

pub type PackagePublishWasmOutput = (PackageAddress, Bucket);

pub const PACKAGE_PUBLISH_WASM_ADVANCED_IDENT: &str = "publish_wasm_advanced";

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor)]
pub struct PackagePublishWasmAdvancedInput {
    pub owner_role: OwnerRole,
    pub definition: PackageDefinition,
    pub code: Vec<u8>,
    pub metadata: MetadataInit,
    pub package_address: Option<GlobalAddressReservation>,
}

#[derive(Debug, Clone, Eq, PartialEq, ManifestSbor)]
pub struct PackagePublishWasmAdvancedManifestInput {
    pub owner_role: OwnerRole,
    pub definition: PackageDefinition,
    pub code: ManifestBlobRef,
    pub metadata: MetadataInit,
    pub package_address: Option<ManifestAddressReservation>,
}

pub type PackagePublishWasmAdvancedOutput = PackageAddress;

pub const PACKAGE_PUBLISH_NATIVE_IDENT: &str = "publish_native";

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor)]
pub struct PackagePublishNativeInput {
    pub definition: PackageDefinition,
    pub native_package_code_id: u64,
    pub metadata: MetadataInit,
    pub package_address: Option<GlobalAddressReservation>,
}

#[derive(Debug, Clone, Eq, PartialEq, ManifestSbor)]
pub struct PackagePublishNativeManifestInput {
    pub definition: PackageDefinition,
    pub native_package_code_id: u64,
    pub metadata: MetadataInit,
    pub package_address: Option<ManifestAddressReservation>,
}

pub type PackagePublishNativeOutput = PackageAddress;

pub const PACKAGE_CLAIM_ROYALTIES_IDENT: &str = "PackageRoyalty_claim_royalties";

#[cfg_attr(
    feature = "radix_engine_fuzzing",
    derive(arbitrary::Arbitrary, serde::Serialize, serde::Deserialize)
)]
#[derive(
    Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestCategorize, ManifestEncode, ManifestDecode,
)]
pub struct PackageClaimRoyaltiesInput {}

pub type PackageClaimRoyaltiesOutput = Bucket;

#[derive(Debug, Clone, Eq, PartialEq, Default, ScryptoSbor, ManifestSbor)]
pub struct PackageDefinition {
    pub blueprints: IndexMap<String, BlueprintDefinitionInit>,
}

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestSbor)]
pub enum BlueprintType {
    Outer,
    Inner { outer_blueprint: String },
}

impl Default for BlueprintType {
    fn default() -> Self {
        BlueprintType::Outer
    }
}

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestSbor)]
pub struct BlueprintDefinitionInit {
    pub blueprint_type: BlueprintType,
    pub is_transient: bool,
    pub feature_set: IndexSet<String>,
    pub dependencies: IndexSet<GlobalAddress>,
    pub schema: BlueprintSchemaInit,
    pub royalty_config: PackageRoyaltyConfig,
    pub auth_config: AuthConfig,
}

impl Default for BlueprintDefinitionInit {
    fn default() -> Self {
        Self {
            blueprint_type: BlueprintType::default(),
            is_transient: false,
            feature_set: IndexSet::default(),
            dependencies: IndexSet::default(),
            schema: BlueprintSchemaInit::default(),
            royalty_config: PackageRoyaltyConfig::default(),
            auth_config: AuthConfig::default(),
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Default, ScryptoSbor, ManifestSbor)]
pub struct AuthConfig {
    pub function_auth: FunctionAuth,
    pub method_auth: MethodAuthTemplate,
}

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestSbor)]
pub enum FunctionAuth {
    /// All functions are accessible
    AllowAll,
    /// Functions are protected by an access rule
    AccessRules(IndexMap<String, AccessRule>),
    /// Only the root call frame may call all functions.
    /// Used primarily for transaction processor functions, any other use would
    /// essentially make the function inaccessible for any normal transaction
    RootOnly,
}

impl Default for FunctionAuth {
    fn default() -> Self {
        FunctionAuth::AllowAll
    }
}

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestSbor)]
pub enum MethodAuthTemplate {
    /// All methods are accessible
    AllowAll,
    /// Methods are protected by a static method to roles mapping
    StaticRoleDefinition(StaticRoleDefinition),
}

impl Default for MethodAuthTemplate {
    fn default() -> Self {
        MethodAuthTemplate::AllowAll
    }
}

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestSbor)]
pub enum RoleSpecification {
    /// Roles are specified in the current blueprint and defined in the instantiated object.
    Normal(IndexMap<RoleKey, RoleList>),
    /// Roles are specified in the *outer* blueprint and defined in the instantiated *outer* object.
    /// This may only be used by inner blueprints and is currently used by the Vault blueprints
    UseOuter,
}

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, ManifestSbor)]
pub struct StaticRoleDefinition {
    pub roles: RoleSpecification,
    pub methods: IndexMap<MethodKey, MethodAccessibility>,
}

impl Default for StaticRoleDefinition {
    fn default() -> Self {
        Self {
            methods: index_map_new(),
            roles: RoleSpecification::Normal(index_map_new()),
        }
    }
}

impl PackageDefinition {
    // For testing only
    pub fn new_single_function_test_definition(
        blueprint_name: &str,
        function_name: &str,
    ) -> PackageDefinition {
        Self::new_functions_only_test_definition(
            blueprint_name,
            vec![(
                function_name,
                format!("{}_{}", blueprint_name, function_name).as_str(),
                false,
            )],
        )
    }

    // For testing only
    pub fn new_roles_only_test_definition(
        blueprint_name: &str,
        roles: IndexMap<RoleKey, RoleList>,
    ) -> PackageDefinition {
        let mut blueprints = index_map_new();
        blueprints.insert(
            blueprint_name.to_string(),
            BlueprintDefinitionInit {
                auth_config: AuthConfig {
                    function_auth: FunctionAuth::AllowAll,
                    method_auth: MethodAuthTemplate::StaticRoleDefinition(StaticRoleDefinition {
                        roles: RoleSpecification::Normal(roles),
                        ..Default::default()
                    }),
                },
                ..Default::default()
            },
        );
        PackageDefinition { blueprints }
    }

    // For testing only
    pub fn new_functions_only_test_definition(
        blueprint_name: &str,
        functions: Vec<(&str, &str, bool)>,
    ) -> PackageDefinition {
        let mut blueprints = index_map_new();
        blueprints.insert(
            blueprint_name.to_string(),
            BlueprintDefinitionInit {
                schema: BlueprintSchemaInit {
                    functions: BlueprintFunctionsSchemaInit {
                        functions: functions
                            .into_iter()
                            .map(|(function_name, export_name, has_receiver)| {
                                let schema = FunctionSchemaInit {
                                    receiver: if has_receiver {
                                        Some(ReceiverInfo::normal_ref())
                                    } else {
                                        None
                                    },
                                    input: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                    output: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                    export: export_name.to_string(),
                                };
                                (function_name.to_string(), schema)
                            })
                            .collect(),
                    },
                    ..Default::default()
                },
                ..Default::default()
            },
        );
        PackageDefinition { blueprints }
    }

    // For testing only
    pub fn new_with_fields_test_definition(
        blueprint_name: &str,
        num_fields: usize,
        functions: Vec<(&str, &str, bool)>,
    ) -> PackageDefinition {
        let mut blueprints = index_map_new();
        blueprints.insert(
            blueprint_name.to_string(),
            BlueprintDefinitionInit {
                schema: BlueprintSchemaInit {
                    state: BlueprintStateSchemaInit {
                        fields: (0..num_fields)
                            .map(|_| FieldSchema::static_field(LocalTypeId::WellKnown(ANY_TYPE)))
                            .collect(),
                        ..Default::default()
                    },
                    functions: BlueprintFunctionsSchemaInit {
                        functions: functions
                            .into_iter()
                            .map(|(function_name, export_name, has_receiver)| {
                                let schema = FunctionSchemaInit {
                                    receiver: if has_receiver {
                                        Some(ReceiverInfo::normal_ref())
                                    } else {
                                        None
                                    },
                                    input: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                    output: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                    export: export_name.to_string(),
                                };
                                (function_name.to_string(), schema)
                            })
                            .collect(),
                        ..Default::default()
                    },
                    ..Default::default()
                },
                ..Default::default()
            },
        );
        PackageDefinition { blueprints }
    }

    pub fn new_with_field_test_definition(
        blueprint_name: &str,
        functions: Vec<(&str, &str, bool)>,
    ) -> PackageDefinition {
        Self::new_with_fields_test_definition(blueprint_name, 1, functions)
    }

    // For testing only
    pub fn new_with_kv_collection_test_definition(
        blueprint_name: &str,
        functions: Vec<(&str, &str, bool)>,
    ) -> PackageDefinition {
        let mut blueprints = index_map_new();
        blueprints.insert(
            blueprint_name.to_string(),
            BlueprintDefinitionInit {
                schema: BlueprintSchemaInit {
                    state: BlueprintStateSchemaInit {
                        collections: vec![BlueprintCollectionSchema::KeyValueStore(
                            BlueprintKeyValueSchema {
                                key: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                value: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                allow_ownership: true,
                            },
                        )],
                        ..Default::default()
                    },
                    functions: BlueprintFunctionsSchemaInit {
                        functions: functions
                            .into_iter()
                            .map(|(function_name, export_name, has_receiver)| {
                                let schema = FunctionSchemaInit {
                                    receiver: if has_receiver {
                                        Some(ReceiverInfo::normal_ref())
                                    } else {
                                        None
                                    },
                                    input: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                    output: TypeRef::Static(LocalTypeId::WellKnown(ANY_TYPE)),
                                    export: export_name.to_string(),
                                };
                                (function_name.to_string(), schema)
                            })
                            .collect(),
                        ..Default::default()
                    },
                    ..Default::default()
                },
                ..Default::default()
            },
        );
        PackageDefinition { blueprints }
    }
}