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
// TODO - remove once schemars stops causing warning.
#![allow(clippy::field_reassign_with_default)]

use alloc::{boxed::Box, vec::Vec};

#[cfg(feature = "std")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{
    bytesrepr::{self, FromBytes, ToBytes},
    CLType, CLTyped, PublicKey, U512,
};

const SEIGNIORAGE_ALLOCATION_VALIDATOR_TAG: u8 = 0;
const SEIGNIORAGE_ALLOCATION_DELEGATOR_TAG: u8 = 1;

/// Information about a seigniorage allocation
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "std", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub enum SeigniorageAllocation {
    /// Info about a seigniorage allocation for a validator
    Validator {
        /// Validator's public key
        validator_public_key: PublicKey,
        /// Allocated amount
        amount: U512,
    },
    /// Info about a seigniorage allocation for a delegator
    Delegator {
        /// Delegator's public key
        delegator_public_key: PublicKey,
        /// Validator's public key
        validator_public_key: PublicKey,
        /// Allocated amount
        amount: U512,
    },
}

impl SeigniorageAllocation {
    /// Constructs a [`SeigniorageAllocation::Validator`]
    pub const fn validator(validator_public_key: PublicKey, amount: U512) -> Self {
        SeigniorageAllocation::Validator {
            validator_public_key,
            amount,
        }
    }

    /// Constructs a [`SeigniorageAllocation::Delegator`]
    pub const fn delegator(
        delegator_public_key: PublicKey,
        validator_public_key: PublicKey,
        amount: U512,
    ) -> Self {
        SeigniorageAllocation::Delegator {
            delegator_public_key,
            validator_public_key,
            amount,
        }
    }

    /// Returns the amount for a given seigniorage allocation
    pub fn amount(&self) -> &U512 {
        match self {
            SeigniorageAllocation::Validator { amount, .. } => amount,
            SeigniorageAllocation::Delegator { amount, .. } => amount,
        }
    }

    fn tag(&self) -> u8 {
        match self {
            SeigniorageAllocation::Validator { .. } => SEIGNIORAGE_ALLOCATION_VALIDATOR_TAG,
            SeigniorageAllocation::Delegator { .. } => SEIGNIORAGE_ALLOCATION_DELEGATOR_TAG,
        }
    }
}

impl ToBytes for SeigniorageAllocation {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        buffer.append(&mut self.tag().to_bytes()?);
        match self {
            SeigniorageAllocation::Validator {
                validator_public_key,
                amount,
            } => {
                buffer.append(&mut validator_public_key.to_bytes()?);
                buffer.append(&mut amount.to_bytes()?);
            }
            SeigniorageAllocation::Delegator {
                delegator_public_key,
                validator_public_key,
                amount,
            } => {
                buffer.append(&mut delegator_public_key.to_bytes()?);
                buffer.append(&mut validator_public_key.to_bytes()?);
                buffer.append(&mut amount.to_bytes()?);
            }
        }
        Ok(buffer)
    }

    fn serialized_length(&self) -> usize {
        self.tag().serialized_length()
            + match self {
                SeigniorageAllocation::Validator {
                    validator_public_key,
                    amount,
                } => validator_public_key.serialized_length() + amount.serialized_length(),
                SeigniorageAllocation::Delegator {
                    delegator_public_key,
                    validator_public_key,
                    amount,
                } => {
                    delegator_public_key.serialized_length()
                        + validator_public_key.serialized_length()
                        + amount.serialized_length()
                }
            }
    }
}

impl FromBytes for SeigniorageAllocation {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (tag, rem) = <u8>::from_bytes(bytes)?;
        match tag {
            SEIGNIORAGE_ALLOCATION_VALIDATOR_TAG => {
                let (validator_public_key, rem) = PublicKey::from_bytes(rem)?;
                let (amount, rem) = U512::from_bytes(rem)?;
                Ok((
                    SeigniorageAllocation::validator(validator_public_key, amount),
                    rem,
                ))
            }
            SEIGNIORAGE_ALLOCATION_DELEGATOR_TAG => {
                let (delegator_public_key, rem) = PublicKey::from_bytes(rem)?;
                let (validator_public_key, rem) = PublicKey::from_bytes(rem)?;
                let (amount, rem) = U512::from_bytes(rem)?;
                Ok((
                    SeigniorageAllocation::delegator(
                        delegator_public_key,
                        validator_public_key,
                        amount,
                    ),
                    rem,
                ))
            }
            _ => Err(bytesrepr::Error::Formatting),
        }
    }
}

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

/// Auction metadata.  Intended to be recorded at each era.
#[derive(Debug, Default, Clone, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "std", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct EraInfo {
    seigniorage_allocations: Vec<SeigniorageAllocation>,
}

impl EraInfo {
    /// Constructs a [`EraInfo`].
    pub fn new() -> Self {
        let seigniorage_allocations = Vec::new();
        EraInfo {
            seigniorage_allocations,
        }
    }

    /// Returns a reference to the seigniorage allocations collection
    pub fn seigniorage_allocations(&self) -> &Vec<SeigniorageAllocation> {
        &self.seigniorage_allocations
    }

    /// Returns a mutable reference to the seigniorage allocations collection
    pub fn seigniorage_allocations_mut(&mut self) -> &mut Vec<SeigniorageAllocation> {
        &mut self.seigniorage_allocations
    }

    /// Returns all seigniorage allocations that match the provided public key
    /// using the following criteria:
    /// * If the match candidate is a validator allocation, the provided public key is matched
    ///   against the validator public key.
    /// * If the match candidate is a delegator allocation, the provided public key is matched
    ///   against the delegator public key.
    pub fn select(&self, public_key: PublicKey) -> impl Iterator<Item = &SeigniorageAllocation> {
        self.seigniorage_allocations
            .iter()
            .filter(move |allocation| match allocation {
                SeigniorageAllocation::Validator {
                    validator_public_key,
                    ..
                } => public_key == *validator_public_key,
                SeigniorageAllocation::Delegator {
                    delegator_public_key,
                    ..
                } => public_key == *delegator_public_key,
            })
    }
}

impl ToBytes for EraInfo {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        self.seigniorage_allocations.to_bytes()
    }

    fn serialized_length(&self) -> usize {
        self.seigniorage_allocations.serialized_length()
    }
}

impl FromBytes for EraInfo {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (seigniorage_allocations, rem) = Vec::<SeigniorageAllocation>::from_bytes(bytes)?;
        Ok((
            EraInfo {
                seigniorage_allocations,
            },
            rem,
        ))
    }
}

impl CLTyped for EraInfo {
    fn cl_type() -> CLType {
        CLType::List(Box::new(SeigniorageAllocation::cl_type()))
    }
}

/// Generators for [`SeigniorageAllocation`] and [`EraInfo`]
#[cfg(any(feature = "gens", test))]
pub mod gens {
    use proptest::{
        collection::{self, SizeRange},
        prelude::Strategy,
        prop_oneof,
    };

    use crate::{
        crypto::gens::public_key_arb,
        gens::u512_arb,
        system::auction::{EraInfo, SeigniorageAllocation},
    };

    fn seigniorage_allocation_validator_arb() -> impl Strategy<Value = SeigniorageAllocation> {
        (public_key_arb(), u512_arb()).prop_map(|(validator_public_key, amount)| {
            SeigniorageAllocation::validator(validator_public_key, amount)
        })
    }

    fn seigniorage_allocation_delegator_arb() -> impl Strategy<Value = SeigniorageAllocation> {
        (public_key_arb(), public_key_arb(), u512_arb()).prop_map(
            |(delegator_public_key, validator_public_key, amount)| {
                SeigniorageAllocation::delegator(delegator_public_key, validator_public_key, amount)
            },
        )
    }

    /// Creates an arbitrary [`SeignorageAllocation`](crate::system::auction::SeigniorageAllocation)
    pub fn seigniorage_allocation_arb() -> impl Strategy<Value = SeigniorageAllocation> {
        prop_oneof![
            seigniorage_allocation_validator_arb(),
            seigniorage_allocation_delegator_arb()
        ]
    }

    /// Creates an arbitrary [`EraInfo`]
    pub fn era_info_arb(size: impl Into<SizeRange>) -> impl Strategy<Value = EraInfo> {
        collection::vec(seigniorage_allocation_arb(), size).prop_map(|allocations| {
            let mut era_info = EraInfo::new();
            *era_info.seigniorage_allocations_mut() = allocations;
            era_info
        })
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use crate::bytesrepr;

    use super::gens;

    proptest! {
        #[test]
        fn test_serialization_roundtrip(era_info in gens::era_info_arb(0..32)) {
            bytesrepr::test_serialization_roundtrip(&era_info)
        }
    }
}