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
//! 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::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
    }
}

/// 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 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::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::decode(encoded_base64).unwrap())
                .expect("round roots should deserialize correctly");
            assert_eq!(
                dec, rr,
                "decoded round roots should match the expected value"
            );
        }
    }
}