casper_types/
runtime_footprint.rs

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
use crate::{
    account::AccountHash,
    addressable_entity::{AssociatedKeys, Weight},
    contracts::{ContractHash, NamedKeys},
    system::SystemEntityType,
    Account, AddressableEntity, ContextAccessRights, Contract, EntityAddr, EntityKind, EntryPoints,
    HashAddr, Key, ProtocolVersion, TransactionRuntime, URef,
};
use alloc::{
    collections::{BTreeMap, BTreeSet},
    string::String,
};
use core::{fmt::Debug, iter};
#[cfg(feature = "datasize")]
use datasize::DataSize;
#[cfg(feature = "json-schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Runtime Address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
pub enum RuntimeAddress {
    /// Account address
    Hash(HashAddr),
    /// Runtime executable address.
    StoredContract {
        /// The hash addr of the runtime entity
        hash_addr: HashAddr,
        /// The package hash
        package_hash_addr: HashAddr,
        /// The wasm hash
        wasm_hash_addr: HashAddr,
        /// protocol version
        protocol_version: ProtocolVersion,
    },
}

impl RuntimeAddress {
    /// Returns a new hash
    pub fn new_hash(hash_addr: HashAddr) -> Self {
        Self::Hash(hash_addr)
    }

    /// Returns new stored contract
    pub fn new_stored_contract(
        hash_addr: HashAddr,
        package_hash_addr: HashAddr,
        wasm_hash_addr: HashAddr,
        protocol_version: ProtocolVersion,
    ) -> Self {
        Self::StoredContract {
            hash_addr,
            package_hash_addr,
            wasm_hash_addr,
            protocol_version,
        }
    }

    /// The hash addr for the runtime.
    pub fn hash_addr(&self) -> HashAddr {
        match self {
            RuntimeAddress::Hash(hash_addr) => *hash_addr,
            RuntimeAddress::StoredContract { hash_addr, .. } => *hash_addr,
        }
    }
}

#[repr(u8)]
#[allow(clippy::enum_variant_names)]
pub(crate) enum Action {
    KeyManagement = 0,
    DeployManagement,
    UpgradeManagement,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
pub struct RuntimeFootprint {
    named_keys: NamedKeys,
    action_thresholds: BTreeMap<u8, Weight>,
    associated_keys: AssociatedKeys,
    entry_points: EntryPoints,
    entity_kind: EntityKind,

    main_purse: Option<URef>,
    runtime_address: RuntimeAddress,
}

impl RuntimeFootprint {
    pub fn new(
        named_keys: NamedKeys,
        action_thresholds: BTreeMap<u8, Weight>,
        associated_keys: AssociatedKeys,
        entry_points: EntryPoints,
        entity_kind: EntityKind,
        main_purse: Option<URef>,
        runtime_address: RuntimeAddress,
    ) -> Self {
        Self {
            named_keys,
            action_thresholds,
            associated_keys,
            entry_points,
            entity_kind,
            main_purse,
            runtime_address,
        }
    }

    pub fn new_account_footprint(account: Account) -> Self {
        let named_keys = account.named_keys().clone();
        let action_thresholds = {
            let mut ret = BTreeMap::new();
            ret.insert(
                Action::KeyManagement as u8,
                Weight::new(account.action_thresholds().key_management.value()),
            );
            ret.insert(
                Action::DeployManagement as u8,
                Weight::new(account.action_thresholds().deployment.value()),
            );
            ret
        };
        let associated_keys = account.associated_keys().clone().into();
        let entry_points = EntryPoints::new();
        let entity_kind = EntityKind::Account(account.account_hash());
        let main_purse = Some(account.main_purse());
        let runtime_address = RuntimeAddress::new_hash(account.account_hash().value());

        Self::new(
            named_keys,
            action_thresholds,
            associated_keys,
            entry_points,
            entity_kind,
            main_purse,
            runtime_address,
        )
    }

    pub fn new_contract_footprint(
        contract_hash: ContractHash,
        contract: Contract,
        system_entity_type: Option<SystemEntityType>,
    ) -> Self {
        let contract_package_hash = contract.contract_package_hash();
        let contract_wasm_hash = contract.contract_wasm_hash();
        let entry_points = contract.entry_points().clone().into();
        let protocol_version = contract.protocol_version();
        let named_keys = contract.take_named_keys();

        let runtime_address = RuntimeAddress::new_stored_contract(
            contract_hash.value(),
            contract_package_hash.value(),
            contract_wasm_hash.value(),
            protocol_version,
        );

        let main_purse = None;
        let action_thresholds = BTreeMap::new();
        let associated_keys = AssociatedKeys::empty_keys();

        let entity_kind = match system_entity_type {
            None => EntityKind::SmartContract(TransactionRuntime::VmCasperV1),
            Some(kind) => EntityKind::System(kind),
        };

        Self::new(
            named_keys,
            action_thresholds,
            associated_keys,
            entry_points,
            entity_kind,
            main_purse,
            runtime_address,
        )
    }

    pub fn new_entity_footprint(
        entity_addr: EntityAddr,
        entity: AddressableEntity,
        named_keys: NamedKeys,
        entry_points: EntryPoints,
    ) -> Self {
        let runtime_address = RuntimeAddress::new_stored_contract(
            entity_addr.value(),
            entity.package_hash().value(),
            entity.byte_code_hash().value(),
            entity.protocol_version(),
        );
        let action_thresholds = {
            let mut ret = BTreeMap::new();
            ret.insert(
                Action::KeyManagement as u8,
                entity.action_thresholds().key_management,
            );
            ret.insert(
                Action::DeployManagement as u8,
                entity.action_thresholds().key_management,
            );
            ret.insert(
                Action::UpgradeManagement as u8,
                entity.action_thresholds().upgrade_management,
            );
            ret
        };
        Self::new(
            named_keys,
            action_thresholds,
            entity.associated_keys().clone(),
            entry_points,
            entity.entity_kind(),
            Some(entity.main_purse()),
            runtime_address,
        )
    }

    pub fn package_hash(&self) -> Option<HashAddr> {
        match &self.runtime_address {
            RuntimeAddress::Hash(_) => None,
            RuntimeAddress::StoredContract {
                package_hash_addr, ..
            } => Some(*package_hash_addr),
        }
    }

    pub fn associated_keys(&self) -> &AssociatedKeys {
        &self.associated_keys
    }

    pub fn wasm_hash(&self) -> Option<HashAddr> {
        match &self.runtime_address {
            RuntimeAddress::Hash(_) => None,
            RuntimeAddress::StoredContract { wasm_hash_addr, .. } => Some(*wasm_hash_addr),
        }
    }

    pub fn hash_addr(&self) -> HashAddr {
        match &self.runtime_address {
            RuntimeAddress::Hash(hash_addr) => *hash_addr,
            RuntimeAddress::StoredContract { hash_addr, .. } => *hash_addr,
        }
    }

    pub fn named_keys(&self) -> &NamedKeys {
        &self.named_keys
    }

    pub fn insert_into_named_keys(&mut self, name: String, key: Key) {
        self.named_keys.insert(name, key);
    }

    pub fn named_keys_mut(&mut self) -> &mut NamedKeys {
        &mut self.named_keys
    }

    pub fn take_named_keys(self) -> NamedKeys {
        self.named_keys
    }

    pub fn main_purse(&self) -> Option<URef> {
        self.main_purse
    }

    pub fn set_main_purse(&mut self, purse: URef) {
        self.main_purse = Some(purse);
    }

    pub fn entry_points(&self) -> &EntryPoints {
        &self.entry_points
    }

    pub fn entity_kind(&self) -> EntityKind {
        self.entity_kind
    }

    /// Checks whether all authorization keys are associated with this addressable entity.
    pub fn can_authorize(&self, authorization_keys: &BTreeSet<AccountHash>) -> bool {
        !authorization_keys.is_empty()
            && authorization_keys
                .iter()
                .any(|e| self.associated_keys.contains_key(e))
    }

    /// Checks whether the sum of the weights of all authorization keys is
    /// greater or equal to key management threshold.
    pub fn can_manage_keys_with(&self, authorization_keys: &BTreeSet<AccountHash>) -> bool {
        let total_weight = self
            .associated_keys
            .calculate_keys_weight(authorization_keys);

        match self.action_thresholds.get(&(Action::KeyManagement as u8)) {
            None => false,
            Some(weight) => total_weight >= *weight,
        }
    }

    /// Checks whether the sum of the weights of all authorization keys is
    /// greater or equal to deploy threshold.
    pub fn can_deploy_with(&self, authorization_keys: &BTreeSet<AccountHash>) -> bool {
        let total_weight = self
            .associated_keys
            .calculate_keys_weight(authorization_keys);

        match self
            .action_thresholds
            .get(&(Action::DeployManagement as u8))
        {
            None => false,
            Some(weight) => total_weight >= *weight,
        }
    }

    pub fn can_upgrade_with(&self, authorization_keys: &BTreeSet<AccountHash>) -> bool {
        let total_weight = self
            .associated_keys
            .calculate_keys_weight(authorization_keys);

        match self
            .action_thresholds
            .get(&(Action::UpgradeManagement as u8))
        {
            None => false,
            Some(weight) => total_weight >= *weight,
        }
    }

    /// Extracts the access rights from the named keys of the addressable entity.
    pub fn extract_access_rights(&self, hash_addr: HashAddr) -> ContextAccessRights {
        match self.main_purse {
            Some(purse) => {
                let urefs_iter = self
                    .named_keys
                    .keys()
                    .filter_map(|key| key.as_uref().copied())
                    .chain(iter::once(purse));
                ContextAccessRights::new(hash_addr, urefs_iter)
            }
            None => {
                let urefs_iter = self
                    .named_keys
                    .keys()
                    .filter_map(|key| key.as_uref().copied());
                ContextAccessRights::new(hash_addr, urefs_iter)
            }
        }
    }
}