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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Types used by the worker-host protocol.
use std::collections::BTreeMap;

use thiserror::Error;

use crate::{
    common::{
        crypto::{
            hash::Hash,
            signature::{self, Signature},
            x25519,
        },
        namespace::Namespace,
        sgx::{ias::AVR, Quote, QuotePolicy},
        version::Version,
    },
    consensus::{
        self,
        beacon::EpochTime,
        roothash::{self, Block, ComputeResultsHeader, Header},
        state::keymanager::Status as KeyManagerStatus,
        transaction::{Proof, SignedTransaction},
        LightBlock,
    },
    enclave_rpc,
    storage::mkvs::{sync, WriteLog},
    transaction::types::TxnBatch,
};

/// Computed batch.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct ComputedBatch {
    /// Compute results header.
    pub header: ComputeResultsHeader,
    /// Log that generates the I/O tree.
    pub io_write_log: WriteLog,
    /// Log of changes to the state tree.
    pub state_write_log: WriteLog,
    /// If this runtime uses a TEE, then this is the signature of the batch's
    /// BatchSigMessage with the node's RAK for this runtime.
    pub rak_sig: Signature,
    /// Messages emitted by the runtime.
    pub messages: Vec<roothash::Message>,
}

/// Storage sync request.
#[derive(Debug, cbor::Encode, cbor::Decode)]
pub enum StorageSyncRequest {
    SyncGet(sync::GetRequest),
    SyncGetPrefixes(sync::GetPrefixesRequest),
    SyncIterate(sync::IterateRequest),
}

#[derive(Debug)]
pub struct StorageSyncRequestWithEndpoint {
    pub endpoint: HostStorageEndpoint,
    pub request: StorageSyncRequest,
}

impl cbor::Encode for StorageSyncRequestWithEndpoint {
    fn into_cbor_value(self) -> cbor::Value {
        let mut request = cbor::EncodeAsMap::into_cbor_map(self.request);
        // Add endpoint to the given map.
        let key = cbor::values::IntoCborValue::into_cbor_value("endpoint");
        request.push((key, self.endpoint.into_cbor_value()));
        cbor::Value::Map(request)
    }
}

impl cbor::Decode for StorageSyncRequestWithEndpoint {
    fn try_from_cbor_value(value: cbor::Value) -> Result<Self, cbor::DecodeError> {
        match value {
            cbor::Value::Map(mut items) => {
                // Take the endpoint field from the map and decode the rest.
                let key = cbor::values::IntoCborValue::into_cbor_value("endpoint");
                let (index, _) = items
                    .iter()
                    .enumerate()
                    .find(|(_, v)| v.0 == key)
                    .ok_or(cbor::DecodeError::MissingField)?;
                let endpoint = items.remove(index).1;

                Ok(Self {
                    endpoint: cbor::Decode::try_from_cbor_value(endpoint)?,
                    request: cbor::Decode::try_from_cbor_value(cbor::Value::Map(items))?,
                })
            }
            _ => Err(cbor::DecodeError::UnexpectedType),
        }
    }
}

/// Storage sync response.
#[derive(Debug, cbor::Encode, cbor::Decode)]
pub enum StorageSyncResponse {
    ProofResponse(sync::ProofResponse),
}

/// Host storage endpoint.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, cbor::Encode, cbor::Decode)]
#[repr(u8)]
pub enum HostStorageEndpoint {
    Runtime = 0,
    Consensus = 1,
}

/// Runtime host protocol message body.
#[derive(Debug, cbor::Encode, cbor::Decode)]
pub enum Body {
    // An empty body.
    Empty {},

    // An error response.
    Error(Error),

    // Runtime interface.
    RuntimeInfoRequest(RuntimeInfoRequest),
    RuntimeInfoResponse(RuntimeInfoResponse),
    RuntimePingRequest {},
    RuntimeShutdownRequest {},
    RuntimeAbortRequest {},
    RuntimeAbortResponse {},
    RuntimeCapabilityTEERakInitRequest {
        target_info: Vec<u8>,
    },
    RuntimeCapabilityTEERakInitResponse {},
    RuntimeCapabilityTEERakReportRequest {},
    RuntimeCapabilityTEERakReportResponse {
        rak_pub: signature::PublicKey,
        rek_pub: x25519::PublicKey,
        report: Vec<u8>,
        nonce: String,
    },
    RuntimeCapabilityTEERakAvrRequest {
        avr: AVR,
    },
    RuntimeCapabilityTEERakAvrResponse {},
    RuntimeCapabilityTEERakQuoteRequest {
        quote: Quote,
    },
    RuntimeCapabilityTEERakQuoteResponse {
        height: u64,
        signature: Signature,
    },
    RuntimeRPCCallRequest {
        request: Vec<u8>,
        kind: enclave_rpc::types::Kind,
    },
    RuntimeRPCCallResponse {
        response: Vec<u8>,
    },
    RuntimeLocalRPCCallRequest {
        request: Vec<u8>,
    },
    RuntimeLocalRPCCallResponse {
        response: Vec<u8>,
    },
    RuntimeCheckTxBatchRequest {
        consensus_block: LightBlock,
        inputs: TxnBatch,
        block: Block,
        epoch: EpochTime,
        max_messages: u32,
    },
    RuntimeCheckTxBatchResponse {
        results: Vec<CheckTxResult>,
    },
    RuntimeExecuteTxBatchRequest {
        #[cbor(optional)]
        mode: ExecutionMode,
        consensus_block: LightBlock,
        round_results: roothash::RoundResults,
        io_root: Hash,
        #[cbor(optional)]
        inputs: Option<TxnBatch>,
        #[cbor(optional)]
        in_msgs: Vec<roothash::IncomingMessage>,
        block: Block,
        epoch: EpochTime,
        max_messages: u32,
    },
    RuntimeExecuteTxBatchResponse {
        batch: ComputedBatch,

        tx_hashes: Vec<Hash>,
        tx_reject_hashes: Vec<Hash>,
        tx_input_root: Hash,
        tx_input_write_log: WriteLog,
    },
    RuntimeKeyManagerStatusUpdateRequest {
        status: KeyManagerStatus,
    },
    RuntimeKeyManagerStatusUpdateResponse {},
    RuntimeKeyManagerQuotePolicyUpdateRequest {
        policy: QuotePolicy,
    },
    RuntimeKeyManagerQuotePolicyUpdateResponse {},
    RuntimeQueryRequest {
        consensus_block: LightBlock,
        header: Header,
        epoch: EpochTime,
        max_messages: u32,
        method: String,
        #[cbor(optional)]
        args: Vec<u8>,
    },
    RuntimeQueryResponse {
        #[cbor(optional)]
        data: Vec<u8>,
    },
    RuntimeConsensusSyncRequest {
        height: u64,
    },
    RuntimeConsensusSyncResponse {},

    // Host interface.
    HostRPCCallRequest {
        endpoint: String,
        request: Vec<u8>,
        kind: enclave_rpc::types::Kind,
        nodes: Vec<signature::PublicKey>,
        #[cbor(optional, rename = "pf")]
        peer_feedback: Option<enclave_rpc::types::PeerFeedback>,
    },
    HostRPCCallResponse {
        response: Vec<u8>,
        node: signature::PublicKey,
    },
    HostStorageSyncRequest(StorageSyncRequestWithEndpoint),
    HostStorageSyncResponse(StorageSyncResponse),
    HostLocalStorageGetRequest {
        key: Vec<u8>,
    },
    HostLocalStorageGetResponse {
        value: Vec<u8>,
    },
    HostLocalStorageSetRequest {
        key: Vec<u8>,
        value: Vec<u8>,
    },
    HostLocalStorageSetResponse {},
    HostFetchConsensusBlockRequest {
        height: u64,
    },
    HostFetchConsensusBlockResponse {
        block: LightBlock,
    },
    HostFetchConsensusEventsRequest(HostFetchConsensusEventsRequest),
    HostFetchConsensusEventsResponse(HostFetchConsensusEventsResponse),
    HostFetchTxBatchRequest {
        #[cbor(optional)]
        offset: Option<Hash>,
        limit: u32,
    },
    HostFetchTxBatchResponse {
        #[cbor(optional)]
        batch: Option<TxnBatch>,
    },
    HostFetchBlockMetadataTxRequest {
        height: u64,
    },
    HostFetchBlockMetadataTxResponse {
        signed_tx: SignedTransaction,
        proof: Proof,
    },
    HostFetchGenesisHeightRequest {},
    HostFetchGenesisHeightResponse {
        height: u64,
    },
    HostProveFreshnessRequest {
        blob: Vec<u8>,
    },
    HostProveFreshnessResponse {
        signed_tx: SignedTransaction,
        proof: Proof,
    },
    HostIdentityRequest {},
    HostIdentityResponse {
        node_id: signature::PublicKey,
    },
}

impl Default for Body {
    fn default() -> Self {
        Self::Empty {}
    }
}

/// A serializable error.
#[derive(Clone, Debug, Default, Error, cbor::Encode, cbor::Decode)]
#[error("module: {module} code: {code} message: {message}")]
pub struct Error {
    #[cbor(optional)]
    pub module: String,

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

    #[cbor(optional)]
    pub message: String,
}

impl Error {
    /// Create a new error.
    pub fn new(module: &str, code: u32, msg: &str) -> Self {
        Self {
            module: module.to_owned(),
            code,
            message: msg.to_owned(),
        }
    }
}

impl From<anyhow::Error> for Error {
    fn from(err: anyhow::Error) -> Self {
        Self {
            module: "unknown".to_string(),
            code: 1,
            message: err.to_string(),
        }
    }
}

/// Runtime information request.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct RuntimeInfoRequest {
    pub runtime_id: Namespace,
    pub consensus_backend: String,
    pub consensus_protocol_version: Version,
    pub consensus_chain_context: String,

    #[cbor(optional)]
    pub local_config: BTreeMap<String, cbor::Value>,
}

/// Set of supported runtime features.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
pub struct Features {
    /// Schedule control feature.
    #[cbor(optional)]
    pub schedule_control: Option<FeatureScheduleControl>,
    /// A feature specifying that the runtime supports updating key manager's quote policy.
    #[cbor(optional)]
    pub key_manager_quote_policy_updates: bool,
    /// A feature specifying that the runtime supports updating key manager's status.
    #[cbor(optional)]
    pub key_manager_status_updates: bool,
    /// A feature specifying that the runtime supports rotating key manager's master secret.
    #[cbor(optional)]
    pub key_manager_master_secret_rotation: bool,
    /// A feature specifying that the runtime supports same-block consensus validation.
    #[cbor(optional)]
    pub same_block_consensus_validation: bool,
}

impl Default for Features {
    fn default() -> Self {
        Self {
            schedule_control: None,
            key_manager_quote_policy_updates: true,
            key_manager_status_updates: true,
            key_manager_master_secret_rotation: false,
            same_block_consensus_validation: true,
        }
    }
}

/// A feature specifying that the runtime supports controlling the scheduling of batches. This means
/// that the scheduler should only take priority into account and ignore weights, leaving it up to
/// the runtime to decide which transactions to include.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct FeatureScheduleControl {
    /// Size of the initial batch of transactions.
    pub initial_batch_size: u32,
}

/// Runtime information response.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct RuntimeInfoResponse {
    /// The runtime protocol version supported by the runtime.
    pub protocol_version: Version,

    /// The version of the runtime.
    pub runtime_version: Version,

    /// Describes the features supported by the runtime.
    #[cbor(optional)]
    pub features: Option<Features>,
}

/// Batch execution mode.
#[derive(Clone, Debug, PartialEq, Eq, cbor::Encode, cbor::Decode)]
#[cbor(with_default)]
pub enum ExecutionMode {
    /// Execution mode where the batch of transactions is executed as-is without the ability to
    /// perform and modifications to the batch.
    Execute = 0,
    /// Execution mode where the runtime is in control of scheduling and may arbitrarily modify the
    /// batch during execution.
    ///
    /// This execution mode will only be used in case the runtime advertises to support the schedule
    /// control feature. In this case the call will only contain up to InitialBatchSize transactions
    /// and the runtime will need to request more if it needs more.
    Schedule = 1,
}

impl Default for ExecutionMode {
    fn default() -> Self {
        Self::Execute
    }
}

/// Result of a CheckTx operation.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct CheckTxResult {
    pub error: Error,
    pub meta: Option<CheckTxMetadata>,
}

/// CheckTx transaction metadata.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct CheckTxMetadata {
    #[cbor(optional)]
    pub priority: u64,

    #[cbor(optional)]
    pub sender: Vec<u8>,
    #[cbor(optional)]
    pub sender_seq: u64,
    #[cbor(optional)]
    pub sender_state_seq: u64,
}

/// Consensus event kind.
#[derive(Clone, Copy, Debug, cbor::Encode, cbor::Decode)]
#[repr(u8)]
pub enum EventKind {
    Staking = 1,
    Registry = 2,
    RootHash = 3,
    Governance = 4,
}

/// Request to host to fetch the consensus events for the given height.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
#[cbor(no_default)]
pub struct HostFetchConsensusEventsRequest {
    pub height: u64,
    pub kind: EventKind,
}

/// Response from host fetching the consensus events for the given height.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct HostFetchConsensusEventsResponse {
    pub events: Vec<consensus::Event>,
}

#[derive(Clone, Copy, Debug, cbor::Encode, cbor::Decode)]
#[repr(u8)]
pub enum MessageType {
    /// Invalid message (should never be seen on the wire).
    Invalid = 0,
    /// Request.
    Request = 1,
    /// Response.
    Response = 2,
}

impl Default for MessageType {
    fn default() -> Self {
        Self::Invalid
    }
}

/// Runtime protocol message.
#[derive(Debug, Default, cbor::Encode, cbor::Decode)]
pub struct Message {
    /// Unique request identifier.
    pub id: u64,
    /// Message type.
    pub message_type: MessageType,
    /// Message body.
    pub body: Body,
}