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
use crate::commands::builtin::{InitRPC, ManifestRPC};
use crate::commands::types::{CLNConf, RPCHookInfo, RPCMethodInfo};
use crate::commands::RPCCommand;
use crate::errors::PluginError;
use crate::types::{LogLevel, RpcOption};
use clightningrpc_common::json_utils::{add_str, init_payload, init_success_response};
use clightningrpc_common::types::Request;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::string::String;
use std::{io, io::Write};
pub type OnInit<T> = dyn Fn(&mut Plugin<T>) -> Value + Send + 'static;
#[derive(Clone)]
#[allow(dead_code)]
pub struct Plugin<T>
where
T: 'static + Clone,
{
pub state: T,
pub option: HashMap<String, RpcOption>,
pub rpc_method: HashMap<String, Box<dyn RPCCommand<T>>>,
pub rpc_info: HashSet<RPCMethodInfo>,
pub rpc_hook: HashMap<String, Box<dyn RPCCommand<T>>>,
pub hook_info: HashSet<RPCHookInfo>,
pub rpc_notification: HashMap<String, Box<dyn RPCCommand<T>>>,
pub dynamic: bool,
pub configuration: Option<CLNConf>,
on_init: Option<&'static OnInit<T>>,
}
impl<'a, T: 'a + Clone> Plugin<T> {
pub fn new(state: T, dynamic: bool) -> Self {
Plugin {
state,
option: HashMap::new(),
rpc_method: HashMap::new(),
rpc_info: HashSet::new(),
rpc_hook: HashMap::new(),
hook_info: HashSet::new(),
rpc_notification: HashMap::new(),
dynamic,
configuration: None,
on_init: None,
}
}
pub fn on_init(&'a mut self, callback: &'static OnInit<T>) -> Self {
self.on_init = Some(callback);
self.clone()
}
pub fn log(&self, level: LogLevel, msg: &str) {
let mut writer = io::stdout();
let mut payload = init_payload();
let level = match level {
LogLevel::Debug => "debug",
LogLevel::Info => "info",
};
add_str(&mut payload, "level", level);
add_str(&mut payload, "message", msg);
let request = Request {
id: None,
jsonrpc: "2.0",
method: "log",
params: payload,
};
writer
.write_all(serde_json::to_string(&request).unwrap().as_bytes())
.unwrap();
writer.flush().unwrap();
}
pub fn add_opt(
&mut self,
name: &str,
opt_type: &str,
def_val: Option<String>,
description: &str,
deprecated: bool,
) -> &mut Self {
self.option.insert(
name.to_owned(),
RpcOption {
name: name.to_string(),
opt_typ: opt_type.to_string(),
default: def_val,
description: description.to_string(),
deprecated,
value: None,
},
);
self
}
pub fn get_opt<R: for<'de> serde::de::Deserialize<'de>>(
&self,
name: &str,
) -> Result<R, PluginError> {
let opt = self.option.get(name).unwrap();
Ok(opt.value())
}
pub fn add_rpc_method<F: 'static>(
&'a mut self,
name: &str,
usage: &str,
description: &str,
callback: F,
) -> Self
where
F: RPCCommand<T> + 'static,
{
self.rpc_method.insert(name.to_owned(), Box::new(callback));
self.rpc_info.insert(RPCMethodInfo {
name: name.to_string(),
usage: usage.to_string(),
description: description.to_string(),
long_description: description.to_string(),
deprecated: false,
});
self.clone()
}
fn call_rpc_method(
&'a mut self,
name: &str,
params: &serde_json::Value,
) -> Result<serde_json::Value, PluginError> {
let command = self.rpc_method.get(name).unwrap().clone();
command.call(self, params)
}
fn handle_notification(&'a mut self, name: &str, params: &serde_json::Value) {
let notification = self.rpc_notification.get(name).unwrap().clone();
if let Err(json_res) = notification.call(self, params) {
self.log(
LogLevel::Debug,
format!("Notification end with and error: {}", json_res).as_str(),
);
}
}
pub fn register_hook<F: 'static>(
&'a mut self,
hook_name: &str,
before: Option<Vec<String>>,
after: Option<Vec<String>>,
callback: F,
) -> Self
where
F: RPCCommand<T> + 'static,
{
self.rpc_hook
.insert(hook_name.to_owned(), Box::new(callback));
self.hook_info.insert(RPCHookInfo {
name: hook_name.to_owned(),
before,
after,
});
self.clone()
}
pub fn register_notification<F: 'static>(&mut self, name: &str, callback: F) -> Self
where
F: 'static + RPCCommand<T> + Clone,
{
self.rpc_notification
.insert(name.to_owned(), Box::new(callback));
self.clone()
}
fn write_respose(
&mut self,
result: &Result<serde_json::Value, PluginError>,
response: &mut serde_json::Value,
) {
match result {
Ok(json_resp) => response["result"] = json_resp.to_owned(),
Err(json_err) => {
let err_resp = serde_json::to_value(json_err).unwrap();
response["error"] = err_resp;
}
}
}
pub fn start(mut self) {
let reader = io::stdin();
let mut writer = io::stdout();
let mut buffer = String::new();
self.rpc_method
.insert("getmanifest".to_owned(), Box::new(ManifestRPC {}));
self.rpc_method.insert(
"init".to_owned(),
Box::new(InitRPC::<T> {
on_init: self.on_init,
}),
);
loop {
let _ = reader.read_line(&mut buffer);
let req_str = buffer.to_string();
if req_str.trim().is_empty() {
continue;
}
buffer.clear();
let request: Request<serde_json::Value> = serde_json::from_str(&req_str).unwrap();
if let Some(id) = request.id {
let response = self.call_rpc_method(request.method, &request.params);
let mut rpc_response = init_success_response(id);
self.write_respose(&response, &mut rpc_response);
writer
.write_all(serde_json::to_string(&rpc_response).unwrap().as_bytes())
.unwrap();
writer.flush().unwrap();
} else {
self.handle_notification(request.method, &request.params);
}
}
}
}