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
//! Consensus roothash structures.
//!
//! # Note
//!
//! This **MUST** be kept in sync with go/roothash/api.
//!
use thiserror::Error;

use crate::{
    common::{
        crypto::{hash::Hash, signature::PublicKey},
        namespace::Namespace,
    },
    consensus::{registry::Runtime, scheduler::Committee, state::StateError},
};

// Modules.
mod block;
mod commitment;
mod message;

// Re-exports.
pub use block::*;
pub use commitment::*;
pub use message::*;

/// Errors emitted by the roothash module.
#[derive(Debug, Error)]
pub enum Error {
    #[error("roothash: invalid runtime {0}")]
    InvalidRuntime(Namespace),

    #[error(transparent)]
    State(#[from] StateError),

    #[error("roothash/commitment: no runtime configured")]
    NoRuntime,

    #[error("roothash/commitment: no committee configured")]
    NoCommittee,

    #[error("roothash/commitment: invalid committee kind")]
    InvalidCommitteeKind,

    #[error("roothash/commitment: batch RAK signature invalid")]
    RakSigInvalid,

    #[error("roothash/commitment: node not part of committee")]
    NotInCommittee,

    #[error("roothash/commitment: node already sent commitment")]
    AlreadyCommitted,

    #[error("roothash/commitment: submitted commitment is not based on correct block")]
    NotBasedOnCorrectBlock,

    #[error("roothash/commitment: discrepancy detected")]
    DiscrepancyDetected,

    #[error("roothash/commitment: still waiting for commits")]
    StillWaiting,

    #[error("roothash/commitment: insufficient votes to finalize discrepancy resolution round")]
    InsufficientVotes,

    #[error("roothash/commitment: bad executor commitment")]
    BadExecutorCommitment,

    #[error("roothash/commitment: invalid messages")]
    InvalidMessages,

    #[error("roothash/commitment: invalid round")]
    InvalidRound,

    #[error("roothash/commitment: no proposer commitment")]
    NoProposerCommitment,

    #[error("roothash/commitment: bad proposer commitment")]
    BadProposerCommitment,
}

/// Runtime block annotated with consensus information.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, cbor::Encode, cbor::Decode)]
pub struct AnnotatedBlock {
    /// Consensus height at which this runtime block was produced.
    pub consensus_height: i64,
    /// Runtime block.
    pub block: Block,
}

/// Result of a message being processed by the consensus layer.
#[derive(Clone, Debug, Default, PartialEq, Eq, cbor::Encode, cbor::Decode)]
pub struct MessageEvent {
    #[cbor(optional)]
    pub module: String,

    #[cbor(optional)]
    pub code: u32,

    #[cbor(optional)]
    pub index: u32,

    #[cbor(optional)]
    pub result: Option<cbor::Value>,
}

impl MessageEvent {
    /// Returns true if the event indicates that the message was successfully processed.
    pub fn is_success(&self) -> bool {
        self.code == 0
    }
}

/// Per-runtime state.
#[derive(Clone, Debug, Default, PartialEq, Eq, cbor::Encode, cbor::Decode)]
#[cbor(allow_unknown)]
pub struct RuntimeState {
    /// Latest per-epoch runtime descriptor.
    pub runtime: Runtime,
    /// Flag indicating whether the runtime is currently suspended.
    #[cbor(optional)]
    pub suspended: bool,

    // Runtime's first block.
    pub genesis_block: Block,

    /// Runtime's most recently finalized block.
    pub last_block: Block,
    /// Height at which the runtime's most recent block was finalized.
    pub last_block_height: i64,

    /// Runtime round which was normally processed by the runtime. This is also the round that
    /// contains the message results for the last processed runtime messages.
    pub last_normal_round: u64,
    /// Consensus block height corresponding to `last_normal_round`.
    pub last_normal_height: i64,

    /// Committee the executor pool is collecting commitments for.
    #[cbor(optional)]
    pub commitee: Option<Committee>,
    // NOTE: Commitment pool deserialization is currently not supported.
    /// Consensus height at which the round is scheduled for forced finalization.
    #[cbor(optional)]
    pub next_timeout: i64,

    /// Liveness statistics for the current epoch.
    pub liveness_stats: Option<LivenessStatistics>,
}

/// Per-epoch liveness statistics for nodes.
#[derive(Clone, Debug, Default, PartialEq, Eq, cbor::Encode, cbor::Decode)]
pub struct LivenessStatistics {
    /// Total number of rounds in the last epoch, excluding any rounds generated by the roothash
    /// service itself.
    pub total_rounds: u64,

    /// A list of counters, specified in committee order (e.g. counter at index i has the value for
    /// node i in the committee).
    pub good_rounds: Vec<u64>,

    /// A list that records the number of finalized rounds when a node acted as a proposed with the
    /// highest rank.
    ///
    /// The list is ordered according to the committee arrangement (i.e., the counter at index i
    /// holds the value for the node at index i in the committee).
    pub finalized_proposals: Vec<u64>,

    /// A list that records the number of failed rounds when a node/ acted as a proposer with the
    /// highest rank.
    ///
    /// The list is ordered according to the committee arrangement (i.e., the counter at index i
    /// holds the value for the node at index i in the committee).
    pub missed_proposals: Vec<u64>,
}

/// Information about how a particular round was executed by the consensus layer.
#[derive(Clone, Debug, Default, PartialEq, Eq, cbor::Encode, cbor::Decode)]
pub struct RoundResults {
    /// Results of executing emitted runtime messages.
    #[cbor(optional)]
    pub messages: Vec<MessageEvent>,

    /// Public keys of compute nodes' controlling entities that positively contributed to the round
    /// by replicating the computation correctly.
    #[cbor(optional)]
    pub good_compute_entities: Vec<PublicKey>,
    /// Public keys of compute nodes' controlling entities that negatively contributed to the round
    /// by causing discrepancies.
    #[cbor(optional)]
    pub bad_compute_entities: Vec<PublicKey>,
}

/// Per-round state and I/O roots that are stored in consensus state.
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, cbor::Encode, cbor::Decode)]
#[cbor(as_array)]
pub struct RoundRoots {
    pub state_root: Hash,
    pub io_root: Hash,
}

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

    use super::*;

    #[test]
    fn test_consistent_round_results() {
        let tcs = vec![
            ("oA==", RoundResults::default()),
            ("oWhtZXNzYWdlc4GiZGNvZGUBZm1vZHVsZWR0ZXN0", RoundResults {
                messages: vec![MessageEvent{module: "test".to_owned(), code: 1, index: 0, result: None}],
                ..Default::default()
            }),
            ("omhtZXNzYWdlc4GkZGNvZGUYKmVpbmRleAFmbW9kdWxlZHRlc3RmcmVzdWx0a3Rlc3QtcmVzdWx0dWdvb2RfY29tcHV0ZV9lbnRpdGllc4NYIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI=",
                RoundResults {
                    messages: vec![MessageEvent{module: "test".to_owned(), code: 42, index: 1, result: Some(cbor::Value::TextString("test-result".to_string()))}],
                    good_compute_entities: vec![
                        "0000000000000000000000000000000000000000000000000000000000000000".into(),
                        "0000000000000000000000000000000000000000000000000000000000000001".into(),
                        "0000000000000000000000000000000000000000000000000000000000000002".into(),
                    ],
                    ..Default::default()
                }),
            ("o2htZXNzYWdlc4GkZGNvZGUYKmVpbmRleAFmbW9kdWxlZHRlc3RmcmVzdWx0a3Rlc3QtcmVzdWx0dGJhZF9jb21wdXRlX2VudGl0aWVzgVggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF1Z29vZF9jb21wdXRlX2VudGl0aWVzglggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC",
                RoundResults {
                    messages: vec![MessageEvent{module: "test".to_owned(), code: 42, index: 1, result: Some(cbor::Value::TextString("test-result".to_string()))}],
                    good_compute_entities: vec![
                        "0000000000000000000000000000000000000000000000000000000000000000".into(),
                        "0000000000000000000000000000000000000000000000000000000000000002".into(),
                    ],
                    bad_compute_entities: vec![
                        "0000000000000000000000000000000000000000000000000000000000000001".into(),
                    ],
                }),
        ];
        for (encoded_base64, rr) in tcs {
            let dec: RoundResults =
                cbor::from_slice(&BASE64_STANDARD.decode(encoded_base64).unwrap())
                    .expect("round results should deserialize correctly");
            assert_eq!(dec, rr, "decoded results should match the expected value");
        }
    }

    #[test]
    fn test_consistent_round_roots() {
        let tcs = vec![
            ("glggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", RoundRoots::default()),
            ("glggPTf+WENeDYcyPe5KLBsznvlU3mNxbuefV0f5TZdPkT9YIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", RoundRoots {
                state_root: Hash::digest_bytes(b"test"),
                ..Default::default()
            }),
            ("glggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYID03/lhDXg2HMj3uSiwbM575VN5jcW7nn1dH+U2XT5E/", RoundRoots {
                io_root: Hash::digest_bytes(b"test"),
                ..Default::default()
            }),
            ("glggPTf+WENeDYcyPe5KLBsznvlU3mNxbuefV0f5TZdPkT9YID03/lhDXg2HMj3uSiwbM575VN5jcW7nn1dH+U2XT5E/",
                RoundRoots {
                    state_root: Hash::digest_bytes(b"test"),
                    io_root: Hash::digest_bytes(b"test"),
                }),
            ("glggC4+lzfqNgLxCHLxwDp+Bf5PLLb0DILrUZWwF+lp6Z/NYIJ3seczGUDFDvmAEdVCeep6Xsn8XRosTKWpu9wZ3mQRq",
                RoundRoots {
                    state_root: Hash::digest_bytes(b"test1"),
                    io_root: Hash::digest_bytes(b"test2"),
                }),
            ("glggnex5zMZQMUO+YAR1UJ56npeyfxdGixMpam73BneZBGpYIAuPpc36jYC8Qhy8cA6fgX+Tyy29AyC61GVsBfpaemfz",
                RoundRoots {
                    state_root: Hash::digest_bytes(b"test2"),
                    io_root: Hash::digest_bytes(b"test1"),
                }),
        ];

        for (encoded_base64, rr) in tcs {
            let dec: RoundRoots =
                cbor::from_slice(&BASE64_STANDARD.decode(encoded_base64).unwrap())
                    .expect("round roots should deserialize correctly");
            assert_eq!(
                dec, rr,
                "decoded round roots should match the expected value"
            );
        }
    }
}