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
//! Registry state in the consensus layer.
use anyhow::anyhow;

use crate::{
    common::{
        crypto::{
            hash::Hash,
            signature::{MultiSigned, PublicKey},
        },
        key_format::{KeyFormat, KeyFormatAtom},
        namespace::Namespace,
    },
    consensus::{
        registry::{Node, Runtime},
        state::StateError,
    },
    key_format,
    storage::mkvs::ImmutableMKVS,
};

/// Consensus registry state wrapper.
pub struct ImmutableState<'a, T: ImmutableMKVS> {
    mkvs: &'a T,
}

impl<'a, T: ImmutableMKVS> ImmutableState<'a, T> {
    /// Constructs a new ImmutableMKVS.
    pub fn new(mkvs: &'a T) -> ImmutableState<'a, T> {
        ImmutableState { mkvs }
    }
}

key_format!(SignedNodeKeyFmt, 0x11, Hash);
key_format!(RuntimeKeyFmt, 0x13, Hash);
key_format!(SuspendedRuntimeKeyFmt, 0x18, Hash);

impl<'a, T: ImmutableMKVS> ImmutableState<'a, T> {
    fn decode_node(&self, data: &[u8]) -> Result<Node, StateError> {
        let signed: MultiSigned =
            cbor::from_slice(data).map_err(|err| StateError::Unavailable(anyhow!(err)))?;
        // The signed blob is transported as-is so we need to use non-strict decoding.
        cbor::from_slice_non_strict(&signed.blob)
            .map_err(|err| StateError::Unavailable(anyhow!(err)))
    }

    /// Looks up a specific node by its identifier.
    pub fn node(&self, id: &PublicKey) -> Result<Option<Node>, StateError> {
        let h = Hash::digest_bytes(id.as_ref());
        match self.mkvs.get(&SignedNodeKeyFmt(h).encode()) {
            Ok(Some(b)) => Ok(Some(self.decode_node(&b)?)),
            Ok(None) => Ok(None),
            Err(err) => Err(StateError::Unavailable(anyhow!(err))),
        }
    }

    /// Returns the list of all registered nodes.
    pub fn nodes(&self) -> Result<Vec<Node>, StateError> {
        let mut it = self.mkvs.iter();
        it.seek(&SignedNodeKeyFmt::default().encode_partial(0));

        let mut result: Vec<Node> = Vec::new();

        while let Some(value) = it
            .next()
            .and_then(|(key, value)| SignedNodeKeyFmt::decode(&key).map(|_| value))
        {
            result.push(self.decode_node(&value)?)
        }

        Ok(result)
    }

    fn decode_runtime(&self, data: &[u8]) -> Result<Runtime, StateError> {
        cbor::from_slice(data).map_err(|err| StateError::Unavailable(anyhow!(err)))
    }

    /// Looks up a specific runtime by its identifier.
    ///
    /// # Note
    ///
    /// This includes both non-suspended and suspended runtimes.
    pub fn runtime(&self, id: &Namespace) -> Result<Option<Runtime>, StateError> {
        let h = Hash::digest_bytes(id.as_ref());

        // Try non-suspended first.
        match self.mkvs.get(&RuntimeKeyFmt(h).encode()) {
            Ok(Some(b)) => Ok(Some(self.decode_runtime(&b)?)),
            Ok(None) => {
                // Also try suspended.
                match self.mkvs.get(&SuspendedRuntimeKeyFmt(h).encode()) {
                    Ok(Some(b)) => Ok(Some(self.decode_runtime(&b)?)),
                    Ok(None) => Ok(None),
                    Err(err) => Err(StateError::Unavailable(anyhow!(err))),
                }
            }
            Err(err) => Err(StateError::Unavailable(anyhow!(err))),
        }
    }
}

#[cfg(test)]
mod test {
    use std::collections::BTreeMap;

    use crate::{
        common::crypto::signature,
        consensus::registry::{
            AnyNodeRuntimeAdmissionPolicy, Capabilities, CapabilityTEE, ConsensusInfo,
            EntityWhitelistRoleAdmissionPolicy, NodeRuntime, P2PInfo, PerRoleAdmissionPolicy,
            RolesMask, RuntimeAdmissionPolicy, RuntimeKind, TEEHardware, TLSInfo, VRFInfo,
            VersionInfo,
        },
        storage::mkvs::{
            interop::{Fixture, ProtocolServer},
            Root, RootType, Tree,
        },
        Version,
    };

    use super::*;

    #[test]
    fn test_registry_state_interop() {
        // Keep in sync with go/consensus/cometbft/apps/registry/state/interop/interop.go.
        // If mock consensus state changes, update the root hash bellow.
        // See protocol server stdout for hash.
        // To make the hash show up during tests, run "cargo test" as
        // "cargo test -- --nocapture".

        // Setup protocol server with initialized mock consensus state.
        let server = ProtocolServer::new(Fixture::ConsensusMock.into());
        let mock_consensus_root = Root {
            version: 1,
            root_type: RootType::State,
            hash: Hash::from("8e39bf193f8a954ab8f8d7cb6388c591fd0785ea060bbd8e3752e266b54499d3"),
            ..Default::default()
        };
        let mkvs = Tree::builder()
            .with_capacity(100_000, 10_000_000)
            .with_root(mock_consensus_root)
            .build(server.read_sync());
        let registry_state = ImmutableState::new(&mkvs);

        // Test get nodes.
        let nodes = registry_state.nodes().expect("nodes query should work");
        assert_eq!(
            nodes.len(),
            2,
            "expected number of nodes should be returned"
        );

        let expected_nodes = vec![
                Node{
                    v: 3,
                    id: signature::PublicKey::from("43e5aaee54c768867718837ef4f6a6161e0615da0fcf8da394e5c8b7a0d54c18"),
                    entity_id: signature::PublicKey::from("761950dfe65936f6e9d06a0124bc930f7d5b1812ceefdfb2cae0ef5841291531"),
                    expiration: 32,
                    ..Default::default()
                },
                Node{
                    v: 3,
                    id: signature::PublicKey::from("f43c3559658f76b85d0630f56dc75d603807ac60be0ca3aada66799289066758"),
                    entity_id: signature::PublicKey::from("761950dfe65936f6e9d06a0124bc930f7d5b1812ceefdfb2cae0ef5841291531"),
                    expiration: 32,
                    tls: TLSInfo{
                        pub_key: signature::PublicKey::from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0"),
                        ..Default::default()
                    },
                    p2p: P2PInfo{
                        id: signature::PublicKey::from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3"),
                        addresses: Some(Vec::new()),
                    },
                    consensus: ConsensusInfo{
                        id: signature::PublicKey::from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff4"),
                        addresses: Some(Vec::new()),
                    },
                    vrf: VRFInfo{
                        id: PublicKey::from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff5"),
                    },
                    runtimes: Some(vec![
                        NodeRuntime{
                            id: Namespace::from("8000000000000000000000000000000000000000000000000000000000000010"),
                            version: Version::from(321),
                            ..Default::default()
                        },
                        NodeRuntime{
                            id: Namespace::from("8000000000000000000000000000000000000000000000000000000000000011"),
                            version: Version::from(123),
                            capabilities: Capabilities{
                               tee: Some(CapabilityTEE{
                                   hardware: TEEHardware::TEEHardwareIntelSGX,
                                    rak: signature::PublicKey::from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8"),
                                    attestation: vec![0, 1,2,3,4,5],
                                    ..Default::default()
                               }),
                            },
                            extra_info: Some(vec![5,3,2,1]),
                        },
                    ]),
                    ..Default::default()
                },
            ];
        assert_eq!(nodes, expected_nodes,);

        let node = registry_state
            .node(&expected_nodes.get(1).unwrap().id)
            .expect("node query should work");
        assert_eq!(node, Some(expected_nodes.get(1).unwrap().clone()));

        let node = registry_state
            .node(&signature::PublicKey::from(
                "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            ))
            .expect("node query should work");
        assert_eq!(node, None);

        let expected_runtimes = vec![
            Runtime {
                v: 3,
                id: Namespace::from(
                    "8000000000000000000000000000000000000000000000000000000000000010",
                ),
                entity_id: signature::PublicKey::from(
                    "761950dfe65936f6e9d06a0124bc930f7d5b1812ceefdfb2cae0ef5841291531",
                ),
                kind: RuntimeKind::KindCompute,
                tee_hardware: TEEHardware::TEEHardwareInvalid,
                admission_policy: RuntimeAdmissionPolicy {
                    any_node: Some(AnyNodeRuntimeAdmissionPolicy {}),
                    ..Default::default()
                },
                deployments: vec![
                    VersionInfo {
                        version: Version::from(321),
                        valid_from: 42,
                        ..Default::default()
                    },
                    VersionInfo {
                        version: Version::from(320),
                        valid_from: 10,
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            Runtime {
                v: 3,
                id: Namespace::from(
                    "8000000000000000000000000000000000000000000000000000000000000011",
                ),
                entity_id: signature::PublicKey::from(
                    "761950dfe65936f6e9d06a0124bc930f7d5b1812ceefdfb2cae0ef5841291531",
                ),
                kind: RuntimeKind::KindCompute,
                tee_hardware: TEEHardware::TEEHardwareIntelSGX,
                admission_policy: RuntimeAdmissionPolicy {
                    any_node: Some(AnyNodeRuntimeAdmissionPolicy {}),
                    ..Default::default()
                },
                deployments: vec![
                    VersionInfo {
                        version: Version::from(123),
                        valid_from: 42,
                        tee: vec![1, 2, 3, 4, 5],
                        bundle_checksum: vec![0x5; 32],
                    },
                    VersionInfo {
                        version: Version::from(120),
                        valid_from: 10,
                        tee: vec![5, 4, 3, 2, 1],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            Runtime {
                v: 3,
                id: Namespace::from(
                    "8000000000000000000000000000000000000000000000000000000000000012",
                ),
                entity_id: signature::PublicKey::from(
                    "761950dfe65936f6e9d06a0124bc930f7d5b1812ceefdfb2cae0ef5841291531",
                ),
                kind: RuntimeKind::KindCompute,
                tee_hardware: TEEHardware::TEEHardwareIntelSGX,
                admission_policy: RuntimeAdmissionPolicy {
                    per_role: BTreeMap::from([(
                        RolesMask::ROLE_OBSERVER,
                        PerRoleAdmissionPolicy {
                            entity_whitelist: Some(EntityWhitelistRoleAdmissionPolicy {
                                entities: BTreeMap::new(),
                            }),
                        },
                    )]),
                    ..Default::default()
                },
                deployments: vec![VersionInfo {
                    version: Version::from(123),
                    valid_from: 42,
                    tee: vec![1, 2, 3, 4, 5],
                    bundle_checksum: vec![0x5; 32],
                }],
                ..Default::default()
            },
        ];

        for rt in expected_runtimes {
            let ext_rt = registry_state
                .runtime(&rt.id)
                .expect("runtime query should work");
            assert_eq!(ext_rt, Some(rt));
        }
    }
}