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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// LNP/BP Core Library implementing LNPBP specifications & standards
// Written in 2020 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// 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 std::any::Any;
#[cfg(feature = "keygen")]
use std::net::TcpListener;

#[cfg(feature = "keygen")]
use addr::NodeAddr;
use addr::NodeId;
use amplify::Bipolar;
#[cfg(feature = "keygen")]
use inet2_addr::InetSocketAddr;
#[cfg(feature = "zmq")]
use inet2_addr::ServiceAddr;

use super::{Decrypt, Encrypt, Transcode};
use crate::session::noise::FramingProtocol;
use crate::session::{noise, PlainTranscoder};
use crate::transport::{
    encrypted, unencrypted, DuplexConnection, Error, RecvFrame, RoutedFrame,
    SendFrame,
};
#[cfg(feature = "zmq")]
use crate::zeromq;
use crate::{NoiseDecryptor, NoiseTranscoder};

// Generics prevents us from using session as `&dyn` reference, so we have
// to avoid `where Self: Input + Output` and generic parameters, unlike with
// `Transcode`
pub trait SendRecvMessage {
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error>;
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error>;
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error>;
    fn send_routed_message(
        &mut self,
        source: &[u8],
        route: &[u8],
        dest: &[u8],
        raw: &[u8],
    ) -> Result<usize, Error>;
    fn into_any(self: Box<Self>) -> Box<dyn Any>;
}

pub trait Split {
    fn split(
        self,
    ) -> (Box<dyn RecvMessage + Send>, Box<dyn SendMessage + Send>);
}

pub trait RecvMessage {
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error>;
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        // We panic here because this is a program architecture design
        // error and developer must be notified about it; the program using
        // this pattern can't work
        panic!("Multipeer sockets are not possible with the chosen transport")
    }
}

pub trait SendMessage {
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error>;
    fn send_routed_message(
        &mut self,
        _source: &[u8],
        _route: &[u8],
        _dest: &[u8],
        _raw: &[u8],
    ) -> Result<usize, Error> {
        // We panic here because this is a program architecture design
        // error and developer must be notified about it; the program using
        // this pattern can't work
        panic!("Multipeer sockets are not possible with the chosen transport")
    }
}

pub struct Session<T, C>
where
    T: Transcode,
    T::Left: Decrypt,
    T::Right: Encrypt,
    C: DuplexConnection + Bipolar,
    C::Left: RecvFrame,
    C::Right: SendFrame,
{
    pub(self) transcoder: T,
    pub(self) connection: C,
}

pub struct Receiver<D, R>
where
    D: Decrypt,
    R: RecvFrame,
{
    pub(self) decryptor: D,
    pub(self) input: R,
}

pub struct Sender<E, S>
where
    E: Encrypt,
    S: SendFrame,
{
    pub(self) encryptor: E,
    pub(self) output: S,
}

// Private trait used to avoid code duplication below
trait InternalSession {
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error>;
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error>;
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error>;
    fn send_routed_message(
        &mut self,
        source: &[u8],
        route: &[u8],
        dest: &[u8],
        raw: &[u8],
    ) -> Result<usize, Error>;
}

impl<T, C> InternalSession for Session<T, C>
where
    T: Transcode + 'static,
    T::Left: Decrypt,
    T::Right: Encrypt,
    C: DuplexConnection + Bipolar + 'static,
    C::Left: RecvFrame,
    C::Right: SendFrame,
    Error: From<T::Error> + From<<T::Left as Decrypt>::Error>,
{
    #[inline]
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        let reader = self.connection.as_receiver();
        Ok(self.transcoder.decrypt(reader.recv_frame()?)?)
    }

    #[inline]
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error> {
        let writer = self.connection.as_sender();
        writer.send_frame(&self.transcoder.encrypt(raw))
    }

    #[inline]
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        let reader = self.connection.as_receiver();
        let mut routed_frame = reader.recv_routed()?;
        routed_frame.msg = self.transcoder.decrypt(routed_frame.msg)?;
        Ok(routed_frame)
    }

    #[inline]
    fn send_routed_message(
        &mut self,
        source: &[u8],
        route: &[u8],
        dest: &[u8],
        raw: &[u8],
    ) -> Result<usize, Error> {
        let writer = self.connection.as_sender();
        writer.send_routed(source, route, dest, &self.transcoder.encrypt(raw))
    }
}

impl SendRecvMessage for Session<PlainTranscoder, unencrypted::Connection> {
    #[inline]
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        InternalSession::recv_raw_message(self)
    }
    #[inline]
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error> {
        InternalSession::send_raw_message(self, raw)
    }
    #[inline]
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        InternalSession::recv_routed_message(self)
    }
    #[inline]
    fn send_routed_message(
        &mut self,
        source: &[u8],
        route: &[u8],
        dest: &[u8],
        raw: &[u8],
    ) -> Result<usize, Error> {
        InternalSession::send_routed_message(self, source, route, dest, raw)
    }
    #[inline]
    fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
}

fn recv_noise_message<const LEN_SIZE: usize>(
    reader: &mut dyn RecvFrame,
    decrypt: &mut NoiseDecryptor<LEN_SIZE>,
) -> Result<Vec<u8>, Error> {
    // Reading & decrypting length
    let encrypted_len = reader.recv_frame()?;
    decrypt.decrypt(encrypted_len)?;
    let len = decrypt.pending_message_len().ok_or(Error::NoNoiseHeader)?;
    // Reading & decrypting payload
    let encrypted_payload = reader.recv_raw(len + noise::chacha::TAG_SIZE)?;
    let payload = decrypt.decrypt(encrypted_payload)?;
    Ok(payload)
}

impl<const LEN_SIZE: usize> SendRecvMessage
    for Session<NoiseTranscoder<LEN_SIZE>, encrypted::Connection<LEN_SIZE>>
{
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        let reader = self.connection.as_receiver();
        recv_noise_message(reader, &mut self.transcoder.decryptor)
    }

    #[inline]
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error> {
        InternalSession::send_raw_message(self, raw)
    }
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        unimplemented!(
            "to route brontide messages use presentation-level onion routing"
        )
    }
    fn send_routed_message(
        &mut self,
        source: &[u8],
        route: &[u8],
        dest: &[u8],
        raw: &[u8],
    ) -> Result<usize, Error> {
        unimplemented!(
            "to route brontide messages use presentation-level onion routing"
        )
    }
    #[inline]
    fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
}

#[cfg(feature = "zmq")]
impl SendRecvMessage for Session<PlainTranscoder, zeromq::Connection> {
    #[inline]
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        InternalSession::recv_raw_message(self)
    }
    #[inline]
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error> {
        InternalSession::send_raw_message(self, raw)
    }
    #[inline]
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        InternalSession::recv_routed_message(self)
    }
    #[inline]
    fn send_routed_message(
        &mut self,
        source: &[u8],
        route: &[u8],
        dest: &[u8],
        raw: &[u8],
    ) -> Result<usize, Error> {
        InternalSession::send_routed_message(self, source, route, dest, raw)
    }
    #[inline]
    fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
}

impl<T, C> Split for Session<T, C>
where
    T: Transcode,
    T::Left: Decrypt + Send + 'static,
    T::Right: Encrypt + Send + 'static,
    C: DuplexConnection + Bipolar,
    C::Left: RecvFrame + Send + 'static,
    C::Right: SendFrame + Send + 'static,
    Receiver<T::Left, C::Left>: RecvMessage,
    Error: From<T::Error> + From<<T::Left as Decrypt>::Error>,
{
    #[inline]
    fn split(
        self,
    ) -> (Box<dyn RecvMessage + Send>, Box<dyn SendMessage + Send>) {
        let (decryptor, encryptor) = self.transcoder.split();
        let (input, output) = Bipolar::split(self.connection);
        (
            Box::new(Receiver { decryptor, input }),
            Box::new(Sender { encryptor, output }),
        )
    }
}

pub type BrontideSession = Session<
    NoiseTranscoder<{ FramingProtocol::Brontide.message_len_size() }>,
    encrypted::Connection<2>,
>;
pub type BrontozaurSession = Session<
    NoiseTranscoder<{ FramingProtocol::Brontozaur.message_len_size() }>,
    encrypted::Connection<3>,
>;
#[cfg(feature = "zmq")]
pub type LocalSession = Session<PlainTranscoder, zeromq::Connection>;
#[cfg(feature = "zmq")]
pub type RpcSession = Session<
    NoiseTranscoder<{ FramingProtocol::Brontozaur.message_len_size() }>,
    zeromq::Connection,
>;

impl<const LEN_SIZE: usize>
    Session<NoiseTranscoder<LEN_SIZE>, encrypted::Connection<LEN_SIZE>>
{
    #[inline]
    pub fn remote_id(&self) -> NodeId { self.transcoder.remote_pubkey().into() }
}

#[cfg(feature = "keygen")]
impl BrontideSession {
    pub fn with(
        stream: std::net::TcpStream,
        local_key: secp256k1::SecretKey,
        remote_addr: InetSocketAddr,
    ) -> Result<Self, Error> {
        BrontideSession::with_tcp_encrypted(stream, local_key, remote_addr)
    }

    pub fn connect(
        local_key: secp256k1::SecretKey,
        remote_node: NodeAddr,
    ) -> Result<Self, Error> {
        BrontideSession::connect_tcp_encrypted(local_key, remote_node)
    }

    pub fn accept(
        local_key: secp256k1::SecretKey,
        listener: &TcpListener,
    ) -> Result<Self, Error> {
        BrontideSession::accept_tcp_encrypted(local_key, listener)
    }
}

#[cfg(feature = "keygen")]
impl BrontozaurSession {
    pub fn with(
        stream: std::net::TcpStream,
        local_key: secp256k1::SecretKey,
        remote_addr: InetSocketAddr,
    ) -> Result<Self, Error> {
        BrontozaurSession::with_tcp_encrypted(stream, local_key, remote_addr)
    }

    pub fn connect_with(
        stream: std::net::TcpStream,
        local_key: secp256k1::SecretKey,
        remote_node: NodeAddr,
    ) -> Result<Self, Error> {
        BrontozaurSession::connect_with_tcp_encrypted(
            stream,
            local_key,
            remote_node,
        )
    }

    pub fn connect(
        local_key: secp256k1::SecretKey,
        remote_node: NodeAddr,
    ) -> Result<Self, Error> {
        BrontozaurSession::connect_tcp_encrypted(local_key, remote_node)
    }

    pub fn accept(
        local_key: secp256k1::SecretKey,
        listener: &TcpListener,
    ) -> Result<Self, Error> {
        BrontozaurSession::accept_tcp_encrypted(local_key, listener)
    }
}

#[cfg(feature = "zmq")]
impl LocalSession {
    pub fn connect(
        zmq_type: zeromq::ZmqSocketType,
        remote: &ServiceAddr,
        local: Option<&ServiceAddr>,
        identity: Option<&[u8]>,
        context: &zmq::Context,
    ) -> Result<Self, Error> {
        LocalSession::connect_zmq_unencrypted(
            zmq_type, remote, local, identity, context,
        )
    }

    pub fn with_zmq_socket(
        zmq_type: zeromq::ZmqSocketType,
        socket: zmq::Socket,
    ) -> Self {
        LocalSession::with_zmq_socket_unencrypted(zmq_type, socket)
    }
}

/* TODO: Needs more work due to ZMQ PUSH/PULL sockets using two connections
#[cfg(all(feature = "zmq", feature = "keygen"))]
impl RpcSession {
    pub fn connect(
        zmq_type: zeromq::ZmqSocketType,
        remote: &ServiceAddr,
        local: Option<ServiceAddr>,
        identity: Option<&[u8]>,
        context: &zmq::Context,
    ) -> Result<Self, Error> {
        RpcSession::with_zmq_encrypted(
            zmq_type, remote, local, identity, context,
        )
    }

    pub fn with_zmq_socket(
        zmq_type: zeromq::ZmqSocketType,
        socket: zmq::Socket,
    ) -> Self {
        RpcSession::from_zmq_socket_encrypted(zmq_type, socket)
    }
}
 */

#[cfg(feature = "keygen")]
impl<const LEN_SIZE: usize>
    Session<NoiseTranscoder<LEN_SIZE>, encrypted::Connection<LEN_SIZE>>
{
    fn with_tcp_encrypted(
        stream: std::net::TcpStream,
        local_key: secp256k1::SecretKey,
        remote_addr: InetSocketAddr,
    ) -> Result<Self, Error> {
        Self::init_tcp_encrypted(
            local_key,
            encrypted::Connection::with(stream, remote_addr),
        )
    }

    fn connect_with_tcp_encrypted(
        stream: std::net::TcpStream,
        local_key: secp256k1::SecretKey,
        remote_node: NodeAddr,
    ) -> Result<Self, Error> {
        let mut connection =
            encrypted::Connection::with(stream, remote_node.addr);
        let transcoder = NoiseTranscoder::new_initiator(
            local_key,
            remote_node.public_key(),
            &mut connection,
        )?;
        Ok(Self {
            transcoder,
            connection,
        })
    }

    fn connect_tcp_encrypted(
        local_key: secp256k1::SecretKey,
        remote_node: NodeAddr,
    ) -> Result<Self, Error> {
        let mut connection = encrypted::Connection::connect(remote_node.addr)?;
        let transcoder = NoiseTranscoder::new_initiator(
            local_key,
            remote_node.public_key(),
            &mut connection,
        )?;
        Ok(Self {
            transcoder,
            connection,
        })
    }

    fn accept_tcp_encrypted(
        local_key: secp256k1::SecretKey,
        listener: &TcpListener,
    ) -> Result<Self, Error> {
        Self::init_tcp_encrypted(
            local_key,
            encrypted::Connection::accept(listener)?,
        )
    }

    fn init_tcp_encrypted(
        local_key: secp256k1::SecretKey,
        mut connection: encrypted::Connection<LEN_SIZE>,
    ) -> Result<Self, Error> {
        let transcoder =
            NoiseTranscoder::new_responder(local_key, &mut connection)?;
        Ok(Self {
            transcoder,
            connection,
        })
    }
}

/* TODO: Needs more work due to ZMQ PUSH/PULL sockets using two connections
#[cfg(all(feature = "zmq", feature = "keygen"))]
impl
    Session<
        NoiseTranscoder<{ FramingProtocol::Brontozaur.message_len_size() }>,
        zeromq::Connection,
    >
{
    fn connect_zmq_encrypted(
        zmq_type: ZmqConnectionType,
        remote_node: &NodeAddr,
        local_key: secp256k1::SecretKey,
        local: Option<ServiceAddr>,
        identity: Option<&[u8]>,
        context: &zmq::Context,
    ) -> Result<Self, Error> {
        let mut socket = SocketAddr::try_from(remote_node.addr).map_err(|_| Error::TorNotSupportedYet)?;
        let mut connection = zeromq::Connection::with(
            zmq_type.socket_out_type(), &ServiceAddr::Tcp(socket), local, identity, context,
        )?;
        let transcoder = NoiseTranscoder::new_initiator(local_key, remote_node.public_key(), &mut connection)?;
        Ok(Self {
            transcoder,
            connection
        })
    }

    fn bind_zmq_encrypted(
        zmq_type: ZmqConnectionType,
        bind_addr: &InetSocketAddr,
        local_key: secp256k1::SecretKey,
        identity: Option<&[u8]>,
        context: &zmq::Context,
    ) -> Result<Self, Error> {
        let mut socket = SocketAddr::try_from(remote_node).map_err(|_| Error::TorNotSupportedYet)?;
        let mut connection = zeromq::Connection::with(
            zmq_type.socket_in_type(), &ServiceAddr::Tcp(socket), local, identity, context,
        )?;
        let transcoder = NoiseTranscoder::new_responder(local_key, &mut connection)?;
        Ok(Self {
            transcoder,
            connection
        })
    }
}
 */

#[cfg(feature = "zmq")]
impl Session<PlainTranscoder, zeromq::Connection> {
    fn connect_zmq_unencrypted(
        zmq_type: zeromq::ZmqSocketType,
        remote: &ServiceAddr,
        local: Option<&ServiceAddr>,
        identity: Option<&[u8]>,
        context: &zmq::Context,
    ) -> Result<Self, Error> {
        Ok(Self {
            transcoder: PlainTranscoder,
            connection: zeromq::Connection::connect(
                zmq_type, remote, local, identity, context,
            )?,
        })
    }

    fn with_zmq_socket_unencrypted(
        zmq_type: zeromq::ZmqSocketType,
        socket: zmq::Socket,
    ) -> Self {
        Self {
            transcoder: PlainTranscoder,
            connection: zeromq::Connection::with_socket(zmq_type, socket),
        }
    }
}

#[cfg(feature = "zmq")]
impl<T> Session<T, zeromq::Connection>
where
    T: Transcode,
    T::Left: Decrypt + Send + 'static,
    T::Right: Encrypt + Send + 'static,
{
    pub fn as_socket(&self) -> &zmq::Socket { self.connection.as_socket() }

    pub fn set_identity(
        &mut self,
        identity: &impl AsRef<[u8]>,
        context: &zmq::Context,
    ) -> Result<(), Error> {
        self.connection
            .set_identity(identity, context)
            .map_err(Error::from)
    }
}

// Private trait used to avoid code duplication below
trait InternalInput {
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error>;
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error>;
}

impl<T, C> InternalInput for Receiver<T, C>
where
    T: Decrypt,
    C: RecvFrame,
    // TODO: (new) Use session-level error type
    Error: From<T::Error>,
{
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        Ok(self.decryptor.decrypt(self.input.recv_frame()?)?)
    }
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        let mut routed_frame = self.input.recv_routed()?;
        routed_frame.msg = self.decryptor.decrypt(routed_frame.msg)?;
        Ok(routed_frame)
    }
}

impl RecvMessage for Receiver<PlainTranscoder, unencrypted::Stream> {
    #[inline]
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        InternalInput::recv_raw_message(self)
    }
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        InternalInput::recv_routed_message(self)
    }
}

impl<const LEN_SIZE: usize> RecvMessage
    for Receiver<NoiseDecryptor<LEN_SIZE>, encrypted::Stream<LEN_SIZE>>
{
    #[inline]
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        recv_noise_message(&mut self.input, &mut self.decryptor)
    }
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        InternalInput::recv_routed_message(self)
    }
}

#[cfg(feature = "zmq")]
impl RecvMessage for Receiver<PlainTranscoder, zeromq::WrappedSocket> {
    #[inline]
    fn recv_raw_message(&mut self) -> Result<Vec<u8>, Error> {
        InternalInput::recv_raw_message(self)
    }
    fn recv_routed_message(&mut self) -> Result<RoutedFrame, Error> {
        InternalInput::recv_routed_message(self)
    }
}

impl<T, C> SendMessage for Sender<T, C>
where
    T: Encrypt,
    C: SendFrame,
{
    fn send_raw_message(&mut self, raw: &[u8]) -> Result<usize, Error> {
        self.output.send_frame(&self.encryptor.encrypt(raw))
    }
    fn send_routed_message(
        &mut self,
        source: &[u8],
        route: &[u8],
        dest: &[u8],
        raw: &[u8],
    ) -> Result<usize, Error> {
        let encrypted = self.encryptor.encrypt(raw);
        self.output.send_routed(source, route, dest, &encrypted)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    #[cfg(feature = "zmq")]
    fn test_zmq_no_encryption() {
        let ctx = zmq::Context::new();
        let locator = ServiceAddr::Inproc(s!("test"));
        let mut rx = Session::connect_zmq_unencrypted(
            zeromq::ZmqSocketType::Rep,
            &locator,
            None,
            None,
            &ctx,
        )
        .unwrap();
        let mut tx = Session::connect_zmq_unencrypted(
            zeromq::ZmqSocketType::Req,
            &locator,
            None,
            None,
            &ctx,
        )
        .unwrap();

        let msg = b"Some message";
        SendRecvMessage::send_raw_message(&mut tx, msg).unwrap();
        assert_eq!(SendRecvMessage::recv_raw_message(&mut rx).unwrap(), msg);

        let msg = b"";
        SendRecvMessage::send_raw_message(&mut rx, msg).unwrap();
        assert_eq!(SendRecvMessage::recv_raw_message(&mut tx).unwrap(), msg);
    }
}