casper-storage 2.1.1

Storage for a node on the Casper network.
Documentation
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
use crate::{
    global_state::{error::Error as GlobalStateReader, state::StateReader},
    tracking_copy::{TrackingCopyEntityExt, TrackingCopyError, TrackingCopyExt},
    AddressGenerator, TrackingCopy,
};
use casper_types::{
    account::AccountHash, contracts::NamedKeys, Chainspec, ContextAccessRights, EntityAddr,
    FeeHandling, Key, Phase, ProtocolVersion, PublicKey, RefundHandling, RuntimeFootprint,
    StoredValue, TransactionHash, Transfer, URef, U512,
};
use num_rational::Ratio;
use parking_lot::RwLock;
use std::{cell::RefCell, collections::BTreeSet, rc::Rc, sync::Arc};
use tracing::error;

/// Configuration settings.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Config {
    transfer_config: TransferConfig,
    fee_handling: FeeHandling,
    refund_handling: RefundHandling,
    vesting_schedule_period_millis: u64,
    allow_auction_bids: bool,
    compute_rewards: bool,
    max_delegators_per_validator: u32,
    minimum_bid_amount: u64,
    minimum_delegation_amount: u64,
    balance_hold_interval: u64,
    include_credits: bool,
    credit_cap: Ratio<U512>,
    enable_addressable_entity: bool,
    native_transfer_cost: u32,
}

impl Config {
    /// Ctor.
    #[allow(clippy::too_many_arguments)]
    pub const fn new(
        transfer_config: TransferConfig,
        fee_handling: FeeHandling,
        refund_handling: RefundHandling,
        vesting_schedule_period_millis: u64,
        allow_auction_bids: bool,
        compute_rewards: bool,
        max_delegators_per_validator: u32,
        minimum_bid_amount: u64,
        minimum_delegation_amount: u64,
        balance_hold_interval: u64,
        include_credits: bool,
        credit_cap: Ratio<U512>,
        enable_addressable_entity: bool,
        native_transfer_cost: u32,
    ) -> Self {
        Config {
            transfer_config,
            fee_handling,
            refund_handling,
            vesting_schedule_period_millis,
            allow_auction_bids,
            compute_rewards,
            max_delegators_per_validator,
            minimum_bid_amount,
            minimum_delegation_amount,
            balance_hold_interval,
            include_credits,
            credit_cap,
            enable_addressable_entity,
            native_transfer_cost,
        }
    }

    /// Ctor from chainspec.
    pub fn from_chainspec(chainspec: &Chainspec) -> Self {
        let transfer_config = TransferConfig::from_chainspec(chainspec);
        let fee_handling = chainspec.core_config.fee_handling;
        let refund_handling = chainspec.core_config.refund_handling;
        let vesting_schedule_period_millis = chainspec.core_config.vesting_schedule_period.millis();
        let allow_auction_bids = chainspec.core_config.allow_auction_bids;
        let compute_rewards = chainspec.core_config.compute_rewards;
        let max_delegators_per_validator = chainspec.core_config.max_delegators_per_validator;
        let minimum_bid_amount = chainspec.core_config.minimum_bid_amount;
        let minimum_delegation_amount = chainspec.core_config.minimum_delegation_amount;
        let balance_hold_interval = chainspec.core_config.gas_hold_interval.millis();
        let include_credits = chainspec.core_config.fee_handling == FeeHandling::NoFee;
        let credit_cap = Ratio::new_raw(
            U512::from(*chainspec.core_config.validator_credit_cap.numer()),
            U512::from(*chainspec.core_config.validator_credit_cap.denom()),
        );
        let enable_addressable_entity = chainspec.core_config.enable_addressable_entity;
        let native_transfer_cost = chainspec.system_costs_config.mint_costs().transfer;
        Config::new(
            transfer_config,
            fee_handling,
            refund_handling,
            vesting_schedule_period_millis,
            allow_auction_bids,
            compute_rewards,
            max_delegators_per_validator,
            minimum_bid_amount,
            minimum_delegation_amount,
            balance_hold_interval,
            include_credits,
            credit_cap,
            enable_addressable_entity,
            native_transfer_cost,
        )
    }

    /// Returns transfer config.
    pub fn transfer_config(&self) -> &TransferConfig {
        &self.transfer_config
    }

    /// Returns fee handling setting.
    pub fn fee_handling(&self) -> &FeeHandling {
        &self.fee_handling
    }

    /// Returns refund handling setting.
    pub fn refund_handling(&self) -> &RefundHandling {
        &self.refund_handling
    }

    /// Returns vesting schedule period millis setting.
    pub fn vesting_schedule_period_millis(&self) -> u64 {
        self.vesting_schedule_period_millis
    }

    /// Returns if auction bids are allowed.
    pub fn allow_auction_bids(&self) -> bool {
        self.allow_auction_bids
    }

    /// Returns if rewards should be computed.
    pub fn compute_rewards(&self) -> bool {
        self.compute_rewards
    }

    /// Returns max delegators per validator setting.
    pub fn max_delegators_per_validator(&self) -> u32 {
        self.max_delegators_per_validator
    }

    /// Returns minimum bid amount setting.
    pub fn minimum_bid_amount(&self) -> u64 {
        self.minimum_bid_amount
    }

    /// Returns minimum delegation amount setting.
    pub fn minimum_delegation_amount(&self) -> u64 {
        self.minimum_delegation_amount
    }

    /// Returns balance hold interval setting.
    pub fn balance_hold_interval(&self) -> u64 {
        self.balance_hold_interval
    }

    /// Returns include credit setting.
    pub fn include_credits(&self) -> bool {
        self.include_credits
    }

    /// Returns validator credit cap setting.
    pub fn credit_cap(&self) -> Ratio<U512> {
        self.credit_cap
    }

    /// Enable the addressable entity and migrate accounts/contracts to entities.
    pub fn enable_addressable_entity(&self) -> bool {
        self.enable_addressable_entity
    }

    /// Changes the transfer config.
    pub fn set_transfer_config(self, transfer_config: TransferConfig) -> Self {
        Config {
            transfer_config,
            fee_handling: self.fee_handling,
            refund_handling: self.refund_handling,
            vesting_schedule_period_millis: self.vesting_schedule_period_millis,
            max_delegators_per_validator: self.max_delegators_per_validator,
            allow_auction_bids: self.allow_auction_bids,
            minimum_bid_amount: self.minimum_bid_amount,
            minimum_delegation_amount: self.minimum_delegation_amount,
            compute_rewards: self.compute_rewards,
            balance_hold_interval: self.balance_hold_interval,
            include_credits: self.include_credits,
            credit_cap: self.credit_cap,
            enable_addressable_entity: self.enable_addressable_entity,
            native_transfer_cost: self.native_transfer_cost,
        }
    }
}

/// Configuration for transfer.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum TransferConfig {
    /// Transfers are affected by the existence of administrative_accounts. This is a
    /// behavior specific to private or managed chains, not a public chain.
    Administered {
        /// Retrusn the set of account hashes for all administrators.
        administrative_accounts: BTreeSet<AccountHash>,
        /// If true, transfers are unrestricted.
        /// If false, the source and / or target of a transfer must be an administrative account.
        allow_unrestricted_transfers: bool,
    },
    /// Transfers are not affected by the existence of administrative_accounts (the standard
    /// behavior).
    #[default]
    Unadministered,
}

impl TransferConfig {
    /// Returns a new instance.
    pub fn new(
        administrative_accounts: BTreeSet<AccountHash>,
        allow_unrestricted_transfers: bool,
    ) -> Self {
        if administrative_accounts.is_empty() && allow_unrestricted_transfers {
            TransferConfig::Unadministered
        } else {
            TransferConfig::Administered {
                administrative_accounts,
                allow_unrestricted_transfers,
            }
        }
    }

    /// New instance from chainspec.
    pub fn from_chainspec(chainspec: &Chainspec) -> Self {
        let administrative_accounts: BTreeSet<AccountHash> = chainspec
            .core_config
            .administrators
            .iter()
            .map(|x| x.to_account_hash())
            .collect();
        let allow_unrestricted_transfers = chainspec.core_config.allow_unrestricted_transfers;
        if administrative_accounts.is_empty() && allow_unrestricted_transfers {
            TransferConfig::Unadministered
        } else {
            TransferConfig::Administered {
                administrative_accounts,
                allow_unrestricted_transfers,
            }
        }
    }

    /// Does account hash belong to an administrative account?
    pub fn is_administrator(&self, account_hash: &AccountHash) -> bool {
        match self {
            TransferConfig::Administered {
                administrative_accounts,
                ..
            } => administrative_accounts.contains(account_hash),
            TransferConfig::Unadministered => false,
        }
    }

    /// Administrative accounts, if any.
    pub fn administrative_accounts(&self) -> BTreeSet<AccountHash> {
        match self {
            TransferConfig::Administered {
                administrative_accounts,
                ..
            } => administrative_accounts.clone(),
            TransferConfig::Unadministered => BTreeSet::default(),
        }
    }

    /// Allow unrestricted transfers.
    pub fn allow_unrestricted_transfers(&self) -> bool {
        match self {
            TransferConfig::Administered {
                allow_unrestricted_transfers,
                ..
            } => *allow_unrestricted_transfers,
            TransferConfig::Unadministered => true,
        }
    }

    /// Restricted transfer should be enforced.
    pub fn enforce_transfer_restrictions(&self, account_hash: &AccountHash) -> bool {
        !self.allow_unrestricted_transfers() && !self.is_administrator(account_hash)
    }
}

/// Id for runtime processing.
pub enum Id {
    /// Hash of current transaction.
    Transaction(TransactionHash),
    /// An arbitrary set of bytes to be used as a seed value.
    Seed(Vec<u8>),
}

impl Id {
    /// Ctor for id enum.
    pub fn seed(&self) -> Vec<u8> {
        match self {
            Id::Transaction(hash) => hash.digest().into_vec(),
            Id::Seed(bytes) => bytes.clone(),
        }
    }
}

/// State held by an instance of runtime native.
pub struct RuntimeNative<S> {
    config: Config,

    id: Id,
    address_generator: Arc<RwLock<AddressGenerator>>,
    protocol_version: ProtocolVersion,

    tracking_copy: Rc<RefCell<TrackingCopy<S>>>,
    address: AccountHash,
    context_key: Key,
    runtime_footprint: RuntimeFootprint,
    access_rights: ContextAccessRights,
    remaining_spending_limit: U512,
    transfers: Vec<Transfer>,
    phase: Phase,
}

impl<S> RuntimeNative<S>
where
    S: StateReader<Key, StoredValue, Error = GlobalStateReader>,
{
    /// Ctor.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        config: Config,
        protocol_version: ProtocolVersion,
        id: Id,
        address_generator: Arc<RwLock<AddressGenerator>>,
        tracking_copy: Rc<RefCell<TrackingCopy<S>>>,
        address: AccountHash,
        context_key: Key,
        runtime_footprint: RuntimeFootprint,
        access_rights: ContextAccessRights,
        remaining_spending_limit: U512,
        phase: Phase,
    ) -> Self {
        let transfers = vec![];
        RuntimeNative {
            config,

            id,
            address_generator,
            protocol_version,

            tracking_copy,
            address,
            context_key,
            runtime_footprint,
            access_rights,
            remaining_spending_limit,
            transfers,
            phase,
        }
    }

    /// Creates a runtime with elevated permissions for systemic behaviors.
    pub fn new_system_runtime(
        config: Config,
        protocol_version: ProtocolVersion,
        id: Id,
        address_generator: Arc<RwLock<AddressGenerator>>,
        tracking_copy: Rc<RefCell<TrackingCopy<S>>>,
        phase: Phase,
    ) -> Result<Self, TrackingCopyError> {
        let transfers = vec![];
        let (entity_addr, runtime_footprint, access_rights) = tracking_copy
            .borrow_mut()
            .system_entity_runtime_footprint(protocol_version)?;
        let address = PublicKey::System.to_account_hash();
        let context_key = if config.enable_addressable_entity {
            Key::AddressableEntity(entity_addr)
        } else {
            Key::Hash(entity_addr.value())
        };
        let remaining_spending_limit = U512::MAX; // system has no spending limit
        Ok(RuntimeNative {
            config,
            id,
            address_generator,
            protocol_version,

            tracking_copy,
            address,
            context_key,
            runtime_footprint,
            access_rights,
            remaining_spending_limit,
            transfers,
            phase,
        })
    }

    /// Creates a runtime context for a system contract.
    pub fn new_system_contract_runtime(
        config: Config,
        protocol_version: ProtocolVersion,
        id: Id,
        address_generator: Arc<RwLock<AddressGenerator>>,
        tracking_copy: Rc<RefCell<TrackingCopy<S>>>,
        phase: Phase,
        name: &str,
    ) -> Result<Self, TrackingCopyError> {
        let transfers = vec![];

        let system_entity_registry = tracking_copy.borrow().get_system_entity_registry()?;
        let hash = match system_entity_registry.get(name).copied() {
            Some(hash) => hash,
            None => {
                error!("unexpected failure; system contract {} not found", name);
                return Err(TrackingCopyError::MissingSystemContractHash(
                    name.to_string(),
                ));
            }
        };
        let context_key = if config.enable_addressable_entity {
            Key::AddressableEntity(EntityAddr::System(hash))
        } else {
            Key::Hash(hash)
        };
        let runtime_footprint = tracking_copy
            .borrow_mut()
            .runtime_footprint_by_hash_addr(hash)?;
        let access_rights = runtime_footprint.extract_access_rights(hash);
        let address = PublicKey::System.to_account_hash();
        let remaining_spending_limit = U512::MAX; // system has no spending limit
        Ok(RuntimeNative {
            config,
            id,
            address_generator,
            protocol_version,

            tracking_copy,
            address,
            context_key,
            runtime_footprint,
            access_rights,
            remaining_spending_limit,
            transfers,
            phase,
        })
    }

    /// Returns mutable reference to address generator.
    pub fn address_generator(&mut self) -> Arc<RwLock<AddressGenerator>> {
        Arc::clone(&self.address_generator)
    }

    /// Returns reference to config.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Returns reference to transfer config.
    pub fn transfer_config(&self) -> &TransferConfig {
        &self.config.transfer_config
    }

    /// Returns protocol version.
    pub fn protocol_version(&self) -> ProtocolVersion {
        self.protocol_version
    }

    /// Returns handle to tracking copy.
    pub fn tracking_copy(&self) -> Rc<RefCell<TrackingCopy<S>>> {
        Rc::clone(&self.tracking_copy)
    }

    /// Returns account hash being used by this instance.
    pub fn address(&self) -> AccountHash {
        self.address
    }

    /// Changes the account hash being used by this instance.
    pub fn with_address(&mut self, account_hash: AccountHash) {
        self.address = account_hash;
    }

    /// Returns the context key being used by this instance.
    pub fn context_key(&self) -> &Key {
        &self.context_key
    }

    /// Returns a reference to the runtime footprint used by this instance.
    pub fn runtime_footprint(&self) -> &RuntimeFootprint {
        &self.runtime_footprint
    }

    /// Returns the addressable entity being used by this instance.
    pub fn runtime_footprint_mut(&mut self) -> &mut RuntimeFootprint {
        &mut self.runtime_footprint
    }

    /// Changes the addressable entity being used by this instance.
    pub fn with_addressable_entity(&mut self, runtime_footprint: RuntimeFootprint) {
        self.runtime_footprint = runtime_footprint;
    }

    /// Returns a reference to the named keys being used by this instance.
    pub fn named_keys(&self) -> &NamedKeys {
        self.runtime_footprint().named_keys()
    }

    /// Returns a mutable reference to the named keys being used by this instance.
    pub fn named_keys_mut(&mut self) -> &mut NamedKeys {
        self.runtime_footprint.named_keys_mut()
    }

    /// Returns a reference to the access rights being used by this instance.
    pub fn access_rights(&self) -> &ContextAccessRights {
        &self.access_rights
    }

    /// Returns a mutable reference to the access rights being used by this instance.
    pub fn access_rights_mut(&mut self) -> &mut ContextAccessRights {
        &mut self.access_rights
    }

    /// Extends the access rights being used by this instance.
    pub fn extend_access_rights(&mut self, urefs: &[URef]) {
        self.access_rights.extend(urefs)
    }

    /// Returns the remaining spending limit.
    pub fn remaining_spending_limit(&self) -> U512 {
        self.remaining_spending_limit
    }

    /// Set remaining spending limit.
    pub fn set_remaining_spending_limit(&mut self, remaining: U512) {
        self.remaining_spending_limit = remaining;
    }

    /// Get references to transfers.
    pub fn transfers(&self) -> &Vec<Transfer> {
        &self.transfers
    }

    /// Push transfer instance.
    pub fn push_transfer(&mut self, transfer: Transfer) {
        self.transfers.push(transfer);
    }

    /// Get id.
    pub fn id(&self) -> &Id {
        &self.id
    }

    /// Get phase.
    pub fn phase(&self) -> Phase {
        self.phase
    }

    /// Vesting schedule period in milliseconds.
    pub fn vesting_schedule_period_millis(&self) -> u64 {
        self.config.vesting_schedule_period_millis
    }

    /// Are auction bids allowed?
    pub fn allow_auction_bids(&self) -> bool {
        self.config.allow_auction_bids
    }

    /// Are rewards computed?
    pub fn compute_rewards(&self) -> bool {
        self.config.compute_rewards
    }

    /// Extracts transfer items.
    pub fn into_transfers(self) -> Vec<Transfer> {
        self.transfers
    }

    pub(crate) fn native_transfer_cost(&self) -> u32 {
        self.config.native_transfer_cost
    }
}