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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
use crate::prefabs::ClientServerRemote;
use crate::prelude::results::{PeerConnectSuccess, PeerRegisterStatus};
use crate::prelude::*;
use crate::remote_ext::remote_specialization::PeerRemote;
use crate::remote_ext::results::LocalGroupPeer;
use crate::remote_ext::user_ids::{SymmetricIdentifierHandleRef, TargetLockedRemote};

use citadel_proto::auth::AuthenticationRequest;
use citadel_types::proto::ConnectMode;
use citadel_types::proto::ObjectTransferStatus;
use futures::StreamExt;
use std::path::PathBuf;
use std::time::Duration;

pub(crate) mod user_ids {
    use crate::prelude::*;
    use std::ops::Deref;

    #[derive(Debug)]
    /// A reference to a user identifier
    pub struct SymmetricIdentifierHandleRef<'a> {
        pub(crate) user: VirtualTargetType,
        pub(crate) remote: &'a NodeRemote,
        pub(crate) target_username: Option<String>,
    }

    impl SymmetricIdentifierHandleRef<'_> {
        pub fn into_owned(self) -> SymmetricIdentifierHandle {
            SymmetricIdentifierHandle {
                user: self.user,
                remote: self.remote.clone(),
                target_username: self.target_username,
            }
        }
    }

    #[derive(Clone, Debug)]
    /// A convenience structure for executing commands that depend on a specific registered user
    pub struct SymmetricIdentifierHandle {
        user: VirtualTargetType,
        remote: NodeRemote,
        target_username: Option<String>,
    }

    pub trait TargetLockedRemote: Send + Sync {
        fn user(&self) -> &VirtualTargetType;
        fn remote(&self) -> &NodeRemote;
        fn target_username(&self) -> Option<&String>;
        fn user_mut(&mut self) -> &mut VirtualTargetType;
        fn session_security_settings(&self) -> Option<&SessionSecuritySettings>;
    }

    impl TargetLockedRemote for SymmetricIdentifierHandleRef<'_> {
        fn user(&self) -> &VirtualTargetType {
            &self.user
        }
        fn remote(&self) -> &NodeRemote {
            self.remote
        }
        fn target_username(&self) -> Option<&String> {
            self.target_username.as_ref()
        }
        fn user_mut(&mut self) -> &mut VirtualTargetType {
            &mut self.user
        }

        fn session_security_settings(&self) -> Option<&SessionSecuritySettings> {
            None
        }
    }

    impl TargetLockedRemote for SymmetricIdentifierHandle {
        fn user(&self) -> &VirtualTargetType {
            &self.user
        }
        fn remote(&self) -> &NodeRemote {
            &self.remote
        }
        fn target_username(&self) -> Option<&String> {
            self.target_username.as_ref()
        }
        fn user_mut(&mut self) -> &mut VirtualTargetType {
            &mut self.user
        }

        fn session_security_settings(&self) -> Option<&SessionSecuritySettings> {
            None
        }
    }

    impl From<SymmetricIdentifierHandleRef<'_>> for SymmetricIdentifierHandle {
        fn from(this: SymmetricIdentifierHandleRef<'_>) -> Self {
            this.into_owned()
        }
    }

    impl Deref for SymmetricIdentifierHandle {
        type Target = NodeRemote;

        fn deref(&self) -> &Self::Target {
            &self.remote
        }
    }

    impl Deref for SymmetricIdentifierHandleRef<'_> {
        type Target = NodeRemote;

        fn deref(&self) -> &Self::Target {
            self.remote
        }
    }
}

/// Contains the elements required to communicate with the adjacent node
pub struct ConnectionSuccess {
    /// An interface to send ordered, reliable, and encrypted messages
    pub channel: PeerChannel,
    /// Only available if UdpMode was enabled at the beginning of a session
    pub udp_channel_rx: Option<tokio::sync::oneshot::Receiver<UdpChannel>>,
    /// Contains the Google auth minted at the central server (if the central server enabled it), as well as any other services enabled by the central server
    pub services: ServicesObject,
    pub cid: u64,
    pub session_security_settings: SessionSecuritySettings,
}

/// Contains the elements entailed by a successful registration
pub struct RegisterSuccess {}

#[async_trait]
/// Endows the [NodeRemote](NodeRemote) with additional functions
pub trait ProtocolRemoteExt: Remote {
    /// Registers with custom settings
    /// Returns a ticket which is used to uniquely identify the request in the protocol
    async fn register<
        T: std::net::ToSocketAddrs + Send,
        R: Into<String> + Send,
        V: Into<String> + Send,
        K: Into<SecBuffer> + Send,
    >(
        &self,
        addr: T,
        full_name: R,
        username: V,
        proposed_password: K,
        default_security_settings: SessionSecuritySettings,
    ) -> Result<RegisterSuccess, NetworkError> {
        let creds =
            ProposedCredentials::new_register(full_name, username, proposed_password.into())
                .await?;
        let register_request = NodeRequest::RegisterToHypernode(RegisterToHypernode {
            remote_addr: addr
                .to_socket_addrs()?
                .next()
                .ok_or(NetworkError::InternalError("Invalid socket addr"))?,
            proposed_credentials: creds,
            static_security_settings: default_security_settings,
        });

        match map_errors(self.send_callback(register_request).await?)? {
            NodeResult::RegisterOkay(RegisterOkay { .. }) => Ok(RegisterSuccess {}),
            res => Err(NetworkError::msg(format!(
                "An unexpected response occurred: {res:?}"
            ))),
        }
    }

    /// Registers using the default settings. The default uses No Google FCM keys and the default session security settings
    /// Returns a ticket which is used to uniquely identify the request in the protocol
    async fn register_with_defaults<
        T: std::net::ToSocketAddrs + Send,
        R: Into<String> + Send,
        V: Into<String> + Send,
        K: Into<SecBuffer> + Send,
    >(
        &self,
        addr: T,
        full_name: R,
        username: V,
        proposed_password: K,
    ) -> Result<RegisterSuccess, NetworkError> {
        self.register(
            addr,
            full_name,
            username,
            proposed_password,
            Default::default(),
        )
        .await
    }

    /// Connects with custom settings
    /// Returns a ticket which is used to uniquely identify the request in the protocol
    async fn connect(
        &self,
        auth: AuthenticationRequest,
        connect_mode: ConnectMode,
        udp_mode: UdpMode,
        keep_alive_timeout: Option<Duration>,
        session_security_settings: SessionSecuritySettings,
    ) -> Result<ConnectionSuccess, NetworkError> {
        //let fcm_keys = fcm_keys.or_else(||cnac.get_fcm_keys()); // use the specified keys, or else get the fcm keys created during the registration phase

        let connect_request = NodeRequest::ConnectToHypernode(ConnectToHypernode {
            auth_request: auth,
            connect_mode,
            udp_mode,
            keep_alive_timeout: keep_alive_timeout.map(|r| r.as_secs()),
            session_security_settings,
        });

        match map_errors(self.send_callback(connect_request).await?)? {
            NodeResult::ConnectSuccess(ConnectSuccess {
                ticket: _,
                implicated_cid: cid,
                remote_addr: _,
                is_personal: _,
                v_conn_type: _,
                services,
                welcome_message: _,
                channel,
                udp_rx_opt: udp_channel_rx,
                session_security_settings,
            }) => Ok(ConnectionSuccess {
                channel,
                udp_channel_rx,
                services,
                cid,
                session_security_settings,
            }),
            NodeResult::ConnectFail(ConnectFail {
                ticket: _,
                cid_opt: _,
                error_message: err,
            }) => Err(NetworkError::Generic(err)),
            res => Err(NetworkError::msg(format!(
                "[connect] An unexpected response occurred: {res:?}"
            ))),
        }
    }

    /// Connects with the default settings
    /// If FCM keys were created during the registration phase, then those keys will be used for the session. If new FCM keys need to be used, consider using [`Self::connect`]
    async fn connect_with_defaults(
        &self,
        auth: AuthenticationRequest,
    ) -> Result<ConnectionSuccess, NetworkError> {
        self.connect(
            auth,
            Default::default(),
            Default::default(),
            None,
            Default::default(),
        )
        .await
    }

    /// Creates a valid target identifier used to make protocol requests. Raw user IDs or usernames can be used
    /// ```
    /// use citadel_sdk::prelude::*;
    /// # use citadel_sdk::prefabs::client::single_connection::SingleClientServerConnectionKernel;
    /// # SingleClientServerConnectionKernel::new_connect_defaults("", "", |_, mut remote| async move {
    /// remote.find_target("my_account", "my_peer").await?.send_file("/path/to/file.pdf").await
    /// // or: remote.find_target(1234, "my_peer").await? [...]
    /// # });
    /// ```
    async fn find_target<T: Into<UserIdentifier> + Send, R: Into<UserIdentifier> + Send>(
        &self,
        local_user: T,
        peer: R,
    ) -> Result<SymmetricIdentifierHandleRef<'_>, NetworkError> {
        let account_manager = self.account_manager();
        account_manager
            .find_target_information(local_user, peer)
            .await?
            .map(move |(cid, peer)| {
                if peer.parent_icid != 0 {
                    SymmetricIdentifierHandleRef {
                        user: VirtualTargetType::ExternalGroupPeer {
                            implicated_cid: cid,
                            interserver_cid: peer.parent_icid,
                            peer_cid: peer.cid,
                        },
                        remote: self.remote_ref(),
                        target_username: None,
                    }
                } else {
                    SymmetricIdentifierHandleRef {
                        user: VirtualTargetType::LocalGroupPeer {
                            implicated_cid: cid,
                            peer_cid: peer.cid,
                        },
                        remote: self.remote_ref(),
                        target_username: None,
                    }
                }
            })
            .ok_or_else(|| NetworkError::msg("Target pair not found"))
    }

    /// Creates a proposed target from the valid local user to an unregistered peer in the network. Used when creating registration requests for peers.
    /// Currently only supports LocalGroup <-> LocalGroup peer connections
    async fn propose_target<T: Into<UserIdentifier> + Send, P: Into<UserIdentifier> + Send>(
        &self,
        local_user: T,
        peer: P,
    ) -> Result<SymmetricIdentifierHandleRef<'_>, NetworkError> {
        let local_cid = self.get_implicated_cid(local_user).await?;
        match peer.into() {
            UserIdentifier::ID(peer_cid) => Ok(SymmetricIdentifierHandleRef {
                user: VirtualTargetType::LocalGroupPeer {
                    implicated_cid: local_cid,
                    peer_cid,
                },
                remote: self.remote_ref(),
                target_username: None,
            }),
            UserIdentifier::Username(uname) => Ok(SymmetricIdentifierHandleRef {
                user: VirtualTargetType::LocalGroupPeer {
                    implicated_cid: local_cid,
                    peer_cid: 0,
                },
                remote: self.remote_ref(),
                target_username: Some(uname),
            }),
        }
    }

    /// Returns a list of local group peers on the network for local_user. May or may not be registered to the user. To get a list of registered users to local_user, run [`Self::get_local_group_mutual_peers`]
    /// - limit: if None, all peers are obtained. If Some, at most the specified number of peers will be obtained
    async fn get_local_group_peers<T: Into<UserIdentifier> + Send>(
        &self,
        local_user: T,
        limit: Option<usize>,
    ) -> Result<Vec<LocalGroupPeer>, NetworkError> {
        let local_cid = self.get_implicated_cid(local_user).await?;
        let command = NodeRequest::PeerCommand(PeerCommand {
            implicated_cid: local_cid,
            command: PeerSignal::GetRegisteredPeers {
                peer_conn_type: NodeConnectionType::LocalGroupPeerToLocalGroupServer(local_cid),
                response: None,
                limit: limit.map(|r| r as i32),
            },
        });

        let mut stream = self.send_callback_subscription(command).await?;

        while let Some(status) = stream.next().await {
            if let NodeResult::PeerEvent(PeerEvent {
                event:
                    PeerSignal::GetRegisteredPeers {
                        peer_conn_type: _,
                        response: Some(PeerResponse::RegisteredCids(cids, is_onlines)),
                        limit: _,
                    },
                ticket: _,
            }) = map_errors(status)?
            {
                return Ok(cids
                    .into_iter()
                    .zip(is_onlines.into_iter())
                    .map(|(cid, is_online)| LocalGroupPeer { cid, is_online })
                    .collect());
            }
        }

        Err(NetworkError::InternalError("Internal kernel stream died"))
    }

    /// Returns a list of mutually-registered peers with the local_user
    async fn get_local_group_mutual_peers<T: Into<UserIdentifier> + Send>(
        &self,
        local_user: T,
    ) -> Result<Vec<LocalGroupPeer>, NetworkError> {
        let local_cid = self.get_implicated_cid(local_user).await?;
        let command = NodeRequest::PeerCommand(PeerCommand {
            implicated_cid: local_cid,
            command: PeerSignal::GetMutuals {
                v_conn_type: NodeConnectionType::LocalGroupPeerToLocalGroupServer(local_cid),
                response: None,
            },
        });

        let mut stream = self.send_callback_subscription(command).await?;

        while let Some(status) = stream.next().await {
            if let NodeResult::PeerEvent(PeerEvent {
                event:
                    PeerSignal::GetMutuals {
                        v_conn_type: _,
                        response: Some(PeerResponse::RegisteredCids(cids, is_onlines)),
                    },
                ticket: _,
            }) = map_errors(status)?
            {
                return Ok(cids
                    .into_iter()
                    .zip(is_onlines.into_iter())
                    .map(|(cid, is_online)| LocalGroupPeer { cid, is_online })
                    .collect());
            }
        }

        Err(NetworkError::InternalError("Internal kernel stream died"))
    }

    #[doc(hidden)]
    fn remote_ref(&self) -> &NodeRemote;

    #[doc(hidden)]
    async fn get_implicated_cid<T: Into<UserIdentifier> + Send>(
        &self,
        local_user: T,
    ) -> Result<u64, NetworkError> {
        let account_manager = self.account_manager();
        Ok(account_manager
            .find_local_user_information(local_user)
            .await?
            .ok_or(NetworkError::InvalidRequest("User does not exist"))?)
    }
}

pub fn map_errors(result: NodeResult) -> Result<NodeResult, NetworkError> {
    match result {
        NodeResult::InternalServerError(InternalServerError {
            ticket_opt: _,
            message: err,
        }) => Err(NetworkError::Generic(err)),
        NodeResult::PeerEvent(PeerEvent {
            event:
                PeerSignal::SignalError {
                    ticket: _,
                    error: err,
                },
            ticket: _,
        }) => Err(NetworkError::Generic(err)),
        res => Ok(res),
    }
}

impl ProtocolRemoteExt for NodeRemote {
    fn remote_ref(&self) -> &NodeRemote {
        self
    }
}

impl ProtocolRemoteExt for ClientServerRemote {
    fn remote_ref(&self) -> &NodeRemote {
        &self.inner
    }
}

#[async_trait]
/// Some functions require that a target exists
pub trait ProtocolRemoteTargetExt: TargetLockedRemote {
    /// Sends a file with a custom size. The smaller the chunks, the higher the degree of scrambling, but the higher the performance cost. A chunk size of zero will use the default
    async fn send_file_with_custom_opts<T: ObjectSource>(
        &self,
        source: T,
        chunk_size: usize,
        transfer_type: TransferType,
    ) -> Result<(), NetworkError> {
        let chunk_size = if chunk_size == 0 {
            None
        } else {
            Some(chunk_size)
        };
        let implicated_cid = self.user().get_implicated_cid();
        let user = *self.user();
        let remote = self.remote();

        let result = remote
            .send_callback(NodeRequest::SendObject(SendObject {
                source: Box::new(source),
                chunk_size,
                implicated_cid,
                v_conn_type: user,
                transfer_type,
            }))
            .await?;
        match map_errors(result)? {
            NodeResult::ObjectTransferHandle(ObjectTransferHandle {
                ticket: _ticket,
                mut handle,
            }) => {
                while let Some(res) = handle.next().await {
                    log::trace!(target: "citadel", "Client received RES {:?}", res);
                    if let ObjectTransferStatus::TransferComplete = res {
                        return Ok(());
                    }
                }
            }

            res => {
                log::error!(target: "citadel", "Invalid NodeResult for FileTransfer request received: {:?}", res)
            }
        }

        Err(NetworkError::InternalError("File transfer stream died"))
    }

    /// Sends a file to the provided target using the default chunking size
    async fn send_file<T: ObjectSource>(&self, source: T) -> Result<(), NetworkError> {
        self.send_file_with_custom_opts(source, 0, TransferType::FileTransfer)
            .await
    }

    /// Sends a file to the provided target using custom chunking size with local encryption.
    /// Only this local node may decrypt the information send to the adjacent node.
    async fn remote_encrypted_virtual_filesystem_push_custom_chunking<
        T: ObjectSource,
        R: Into<PathBuf> + Send,
    >(
        &self,
        source: T,
        virtual_directory: R,
        chunk_size: usize,
        security_level: SecurityLevel,
    ) -> Result<(), NetworkError> {
        self.can_use_revfs()?;
        let mut virtual_path = virtual_directory.into();
        virtual_path = prepare_virtual_path(virtual_path);
        validate_virtual_path(&virtual_path)
            .map_err(|err| NetworkError::Generic(err.into_string()))?;
        let tx_type = TransferType::RemoteEncryptedVirtualFilesystem {
            virtual_path,
            security_level,
        };
        self.send_file_with_custom_opts(source, chunk_size, tx_type)
            .await
    }

    /// Sends a file to the provided target using the default chunking size with local encryption.
    /// Only this local node may decrypt the information send to the adjacent node.
    async fn remote_encrypted_virtual_filesystem_push<T: ObjectSource, R: Into<PathBuf> + Send>(
        &self,
        source: T,
        virtual_directory: R,
        security_level: SecurityLevel,
    ) -> Result<(), NetworkError> {
        self.remote_encrypted_virtual_filesystem_push_custom_chunking(
            source,
            virtual_directory,
            0,
            security_level,
        )
        .await
    }

    /// Pulls a virtual file from the RE-VFS. If `delete_on_pull` is true, then, the virtual file
    /// will be taken from the RE-VFS
    async fn remote_encrypted_virtual_filesystem_pull<R: Into<PathBuf> + Send>(
        &self,
        virtual_directory: R,
        transfer_security_level: SecurityLevel,
        delete_on_pull: bool,
    ) -> Result<PathBuf, NetworkError> {
        self.can_use_revfs()?;
        let request = NodeRequest::PullObject(PullObject {
            v_conn: *self.user(),
            virtual_dir: virtual_directory.into(),
            delete_on_pull,
            transfer_security_level,
        });

        match map_errors(self.remote().send_callback(request).await?)? {
            NodeResult::ObjectTransferHandle(ObjectTransferHandle {
                ticket: _ticket,
                mut handle,
            }) => {
                let mut local_path = None;
                while let Some(res) = handle.next().await {
                    log::trace!(target: "citadel", "Client received RES {:?}", res);
                    match res {
                        ObjectTransferStatus::ReceptionBeginning(path, _) => {
                            local_path = Some(path)
                        }
                        ObjectTransferStatus::TransferComplete => {
                            break;
                        }

                        _ => {}
                    }
                }

                Ok(local_path.ok_or(NetworkError::InternalError("Local path never loaded"))?)
            }

            res => {
                log::error!(target: "citadel", "Invalid NodeResult for FileTransfer request received: {:?}", res);
                Err(NetworkError::InternalError(
                    "Received invalid response from protocol",
                ))
            }
        }
    }

    /// Deletes the file from the RE-VFS. If the contents are desired on delete,
    /// consider calling `Self::remote_encrypted_virtual_filesystem_pull` with the delete
    /// parameter set to true
    async fn remote_encrypted_virtual_filesystem_delete<R: Into<PathBuf> + Send>(
        &self,
        virtual_directory: R,
    ) -> Result<(), NetworkError> {
        self.can_use_revfs()?;
        let request = NodeRequest::DeleteObject(DeleteObject {
            v_conn: *self.user(),
            virtual_dir: virtual_directory.into(),
            security_level: Default::default(),
        });

        let response = map_errors(self.remote().send_callback(request).await?)?;
        if let NodeResult::ReVFS(result) = response {
            if let Some(error) = result.error_message {
                Err(NetworkError::Generic(error))
            } else {
                Ok(())
            }
        } else {
            Err(NetworkError::InternalError("Invalid NodeRequest response"))
        }
    }

    /// Connects to the peer with custom settings
    async fn connect_to_peer_custom(
        &self,
        session_security_settings: SessionSecuritySettings,
        udp_mode: UdpMode,
    ) -> Result<PeerConnectSuccess, NetworkError> {
        let implicated_cid = self.user().get_implicated_cid();
        let peer_target = self.try_as_peer_connection().await?;

        let mut stream = self
            .remote()
            .send_callback_subscription(NodeRequest::PeerCommand(PeerCommand {
                implicated_cid,
                command: PeerSignal::PostConnect {
                    peer_conn_type: peer_target,
                    ticket_opt: None,
                    invitee_response: None,
                    session_security_settings,
                    udp_mode,
                },
            }))
            .await?;

        while let Some(status) = stream.next().await {
            match map_errors(status)? {
                NodeResult::PeerChannelCreated(PeerChannelCreated {
                    ticket: _,
                    channel,
                    udp_rx_opt,
                }) => {
                    let username = self.target_username().cloned();
                    let remote = PeerRemote {
                        inner: self.remote().clone(),
                        peer: peer_target.as_virtual_connection(),
                        username,
                        session_security_settings,
                    };

                    return Ok(PeerConnectSuccess {
                        remote,
                        channel,
                        udp_channel_rx: udp_rx_opt,
                        incoming_object_transfer_handles: None,
                    });
                }

                NodeResult::PeerEvent(PeerEvent {
                    event:
                        PeerSignal::PostConnect {
                            peer_conn_type: _,
                            ticket_opt: _,
                            invitee_response: Some(PeerResponse::Decline),
                            ..
                        },
                    ..
                }) => return Err(NetworkError::msg("Peer declined to connect")),

                _ => {}
            }
        }

        Err(NetworkError::InternalError("Internal kernel stream died"))
    }

    /// Connects to the target peer with default settings
    async fn connect_to_peer(&self) -> Result<PeerConnectSuccess, NetworkError> {
        self.connect_to_peer_custom(Default::default(), Default::default())
            .await
    }

    /// Posts a registration request to a peer
    async fn register_to_peer(&self) -> Result<PeerRegisterStatus, NetworkError> {
        let implicated_cid = self.user().get_implicated_cid();
        let peer_target = self.try_as_peer_connection().await?;
        // TODO: Get rid of this step. Should be handled by the protocol
        let local_username = self
            .remote()
            .account_manager()
            .get_username_by_cid(implicated_cid)
            .await?
            .ok_or_else(|| NetworkError::msg("Unable to find username for local user"))?;
        let peer_username_opt = self.target_username().cloned();

        let mut stream = self
            .remote()
            .send_callback_subscription(NodeRequest::PeerCommand(PeerCommand {
                implicated_cid,
                command: PeerSignal::PostRegister {
                    peer_conn_type: peer_target,
                    inviter_username: local_username,
                    invitee_username: peer_username_opt,
                    ticket_opt: None,
                    invitee_response: None,
                },
            }))
            .await?;

        while let Some(status) = stream.next().await {
            if let NodeResult::PeerEvent(PeerEvent {
                event:
                    PeerSignal::PostRegister {
                        peer_conn_type: _,
                        inviter_username: _,
                        invitee_username: _,
                        ticket_opt: _,
                        invitee_response: Some(resp),
                    },
                ticket: _,
            }) = map_errors(status)?
            {
                match resp {
                    PeerResponse::Accept(..) => return Ok(PeerRegisterStatus::Accepted),
                    PeerResponse::Decline => return Ok(PeerRegisterStatus::Declined),
                    PeerResponse::Timeout => return Ok(PeerRegisterStatus::Failed { reason: Some("Timeout on register request. Peer did not accept in time. Try again later".to_string()) }),
                    _ => {}
                }
            }
        }

        Err(NetworkError::InternalError("Internal kernel stream died"))
    }

    /// Deregisters the currently locked target. If the target is a client to server
    /// connection, deregisters from the server. If the target is a p2p connection,
    /// deregisters the p2p
    async fn deregister(&self) -> Result<(), NetworkError> {
        if let Ok(peer_conn) = self.try_as_peer_connection().await {
            let peer_request = PeerSignal::Deregister {
                peer_conn_type: peer_conn,
            };
            let implicated_cid = self.user().get_implicated_cid();
            let request = NodeRequest::PeerCommand(PeerCommand {
                implicated_cid,
                command: peer_request,
            });

            let mut subscription = self.remote().send_callback_subscription(request).await?;
            while let Some(result) = subscription.next().await {
                if let NodeResult::PeerEvent(PeerEvent {
                    event: PeerSignal::DeregistrationSuccess { .. },
                    ticket: _,
                }) = map_errors(result)?
                {
                    return Ok(());
                }
            }
        } else {
            // c2s conn
            let cid = self.user().get_implicated_cid();
            let request = NodeRequest::DeregisterFromHypernode(DeregisterFromHypernode {
                implicated_cid: cid,
                v_conn_type: *self.user(),
            });
            let mut subscription = self.remote().send_callback_subscription(request).await?;
            while let Some(result) = subscription.next().await {
                match map_errors(result)? {
                    NodeResult::DeRegistration(DeRegistration {
                        implicated_cid: _,
                        ticket_opt: _,
                        success: true,
                    }) => return Ok(()),
                    NodeResult::DeRegistration(DeRegistration {
                        implicated_cid: _,
                        ticket_opt: _,
                        success: false,
                    }) => {
                        return Err(NetworkError::msg(
                            "Unable to deregister: status=false".to_string(),
                        ))
                    }

                    _ => {}
                }
            }
        }

        Err(NetworkError::InternalError("Deregister ended unexpectedly"))
    }

    async fn disconnect(&self) -> Result<(), NetworkError> {
        if let Ok(peer_conn) = self.try_as_peer_connection().await {
            if let PeerConnectionType::LocalGroupPeer {
                implicated_cid,
                peer_cid: _,
            } = peer_conn
            {
                let request = NodeRequest::PeerCommand(PeerCommand {
                    implicated_cid,
                    command: PeerSignal::Disconnect {
                        peer_conn_type: peer_conn,
                        disconnect_response: None,
                    },
                });

                let mut subscription = self.remote().send_callback_subscription(request).await?;

                while let Some(event) = subscription.next().await {
                    if let NodeResult::PeerEvent(PeerEvent {
                        event:
                            PeerSignal::Disconnect {
                                peer_conn_type: _,
                                disconnect_response: Some(_),
                            },
                        ticket: _,
                    }) = map_errors(event)?
                    {
                        return Ok(());
                    }
                }

                Err(NetworkError::InternalError(
                    "Unable to receive valid disconnect event",
                ))
            } else {
                Err(NetworkError::msg(
                    "External group peer functionality not enabled",
                ))
            }
        } else {
            //c2s conn
            let cid = self.user().get_implicated_cid();
            let request = NodeRequest::DisconnectFromHypernode(DisconnectFromHypernode {
                implicated_cid: cid,
            });

            let mut subscription = self.remote().send_callback_subscription(request).await?;
            while let Some(event) = subscription.next().await {
                if let NodeResult::Disconnect(Disconnect {
                    success, message, ..
                }) = map_errors(event)?
                {
                    return if success {
                        Ok(())
                    } else {
                        Err(NetworkError::msg(message))
                    };
                }
            }

            Err(NetworkError::InternalError(
                "Unable to receive valid disconnect event",
            ))
        }
    }

    async fn create_group(
        &self,
        initial_users_to_invite: Option<Vec<UserIdentifier>>,
    ) -> Result<GroupChannel, NetworkError> {
        let implicated_cid = self.user().get_implicated_cid();

        let mut initial_users = vec![];
        // TODO: allow for custom message group options. For now, don't
        let options = MessageGroupOptions::default();
        // TODO/NOTE: default is PRIVATE mode, meaning all users in group must be registered to the owner
        // in the future, allow for private/public modes by adjusting the below. Initial users should be
        // a UserIdentifier
        if let Some(initial_users_to_invite) = initial_users_to_invite {
            for user in initial_users_to_invite {
                initial_users.push(
                    self.remote()
                        .account_manager()
                        .find_target_information(implicated_cid, user.clone())
                        .await
                        .map_err(|err| NetworkError::msg(err.into_string()))?
                        .ok_or_else(|| {
                            NetworkError::msg(format!(
                                "Account {user:?} not found for local user {implicated_cid:?}"
                            ))
                        })
                        .map(|r| r.1.cid)?,
                )
            }
        }

        let group_request = GroupBroadcast::Create {
            initial_invitees: initial_users,
            options,
        };
        let request = NodeRequest::GroupBroadcastCommand(GroupBroadcastCommand {
            implicated_cid,
            command: group_request,
        });
        let mut subscription = self.remote().send_callback_subscription(request).await?;

        while let Some(evt) = subscription.next().await {
            if let NodeResult::GroupChannelCreated(GroupChannelCreated { ticket: _, channel }) = evt
            {
                return Ok(channel);
            }
        }

        Err(NetworkError::InternalError(
            "Create_group ended unexpectedly",
        ))
    }

    /// Lists all groups that which the current peer owns
    async fn list_owned_groups(&self) -> Result<Vec<MessageGroupKey>, NetworkError> {
        let implicated_cid = self.user().get_implicated_cid();
        let group_request = GroupBroadcast::ListGroupsFor {
            cid: implicated_cid,
        };
        let request = NodeRequest::GroupBroadcastCommand(GroupBroadcastCommand {
            implicated_cid,
            command: group_request,
        });
        let mut subscription = self.remote().send_callback_subscription(request).await?;

        while let Some(evt) = subscription.next().await {
            if let NodeResult::GroupEvent(GroupEvent {
                implicated_cid: _,
                ticket: _,
                event: GroupBroadcast::ListResponse { groups },
            }) = evt
            {
                return Ok(groups);
            }
        }

        Err(NetworkError::InternalError(
            "List_members ended unexpectedly",
        ))
    }

    /// Begins a re-key, updating the container in the process.
    /// Returns the new key matrix version. Does not return the new key version
    /// if the rekey fails, or, if a current rekey is already executing
    async fn rekey(&self) -> Result<Option<u32>, NetworkError> {
        let request = NodeRequest::ReKey(ReKey {
            v_conn_type: *self.user(),
        });
        let mut subscription = self.remote().send_callback_subscription(request).await?;

        while let Some(evt) = subscription.next().await {
            if let NodeResult::ReKeyResult(result) = evt {
                return match result.status {
                    ReKeyReturnType::Success { version } => Ok(Some(version)),
                    ReKeyReturnType::AlreadyInProgress => Ok(None),
                    ReKeyReturnType::Failure => {
                        Err(NetworkError::InternalError("The rekey request failed"))
                    }
                };
            }
        }

        Err(NetworkError::InternalError(
            "List_members ended unexpectedly",
        ))
    }

    /// Checks if the locked target is registered
    async fn is_peer_registered(&self) -> Result<bool, NetworkError> {
        let target = self.try_as_peer_connection().await?;
        if let PeerConnectionType::LocalGroupPeer {
            implicated_cid: local_cid,
            peer_cid,
        } = target
        {
            let peers = self.remote().get_local_group_peers(local_cid, None).await?;
            citadel_logging::info!(target: "citadel", "Checking to see if {target} is registered in {peers:?}");
            Ok(peers.iter().any(|p| p.cid == peer_cid))
        } else {
            Err(NetworkError::Generic(
                "External group peers are not supported yet".to_string(),
            ))
        }
    }

    #[doc(hidden)]
    async fn try_as_peer_connection(&self) -> Result<PeerConnectionType, NetworkError> {
        let verified_return = |user: &VirtualTargetType| {
            user.try_as_peer_connection()
                .ok_or(NetworkError::InvalidRequest("Target is not a peer"))
        };

        if self.user().get_target_cid() == 0 {
            // in this case, the user re-used a remote locked to a registration target
            // where the username was provided, but the cid was 0 (unknown).
            let peer_username = self
                .target_username()
                .ok_or_else(|| NetworkError::msg("target_cid=0, yet, no username was provided"))?
                .clone();
            let implicated_cid = self.user().get_implicated_cid();
            let expected_peer_cid = self
                .remote()
                .account_manager()
                .get_persistence_handler()
                .get_cid_by_username(&peer_username);
            // get the peer cid from the account manager (implying the peers are already registered).
            // fallback to the mapped cid if the peer is not registered
            let peer_cid = self
                .remote()
                .account_manager()
                .find_target_information(implicated_cid, peer_username)
                .await
                .map_err(|err| NetworkError::Generic(err.into_string()))?
                .map(|r| r.1.cid)
                .unwrap_or(expected_peer_cid);

            let mut user = *self.user();
            user.set_target_cid(peer_cid);
            verified_return(&user)
        } else {
            verified_return(self.user())
        }
    }

    #[doc(hidden)]
    fn can_use_revfs(&self) -> Result<(), NetworkError> {
        if let Some(sess) = self.session_security_settings() {
            if sess.crypto_params.kem_algorithm == KemAlgorithm::Kyber {
                Ok(())
            } else {
                Err(NetworkError::InvalidRequest(
                    "RE-VFS can only be used with Kyber KEM",
                ))
            }
        } else {
            Err(NetworkError::InvalidRequest(
                "RE-VFS cannot be used with this remote type",
            ))
        }
    }
}

impl<T: TargetLockedRemote> ProtocolRemoteTargetExt for T {}

pub mod results {
    use crate::prelude::{ObjectTransferHandler, PeerChannel, UdpChannel};
    use crate::remote_ext::remote_specialization::PeerRemote;
    use citadel_proto::prelude::NetworkError;
    use tokio::sync::mpsc::UnboundedReceiver;
    use tokio::sync::oneshot::Receiver;

    #[derive(Debug)]
    pub struct PeerConnectSuccess {
        pub channel: PeerChannel,
        pub udp_channel_rx: Option<Receiver<UdpChannel>>,
        pub remote: PeerRemote,
        /// Receives incoming file/object transfer requests. The handles must be
        /// .accepted() before the file/object transfer is allowed to proceed
        pub(crate) incoming_object_transfer_handles:
            Option<UnboundedReceiver<ObjectTransferHandler>>,
    }

    impl PeerConnectSuccess {
        /// Obtains a receiver which yields incoming file/object transfer handles
        pub fn get_incoming_file_transfer_handle(
            &mut self,
        ) -> Result<UnboundedReceiver<ObjectTransferHandler>, NetworkError> {
            self.incoming_object_transfer_handles
                .take()
                .ok_or(NetworkError::InternalError(
                    "This function has already been called",
                ))
        }
    }

    pub enum PeerRegisterStatus {
        Accepted,
        Declined,
        Failed { reason: Option<String> },
    }

    #[derive(Clone, Debug)]
    pub struct LocalGroupPeer {
        pub cid: u64,
        pub is_online: bool,
    }
}

pub mod remote_specialization {
    use crate::prelude::*;

    #[derive(Debug, Clone)]
    pub struct PeerRemote {
        pub(crate) inner: NodeRemote,
        pub(crate) peer: VirtualTargetType,
        pub(crate) username: Option<String>,
        pub(crate) session_security_settings: SessionSecuritySettings,
    }

    impl TargetLockedRemote for PeerRemote {
        fn user(&self) -> &VirtualTargetType {
            &self.peer
        }
        fn remote(&self) -> &NodeRemote {
            &self.inner
        }
        fn target_username(&self) -> Option<&String> {
            self.username.as_ref()
        }
        fn user_mut(&mut self) -> &mut VirtualTargetType {
            &mut self.peer
        }

        fn session_security_settings(&self) -> Option<&SessionSecuritySettings> {
            Some(&self.session_security_settings)
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::builder::node_builder::{NodeBuilder, NodeFuture};
    use crate::prefabs::client::single_connection::SingleClientServerConnectionKernel;
    use crate::prelude::ProtocolRemoteTargetExt;
    use crate::prelude::*;
    use rstest::rstest;
    use std::net::SocketAddr;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use uuid::Uuid;

    pub struct ReceiverFileTransferKernel(pub Option<NodeRemote>, pub Arc<AtomicBool>);

    #[async_trait]
    impl NetKernel for ReceiverFileTransferKernel {
        fn load_remote(&mut self, node_remote: NodeRemote) -> Result<(), NetworkError> {
            self.0 = Some(node_remote);
            Ok(())
        }

        async fn on_start(&self) -> Result<(), NetworkError> {
            Ok(())
        }

        async fn on_node_event_received(&self, message: NodeResult) -> Result<(), NetworkError> {
            log::trace!(target: "citadel", "SERVER received {:?}", message);
            if let NodeResult::ObjectTransferHandle(ObjectTransferHandle {
                ticket: _,
                mut handle,
            }) = map_errors(message)?
            {
                let mut path = None;
                // accept the transfer
                handle
                    .accept()
                    .map_err(|err| NetworkError::msg(err.into_string()))?;

                use citadel_types::proto::ObjectTransferStatus;
                use futures::StreamExt;
                while let Some(status) = handle.next().await {
                    match status {
                        ObjectTransferStatus::ReceptionComplete => {
                            log::trace!(target: "citadel", "Server has finished receiving the file!");
                            let cmp = include_bytes!("../../resources/TheBridge.pdf");
                            let streamed_data =
                                tokio::fs::read(path.clone().unwrap()).await.unwrap();
                            assert_eq!(
                                cmp,
                                streamed_data.as_slice(),
                                "Original data and streamed data does not match"
                            );

                            self.1.store(true, Ordering::Relaxed);
                            self.0.clone().unwrap().shutdown().await?;
                        }

                        ObjectTransferStatus::ReceptionBeginning(file_path, vfm) => {
                            path = Some(file_path);
                            assert_eq!(vfm.name, "TheBridge.pdf")
                        }

                        _ => {}
                    }
                }
            }

            Ok(())
        }

        async fn on_stop(&mut self) -> Result<(), NetworkError> {
            Ok(())
        }
    }

    pub fn server_info<'a>(
        switch: Arc<AtomicBool>,
    ) -> (NodeFuture<'a, ReceiverFileTransferKernel>, SocketAddr) {
        crate::test_common::server_test_node(ReceiverFileTransferKernel(None, switch), |_| {})
    }

    #[rstest]
    #[timeout(std::time::Duration::from_secs(90))]
    #[case(
        EncryptionAlgorithm::AES_GCM_256,
        KemAlgorithm::Kyber,
        SigAlgorithm::None
    )]
    #[case(
        EncryptionAlgorithm::Kyber,
        KemAlgorithm::Kyber,
        SigAlgorithm::Falcon1024
    )]
    #[tokio::test]
    async fn test_c2s_file_transfer(
        #[case] enx: EncryptionAlgorithm,
        #[case] kem: KemAlgorithm,
        #[case] sig: SigAlgorithm,
    ) {
        citadel_logging::setup_log();
        let client_success = &AtomicBool::new(false);
        let server_success = &Arc::new(AtomicBool::new(false));
        let (server, server_addr) = server_info(server_success.clone());
        let uuid = Uuid::new_v4();

        let session_security_settings = SessionSecuritySettingsBuilder::default()
            .with_crypto_params(enx + kem + sig)
            .build()
            .unwrap();

        let client_kernel = SingleClientServerConnectionKernel::new_passwordless(
            uuid,
            server_addr,
            UdpMode::Disabled,
            session_security_settings,
            |_channel, remote| async move {
                log::trace!(target: "citadel", "***CLIENT LOGIN SUCCESS :: File transfer next ***");
                remote
                    .send_file_with_custom_opts(
                        "../resources/TheBridge.pdf",
                        32 * 1024,
                        TransferType::FileTransfer,
                    )
                    .await
                    .unwrap();
                log::trace!(target: "citadel", "***CLIENT FILE TRANSFER SUCCESS***");
                client_success.store(true, Ordering::Relaxed);
                remote.shutdown_kernel().await
            },
        )
        .unwrap();

        let client = NodeBuilder::default().build(client_kernel).unwrap();

        let joined = futures::future::try_join(server, client);

        let _ = joined.await.unwrap();

        assert!(client_success.load(Ordering::Relaxed));
        assert!(server_success.load(Ordering::Relaxed));
    }
}