1use crate::{
2 DiscoveryKey, Key, Message, discovery_key,
3 message::ChannelMessage,
4 schema::*,
5 util::{map_channel_err, pretty_hash},
6};
7use async_channel::{Receiver, Sender, TrySendError};
8use futures_lite::{ready, stream::Stream};
9use std::{
10 collections::HashMap,
11 fmt,
12 io::{Error, ErrorKind, Result},
13 pin::Pin,
14 sync::{
15 Arc,
16 atomic::{AtomicBool, Ordering},
17 },
18 task::Poll,
19};
20use tracing::instrument;
21
22#[derive(Clone)]
26pub struct Channel {
27 inbound_rx: Option<Receiver<Message>>,
28 direct_inbound_tx: Sender<Message>,
29 outbound_tx: Sender<Vec<ChannelMessage>>,
30 key: Key,
31 discovery_key: DiscoveryKey,
32 local_id: usize,
33 closed: Arc<AtomicBool>,
34}
35
36impl PartialEq for Channel {
37 fn eq(&self, other: &Self) -> bool {
38 self.key == other.key
39 && self.discovery_key == other.discovery_key
40 && self.local_id == other.local_id
41 }
42}
43
44impl fmt::Debug for Channel {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 f.debug_struct("Channel")
47 .field("discovery_key", &pretty_hash(&self.discovery_key))
48 .finish()
49 }
50}
51
52impl Channel {
53 fn new(
54 inbound_rx: Option<Receiver<Message>>,
55 direct_inbound_tx: Sender<Message>,
56 outbound_tx: Sender<Vec<ChannelMessage>>,
57 discovery_key: DiscoveryKey,
58 key: Key,
59 local_id: usize,
60 closed: Arc<AtomicBool>,
61 ) -> Self {
62 Self {
63 inbound_rx,
64 direct_inbound_tx,
65 outbound_tx,
66 key,
67 discovery_key,
68 local_id,
69 closed,
70 }
71 }
72 pub fn discovery_key(&self) -> &[u8; 32] {
74 &self.discovery_key
75 }
76
77 pub fn key(&self) -> &[u8; 32] {
79 &self.key
80 }
81
82 pub fn id(&self) -> usize {
84 self.local_id
85 }
86
87 pub fn closed(&self) -> bool {
89 self.closed.load(Ordering::SeqCst)
90 }
91
92 pub async fn send(&self, message: Message) -> Result<()> {
94 if self.closed() {
95 return Err(Error::new(
96 ErrorKind::ConnectionAborted,
97 "Channel is closed",
98 ));
99 }
100 let message = ChannelMessage::new(self.local_id as u64, message);
101 self.outbound_tx
102 .send(vec![message])
103 .await
104 .map_err(map_channel_err)
105 }
106
107 pub async fn send_batch(&self, messages: &[Message]) -> Result<()> {
109 if self.closed() {
120 return Err(Error::new(
121 ErrorKind::ConnectionAborted,
122 "Channel is closed",
123 ));
124 }
125
126 let messages = messages
127 .iter()
128 .map(|message| ChannelMessage::new(self.local_id as u64, message.clone()))
129 .collect();
130
131 self.outbound_tx
132 .send(messages)
133 .await
134 .map_err(map_channel_err)
135 }
136
137 pub fn take_receiver(&mut self) -> Option<Receiver<Message>> {
142 self.inbound_rx.take()
143 }
144
145 pub fn local_sender(&self) -> Sender<Message> {
151 self.direct_inbound_tx.clone()
152 }
153
154 pub async fn close(&self) -> Result<()> {
156 if self.closed() {
157 return Ok(());
158 }
159 let close = Close {
160 channel: self.local_id as u64,
161 };
162 self.send(Message::Close(close)).await?;
163 self.closed.store(true, Ordering::SeqCst);
164 Ok(())
165 }
166
167 pub async fn signal_local_protocol(&self, name: &str, data: Vec<u8>) -> Result<()> {
170 self.send(Message::LocalSignal((name.to_string(), data)))
171 .await?;
172 Ok(())
173 }
174}
175
176impl Stream for Channel {
177 type Item = Message;
178 fn poll_next(
179 self: Pin<&mut Self>,
180 cx: &mut std::task::Context<'_>,
181 ) -> std::task::Poll<Option<Self::Item>> {
182 let this = self.get_mut();
183 match this.inbound_rx.as_mut() {
184 None => Poll::Ready(None),
185 Some(ref mut inbound_rx) => {
186 let message = ready!(Pin::new(inbound_rx).poll_next(cx));
187 Poll::Ready(message)
188 }
189 }
190 }
191}
192
193#[derive(Clone, Debug)]
195pub(crate) struct ChannelHandle {
196 discovery_key: DiscoveryKey,
197 local_state: Option<LocalState>,
198 remote_state: Option<RemoteState>,
199 inbound_tx: Option<Sender<Message>>,
200 closed: Arc<AtomicBool>,
201}
202
203#[derive(Clone, Debug)]
204struct LocalState {
205 key: Key,
206 local_id: usize,
207}
208
209#[derive(Clone, Debug)]
210struct RemoteState {
211 remote_id: usize,
212 remote_capability: Option<Vec<u8>>,
213}
214
215impl ChannelHandle {
216 fn new(discovery_key: DiscoveryKey) -> Self {
217 Self {
218 discovery_key,
219 local_state: None,
220 remote_state: None,
221 inbound_tx: None,
222 closed: Arc::new(AtomicBool::new(false)),
223 }
224 }
225 fn new_local(local_id: usize, discovery_key: DiscoveryKey, key: Key) -> Self {
226 let mut this = Self::new(discovery_key);
227 this.attach_local(local_id, key);
228 this
229 }
230
231 fn new_remote(
232 remote_id: usize,
233 discovery_key: DiscoveryKey,
234 remote_capability: Option<Vec<u8>>,
235 ) -> Self {
236 let mut this = Self::new(discovery_key);
237 this.attach_remote(remote_id, remote_capability);
238 this
239 }
240
241 pub(crate) fn discovery_key(&self) -> &[u8; 32] {
242 &self.discovery_key
243 }
244
245 pub(crate) fn local_id(&self) -> Option<usize> {
246 self.local_state.as_ref().map(|s| s.local_id)
247 }
248
249 pub(crate) fn remote_id(&self) -> Option<usize> {
250 self.remote_state.as_ref().map(|s| s.remote_id)
251 }
252
253 #[instrument(skip_all, fields(local_id = local_id))]
254 pub(crate) fn attach_local(&mut self, local_id: usize, key: Key) {
255 let local_state = LocalState { local_id, key };
256 self.local_state = Some(local_state);
257 }
258
259 pub(crate) fn attach_remote(&mut self, remote_id: usize, remote_capability: Option<Vec<u8>>) {
260 let remote_state = RemoteState {
261 remote_id,
262 remote_capability,
263 };
264 self.remote_state = Some(remote_state);
265 }
266
267 pub(crate) fn is_connected(&self) -> bool {
268 self.local_state.is_some() && self.remote_state.is_some()
269 }
270
271 pub(crate) fn prepare_to_verify(&self) -> Result<(&Key, Option<&Vec<u8>>)> {
272 if !self.is_connected() {
273 return Err(error("Channel is not opened from both local and remote"));
274 }
275 let local_state = self.local_state.as_ref().unwrap();
277 let remote_state = self.remote_state.as_ref().unwrap();
278 Ok((&local_state.key, remote_state.remote_capability.as_ref()))
279 }
280
281 #[instrument(skip_all)]
282 pub(crate) fn open(&mut self, outbound_tx: Sender<Vec<ChannelMessage>>) -> Channel {
283 let local_state = self
284 .local_state
285 .as_ref()
286 .expect("May not open channel that is not locally attached");
287
288 let (inbound_tx, inbound_rx) = async_channel::unbounded();
289 let channel = Channel::new(
290 Some(inbound_rx),
291 inbound_tx.clone(),
292 outbound_tx,
293 self.discovery_key,
294 local_state.key,
295 local_state.local_id,
296 self.closed.clone(),
297 );
298
299 self.inbound_tx = Some(inbound_tx);
300 channel
301 }
302
303 pub(crate) fn try_send_inbound(&mut self, message: Message) -> std::io::Result<()> {
304 if let Some(inbound_tx) = self.inbound_tx.as_mut() {
305 inbound_tx
306 .try_send(message)
307 .map_err(|e| error(format!("Sending to channel failed: {e}").as_str()))
308 } else {
309 Err(error("Channel is not open"))
310 }
311 }
312
313 pub(crate) fn try_send_inbound_tolerate_closed(
314 &mut self,
315 message: Message,
316 ) -> std::io::Result<()> {
317 if let Some(inbound_tx) = self.inbound_tx.as_mut()
318 && let Err(err) = inbound_tx.try_send(message)
319 {
320 match err {
321 TrySendError::Full(e) => {
322 return Err(error(format!("Sending to channel failed: {e}").as_str()));
323 }
324 TrySendError::Closed(_) => {}
325 }
326 }
327 Ok(())
328 }
329}
330
331impl Drop for ChannelHandle {
332 fn drop(&mut self) {
333 self.closed.store(true, Ordering::SeqCst);
334 }
335}
336
337#[derive(Debug)]
339pub(crate) struct ChannelMap {
340 channels: HashMap<String, ChannelHandle>,
341 local_id: Vec<Option<String>>,
342 remote_id: Vec<Option<String>>,
343}
344
345impl ChannelMap {
346 pub(crate) fn new() -> Self {
347 Self {
348 channels: HashMap::new(),
349 local_id: vec![None],
352 remote_id: vec![],
353 }
354 }
355
356 pub(crate) fn attach_local(&mut self, key: Key) -> &ChannelHandle {
357 let discovery_key = discovery_key(&key);
358 let hdkey = hex::encode(discovery_key);
359 let local_id = self.alloc_local();
360
361 self.channels
362 .entry(hdkey.clone())
363 .and_modify(|channel| channel.attach_local(local_id, key))
364 .or_insert_with(|| ChannelHandle::new_local(local_id, discovery_key, key));
365
366 self.local_id[local_id] = Some(hdkey.clone());
367 self.channels.get(&hdkey).unwrap()
368 }
369
370 pub(crate) fn attach_remote(
371 &mut self,
372 discovery_key: DiscoveryKey,
373 remote_id: usize,
374 remote_capability: Option<Vec<u8>>,
375 ) -> &ChannelHandle {
376 let hdkey = hex::encode(discovery_key);
377 self.alloc_remote(remote_id);
378 self.channels
379 .entry(hdkey.clone())
380 .and_modify(|channel| channel.attach_remote(remote_id, remote_capability.clone()))
381 .or_insert_with(|| {
382 ChannelHandle::new_remote(remote_id, discovery_key, remote_capability)
383 });
384 self.remote_id[remote_id] = Some(hdkey.clone());
385 self.channels.get(&hdkey).unwrap()
386 }
387
388 pub(crate) fn get_remote_mut(&mut self, remote_id: usize) -> Option<&mut ChannelHandle> {
389 if let Some(Some(hdkey)) = self.remote_id.get(remote_id).as_ref() {
390 self.channels.get_mut(hdkey)
391 } else {
392 None
393 }
394 }
395
396 pub(crate) fn get_remote(&self, remote_id: usize) -> Option<&ChannelHandle> {
397 if let Some(Some(hdkey)) = self.remote_id.get(remote_id).as_ref() {
398 self.channels.get(hdkey)
399 } else {
400 None
401 }
402 }
403
404 pub(crate) fn get_local_mut(&mut self, local_id: usize) -> Option<&mut ChannelHandle> {
405 if let Some(Some(hdkey)) = self.local_id.get(local_id).as_ref() {
406 self.channels.get_mut(hdkey)
407 } else {
408 None
409 }
410 }
411
412 pub(crate) fn get_local(&self, local_id: usize) -> Option<&ChannelHandle> {
413 if let Some(Some(hdkey)) = self.local_id.get(local_id).as_ref() {
414 self.channels.get(hdkey)
415 } else {
416 None
417 }
418 }
419
420 pub(crate) fn has_channel(&self, discovery_key: &[u8]) -> bool {
421 let hdkey = hex::encode(discovery_key);
422 self.channels.contains_key(&hdkey)
423 }
424
425 pub(crate) fn remove(&mut self, discovery_key: &[u8]) {
426 let hdkey = hex::encode(discovery_key);
427 let channel = self.channels.get(&hdkey);
428 if let Some(channel) = channel {
429 if let Some(local_id) = channel.local_id() {
430 self.local_id[local_id] = None;
431 }
432 if let Some(remote_id) = channel.remote_id() {
433 self.remote_id[remote_id] = None;
434 }
435 }
436 self.channels.remove(&hdkey);
437 }
438
439 #[instrument(skip(self))]
440 pub(crate) fn prepare_to_verify(&self, local_id: usize) -> Result<(&Key, Option<&Vec<u8>>)> {
441 let channel_handle = self
442 .get_local(local_id)
443 .ok_or_else(|| error("Channel not found"))?;
444 channel_handle.prepare_to_verify()
445 }
446
447 pub(crate) fn accept(
448 &mut self,
449 local_id: usize,
450 outbound_tx: Sender<Vec<ChannelMessage>>,
451 ) -> Result<Channel> {
452 let channel_handle = self
453 .get_local_mut(local_id)
454 .ok_or_else(|| error("Channel not found"))?;
455 if !channel_handle.is_connected() {
456 return Err(error("Channel is not opened from remote"));
457 }
458 let channel = channel_handle.open(outbound_tx);
459 Ok(channel)
460 }
461
462 pub(crate) fn forward_inbound_message(
463 &mut self,
464 remote_id: usize,
465 message: Message,
466 ) -> Result<()> {
467 if let Some(channel_handle) = self.get_remote_mut(remote_id) {
468 channel_handle.try_send_inbound(message)?;
469 }
470 Ok(())
471 }
472
473 pub(crate) fn forward_inbound_message_tolerate_closed(
474 &mut self,
475 remote_id: usize,
476 message: Message,
477 ) -> Result<()> {
478 if let Some(channel_handle) = self.get_remote_mut(remote_id) {
479 channel_handle.try_send_inbound_tolerate_closed(message)?;
480 }
481 Ok(())
482 }
483
484 fn alloc_local(&mut self) -> usize {
485 let empty_id = self
486 .local_id
487 .iter()
488 .skip(1)
489 .position(|x| x.is_none())
490 .map(|position| position + 1);
491 match empty_id {
492 Some(empty_id) => empty_id,
493 None => {
494 self.local_id.push(None);
495 self.local_id.len() - 1
496 }
497 }
498 }
499
500 fn alloc_remote(&mut self, id: usize) {
501 if self.remote_id.len() > id {
502 self.remote_id[id] = None;
503 } else {
504 self.remote_id.resize(id + 1, None)
505 }
506 }
507
508 pub(crate) fn iter(&self) -> impl Iterator<Item = &ChannelHandle> {
509 self.channels.values()
510 }
511}
512
513fn error(message: &str) -> Error {
514 Error::other(message)
515}