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
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

use crate::command::helpers::{input_password, password_prompt};
use clap::ArgMatches;
use jsonrpsee::{core::client::ClientT, http_client::HttpClientBuilder};
use serde_json::{Map, Value};

pub struct RpcCommand {
    pub url: String,
    pub method: String,
    pub args: Vec<Value>,
}

impl RpcCommand {
    pub fn parse(matches: &ArgMatches) -> Result<Option<RpcCommand>, String> {
        let method = match matches.get_one::<String>("rpc-method") {
            Some(method) => method,
            None => return Ok(None),
        };

        let url = match matches.get_one::<String>("url") {
            Some(url) => url,
            None => return Err(String::from("RPC URL not specified")),
        };

        let args: Vec<Value> = match matches.get_many::<String>("rpc-args") {
            Some(args) => {
                let mut params = Vec::new();

                for arg in args {
                    match ArgSchema::parse(arg).value(matches)? {
                        Some(val) => params.push(val),
                        None => break,
                    }
                }
                params
            }
            None => Vec::new(),
        };

        Ok(Some(RpcCommand {
            url: url.into(),
            method: method.into(),
            args,
        }))
    }

    pub async fn execute(self) -> Result<String, String> {
        let client = HttpClientBuilder::default()
            .build(&self.url)
            .map_err(|e| e.to_string())?;
        let result: Value = client
            .request(&self.method, self.args)
            .await
            .map_err(|e| e.to_string())?;
        Ok(format!("{:#}", result))
    }
}

struct ArgSchema<'a> {
    arg_name: &'a str,
    arg_type: &'a str,
}

impl<'a> ArgSchema<'a> {
    fn parse(arg: &'a str) -> Self {
        let schema: Vec<&str> = arg.splitn(2, ':').collect();
        ArgSchema {
            arg_name: schema[0],
            arg_type: schema.get(1).cloned().unwrap_or("string"),
        }
    }

    fn value(&self, matches: &ArgMatches) -> Result<Option<Value>, String> {
        match self.arg_type {
            "string" => match matches.get_one::<String>(self.arg_name) {
                Some(val) => Ok(Some(Value::String(val.into()))),
                None => Ok(None),
            },
            "bool" => Ok(Some(Value::Bool(matches.get_flag(self.arg_name)))),
            "u64" => self.u64(matches),
            "password" => Ok(Some(self.password()?)),
            "password2" => Ok(Some(self.password2()?)),
            _ => {
                if self.arg_type.starts_with("map(")
                    && self.arg_type.ends_with(')')
                {
                    return Ok(Some(self.object(matches)?));
                }

                panic!("unsupported RPC argument type: {}", self.arg_type);
            }
        }
    }

    fn u64(&self, matches: &ArgMatches) -> Result<Option<Value>, String> {
        let val = match matches.get_one::<u64>(self.arg_name) {
            Some(val) => val,
            None => return Ok(None),
        };

        Ok(Some(Value::String(format!("{:#x}", val))))
    }

    fn object(&self, matches: &ArgMatches) -> Result<Value, String> {
        let fields: Vec<&str> = self
            .arg_type
            .trim_start_matches("map(")
            .trim_end_matches(')')
            .split(';')
            .collect();

        let mut object = Map::new();

        for field in fields {
            let schema = ArgSchema::parse(field);
            if let Some(val) = schema.value(matches)? {
                object.insert(schema.arg_name.into(), val);
            }
        }

        Ok(Value::Object(object))
    }

    fn password(&self) -> Result<Value, String> {
        input_password().map(|pwd| Value::String(pwd.as_str().to_string()))
    }

    fn password2(&self) -> Result<Value, String> {
        password_prompt().map(|pwd| Value::String(pwd.as_str().to_string()))
    }
}

#[cfg(test)]

mod tests {
    use crate::cli::Cli;

    use super::*;
    use clap::CommandFactory;
    use mockito::{Matcher, Server};
    use serde_json::json;
    use tokio;

    async fn run_rpc_test(
        method: &str, args: Vec<Value>, expected_result_value: Value,
    ) {
        let mut server = Server::new_async().await;
        let url = server.url();

        let expected_request_body = json!({
            "jsonrpc": "2.0",
            "method": method,
            "params": args.clone(),
            "id": 0
        });

        let mock_response_body = json!({
          "jsonrpc": "2.0",
          "id": 0,
          "result": expected_result_value.clone()
        });

        let mock = server
            .mock("POST", "/")
            .match_header("content-type", "application/json")
            .match_body(Matcher::Json(expected_request_body.clone()))
            .with_status(200)
            .with_body(mock_response_body.to_string())
            .create_async()
            .await;

        let command = RpcCommand {
            url,
            method: method.to_string(),
            args,
        };

        let result = command.execute().await;

        mock.assert_async().await;
        assert!(result.is_ok());
        let result_str = result.unwrap();
        assert_eq!(result_str, format!("{:#}", expected_result_value));
    }

    #[tokio::test]
    async fn test_rpc_execute_without_args() {
        let method = "cfx_getStatus";
        let args: Vec<Value> = vec![];
        let expected_result = json!({
            "bestHash": "0x64c936773e434069ede6bec161419b37ab6110409095a1d91d2bb91c344b523f",
            "chainId": "0x1",
            "ethereumSpaceChainId": "0x47",
            "networkId": "0x1",
            "epochNumber": "0xcdee1fd",
            "blockNumber": "0x10be2f9b",
            "pendingTxNumber": "0x8cf",
            "latestCheckpoint": "0xcdd7500",
            "latestConfirmed": "0xcdee1c3",
            "latestState": "0xcdee1f9",
            "latestFinalized": "0xcdee0ac"
        });

        run_rpc_test(method, args, expected_result).await;
    }

    #[tokio::test]
    async fn test_rpc_execute_cfx_epoch_number_with_param() {
        let method = "cfx_epochNumber";
        let args: Vec<Value> = vec![json!("0x4350b21")];
        let expected_result = json!("0x4350b21");

        run_rpc_test(method, args, expected_result).await;
    }

    #[test]
    fn test_rpc_command_parse() {
        #[derive(Debug)]
        struct TestCase {
            name: &'static str,
            args: Vec<&'static str>,
            expected_method: &'static str,
            expected_url: &'static str,
            expected_params: Vec<Value>,
        }

        let test_cases = vec![
            TestCase {
                name: "estimate-gas with many arguments",
                args: vec![
                    "conflux",
                    "rpc",
                    "estimate-gas",
                    "--from",
                    "addr_from",
                    "--to",
                    "addr_to",
                    "--gas-price",
                    "gp_val",
                    "--type",
                    "type_val",
                    "--max-fee-per-gas",
                    "mfpg_val",
                    "--max-priority-fee-per-gas",
                    "mpfpg_val",
                    "--gas",
                    "gas_val",
                    "--value",
                    "value_val",
                    "--data",
                    "data_val",
                    "--nonce",
                    "nonce_val",
                    "--epoch",
                    "epoch_val",
                ],
                expected_method: "cfx_estimateGas",
                expected_url: "http://localhost:12539",
                expected_params: vec![
                    json!({
                        "data": "data_val",
                        "from": "addr_from",
                        "gas": "gas_val",
                        "gas-price": "gp_val",
                        "max-fee-per-gas": "mfpg_val",
                        "max-priority-fee-per-gas": "mpfpg_val",
                        "nonce": "nonce_val",
                        "to": "addr_to",
                        "type": "type_val",
                        "value": "value_val"
                    }),
                    json!("epoch_val"),
                ],
            },
            TestCase {
                name: "balance with custom URL",
                args: vec![
                    "conflux",
                    "rpc",
                    "balance",
                    "--url",
                    "http://0.0.0.0:8080",
                    "--address",
                    "test_address_001",
                    "--epoch",
                    "latest_state",
                ],
                expected_method: "cfx_getBalance",
                expected_url: "http://0.0.0.0:8080",
                expected_params: vec![
                    json!("test_address_001"),
                    json!("latest_state"),
                ],
            },
            TestCase {
                name: "block-by-hash",
                args: vec![
                    "conflux",
                    "rpc",
                    "block-by-hash",
                    "--hash",
                    "0x654321fedcba",
                ],
                expected_method: "cfx_getBlockByHash",
                expected_url: "http://localhost:12539",
                expected_params: vec![json!("0x654321fedcba"), json!(false)],
            },
        ];

        for test_case in test_cases {
            let cli = Cli::command().get_matches_from(test_case.args);
            let mut subcmd_matches = &cli;
            while let Some(m) = subcmd_matches.subcommand() {
                subcmd_matches = m.1;
            }

            let rpc_command = match RpcCommand::parse(subcmd_matches) {
                Ok(Some(cmd)) => cmd,
                Ok(None) => panic!(
                    "Test case '{}': Expected RpcCommand but got None",
                    test_case.name
                ),
                Err(e) => panic!(
                    "Test case '{}': Error parsing RpcCommand: {}",
                    test_case.name, e
                ),
            };

            assert_eq!(
                rpc_command.method, test_case.expected_method,
                "Test case '{}': Method mismatch",
                test_case.name
            );

            assert_eq!(
                rpc_command.url, test_case.expected_url,
                "Test case '{}': URL mismatch",
                test_case.name
            );

            assert_eq!(
                rpc_command.args, test_case.expected_params,
                "Test case '{}': Parameters mismatch",
                test_case.name
            );
        }
    }
}