casper_types/system/auction/
unbond.rs

1use alloc::{string::String, vec::Vec};
2use core::fmt::{self, Display, Formatter};
3#[cfg(feature = "datasize")]
4use datasize::DataSize;
5#[cfg(feature = "json-schema")]
6use schemars::JsonSchema;
7
8use super::{BidAddr, DelegatorKind, UnbondingPurse, WithdrawPurse};
9use crate::{
10    bytesrepr::{self, FromBytes, ToBytes, U8_SERIALIZED_LENGTH},
11    checksummed_hex, CLType, CLTyped, EraId, PublicKey, URef, URefAddr, U512,
12};
13use serde::{de::Error as SerdeError, Deserialize, Deserializer, Serialize, Serializer};
14use serde_helpers::{HumanReadableUnbondKind, NonHumanReadableUnbondKind};
15
16/// UnbondKindTag variants.
17#[allow(clippy::large_enum_variant)]
18#[repr(u8)]
19#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
20pub enum UnbondKindTag {
21    /// Validator bid.
22    Validator = 0,
23    /// Validator bid.
24    DelegatedAccount = 1,
25    /// Delegator bid.
26    DelegatedPurse = 2,
27}
28
29/// Unbond variants.
30#[derive(Debug, PartialEq, Eq, Clone, Ord, PartialOrd)]
31#[cfg_attr(feature = "datasize", derive(DataSize))]
32#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
33pub enum UnbondKind {
34    Validator(PublicKey),
35    DelegatedPublicKey(PublicKey),
36    DelegatedPurse(#[cfg_attr(feature = "json-schema", schemars(with = "String"))] URefAddr),
37}
38
39impl UnbondKind {
40    /// Returns UnbondKindTag.
41    pub fn tag(&self) -> UnbondKindTag {
42        match self {
43            UnbondKind::Validator(_) => UnbondKindTag::Validator,
44            UnbondKind::DelegatedPublicKey(_) => UnbondKindTag::DelegatedAccount,
45            UnbondKind::DelegatedPurse(_) => UnbondKindTag::DelegatedPurse,
46        }
47    }
48
49    /// Returns PublicKey, if any.
50    pub fn maybe_public_key(&self) -> Option<PublicKey> {
51        match self {
52            UnbondKind::Validator(pk) | UnbondKind::DelegatedPublicKey(pk) => Some(pk.clone()),
53            UnbondKind::DelegatedPurse(_) => None,
54        }
55    }
56
57    /// Is this a validator unbond?
58    pub fn is_validator(&self) -> bool {
59        match self {
60            UnbondKind::Validator(_) => true,
61            UnbondKind::DelegatedPublicKey(_) | UnbondKind::DelegatedPurse(_) => false,
62        }
63    }
64
65    /// Is this a delegator unbond?
66    pub fn is_delegator(&self) -> bool {
67        !self.is_validator()
68    }
69
70    /// The correct bid addr for this instance.
71    pub fn bid_addr(&self, validator_public_key: &PublicKey) -> BidAddr {
72        match self {
73            UnbondKind::Validator(pk) => BidAddr::UnbondAccount {
74                validator: validator_public_key.to_account_hash(),
75                unbonder: pk.to_account_hash(),
76            },
77            UnbondKind::DelegatedPublicKey(pk) => BidAddr::DelegatedAccount {
78                delegator: pk.to_account_hash(),
79                validator: validator_public_key.to_account_hash(),
80            },
81            UnbondKind::DelegatedPurse(addr) => BidAddr::DelegatedPurse {
82                validator: validator_public_key.to_account_hash(),
83                delegator: *addr,
84            },
85        }
86    }
87}
88
89impl ToBytes for UnbondKind {
90    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
91        let mut result = bytesrepr::allocate_buffer(self)?;
92        let (tag, mut serialized_data) = match self {
93            UnbondKind::Validator(pk) => (UnbondKindTag::Validator, pk.to_bytes()?),
94            UnbondKind::DelegatedPublicKey(pk) => (UnbondKindTag::DelegatedAccount, pk.to_bytes()?),
95            UnbondKind::DelegatedPurse(addr) => (UnbondKindTag::DelegatedPurse, addr.to_bytes()?),
96        };
97        result.push(tag as u8);
98        result.append(&mut serialized_data);
99        Ok(result)
100    }
101
102    fn serialized_length(&self) -> usize {
103        U8_SERIALIZED_LENGTH
104            + match self {
105                UnbondKind::Validator(pk) => pk.serialized_length(),
106                UnbondKind::DelegatedPublicKey(pk) => pk.serialized_length(),
107                UnbondKind::DelegatedPurse(addr) => addr.serialized_length(),
108            }
109    }
110
111    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
112        writer.push(self.tag() as u8);
113        match self {
114            UnbondKind::Validator(pk) => pk.write_bytes(writer)?,
115            UnbondKind::DelegatedPublicKey(pk) => pk.write_bytes(writer)?,
116            UnbondKind::DelegatedPurse(addr) => addr.write_bytes(writer)?,
117        };
118        Ok(())
119    }
120}
121
122impl FromBytes for UnbondKind {
123    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
124        let (tag, remainder): (u8, &[u8]) = FromBytes::from_bytes(bytes)?;
125        match tag {
126            tag if tag == UnbondKindTag::Validator as u8 => PublicKey::from_bytes(remainder)
127                .map(|(pk, remainder)| (UnbondKind::Validator(pk), remainder)),
128            tag if tag == UnbondKindTag::DelegatedAccount as u8 => PublicKey::from_bytes(remainder)
129                .map(|(pk, remainder)| (UnbondKind::DelegatedPublicKey(pk), remainder)),
130            tag if tag == UnbondKindTag::DelegatedPurse as u8 => URefAddr::from_bytes(remainder)
131                .map(|(delegator_bid, remainder)| {
132                    (UnbondKind::DelegatedPurse(delegator_bid), remainder)
133                }),
134            _ => Err(bytesrepr::Error::Formatting),
135        }
136    }
137}
138
139impl From<DelegatorKind> for UnbondKind {
140    fn from(value: DelegatorKind) -> Self {
141        match value {
142            DelegatorKind::PublicKey(pk) => UnbondKind::DelegatedPublicKey(pk),
143            DelegatorKind::Purse(addr) => UnbondKind::DelegatedPurse(addr),
144        }
145    }
146}
147
148impl Serialize for UnbondKind {
149    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
150        if serializer.is_human_readable() {
151            HumanReadableUnbondKind::from(self).serialize(serializer)
152        } else {
153            NonHumanReadableUnbondKind::from(self).serialize(serializer)
154        }
155    }
156}
157
158#[derive(Debug)]
159enum UnbondKindError {
160    DeserializationError(String),
161}
162
163impl Display for UnbondKindError {
164    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
165        match self {
166            UnbondKindError::DeserializationError(msg) => {
167                write!(f, "Error when deserializing UnbondKind: {}", msg)
168            }
169        }
170    }
171}
172
173impl TryFrom<HumanReadableUnbondKind> for UnbondKind {
174    type Error = UnbondKindError;
175
176    fn try_from(value: HumanReadableUnbondKind) -> Result<Self, Self::Error> {
177        match value {
178            HumanReadableUnbondKind::Validator(public_key) => Ok(UnbondKind::Validator(public_key)),
179            HumanReadableUnbondKind::DelegatedPublicKey(public_key) => {
180                Ok(UnbondKind::DelegatedPublicKey(public_key))
181            }
182            HumanReadableUnbondKind::DelegatedPurse(encoded) => {
183                let decoded = checksummed_hex::decode(encoded).map_err(|e| {
184                    UnbondKindError::DeserializationError(format!(
185                        "Failed to decode encoded URefAddr: {}",
186                        e
187                    ))
188                })?;
189                let uref_addr = URefAddr::try_from(decoded.as_ref()).map_err(|e| {
190                    UnbondKindError::DeserializationError(format!(
191                        "Failed to build uref address: {}",
192                        e
193                    ))
194                })?;
195                Ok(UnbondKind::DelegatedPurse(uref_addr))
196            }
197        }
198    }
199}
200
201impl From<NonHumanReadableUnbondKind> for UnbondKind {
202    fn from(value: NonHumanReadableUnbondKind) -> Self {
203        match value {
204            NonHumanReadableUnbondKind::Validator(public_key) => UnbondKind::Validator(public_key),
205            NonHumanReadableUnbondKind::DelegatedPublicKey(public_key) => {
206                UnbondKind::DelegatedPublicKey(public_key)
207            }
208            NonHumanReadableUnbondKind::DelegatedPurse(uref_addr) => {
209                UnbondKind::DelegatedPurse(uref_addr)
210            }
211        }
212    }
213}
214
215impl<'de> Deserialize<'de> for UnbondKind {
216    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
217        if deserializer.is_human_readable() {
218            let human_readable = HumanReadableUnbondKind::deserialize(deserializer)?;
219            UnbondKind::try_from(human_readable)
220                .map_err(|error| SerdeError::custom(format!("{:?}", error)))
221        } else {
222            let non_human_readable = NonHumanReadableUnbondKind::deserialize(deserializer)?;
223            Ok(UnbondKind::from(non_human_readable))
224        }
225    }
226}
227
228#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
229#[cfg_attr(feature = "datasize", derive(DataSize))]
230#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
231#[serde(deny_unknown_fields)]
232pub struct Unbond {
233    /// Validators public key.
234    validator_public_key: PublicKey,
235    /// Unbond kind.
236    unbond_kind: UnbondKind,
237    /// Unbond amounts per era.
238    eras: Vec<UnbondEra>,
239}
240
241impl Unbond {
242    /// Creates [`Unbond`] instance for an unbonding request.
243    pub const fn new(
244        validator_public_key: PublicKey,
245        unbond_kind: UnbondKind,
246        eras: Vec<UnbondEra>,
247    ) -> Self {
248        Self {
249            validator_public_key,
250            unbond_kind,
251            eras,
252        }
253    }
254
255    /// Creates [`Unbond`] instance for an unbonding request.
256    pub fn new_validator_unbond(validator_public_key: PublicKey, eras: Vec<UnbondEra>) -> Self {
257        Self {
258            validator_public_key: validator_public_key.clone(),
259            unbond_kind: UnbondKind::Validator(validator_public_key),
260            eras,
261        }
262    }
263
264    /// Creates [`Unbond`] instance for an unbonding request.
265    pub const fn new_delegated_account_unbond(
266        validator_public_key: PublicKey,
267        delegator_public_key: PublicKey,
268        eras: Vec<UnbondEra>,
269    ) -> Self {
270        Self {
271            validator_public_key,
272            unbond_kind: UnbondKind::DelegatedPublicKey(delegator_public_key),
273            eras,
274        }
275    }
276
277    /// Creates [`Unbond`] instance for an unbonding request.
278    pub const fn new_delegated_purse_unbond(
279        validator_public_key: PublicKey,
280        delegator_purse_addr: URefAddr,
281        eras: Vec<UnbondEra>,
282    ) -> Self {
283        Self {
284            validator_public_key,
285            unbond_kind: UnbondKind::DelegatedPurse(delegator_purse_addr),
286            eras,
287        }
288    }
289
290    /// Checks if given request is made by a validator by checking if public key of unbonder is same
291    /// as a key owned by validator.
292    pub fn is_validator(&self) -> bool {
293        match self.unbond_kind.maybe_public_key() {
294            Some(pk) => pk == self.validator_public_key,
295            None => false,
296        }
297    }
298
299    /// Returns public key of validator.
300    pub fn validator_public_key(&self) -> &PublicKey {
301        &self.validator_public_key
302    }
303
304    /// Returns unbond kind.
305    pub fn unbond_kind(&self) -> &UnbondKind {
306        &self.unbond_kind
307    }
308
309    /// Returns eras unbond items.
310    pub fn eras(&self) -> &Vec<UnbondEra> {
311        &self.eras
312    }
313
314    /// Returns eras unbond items.
315    pub fn eras_mut(&mut self) -> &mut Vec<UnbondEra> {
316        &mut self.eras
317    }
318
319    /// Takes eras unbond items.
320    pub fn take_eras(mut self) -> Vec<UnbondEra> {
321        let eras = self.eras;
322        self.eras = vec![];
323        eras
324    }
325
326    /// Splits instance into eras that are not expired, and eras that are expired (if any).
327    pub fn expired(self, era_id: EraId, unbonding_delay: u64) -> (Unbond, Option<Vec<UnbondEra>>) {
328        let mut retained = vec![];
329        let mut expired = vec![];
330        for era in self.eras {
331            let threshold = era
332                .era_of_creation()
333                .value()
334                .saturating_add(unbonding_delay);
335            if era_id.value() >= threshold {
336                expired.push(era);
337            } else {
338                retained.push(era)
339            }
340        }
341        let ret = Unbond::new(self.validator_public_key, self.unbond_kind, retained);
342        if !expired.is_empty() {
343            (ret, Some(expired))
344        } else {
345            (ret, None)
346        }
347    }
348}
349
350impl ToBytes for Unbond {
351    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
352        let mut result = bytesrepr::allocate_buffer(self)?;
353        result.extend(&self.validator_public_key.to_bytes()?);
354        result.extend(&self.unbond_kind.to_bytes()?);
355        result.extend(&self.eras.to_bytes()?);
356        Ok(result)
357    }
358    fn serialized_length(&self) -> usize {
359        self.validator_public_key.serialized_length()
360            + self.unbond_kind.serialized_length()
361            + self.eras.serialized_length()
362    }
363
364    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
365        self.validator_public_key.write_bytes(writer)?;
366        self.unbond_kind.write_bytes(writer)?;
367        self.eras.write_bytes(writer)?;
368        Ok(())
369    }
370}
371
372impl FromBytes for Unbond {
373    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
374        let (validator_public_key, remainder) = FromBytes::from_bytes(bytes)?;
375        let (unbond_kind, remainder) = FromBytes::from_bytes(remainder)?;
376        let (eras, remainder) = FromBytes::from_bytes(remainder)?;
377
378        Ok((
379            Unbond {
380                validator_public_key,
381                unbond_kind,
382                eras,
383            },
384            remainder,
385        ))
386    }
387}
388
389impl CLTyped for Unbond {
390    fn cl_type() -> CLType {
391        CLType::Any
392    }
393}
394
395impl Default for Unbond {
396    fn default() -> Self {
397        Self {
398            unbond_kind: UnbondKind::Validator(PublicKey::System),
399            validator_public_key: PublicKey::System,
400            eras: vec![],
401        }
402    }
403}
404
405impl From<UnbondingPurse> for Unbond {
406    fn from(unbonding_purse: UnbondingPurse) -> Self {
407        let unbond_kind =
408            if unbonding_purse.validator_public_key() == unbonding_purse.unbonder_public_key() {
409                UnbondKind::Validator(unbonding_purse.validator_public_key().clone())
410            } else {
411                UnbondKind::DelegatedPublicKey(unbonding_purse.unbonder_public_key().clone())
412            };
413        Unbond::new(
414            unbonding_purse.validator_public_key().clone(),
415            unbond_kind,
416            vec![UnbondEra::new(
417                *unbonding_purse.bonding_purse(),
418                unbonding_purse.era_of_creation(),
419                *unbonding_purse.amount(),
420                None,
421            )],
422        )
423    }
424}
425
426impl From<WithdrawPurse> for Unbond {
427    fn from(withdraw_purse: WithdrawPurse) -> Self {
428        let unbond_kind =
429            if withdraw_purse.validator_public_key == withdraw_purse.unbonder_public_key {
430                UnbondKind::Validator(withdraw_purse.validator_public_key.clone())
431            } else {
432                UnbondKind::DelegatedPublicKey(withdraw_purse.unbonder_public_key.clone())
433            };
434        Unbond::new(
435            withdraw_purse.validator_public_key,
436            unbond_kind,
437            vec![UnbondEra::new(
438                withdraw_purse.bonding_purse,
439                withdraw_purse.era_of_creation,
440                withdraw_purse.amount,
441                None,
442            )],
443        )
444    }
445}
446
447/// Unbond amounts per era.
448#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone, Default)]
449#[cfg_attr(feature = "datasize", derive(DataSize))]
450#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
451#[serde(deny_unknown_fields)]
452pub struct UnbondEra {
453    /// Bonding Purse
454    bonding_purse: URef,
455    /// Era in which this unbonding request was created.
456    era_of_creation: EraId,
457    /// Unbonding Amount.
458    amount: U512,
459    /// The validator public key to re-delegate to.
460    new_validator: Option<PublicKey>,
461}
462
463impl UnbondEra {
464    /// Creates [`UnbondEra`] instance for an unbonding request.
465    pub const fn new(
466        bonding_purse: URef,
467        era_of_creation: EraId,
468        amount: U512,
469        new_validator: Option<PublicKey>,
470    ) -> Self {
471        Self {
472            bonding_purse,
473            era_of_creation,
474            amount,
475            new_validator,
476        }
477    }
478
479    /// Returns bonding purse used to make this unbonding request.
480    pub fn bonding_purse(&self) -> &URef {
481        &self.bonding_purse
482    }
483
484    /// Returns era which was used to create this unbonding request.
485    pub fn era_of_creation(&self) -> EraId {
486        self.era_of_creation
487    }
488
489    /// Returns unbonding amount.
490    pub fn amount(&self) -> &U512 {
491        &self.amount
492    }
493
494    /// Returns the public key for the new validator.
495    pub fn new_validator(&self) -> &Option<PublicKey> {
496        &self.new_validator
497    }
498
499    /// Sets amount to provided value.
500    pub fn with_amount(&mut self, amount: U512) {
501        self.amount = amount;
502    }
503}
504
505impl ToBytes for UnbondEra {
506    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
507        let mut result = bytesrepr::allocate_buffer(self)?;
508        result.extend(&self.bonding_purse.to_bytes()?);
509        result.extend(&self.era_of_creation.to_bytes()?);
510        result.extend(&self.amount.to_bytes()?);
511        result.extend(&self.new_validator.to_bytes()?);
512        Ok(result)
513    }
514    fn serialized_length(&self) -> usize {
515        self.bonding_purse.serialized_length()
516            + self.era_of_creation.serialized_length()
517            + self.amount.serialized_length()
518            + self.new_validator.serialized_length()
519    }
520
521    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
522        self.bonding_purse.write_bytes(writer)?;
523        self.era_of_creation.write_bytes(writer)?;
524        self.amount.write_bytes(writer)?;
525        self.new_validator.write_bytes(writer)?;
526        Ok(())
527    }
528}
529
530impl FromBytes for UnbondEra {
531    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
532        let (bonding_purse, remainder) = FromBytes::from_bytes(bytes)?;
533        let (era_of_creation, remainder) = FromBytes::from_bytes(remainder)?;
534        let (amount, remainder) = FromBytes::from_bytes(remainder)?;
535        let (new_validator, remainder) = Option::<PublicKey>::from_bytes(remainder)?;
536
537        Ok((
538            UnbondEra {
539                bonding_purse,
540                era_of_creation,
541                amount,
542                new_validator,
543            },
544            remainder,
545        ))
546    }
547}
548
549impl CLTyped for UnbondEra {
550    fn cl_type() -> CLType {
551        CLType::Any
552    }
553}
554
555mod serde_helpers {
556    use super::UnbondKind;
557    use crate::{PublicKey, URefAddr};
558    use alloc::string::String;
559    use serde::{Deserialize, Serialize};
560
561    #[derive(Serialize, Deserialize)]
562    pub(super) enum HumanReadableUnbondKind {
563        Validator(PublicKey),
564        DelegatedPublicKey(PublicKey),
565        DelegatedPurse(String),
566    }
567
568    #[derive(Serialize, Deserialize)]
569    pub(super) enum NonHumanReadableUnbondKind {
570        Validator(PublicKey),
571        DelegatedPublicKey(PublicKey),
572        DelegatedPurse(URefAddr),
573    }
574
575    impl From<&UnbondKind> for HumanReadableUnbondKind {
576        fn from(unbond_source: &UnbondKind) -> Self {
577            match unbond_source {
578                UnbondKind::Validator(public_key) => {
579                    HumanReadableUnbondKind::Validator(public_key.clone())
580                }
581                UnbondKind::DelegatedPublicKey(public_key) => {
582                    HumanReadableUnbondKind::DelegatedPublicKey(public_key.clone())
583                }
584                UnbondKind::DelegatedPurse(uref_addr) => {
585                    HumanReadableUnbondKind::DelegatedPurse(base16::encode_lower(uref_addr))
586                }
587            }
588        }
589    }
590
591    impl From<&UnbondKind> for NonHumanReadableUnbondKind {
592        fn from(unbond_kind: &UnbondKind) -> Self {
593            match unbond_kind {
594                UnbondKind::Validator(public_key) => {
595                    NonHumanReadableUnbondKind::Validator(public_key.clone())
596                }
597                UnbondKind::DelegatedPublicKey(public_key) => {
598                    NonHumanReadableUnbondKind::DelegatedPublicKey(public_key.clone())
599                }
600                UnbondKind::DelegatedPurse(uref_addr) => {
601                    NonHumanReadableUnbondKind::DelegatedPurse(*uref_addr)
602                }
603            }
604        }
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use rand::Rng;
611
612    use crate::{
613        bytesrepr,
614        system::auction::{
615            unbond::{Unbond, UnbondKind},
616            UnbondEra,
617        },
618        testing::TestRng,
619        AccessRights, EraId, PublicKey, SecretKey, URef, U512,
620    };
621
622    const BONDING_PURSE: URef = URef::new([14; 32], AccessRights::READ_ADD_WRITE);
623    const ERA_OF_WITHDRAWAL: EraId = EraId::MAX;
624
625    fn validator_public_key() -> PublicKey {
626        let secret_key = SecretKey::ed25519_from_bytes([42; SecretKey::ED25519_LENGTH]).unwrap();
627        PublicKey::from(&secret_key)
628    }
629
630    fn delegated_account_unbond_kind() -> UnbondKind {
631        let secret_key = SecretKey::ed25519_from_bytes([43; SecretKey::ED25519_LENGTH]).unwrap();
632        UnbondKind::DelegatedPublicKey(PublicKey::from(&secret_key))
633    }
634
635    fn amount() -> U512 {
636        U512::max_value() - 1
637    }
638
639    #[test]
640    fn serialization_roundtrip_for_unbond() {
641        let unbond_era = UnbondEra {
642            bonding_purse: BONDING_PURSE,
643            era_of_creation: ERA_OF_WITHDRAWAL,
644            amount: amount(),
645            new_validator: None,
646        };
647
648        let unbond = Unbond {
649            validator_public_key: validator_public_key(),
650            unbond_kind: delegated_account_unbond_kind(),
651            eras: vec![unbond_era],
652        };
653
654        bytesrepr::test_serialization_roundtrip(&unbond);
655    }
656
657    #[test]
658    fn should_be_validator_condition_for_unbond() {
659        let validator_pk = validator_public_key();
660        let validator_unbond = Unbond::new(
661            validator_pk.clone(),
662            UnbondKind::Validator(validator_pk),
663            vec![],
664        );
665        assert!(validator_unbond.is_validator());
666    }
667
668    #[test]
669    fn should_be_delegator_condition_for_unbond() {
670        let delegator_unbond = Unbond::new(
671            validator_public_key(),
672            delegated_account_unbond_kind(),
673            vec![],
674        );
675        assert!(!delegator_unbond.is_validator());
676    }
677
678    #[test]
679    fn purse_serialized_as_string() {
680        let delegator_kind_payload = UnbondKind::DelegatedPurse([1; 32]);
681        let serialized = serde_json::to_string(&delegator_kind_payload).unwrap();
682        assert_eq!(
683            serialized,
684            "{\"DelegatedPurse\":\"0101010101010101010101010101010101010101010101010101010101010101\"}"
685        );
686    }
687
688    #[test]
689    fn given_broken_address_purse_deserialziation_fails() {
690        let failing =
691            "{\"DelegatedPurse\":\"Z101010101010101010101010101010101010101010101010101010101010101\"}";
692        let ret = serde_json::from_str::<UnbondKind>(failing);
693        assert!(ret.is_err());
694        let failing =
695            "{\"DelegatedPurse\":\"01010101010101010101010101010101010101010101010101010101\"}";
696        let ret = serde_json::from_str::<UnbondKind>(failing);
697        assert!(ret.is_err());
698    }
699
700    #[test]
701    fn json_roundtrip() {
702        let rng = &mut TestRng::new();
703
704        let entity = UnbondKind::Validator(PublicKey::random(rng));
705        let json_string = serde_json::to_string_pretty(&entity).unwrap();
706        let decoded: UnbondKind = serde_json::from_str(&json_string).unwrap();
707        assert_eq!(decoded, entity);
708
709        let entity = UnbondKind::DelegatedPublicKey(PublicKey::random(rng));
710        let json_string = serde_json::to_string_pretty(&entity).unwrap();
711        let decoded: UnbondKind = serde_json::from_str(&json_string).unwrap();
712        assert_eq!(decoded, entity);
713
714        let entity = UnbondKind::DelegatedPurse(rng.gen());
715        let json_string = serde_json::to_string_pretty(&entity).unwrap();
716        let decoded: UnbondKind = serde_json::from_str(&json_string).unwrap();
717        assert_eq!(decoded, entity);
718    }
719}