cln_plugin/
messages.rs

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
use crate::options::UntypedConfigOption;
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt::Debug;

#[derive(Deserialize, Debug)]
#[serde(tag = "method", content = "params")]
#[serde(rename_all = "snake_case")]
pub(crate) enum Request {
    // Builtin
    Getmanifest(GetManifestCall),
    Init(InitCall),
    // Hooks
    //     PeerConnected,
    //     CommitmentRevocation,
    //     DbWrite,
    //     InvoicePayment,
    //     Openchannel,
    //     Openchannel2,
    //     Openchannel2Changed,
    //     Openchannel2Sign,
    //     RbfChannel,
    //     HtlcAccepted,
    //     RpcCommand,
    //     Custommsg,
    //     OnionMessage,
    //     OnionMessageBlinded,
    //     OnionMessageOurpath,

    // Bitcoin backend
    //     Getchaininfo,
    //     Estimatefees,
    //     Getrawblockbyheight,
    //     Getutxout,
    //     Sendrawtransaction,
}

#[derive(Deserialize, Debug)]
#[serde(tag = "method", content = "params")]
#[serde(rename_all = "snake_case")]
pub(crate) enum Notification {
    //     ChannelOpened,
    //     ChannelOpenFailed,
    //     ChannelStateChanged,
    //     Connect,
    //     Disconnect,
    //     InvoicePayment,
    //     InvoiceCreation,
    //     Warning,
    //     ForwardEvent,
    //     SendpaySuccess,
    //     SendpayFailure,
    //     CoinMovement,
    //     OpenchannelPeerSigs,
    //     Shutdown,
}

#[derive(Deserialize, Debug)]
pub(crate) struct GetManifestCall {}

#[derive(Deserialize, Debug)]
pub(crate) struct InitCall {
    pub(crate) options: HashMap<String, Value>,
    pub configuration: Configuration,
}

#[derive(Clone, Deserialize, Debug)]
pub struct Configuration {
    #[serde(rename = "lightning-dir")]
    pub lightning_dir: String,
    #[serde(rename = "rpc-file")]
    pub rpc_file: String,
    pub startup: bool,
    pub network: String,
    pub feature_set: HashMap<String, String>,

    // The proxy related options are only populated if a proxy was
    // configured.
    pub proxy: Option<ProxyInfo>,
    #[serde(rename = "torv3-enabled")]
    pub torv3_enabled: Option<bool>,
    pub always_use_proxy: Option<bool>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct ProxyInfo {
    #[serde(alias = "type")]
    pub typ: String,
    pub address: String,
    pub port: i64,
}

#[derive(Debug)]
pub(crate) enum JsonRpc<N, R> {
    Request(serde_json::Value, R),
    Notification(N),
    CustomRequest(serde_json::Value, Value),
    CustomNotification(Value),
}

/// This function disentangles the various cases:
///
///   1) If we have an `id` then it is a request
///
///   2) Otherwise it's a notification that doesn't require a
///   response.
///
/// Furthermore we distinguish between the built-in types and the
/// custom user notifications/methods:
///
///   1) We either match a built-in type above,
///
///   2) Or it's a custom one, so we pass it around just as a
///   `serde_json::Value`
impl<'de, N, R> Deserialize<'de> for JsonRpc<N, R>
where
    N: Deserialize<'de> + Debug,
    R: Deserialize<'de> + Debug,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize, Debug)]
        struct IdHelper {
            id: Option<serde_json::Value>,
        }

        let v = Value::deserialize(deserializer)?;
        let helper = IdHelper::deserialize(&v).map_err(de::Error::custom)?;
        match helper.id {
            Some(id) => match R::deserialize(v.clone()) {
                Ok(r) => Ok(JsonRpc::Request(id, r)),
                Err(_) => Ok(JsonRpc::CustomRequest(id, v)),
            },
            None => match N::deserialize(v.clone()) {
                Ok(n) => Ok(JsonRpc::Notification(n)),
                Err(_) => Ok(JsonRpc::CustomNotification(v)),
            },
        }
    }
}

#[derive(Serialize, Default, Debug)]
pub(crate) struct RpcMethod {
    pub(crate) name: String,
    pub(crate) description: String,
    pub(crate) usage: String,
}

#[derive(Serialize, Default, Debug, Clone)]
pub struct NotificationTopic {
    pub method: String,
}

impl NotificationTopic {
    pub fn method(&self) -> &str {
        &self.method
    }
}

impl NotificationTopic {
    pub fn new(method: &str) -> Self {
        Self {
            method: method.to_string(),
        }
    }
}

#[derive(Serialize, Default, Debug)]
pub(crate) struct GetManifestResponse {
    pub(crate) options: Vec<UntypedConfigOption>,
    pub(crate) rpcmethods: Vec<RpcMethod>,
    pub(crate) subscriptions: Vec<String>,
    pub(crate) notifications: Vec<NotificationTopic>,
    pub(crate) hooks: Vec<String>,
    pub(crate) dynamic: bool,
    pub(crate) featurebits: FeatureBits,
    pub(crate) nonnumericids: bool,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub(crate) custommessages: Vec<u16>,
}

#[derive(Serialize, Default, Debug, Clone)]
pub(crate) struct FeatureBits {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub init: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invoice: Option<String>,
}

#[derive(Serialize, Default, Debug)]
pub struct InitResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disable: Option<String>,
}

pub trait Response: Serialize + Debug {}

#[cfg(test)]
mod test {
    use super::*;
    use crate::messages;
    use serde_json::json;

    #[test]
    fn test_init_message_parsing() {
        let value = json!({
            "jsonrpc": "2.0",
            "method": "init",
            "params": {
                "options": {
                    "greeting": "World",
                    "number": [0]
                },
                "configuration": {
                    "lightning-dir": "/home/user/.lightning/testnet",
                    "rpc-file": "lightning-rpc",
                    "startup": true,
                    "network": "testnet",
                    "feature_set": {
                        "init": "02aaa2",
                        "node": "8000000002aaa2",
                        "channel": "",
                        "invoice": "028200"
                    },
                    "proxy": {
                        "type": "ipv4",
                        "address": "127.0.0.1",
                        "port": 9050
                    },
                    "torv3-enabled": true,
                    "always_use_proxy": false
                }
            },
            "id": "10",
        });
        let req: JsonRpc<Notification, Request> = serde_json::from_value(value).unwrap();
        match req {
            messages::JsonRpc::Request(_, messages::Request::Init(init)) => {
                assert_eq!(init.options["greeting"], "World");
                assert_eq!(
                    init.configuration.lightning_dir,
                    String::from("/home/user/.lightning/testnet")
                );
            }
            _ => panic!("Couldn't parse init message"),
        }
    }
}