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
use std::collections::BTreeSet;

use serde::Serialize;
use thiserror::Error;
use tracing::error;

use casper_types::{
    account::AccountHash,
    bytesrepr::FromBytes,
    execution::Effects,
    system::{
        auction,
        auction::{DelegationRate, DelegatorKind, Reservation},
    },
    CLTyped, CLValue, CLValueError, Chainspec, Digest, InitiatorAddr, ProtocolVersion, PublicKey,
    RuntimeArgs, TransactionEntryPoint, TransactionHash, Transfer, URefAddr, U512,
};

use crate::{
    system::runtime_native::Config as NativeRuntimeConfig, tracking_copy::TrackingCopyError,
};

/// An error returned when constructing an [`AuctionMethod`].
#[derive(Clone, Eq, PartialEq, Error, Serialize, Debug)]
pub enum AuctionMethodError {
    /// Provided entry point is not one of the Auction ones.
    #[error("invalid entry point for auction: {0}")]
    InvalidEntryPoint(TransactionEntryPoint),
    /// Required arg missing.
    #[error("missing '{0}' arg")]
    MissingArg(String),
    /// Failed to parse the given arg.
    #[error("failed to parse '{arg}' arg: {error}")]
    CLValue {
        /// The arg name.
        arg: String,
        /// The failure.
        error: CLValueError,
    },
}

/// Auction method to interact with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuctionMethod {
    /// Activate bid.
    ActivateBid {
        /// Validator public key (must match initiating address).
        validator: PublicKey,
    },
    /// Add bid.
    AddBid {
        /// Validator public key (must match initiating address).
        public_key: PublicKey,
        /// Delegation rate for this validator bid.
        delegation_rate: DelegationRate,
        /// Bid amount.
        amount: U512,
        /// Minimum delegation amount for this validator bid.
        minimum_delegation_amount: u64,
        /// Maximum delegation amount for this validator bid.
        maximum_delegation_amount: u64,
        /// The minimum bid amount a validator must submit to have
        /// their bid considered as valid.
        minimum_bid_amount: u64,
        /// Number of delegator slots which can be reserved for specific delegators
        reserved_slots: u32,
    },
    /// Withdraw bid.
    WithdrawBid {
        /// Validator public key.
        public_key: PublicKey,
        /// Bid amount.
        amount: U512,
        /// The minimum bid amount a validator, if a validator reduces their stake
        /// below this amount, then it is treated as a complete withdrawal.
        minimum_bid_amount: u64,
    },
    /// Delegate to validator.
    Delegate {
        /// Delegator public key.
        delegator: DelegatorKind,
        /// Validator public key.
        validator: PublicKey,
        /// Delegation amount.
        amount: U512,
        /// Max delegators per validator.
        max_delegators_per_validator: u32,
    },
    /// Undelegate from validator.
    Undelegate {
        /// Delegator public key.
        delegator: DelegatorKind,
        /// Validator public key.
        validator: PublicKey,
        /// Undelegation amount.
        amount: U512,
    },
    /// Undelegate from validator and attempt delegation to new validator after unbonding delay
    /// elapses.
    Redelegate {
        /// Delegator public key.
        delegator: DelegatorKind,
        /// Validator public key.
        validator: PublicKey,
        /// Redelegation amount.
        amount: U512,
        /// New validator public key.
        new_validator: PublicKey,
    },
    /// Change the public key associated with a validator to a different public key.
    ChangeBidPublicKey {
        /// Current public key.
        public_key: PublicKey,
        /// New public key.
        new_public_key: PublicKey,
    },
    /// Add delegator slot reservations.
    AddReservations {
        /// List of reservations.
        reservations: Vec<Reservation>,
    },
    /// Remove delegator slot reservations for delegators with specified public keys.
    CancelReservations {
        /// Validator public key.
        validator: PublicKey,
        /// List of delegator public keys.
        delegators: Vec<DelegatorKind>,
        /// Max delegators per validator.
        max_delegators_per_validator: u32,
    },
}

impl AuctionMethod {
    /// Form auction method from parts.
    pub fn from_parts(
        entry_point: TransactionEntryPoint,
        runtime_args: &RuntimeArgs,
        chainspec: &Chainspec,
    ) -> Result<Self, AuctionMethodError> {
        match entry_point {
            TransactionEntryPoint::Call
            | TransactionEntryPoint::Custom(_)
            | TransactionEntryPoint::Transfer
            | TransactionEntryPoint::Burn => {
                Err(AuctionMethodError::InvalidEntryPoint(entry_point))
            }
            TransactionEntryPoint::ActivateBid => Self::new_activate_bid(runtime_args),
            TransactionEntryPoint::AddBid => Self::new_add_bid(
                runtime_args,
                chainspec.core_config.minimum_delegation_amount,
                chainspec.core_config.maximum_delegation_amount,
                chainspec.core_config.minimum_bid_amount,
            ),
            TransactionEntryPoint::WithdrawBid => {
                Self::new_withdraw_bid(runtime_args, chainspec.core_config.minimum_bid_amount)
            }
            TransactionEntryPoint::Delegate => Self::new_delegate(
                runtime_args,
                chainspec.core_config.max_delegators_per_validator,
            ),
            TransactionEntryPoint::Undelegate => Self::new_undelegate(runtime_args),
            TransactionEntryPoint::Redelegate => Self::new_redelegate(runtime_args),
            TransactionEntryPoint::ChangeBidPublicKey => {
                Self::new_change_bid_public_key(runtime_args)
            }
            TransactionEntryPoint::AddReservations => Self::new_add_reservations(runtime_args),
            TransactionEntryPoint::CancelReservations => Self::new_cancel_reservations(
                runtime_args,
                chainspec.core_config.max_delegators_per_validator,
            ),
        }
    }

    fn new_activate_bid(runtime_args: &RuntimeArgs) -> Result<Self, AuctionMethodError> {
        let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
        Ok(Self::ActivateBid { validator })
    }

    fn new_add_bid(
        runtime_args: &RuntimeArgs,
        global_minimum_delegation: u64,
        global_maximum_delegation: u64,
        global_minimum_bid_amount: u64,
    ) -> Result<Self, AuctionMethodError> {
        let public_key = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
        let delegation_rate = Self::get_named_argument(runtime_args, auction::ARG_DELEGATION_RATE)?;
        let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
        let minimum_delegation_amount =
            Self::get_named_argument(runtime_args, auction::ARG_MINIMUM_DELEGATION_AMOUNT)
                .unwrap_or(global_minimum_delegation);
        let maximum_delegation_amount =
            Self::get_named_argument(runtime_args, auction::ARG_MAXIMUM_DELEGATION_AMOUNT)
                .unwrap_or(global_maximum_delegation);
        let reserved_slots =
            Self::get_named_argument(runtime_args, auction::ARG_RESERVED_SLOTS).unwrap_or(0);

        Ok(Self::AddBid {
            public_key,
            delegation_rate,
            amount,
            minimum_delegation_amount,
            maximum_delegation_amount,
            minimum_bid_amount: global_minimum_bid_amount,
            reserved_slots,
        })
    }

    fn new_withdraw_bid(
        runtime_args: &RuntimeArgs,
        global_minimum_bid_amount: u64,
    ) -> Result<Self, AuctionMethodError> {
        let public_key = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
        let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
        Ok(Self::WithdrawBid {
            public_key,
            amount,
            minimum_bid_amount: global_minimum_bid_amount,
        })
    }

    fn new_delegate(
        runtime_args: &RuntimeArgs,
        max_delegators_per_validator: u32,
    ) -> Result<Self, AuctionMethodError> {
        let delegator = {
            match Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR) {
                Ok(pk) => DelegatorKind::PublicKey(pk),
                Err(_) => {
                    let purse: URefAddr =
                        Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR_PURSE)?;
                    DelegatorKind::Purse(purse)
                }
            }
        };
        let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
        let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;

        Ok(Self::Delegate {
            delegator,
            validator,
            amount,
            max_delegators_per_validator,
        })
    }

    fn new_undelegate(runtime_args: &RuntimeArgs) -> Result<Self, AuctionMethodError> {
        let delegator = {
            match Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR) {
                Ok(pk) => DelegatorKind::PublicKey(pk),
                Err(_) => {
                    let purse: URefAddr =
                        Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR_PURSE)?;
                    DelegatorKind::Purse(purse)
                }
            }
        };
        let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
        let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;

        Ok(Self::Undelegate {
            delegator,
            validator,
            amount,
        })
    }

    fn new_redelegate(runtime_args: &RuntimeArgs) -> Result<Self, AuctionMethodError> {
        let delegator = {
            match Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR) {
                Ok(pk) => DelegatorKind::PublicKey(pk),
                Err(_) => {
                    let purse: URefAddr =
                        Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR_PURSE)?;
                    DelegatorKind::Purse(purse)
                }
            }
        };
        let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
        let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;
        let new_validator = Self::get_named_argument(runtime_args, auction::ARG_NEW_VALIDATOR)?;

        Ok(Self::Redelegate {
            delegator,
            validator,
            amount,
            new_validator,
        })
    }

    fn new_change_bid_public_key(runtime_args: &RuntimeArgs) -> Result<Self, AuctionMethodError> {
        let public_key = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
        let new_public_key = Self::get_named_argument(runtime_args, auction::ARG_NEW_PUBLIC_KEY)?;

        Ok(Self::ChangeBidPublicKey {
            public_key,
            new_public_key,
        })
    }

    fn new_add_reservations(runtime_args: &RuntimeArgs) -> Result<Self, AuctionMethodError> {
        let reservations = Self::get_named_argument(runtime_args, auction::ARG_RESERVATIONS)?;

        Ok(Self::AddReservations { reservations })
    }

    fn new_cancel_reservations(
        runtime_args: &RuntimeArgs,
        max_delegators_per_validator: u32,
    ) -> Result<Self, AuctionMethodError> {
        let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
        let delegators = Self::get_named_argument(runtime_args, auction::ARG_DELEGATORS)?;

        Ok(Self::CancelReservations {
            validator,
            delegators,
            max_delegators_per_validator,
        })
    }

    fn get_named_argument<T: FromBytes + CLTyped>(
        args: &RuntimeArgs,
        name: &str,
    ) -> Result<T, AuctionMethodError> {
        let arg: &CLValue = args
            .get(name)
            .ok_or_else(|| AuctionMethodError::MissingArg(name.to_string()))?;
        arg.to_t().map_err(|error| AuctionMethodError::CLValue {
            arg: name.to_string(),
            error,
        })
    }
}

/// Bidding request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BiddingRequest {
    /// The runtime config.
    pub(crate) config: NativeRuntimeConfig,
    /// State root hash.
    pub(crate) state_hash: Digest,
    /// The protocol version.
    pub(crate) protocol_version: ProtocolVersion,
    /// The auction method.
    pub(crate) auction_method: AuctionMethod,
    /// Transaction hash.
    pub(crate) transaction_hash: TransactionHash,
    /// Base account.
    pub(crate) initiator: InitiatorAddr,
    /// List of authorizing accounts.
    pub(crate) authorization_keys: BTreeSet<AccountHash>,
}

impl BiddingRequest {
    /// Creates new request instance with runtime args.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        config: NativeRuntimeConfig,
        state_hash: Digest,
        protocol_version: ProtocolVersion,
        transaction_hash: TransactionHash,
        initiator: InitiatorAddr,
        authorization_keys: BTreeSet<AccountHash>,
        auction_method: AuctionMethod,
    ) -> Self {
        Self {
            config,
            state_hash,
            protocol_version,
            transaction_hash,
            initiator,
            authorization_keys,
            auction_method,
        }
    }

    /// Returns the config.
    pub fn config(&self) -> &NativeRuntimeConfig {
        &self.config
    }

    /// Returns the state hash.
    pub fn state_hash(&self) -> Digest {
        self.state_hash
    }

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

    /// Returns the auction method.
    pub fn auction_method(&self) -> &AuctionMethod {
        &self.auction_method
    }

    /// Returns the transaction hash.
    pub fn transaction_hash(&self) -> TransactionHash {
        self.transaction_hash
    }

    /// Returns the initiator.
    pub fn initiator(&self) -> &InitiatorAddr {
        &self.initiator
    }

    /// Returns the authorization keys.
    pub fn authorization_keys(&self) -> &BTreeSet<AccountHash> {
        &self.authorization_keys
    }
}

/// Auction method ret.
#[derive(Debug, Clone)]
pub enum AuctionMethodRet {
    /// Unit.
    Unit,
    /// Updated amount.
    UpdatedAmount(U512),
}

/// Bidding result.
#[derive(Debug)]
pub enum BiddingResult {
    /// Invalid state root hash.
    RootNotFound,
    /// Bidding request succeeded
    Success {
        /// Transfer records.
        transfers: Vec<Transfer>,
        /// Effects of bidding interaction.
        effects: Effects,
        /// The ret value, if any.
        ret: AuctionMethodRet,
    },
    /// Bidding request failed.
    Failure(TrackingCopyError),
}

impl BiddingResult {
    /// Is this a success.
    pub fn is_success(&self) -> bool {
        matches!(self, BiddingResult::Success { .. })
    }

    /// Effects.
    pub fn effects(&self) -> Effects {
        match self {
            BiddingResult::RootNotFound | BiddingResult::Failure(_) => Effects::new(),
            BiddingResult::Success { effects, .. } => effects.clone(),
        }
    }
}