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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{
    errors::JsonRpcError,
    stream::request::StreamMethod,
    views::{EventView, TransactionView},
    Id, JsonRpcVersion,
};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum StreamJsonRpcResponseView {
    Transaction(TransactionView),
    Event(EventView),
    SubscribeResult(SubscribeResult),
    UnsubscribeResult(UnsubscribeResult),
}

impl StreamJsonRpcResponseView {
    fn from_method(
        method: &StreamMethod,
        value: serde_json::Value,
    ) -> Result<StreamJsonRpcResponseView, serde_json::Error> {
        // The first message in a stream is a `SubscribeResult`
        if value.get("status").is_some() {
            return Ok(Self::SubscribeResult(serde_json::from_value(value)?));
        }
        // Handle unsubscribe results message
        if value.get("unsubscribe").is_some() {
            return Ok(Self::UnsubscribeResult(serde_json::from_value(value)?));
        }
        Ok(match method {
            StreamMethod::SubscribeToTransactions => {
                Self::Transaction(serde_json::from_value(value)?)
            }
            StreamMethod::SubscribeToEvents => Self::Event(serde_json::from_value(value)?),
            StreamMethod::Unsubscribe => Self::UnsubscribeResult(serde_json::from_value(value)?),
        })
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct StreamJsonRpcResponse {
    pub jsonrpc: JsonRpcVersion,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
}

impl StreamJsonRpcResponse {
    pub fn parse_result(
        &self,
        method: &StreamMethod,
    ) -> Result<Option<StreamJsonRpcResponseView>, serde_json::Error> {
        Ok(match self.result.clone() {
            None => None,
            Some(result) => Some(StreamJsonRpcResponseView::from_method(method, result)?),
        })
    }

    pub fn result(id: Option<Id>, result: Option<serde_json::Value>) -> Self {
        Self {
            jsonrpc: JsonRpcVersion::V2,
            id,
            result,
            error: None,
        }
    }

    pub fn error(id: Option<Id>, error: JsonRpcError) -> Self {
        Self {
            jsonrpc: JsonRpcVersion::V2,
            id,
            result: None,
            error: Some(error),
        }
    }
}

impl From<StreamJsonRpcResponse> for serde_json::Value {
    fn from(response: StreamJsonRpcResponse) -> Self {
        serde_json::to_value(&response).unwrap()
    }
}

impl FromStr for StreamJsonRpcResponse {
    type Err = serde_json::Error;

    fn from_str(string: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(string)
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum SubscriptionResult {
    #[serde(rename = "OK")]
    OK,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct UnsubscribeResult {
    pub unsubscribe: SubscriptionResult,
}

impl UnsubscribeResult {
    pub fn ok() -> Self {
        Self {
            unsubscribe: SubscriptionResult::OK,
        }
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct SubscribeResult {
    pub status: SubscriptionResult,
    pub transaction_version: u64,
}

impl SubscribeResult {
    pub fn ok(transaction_version: u64) -> Self {
        Self {
            status: SubscriptionResult::OK,
            transaction_version,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::views::{BytesView, TransactionDataView, VMStatusView};
    use diem_crypto::HashValue;

    fn response_view_helper(method: &StreamMethod, input: String) -> StreamJsonRpcResponseView {
        let response: StreamJsonRpcResponse =
            serde_json::from_str(&input).expect("Could not parse input");
        assert_eq!(
            response.id.clone().expect("Expected ID"),
            Id::String(Box::from("my-id"))
        );
        assert_eq!(response.jsonrpc, JsonRpcVersion::V2);

        response
            .parse_result(method)
            .expect("Err when parsing result")
            .expect("None when parsing result")
    }

    #[test]
    fn test_ok_result_parsing() {
        let input = serde_json::json!({
          "jsonrpc": "2.0",
          "id": "my-id",
          "result": {
            "status": "OK",
            "transaction_version": 77
          }
        })
        .to_string();
        let result = response_view_helper(&StreamMethod::SubscribeToTransactions, input);

        let expected = StreamJsonRpcResponseView::SubscribeResult(SubscribeResult {
            status: SubscriptionResult::OK,
            transaction_version: 77,
        });
        assert_eq!(result, expected);
    }

    #[test]
    fn test_data_result_parsing() {
        let input = serde_json::json!({
          "jsonrpc": "2.0",
          "id": "my-id",
          "result": {
            "version": 124,
            "transaction": {
              "type": "blockmetadata",
              "timestamp_usecs": 1624389817286906_u64
            },
            "hash": "496176cd664651d81673832598c2dcdc47e9d2f900121a464351610bfa6d29fa",
            "bytes": "0000",
            "events": [],
            "vm_status": { "type": "executed" },
            "gas_used": 100000000
          }
        })
        .to_string();
        let result = response_view_helper(&StreamMethod::SubscribeToTransactions, input);

        let expected = StreamJsonRpcResponseView::Transaction(TransactionView {
            version: 124,
            transaction: TransactionDataView::BlockMetadata {
                timestamp_usecs: 1624389817286906,
            },
            hash: HashValue::from_hex(
                "496176cd664651d81673832598c2dcdc47e9d2f900121a464351610bfa6d29fa",
            )
            .expect("Could not parse HashValue hex"),
            bytes: BytesView::from(vec![0, 0]),
            events: vec![],
            vm_status: VMStatusView::Executed,
            gas_used: 100000000,
        });
        assert_eq!(result, expected);
    }
}