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
// 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 jsonrpc_core::{Params, Value};
use jsonrpc_core_client::{transports::http::connect, RawClient};
use serde_json::Map;
use std::str::FromStr;

pub struct RpcCommand {
    pub url: String,
    pub method: String,
    pub args: Params,
}

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

        let url = matches
            .value_of("url")
            .ok_or_else(|| String::from("RPC URL not specified"))?;

        let args = match matches.values_of("rpc-args") {
            Some(args) => args,
            None => {
                return Ok(Some(RpcCommand {
                    url: url.into(),
                    method: method.into(),
                    args: Params::None,
                }));
            }
        };

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

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

    pub async fn execute(self) -> Result<String, String> {
        let client = connect::<RawClient>(self.url.as_str())
            .await
            .map_err(|e| e.to_string())?;
        let result = client
            .call_method(self.method.as_str(), 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.value_of(self.arg_name) {
                Some(val) => Ok(Some(Value::String(val.into()))),
                None => Ok(None),
            },
            "bool" => Ok(Some(Value::Bool(matches.is_present(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.value_of(self.arg_name) {
            Some(val) => val,
            None => return Ok(None),
        };

        let val = u64::from_str(val).map_err(|e| {
            format!("failed to parse argument [--{}]: {:?}", self.arg_name, e)
        })?;

        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()))
    }
}