forked from LNP-WG/lnp-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime.rs
500 lines (459 loc) · 16.9 KB
/
runtime.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// LNP Node: node running lightning network protocol and generalized lightning
// channels.
// Written in 2020 by
// Dr. Maxim Orlovsky <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
use amplify::Wrapper;
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::ffi::OsStr;
use std::io;
use std::net::SocketAddr;
use std::process;
use std::time::{Duration, SystemTime};
use lnpbp::bitcoin::hashes::hex::ToHex;
use lnpbp::bitcoin::secp256k1;
use lnpbp::lnp::{
message, ChannelId, Messages, NodeAddr, RemoteSocketAddr, TypedEnum,
};
use lnpbp_services::esb::{self, Handler};
use lnpbp_services::rpc::Failure;
use crate::rpc::request::{IntoProgressOrFalure, NodeInfo, OptionDetails};
use crate::rpc::{request, Request, ServiceBus};
use crate::{Config, Error, LogStyle, Service, ServiceId};
pub fn run(config: Config, node_id: secp256k1::PublicKey) -> Result<(), Error> {
let runtime = Runtime {
identity: ServiceId::Lnpd,
node_id,
listens: none!(),
started: SystemTime::now(),
connections: none!(),
channels: none!(),
spawning_services: none!(),
opening_channels: none!(),
accepting_channels: none!(),
};
Service::run(config, runtime, true)
}
pub struct Runtime {
identity: ServiceId,
node_id: secp256k1::PublicKey,
listens: HashSet<RemoteSocketAddr>,
started: SystemTime,
connections: HashSet<NodeAddr>,
channels: HashSet<ChannelId>,
spawning_services: HashMap<ServiceId, ServiceId>,
opening_channels: HashMap<ServiceId, request::CreateChannel>,
accepting_channels: HashMap<ServiceId, request::CreateChannel>,
}
impl esb::Handler<ServiceBus> for Runtime {
type Request = Request;
type Address = ServiceId;
type Error = Error;
fn identity(&self) -> ServiceId {
self.identity.clone()
}
fn handle(
&mut self,
senders: &mut esb::SenderList<ServiceBus, ServiceId>,
bus: ServiceBus,
source: ServiceId,
request: Request,
) -> Result<(), Self::Error> {
match bus {
ServiceBus::Msg => self.handle_rpc_msg(senders, source, request),
ServiceBus::Ctl => self.handle_rpc_ctl(senders, source, request),
_ => {
Err(Error::NotSupported(ServiceBus::Bridge, request.get_type()))
}
}
}
fn handle_err(&mut self, _: esb::Error) -> Result<(), esb::Error> {
// We do nothing and do not propagate error; it's already being reported
// with `error!` macro by the controller. If we propagate error here
// this will make whole daemon panic
Ok(())
}
}
impl Runtime {
fn handle_rpc_msg(
&mut self,
_senders: &mut esb::SenderList<ServiceBus, ServiceId>,
source: ServiceId,
request: Request,
) -> Result<(), Error> {
match request {
Request::Hello => {
// Ignoring; this is used to set remote identity at ZMQ level
}
Request::SendMessage(Messages::OpenChannel(open_channel)) => {
info!("Creating channel by peer request from {}", source);
self.create_channel(source, None, open_channel, true)?;
}
Request::SendMessage(_) => {
// Ignore the rest of LN peer messages
}
_ => {
error!(
"MSG RPC can be only used for forwarding LNPWP messages"
);
return Err(Error::NotSupported(
ServiceBus::Msg,
request.get_type(),
));
}
}
Ok(())
}
fn handle_rpc_ctl(
&mut self,
senders: &mut esb::SenderList<ServiceBus, ServiceId>,
source: ServiceId,
request: Request,
) -> Result<(), Error> {
let mut notify_cli = None;
match request {
Request::Hello => {
// Ignoring; this is used to set remote identity at ZMQ level
info!("{} daemon is {}", source.ended(), "connected".ended());
match &source {
ServiceId::Lnpd => {
error!(
"{}",
"Unexpected another lnpd instance connection".err()
);
}
ServiceId::Peer(connection_id) => {
if self.connections.insert(connection_id.clone()) {
info!(
"Connection daemon {} is registered; total {} \
connections are known",
connection_id,
self.connections.len()
);
} else {
warn!(
"Connection {} was already registered; the \
service probably was relaunched",
connection_id
);
}
}
ServiceId::Channel(channel_id) => {
if self.channels.insert(channel_id.clone()) {
info!(
"Channel daemon {} is registered; total {} \
channels are known",
channel_id,
self.channels.len()
);
} else {
warn!(
"Channel {} was already registered; the \
service probably was relaunched",
channel_id
);
}
}
_ => {
// Ignoring the rest of daemon/client types
}
}
if let Some(channel_params) = self.opening_channels.get(&source)
{
// Tell channeld channel options and link it with the
// connection daemon
debug!(
"Daemon {} is known: we spawned it to create a channel. \
Ordering channel opening", source
);
notify_cli = Some((
channel_params.report_to.clone(),
Request::Progress(format!(
"Channel daemon {} operational",
source
)),
));
senders.send_to(
ServiceBus::Ctl,
self.identity(),
source.clone(),
Request::OpenChannelWith(channel_params.clone()),
)?;
self.opening_channels.remove(&source);
} else if let Some(channel_params) =
self.accepting_channels.get(&source)
{
// Tell channeld channel options and link it with the
// connection daemon
debug!(
"Daemon {} is known: we spawned it to create a channel. \
Ordering channel acceptance", source
);
senders.send_to(
ServiceBus::Ctl,
self.identity(),
source.clone(),
Request::AcceptChannelFrom(channel_params.clone()),
)?;
self.accepting_channels.remove(&source);
} else if let Some(enquirer) =
self.spawning_services.get(&source)
{
debug!(
"Daemon {} is known: we spawned it to create a new peer \
connection by a request from {}",
source, enquirer
);
notify_cli = Some((
Some(enquirer.clone()),
Request::Success(OptionDetails::with(format!(
"Peer connected to {}",
source
))),
));
self.spawning_services.remove(&source);
}
}
Request::GetInfo => {
senders.send_to(
ServiceBus::Ctl,
ServiceId::Lnpd,
source,
Request::NodeInfo(NodeInfo {
node_id: self.node_id,
listens: self.listens.iter().cloned().collect(),
uptime: SystemTime::now()
.duration_since(self.started)
.unwrap_or(Duration::from_secs(0)),
since: self
.started
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or(Duration::from_secs(0))
.as_secs(),
peers: self.connections.len(),
channels: self.channels.len(),
}),
)?;
}
Request::ListPeers => {
senders.send_to(
ServiceBus::Ctl,
ServiceId::Lnpd,
source,
Request::PeerList(vec![].into()),
)?;
}
Request::ListChannels => {
senders.send_to(
ServiceBus::Ctl,
ServiceId::Lnpd,
source,
Request::ChannelList(vec![].into()),
)?;
}
Request::Listen(addr) => {
let addr_str = addr.addr();
if self.listens.contains(&addr) {
let msg = format!(
"Listener on {} already exists, ignoring request",
addr
);
warn!("{}", msg.err());
notify_cli = Some((
Some(source.clone()),
Request::Failure(Failure { code: 1, info: msg }),
));
} else {
self.listens.insert(addr);
info!(
"{} for incoming LN peer connections on {}",
"Starting listener".promo(),
addr_str
);
let resp = self.listen(addr);
match resp {
Ok(_) => info!("Connection daemon {} for incoming LN peer connections on {}",
"listens".ended(), addr_str),
Err(ref err) => error!("{}", err.err())
}
senders.send_to(
ServiceBus::Ctl,
ServiceId::Lnpd,
source.clone(),
resp.into_progress_or_failure(),
)?;
notify_cli = Some((
Some(source.clone()),
Request::Success(OptionDetails::with(format!(
"Node {} listens for connections on {}",
self.node_id, addr
))),
));
}
}
Request::ConnectPeer(addr) => {
info!(
"{} to remote peer {}",
"Connecting".promo(),
addr.promoter()
);
let resp = self.connect_peer(source.clone(), addr);
match resp {
Ok(_) => {}
Err(ref err) => error!("{}", err.err()),
}
notify_cli = Some((
Some(source.clone()),
resp.into_progress_or_failure(),
));
}
Request::OpenChannelWith(request::CreateChannel {
channel_req,
peerd,
report_to,
}) => {
info!(
"{} by request from {}",
"Creating channel".promo(),
source.promoter()
);
let resp =
self.create_channel(peerd, report_to, channel_req, false);
match resp {
Ok(_) => {}
Err(ref err) => error!("{}", err.err()),
}
notify_cli = Some((
Some(source.clone()),
resp.into_progress_or_failure(),
));
}
_ => {
error!(
"{}",
"Request is not supported by the CTL interface".err()
);
return Err(Error::NotSupported(
ServiceBus::Ctl,
request.get_type(),
));
}
}
if let Some((Some(respond_to), resp)) = notify_cli {
senders.send_to(
ServiceBus::Ctl,
ServiceId::Lnpd,
respond_to,
resp,
)?;
}
Ok(())
}
fn listen(&mut self, addr: RemoteSocketAddr) -> Result<String, Error> {
if let RemoteSocketAddr::Ftcp(inet) = addr {
let socket_addr = SocketAddr::try_from(inet)?;
let ip = socket_addr.ip();
let port = socket_addr.port();
debug!("Instantiating peerd...");
// Start channeld
let child = launch(
"peerd",
&["--listen", &ip.to_string(), "--port", &port.to_string()],
)?;
let msg = format!(
"New instance of peerd launched with PID {}",
child.id()
);
info!("{}", msg);
Ok(msg)
} else {
Err(Error::Other(s!(
"Only TCP is supported for now as an overlay protocol"
)))
}
}
fn connect_peer(
&mut self,
source: ServiceId,
node_addr: NodeAddr,
) -> Result<String, Error> {
debug!("Instantiating peerd...");
// Start channeld
let child = launch("peerd", &["--connect", &node_addr.to_string()])?;
let msg =
format!("New instance of peerd launched with PID {}", child.id());
info!("{}", msg);
self.spawning_services
.insert(ServiceId::Peer(node_addr), source);
debug!("Awaiting for peerd to connect...");
Ok(msg)
}
fn create_channel(
&mut self,
source: ServiceId,
report_to: Option<ServiceId>,
open_channel: message::OpenChannel,
accept: bool,
) -> Result<String, Error> {
debug!("Instantiating channeld...");
// Start channeld
let child =
launch("channeld", &[open_channel.temporary_channel_id.to_hex()])?;
let msg = format!(
"New instance of channeld launched with PID {}",
child.id()
);
info!("{}", msg);
let list = if accept {
&mut self.accepting_channels
} else {
&mut self.opening_channels
};
list.insert(
ServiceId::Channel(ChannelId::from_inner(
open_channel.temporary_channel_id.into_inner(),
)),
request::CreateChannel {
channel_req: open_channel,
peerd: source,
report_to: report_to,
},
);
debug!("Awaiting for channeld to connect...");
Ok(msg)
}
}
fn launch(
name: &str,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> io::Result<process::Child> {
let mut bin_path = std::env::current_exe().map_err(|err| {
error!("Unable to detect binary directory: {}", err);
err
})?;
bin_path.pop();
bin_path.push(name);
#[cfg(target_os = "windows")]
bin_path.set_extension("exe");
debug!(
"Launching {} as a separate process using `{}` as binary",
name,
bin_path.to_string_lossy()
);
let mut cmd = process::Command::new(bin_path);
cmd.args(std::env::args().skip(1)).args(args);
trace!("Executing `{:?}`", cmd);
cmd.spawn().map_err(|err| {
error!("Error launching {}: {}", name, err);
err
})
}