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
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
//! This module contains types used to describe the REX network.
use std::{fmt, mem::size_of};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
/// The representation of an epoch ID.
#[derive(
BorshSerialize,
BorshDeserialize,
Clone,
Copy,
Debug,
Default,
Deserialize,
Eq,
Hash,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
#[serde(transparent)]
#[repr(transparent)]
pub struct RexEpochId(u64);
impl RexEpochId {
/// The maximum size used when serializing an [`RexEpochId`] using [`borsh`].
pub const BORSH_SERIALIZED_SIZE: usize = size_of::<u64>();
/// Wraps a raw epoch number.
pub const fn new(epoch: u64) -> Self {
Self(epoch)
}
/// Returns the epoch as a `u64`.
pub const fn as_u64(self) -> u64 {
self.0
}
}
impl fmt::Display for RexEpochId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
/// Index of a committee in the REX configuration.
#[derive(
BorshSerialize,
BorshDeserialize,
Clone,
Copy,
Debug,
Default,
Deserialize,
Eq,
Hash,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
pub struct CommitteeIndex(pub u32);
impl CommitteeIndex {
/// The maximum size used when serializing a [`CommitteeIndex`] using [`borsh`].
pub const BORSH_SERIALIZED_SIZE: usize = size_of::<u32>();
/// Committee 0: the Standard REX committee.
///
/// The TEE Registry orders the committees of a REX configuration by kind,
/// in this fixed order; use these named indices instead of hardcoding
/// `0`/`1`.
pub const STANDARD_REX: Self = Self(0);
/// Committee 1: the DKG / crypto-service committee.
pub const CRYPTO_SERVICE: Self = Self(1);
/// Returns the index as a `usize`, e.g. for indexing the committee `Vec`
/// of a REX configuration.
pub const fn as_usize(self) -> usize {
self.0 as usize
}
}
impl fmt::Display for CommitteeIndex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
/// The REX committees established at genesis, by kind.
///
/// This is the closed, semantic view for code that targets a specific
/// committee: matching on it is exhaustive, and an invalid committee cannot
/// be constructed. [`CommitteeIndex`] remains the open wire representation
/// (a REX configuration's committee `Vec` is not capped by the type system),
/// so conversion from an index is fallible.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum GenesisCommittee {
/// Committee 0: the Standard REX committee.
StandardRex,
/// Committee 1: the DKG / crypto-service committee.
CryptoService,
}
impl GenesisCommittee {
/// All committees established at genesis, in committee-index order.
pub const ALL: [Self; 2] = [Self::StandardRex, Self::CryptoService];
/// Number of REX committees established at genesis.
pub const COUNT: usize = Self::ALL.len();
/// The positional committee index this committee occupies in a REX
/// configuration.
pub const fn index(self) -> CommitteeIndex {
match self {
Self::StandardRex => CommitteeIndex::STANDARD_REX,
Self::CryptoService => CommitteeIndex::CRYPTO_SERVICE,
}
}
}
impl From<GenesisCommittee> for CommitteeIndex {
fn from(committee: GenesisCommittee) -> Self {
committee.index()
}
}
/// Error returned when a [`CommitteeIndex`] does not name a committee
/// established at genesis.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("committee index {0} does not name a genesis committee")]
pub struct UnknownGenesisCommittee(pub CommitteeIndex);
impl TryFrom<CommitteeIndex> for GenesisCommittee {
type Error = UnknownGenesisCommittee;
fn try_from(index: CommitteeIndex) -> Result<Self, Self::Error> {
Self::ALL
.into_iter()
.find(|committee| committee.index() == index)
.ok_or(UnknownGenesisCommittee(index))
}
}
/// Index of a node within a REX committee.
#[derive(
BorshSerialize,
BorshDeserialize,
Clone,
Copy,
Debug,
Default,
Deserialize,
Eq,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
pub struct NodeIndex(pub u32);
impl NodeIndex {
/// The maximum size used when serializing a [`NodeIndex`] using [`borsh`].
pub const BORSH_SERIALIZED_SIZE: usize = size_of::<u32>();
}
impl fmt::Display for NodeIndex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
/// The identifier to locate a REX node in a REX configuration.
#[derive(
BorshSerialize,
BorshDeserialize,
Clone,
Copy,
Debug,
Default,
Deserialize,
Eq,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
pub struct NodeId {
pub epoch: RexEpochId,
pub committee: CommitteeIndex,
pub index: NodeIndex,
}
impl NodeId {
/// The maximum size used when serializing an [`NodeId`] using [`borsh`].
pub const BORSH_SERIALIZED_SIZE: usize = RexEpochId::BORSH_SERIALIZED_SIZE
+ CommitteeIndex::BORSH_SERIALIZED_SIZE
+ NodeIndex::BORSH_SERIALIZED_SIZE;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_genesis_committee_indices_round_trip() {
for committee in GenesisCommittee::ALL {
assert_eq!(GenesisCommittee::try_from(committee.index()), Ok(committee));
}
}
#[test]
fn test_genesis_committee_all_is_in_committee_index_order() {
for (position, committee) in GenesisCommittee::ALL.into_iter().enumerate() {
assert_eq!(committee.index().as_usize(), position);
}
}
#[test]
fn test_genesis_committee_rejects_index_beyond_the_genesis_committees() {
let beyond = CommitteeIndex(GenesisCommittee::COUNT as u32);
assert_eq!(
GenesisCommittee::try_from(beyond),
Err(UnknownGenesisCommittee(beyond))
);
}
// `RexEpochId` is borsh-serialized on-chain (REX configuration, crypto-service
// state) and serde-serialized on the wire. Pin that it is byte-identical to
// the underlying `u64` in every encoding, so `#[serde(transparent)]` /
// `#[repr(transparent)]` leave existing account and wire bytes unchanged.
#[test]
fn test_epoch_id_is_byte_identical_to_u64() {
let raw: u64 = 0x00ad_beef_dead_beef;
let e = RexEpochId::new(raw);
assert_eq!(borsh::to_vec(&e).unwrap(), raw.to_le_bytes());
assert_eq!(RexEpochId::BORSH_SERIALIZED_SIZE, raw.to_le_bytes().len());
assert_eq!(bcs::to_bytes(&e).unwrap(), bcs::to_bytes(&raw).unwrap());
assert_eq!(
bincode::serialize(&e).unwrap(),
bincode::serialize(&raw).unwrap()
);
assert_eq!(serde_json::to_string(&RexEpochId::new(7)).unwrap(), "7");
assert_eq!(
serde_json::from_str::<RexEpochId>("7").unwrap(),
RexEpochId::new(7)
);
}
// `committee_index` is part of the `DBMap<ValidatorRexScoreKey, _>` key
// (typed-store encodes keys as bincode big-endian fixint) and of the
// BCS-encoded `WriteSet::validator_rex_scores` value. Pin that the newtype
// is byte-identical to the underlying `u32` in every encoding, so wrapping
// the field leaves existing on-disk keys and serialized values unchanged.
#[test]
fn test_committee_index_is_byte_identical_to_u32() {
let raw: u32 = 0xdead_beef;
let c = CommitteeIndex(raw);
assert_eq!(borsh::to_vec(&c).unwrap(), raw.to_le_bytes());
assert_eq!(
CommitteeIndex::BORSH_SERIALIZED_SIZE,
raw.to_le_bytes().len()
);
assert_eq!(bcs::to_bytes(&c).unwrap(), bcs::to_bytes(&raw).unwrap());
assert_eq!(
bincode::serialize(&c).unwrap(),
bincode::serialize(&raw).unwrap()
);
assert_eq!(serde_json::to_string(&CommitteeIndex(7)).unwrap(), "7");
assert_eq!(
serde_json::from_str::<CommitteeIndex>("7").unwrap(),
CommitteeIndex(7)
);
}
// `CommitteeIndex::Ord` orders the in-memory `BTreeSet`
// `modified_validator_rex_scores`, which fixes the entry order of the
// serialized `WriteSet::validator_rex_scores` Vec — this must stay
// deterministic across nodes. (Not the RocksDB key order, which is
// byte-lexicographic and covered by the byte-identity test above.)
#[test]
fn test_committee_index_ord_matches_u32() {
let raws: [u32; 5] = [0, 1, 2, 100, u32::MAX];
for &a in &raws {
for &b in &raws {
assert_eq!(
CommitteeIndex(a).cmp(&CommitteeIndex(b)),
a.cmp(&b),
"Ord mismatch for {a} vs {b}"
);
}
}
}
}