casper_types/chainspec/
next_upgrade.rs1use std::fmt::{self, Display, Formatter};
2
3#[cfg(feature = "datasize")]
4use datasize::DataSize;
5#[cfg(feature = "json-schema")]
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use crate::{
10 bytesrepr::{self, FromBytes, ToBytes},
11 ActivationPoint, ProtocolConfig, ProtocolVersion,
12};
13
14#[cfg(any(feature = "testing", test))]
15use rand::Rng;
16
17#[cfg(any(feature = "testing", test))]
18use crate::testing::TestRng;
19
20#[cfg_attr(feature = "datasize", derive(DataSize))]
22#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
23#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone, Copy)]
24pub struct NextUpgrade {
25 activation_point: ActivationPoint,
26 protocol_version: ProtocolVersion,
27}
28
29impl NextUpgrade {
30 pub fn new(activation_point: ActivationPoint, protocol_version: ProtocolVersion) -> Self {
32 NextUpgrade {
33 activation_point,
34 protocol_version,
35 }
36 }
37
38 pub fn activation_point(&self) -> ActivationPoint {
40 self.activation_point
41 }
42
43 #[cfg(any(feature = "testing", test))]
45 pub fn random(rng: &mut TestRng) -> Self {
46 Self {
47 activation_point: ActivationPoint::random(rng),
48 protocol_version: ProtocolVersion::from_parts(rng.gen(), rng.gen(), rng.gen()),
49 }
50 }
51}
52
53impl From<ProtocolConfig> for NextUpgrade {
54 fn from(protocol_config: ProtocolConfig) -> Self {
55 NextUpgrade {
56 activation_point: protocol_config.activation_point,
57 protocol_version: protocol_config.version,
58 }
59 }
60}
61
62impl Display for NextUpgrade {
63 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
64 write!(
65 formatter,
66 "next upgrade to {} at start of era {}",
67 self.protocol_version,
68 self.activation_point.era_id()
69 )
70 }
71}
72
73impl ToBytes for NextUpgrade {
74 fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
75 let mut buffer = bytesrepr::allocate_buffer(self)?;
76 self.write_bytes(&mut buffer)?;
77 Ok(buffer)
78 }
79
80 fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
81 self.activation_point.write_bytes(writer)?;
82 self.protocol_version.write_bytes(writer)
83 }
84
85 fn serialized_length(&self) -> usize {
86 self.activation_point.serialized_length() + self.protocol_version.serialized_length()
87 }
88}
89
90impl FromBytes for NextUpgrade {
91 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
92 let (activation_point, remainder) = ActivationPoint::from_bytes(bytes)?;
93 let (protocol_version, remainder) = ProtocolVersion::from_bytes(remainder)?;
94 Ok((
95 NextUpgrade {
96 activation_point,
97 protocol_version,
98 },
99 remainder,
100 ))
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107 use crate::testing::TestRng;
108
109 #[test]
110 fn bytesrepr_roundtrip() {
111 let rng = &mut TestRng::new();
112
113 let val = NextUpgrade::random(rng);
114 bytesrepr::test_serialization_roundtrip(&val);
115 }
116}