casper_types/system/auction/
unbond.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
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
use alloc::vec::Vec;

#[cfg(feature = "datasize")]
use datasize::DataSize;
#[cfg(feature = "json-schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{
    bytesrepr::{self, FromBytes, ToBytes, U8_SERIALIZED_LENGTH},
    CLType, CLTyped, EraId, PublicKey, URef, URefAddr, U512,
};

use super::{BidAddr, DelegatorKind, UnbondingPurse, WithdrawPurse};

/// UnbondKindTag variants.
#[allow(clippy::large_enum_variant)]
#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
pub enum UnbondKindTag {
    /// Validator bid.
    Validator = 0,
    /// Validator bid.
    DelegatedAccount = 1,
    /// Delegator bid.
    DelegatedPurse = 2,
}

/// Unbond variants.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Ord, PartialOrd)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
pub enum UnbondKind {
    Validator(PublicKey),
    DelegatedPublicKey(PublicKey),
    DelegatedPurse(URefAddr),
}

impl UnbondKind {
    /// Returns UnbondKindTag.
    pub fn tag(&self) -> UnbondKindTag {
        match self {
            UnbondKind::Validator(_) => UnbondKindTag::Validator,
            UnbondKind::DelegatedPublicKey(_) => UnbondKindTag::DelegatedAccount,
            UnbondKind::DelegatedPurse(_) => UnbondKindTag::DelegatedPurse,
        }
    }

    /// Returns PublicKey, if any.
    pub fn maybe_public_key(&self) -> Option<PublicKey> {
        match self {
            UnbondKind::Validator(pk) | UnbondKind::DelegatedPublicKey(pk) => Some(pk.clone()),
            UnbondKind::DelegatedPurse(_) => None,
        }
    }

    /// Is this a validator unbond?
    pub fn is_validator(&self) -> bool {
        match self {
            UnbondKind::Validator(_) => true,
            UnbondKind::DelegatedPublicKey(_) | UnbondKind::DelegatedPurse(_) => false,
        }
    }

    /// Is this a delegator unbond?
    pub fn is_delegator(&self) -> bool {
        !self.is_validator()
    }

    /// The correct bid addr for this instance.
    pub fn bid_addr(&self, validator_public_key: &PublicKey) -> BidAddr {
        match self {
            UnbondKind::Validator(pk) => BidAddr::UnbondAccount {
                validator: validator_public_key.to_account_hash(),
                unbonder: pk.to_account_hash(),
            },
            UnbondKind::DelegatedPublicKey(pk) => BidAddr::DelegatedAccount {
                delegator: pk.to_account_hash(),
                validator: validator_public_key.to_account_hash(),
            },
            UnbondKind::DelegatedPurse(addr) => BidAddr::DelegatedPurse {
                validator: validator_public_key.to_account_hash(),
                delegator: *addr,
            },
        }
    }
}

impl ToBytes for UnbondKind {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut result = bytesrepr::allocate_buffer(self)?;
        let (tag, mut serialized_data) = match self {
            UnbondKind::Validator(pk) => (UnbondKindTag::Validator, pk.to_bytes()?),
            UnbondKind::DelegatedPublicKey(pk) => (UnbondKindTag::DelegatedAccount, pk.to_bytes()?),
            UnbondKind::DelegatedPurse(addr) => (UnbondKindTag::DelegatedPurse, addr.to_bytes()?),
        };
        result.push(tag as u8);
        result.append(&mut serialized_data);
        Ok(result)
    }

    fn serialized_length(&self) -> usize {
        U8_SERIALIZED_LENGTH
            + match self {
                UnbondKind::Validator(pk) => pk.serialized_length(),
                UnbondKind::DelegatedPublicKey(pk) => pk.serialized_length(),
                UnbondKind::DelegatedPurse(addr) => addr.serialized_length(),
            }
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        writer.push(self.tag() as u8);
        match self {
            UnbondKind::Validator(pk) => pk.write_bytes(writer)?,
            UnbondKind::DelegatedPublicKey(pk) => pk.write_bytes(writer)?,
            UnbondKind::DelegatedPurse(addr) => addr.write_bytes(writer)?,
        };
        Ok(())
    }
}

impl FromBytes for UnbondKind {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (tag, remainder): (u8, &[u8]) = FromBytes::from_bytes(bytes)?;
        match tag {
            tag if tag == UnbondKindTag::Validator as u8 => PublicKey::from_bytes(remainder)
                .map(|(pk, remainder)| (UnbondKind::Validator(pk), remainder)),
            tag if tag == UnbondKindTag::DelegatedAccount as u8 => PublicKey::from_bytes(remainder)
                .map(|(pk, remainder)| (UnbondKind::DelegatedPublicKey(pk), remainder)),
            tag if tag == UnbondKindTag::DelegatedPurse as u8 => URefAddr::from_bytes(remainder)
                .map(|(delegator_bid, remainder)| {
                    (UnbondKind::DelegatedPurse(delegator_bid), remainder)
                }),
            _ => Err(bytesrepr::Error::Formatting),
        }
    }
}

impl From<DelegatorKind> for UnbondKind {
    fn from(value: DelegatorKind) -> Self {
        match value {
            DelegatorKind::PublicKey(pk) => UnbondKind::DelegatedPublicKey(pk),
            DelegatorKind::Purse(addr) => UnbondKind::DelegatedPurse(addr),
        }
    }
}

#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Unbond {
    /// Validators public key.
    validator_public_key: PublicKey,
    /// Unbond kind.
    unbond_kind: UnbondKind,
    /// Unbond amounts per era.
    eras: Vec<UnbondEra>,
}

impl Unbond {
    /// Creates [`Unbond`] instance for an unbonding request.
    pub const fn new(
        validator_public_key: PublicKey,
        unbond_kind: UnbondKind,
        eras: Vec<UnbondEra>,
    ) -> Self {
        Self {
            validator_public_key,
            unbond_kind,
            eras,
        }
    }

    /// Creates [`Unbond`] instance for an unbonding request.
    pub fn new_validator_unbond(validator_public_key: PublicKey, eras: Vec<UnbondEra>) -> Self {
        Self {
            validator_public_key: validator_public_key.clone(),
            unbond_kind: UnbondKind::Validator(validator_public_key),
            eras,
        }
    }

    /// Creates [`Unbond`] instance for an unbonding request.
    pub const fn new_delegated_account_unbond(
        validator_public_key: PublicKey,
        delegator_public_key: PublicKey,
        eras: Vec<UnbondEra>,
    ) -> Self {
        Self {
            validator_public_key,
            unbond_kind: UnbondKind::DelegatedPublicKey(delegator_public_key),
            eras,
        }
    }

    /// Creates [`Unbond`] instance for an unbonding request.
    pub const fn new_delegated_purse_unbond(
        validator_public_key: PublicKey,
        delegator_purse_addr: URefAddr,
        eras: Vec<UnbondEra>,
    ) -> Self {
        Self {
            validator_public_key,
            unbond_kind: UnbondKind::DelegatedPurse(delegator_purse_addr),
            eras,
        }
    }

    /// Checks if given request is made by a validator by checking if public key of unbonder is same
    /// as a key owned by validator.
    pub fn is_validator(&self) -> bool {
        match self.unbond_kind.maybe_public_key() {
            Some(pk) => pk == self.validator_public_key,
            None => false,
        }
    }

    /// Returns public key of validator.
    pub fn validator_public_key(&self) -> &PublicKey {
        &self.validator_public_key
    }

    /// Returns unbond kind.
    pub fn unbond_kind(&self) -> &UnbondKind {
        &self.unbond_kind
    }

    /// Returns eras unbond items.
    pub fn eras(&self) -> &Vec<UnbondEra> {
        &self.eras
    }

    /// Returns eras unbond items.
    pub fn eras_mut(&mut self) -> &mut Vec<UnbondEra> {
        &mut self.eras
    }

    /// Takes eras unbond items.
    pub fn take_eras(mut self) -> Vec<UnbondEra> {
        let eras = self.eras;
        self.eras = vec![];
        eras
    }

    /// Splits instance into eras that are not expired, and eras that are expired (if any).
    pub fn expired(self, era_id: EraId, unbonding_delay: u64) -> (Unbond, Option<Vec<UnbondEra>>) {
        let mut retained = vec![];
        let mut expired = vec![];
        for era in self.eras {
            let threshold = era
                .era_of_creation()
                .value()
                .saturating_add(unbonding_delay);
            if era_id.value() >= threshold {
                expired.push(era);
            } else {
                retained.push(era)
            }
        }
        let ret = Unbond::new(self.validator_public_key, self.unbond_kind, retained);
        if !expired.is_empty() {
            (ret, Some(expired))
        } else {
            (ret, None)
        }
    }
}

impl ToBytes for Unbond {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut result = bytesrepr::allocate_buffer(self)?;
        result.extend(&self.validator_public_key.to_bytes()?);
        result.extend(&self.unbond_kind.to_bytes()?);
        result.extend(&self.eras.to_bytes()?);
        Ok(result)
    }
    fn serialized_length(&self) -> usize {
        self.validator_public_key.serialized_length()
            + self.unbond_kind.serialized_length()
            + self.eras.serialized_length()
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.validator_public_key.write_bytes(writer)?;
        self.unbond_kind.write_bytes(writer)?;
        self.eras.write_bytes(writer)?;
        Ok(())
    }
}

impl FromBytes for Unbond {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (validator_public_key, remainder) = FromBytes::from_bytes(bytes)?;
        let (unbond_kind, remainder) = FromBytes::from_bytes(remainder)?;
        let (eras, remainder) = FromBytes::from_bytes(remainder)?;

        Ok((
            Unbond {
                validator_public_key,
                unbond_kind,
                eras,
            },
            remainder,
        ))
    }
}

impl CLTyped for Unbond {
    fn cl_type() -> CLType {
        CLType::Any
    }
}

impl Default for Unbond {
    fn default() -> Self {
        Self {
            unbond_kind: UnbondKind::Validator(PublicKey::System),
            validator_public_key: PublicKey::System,
            eras: vec![],
        }
    }
}

impl From<UnbondingPurse> for Unbond {
    fn from(unbonding_purse: UnbondingPurse) -> Self {
        let unbond_kind =
            if unbonding_purse.validator_public_key() == unbonding_purse.unbonder_public_key() {
                UnbondKind::Validator(unbonding_purse.validator_public_key().clone())
            } else {
                UnbondKind::DelegatedPublicKey(unbonding_purse.unbonder_public_key().clone())
            };
        Unbond::new(
            unbonding_purse.validator_public_key().clone(),
            unbond_kind,
            vec![UnbondEra::new(
                *unbonding_purse.bonding_purse(),
                unbonding_purse.era_of_creation(),
                *unbonding_purse.amount(),
                None,
            )],
        )
    }
}

impl From<WithdrawPurse> for Unbond {
    fn from(withdraw_purse: WithdrawPurse) -> Self {
        let unbond_kind =
            if withdraw_purse.validator_public_key == withdraw_purse.unbonder_public_key {
                UnbondKind::Validator(withdraw_purse.validator_public_key.clone())
            } else {
                UnbondKind::DelegatedPublicKey(withdraw_purse.unbonder_public_key.clone())
            };
        Unbond::new(
            withdraw_purse.validator_public_key,
            unbond_kind,
            vec![UnbondEra::new(
                withdraw_purse.bonding_purse,
                withdraw_purse.era_of_creation,
                withdraw_purse.amount,
                None,
            )],
        )
    }
}

/// Unbond amounts per era.
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone, Default)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct UnbondEra {
    /// Bonding Purse
    bonding_purse: URef,
    /// Era in which this unbonding request was created.
    era_of_creation: EraId,
    /// Unbonding Amount.
    amount: U512,
    /// The validator public key to re-delegate to.
    new_validator: Option<PublicKey>,
}

impl UnbondEra {
    /// Creates [`UnbondEra`] instance for an unbonding request.
    pub const fn new(
        bonding_purse: URef,
        era_of_creation: EraId,
        amount: U512,
        new_validator: Option<PublicKey>,
    ) -> Self {
        Self {
            bonding_purse,
            era_of_creation,
            amount,
            new_validator,
        }
    }

    /// Returns bonding purse used to make this unbonding request.
    pub fn bonding_purse(&self) -> &URef {
        &self.bonding_purse
    }

    /// Returns era which was used to create this unbonding request.
    pub fn era_of_creation(&self) -> EraId {
        self.era_of_creation
    }

    /// Returns unbonding amount.
    pub fn amount(&self) -> &U512 {
        &self.amount
    }

    /// Returns the public key for the new validator.
    pub fn new_validator(&self) -> &Option<PublicKey> {
        &self.new_validator
    }

    /// Sets amount to provided value.
    pub fn with_amount(&mut self, amount: U512) {
        self.amount = amount;
    }
}

impl ToBytes for UnbondEra {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut result = bytesrepr::allocate_buffer(self)?;
        result.extend(&self.bonding_purse.to_bytes()?);
        result.extend(&self.era_of_creation.to_bytes()?);
        result.extend(&self.amount.to_bytes()?);
        result.extend(&self.new_validator.to_bytes()?);
        Ok(result)
    }
    fn serialized_length(&self) -> usize {
        self.bonding_purse.serialized_length()
            + self.era_of_creation.serialized_length()
            + self.amount.serialized_length()
            + self.new_validator.serialized_length()
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.bonding_purse.write_bytes(writer)?;
        self.era_of_creation.write_bytes(writer)?;
        self.amount.write_bytes(writer)?;
        self.new_validator.write_bytes(writer)?;
        Ok(())
    }
}

impl FromBytes for UnbondEra {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (bonding_purse, remainder) = FromBytes::from_bytes(bytes)?;
        let (era_of_creation, remainder) = FromBytes::from_bytes(remainder)?;
        let (amount, remainder) = FromBytes::from_bytes(remainder)?;
        let (new_validator, remainder) = Option::<PublicKey>::from_bytes(remainder)?;

        Ok((
            UnbondEra {
                bonding_purse,
                era_of_creation,
                amount,
                new_validator,
            },
            remainder,
        ))
    }
}

impl CLTyped for UnbondEra {
    fn cl_type() -> CLType {
        CLType::Any
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        bytesrepr,
        system::auction::{
            unbond::{Unbond, UnbondKind},
            UnbondEra,
        },
        AccessRights, EraId, PublicKey, SecretKey, URef, U512,
    };

    const BONDING_PURSE: URef = URef::new([14; 32], AccessRights::READ_ADD_WRITE);
    const ERA_OF_WITHDRAWAL: EraId = EraId::MAX;

    fn validator_public_key() -> PublicKey {
        let secret_key = SecretKey::ed25519_from_bytes([42; SecretKey::ED25519_LENGTH]).unwrap();
        PublicKey::from(&secret_key)
    }

    fn delegated_account_unbond_kind() -> UnbondKind {
        let secret_key = SecretKey::ed25519_from_bytes([43; SecretKey::ED25519_LENGTH]).unwrap();
        UnbondKind::DelegatedPublicKey(PublicKey::from(&secret_key))
    }

    fn amount() -> U512 {
        U512::max_value() - 1
    }

    #[test]
    fn serialization_roundtrip_for_unbond() {
        let unbond_era = UnbondEra {
            bonding_purse: BONDING_PURSE,
            era_of_creation: ERA_OF_WITHDRAWAL,
            amount: amount(),
            new_validator: None,
        };

        let unbond = Unbond {
            validator_public_key: validator_public_key(),
            unbond_kind: delegated_account_unbond_kind(),
            eras: vec![unbond_era],
        };

        bytesrepr::test_serialization_roundtrip(&unbond);
    }

    #[test]
    fn should_be_validator_condition_for_unbond() {
        let validator_pk = validator_public_key();
        let validator_unbond = Unbond::new(
            validator_pk.clone(),
            UnbondKind::Validator(validator_pk),
            vec![],
        );
        assert!(validator_unbond.is_validator());
    }

    #[test]
    fn should_be_delegator_condition_for_unbond() {
        let delegator_unbond = Unbond::new(
            validator_public_key(),
            delegated_account_unbond_kind(),
            vec![],
        );
        assert!(!delegator_unbond.is_validator());
    }
}