network_transports.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_std::{
  19. io,
  20. io::{ReadExt, WriteExt},
  21. task,
  22. };
  23. use url::Url;
  24. use darkfi::net::transport::{Dialer, Listener};
  25. #[async_std::test]
  26. async fn tcp_transport() {
  27. let url = Url::parse("tcp://127.0.0.1:5432").unwrap();
  28. let listener = Listener::new(url.clone()).await.unwrap().listen().await.unwrap();
  29. task::spawn(async move {
  30. let (stream, _) = listener.next().await.unwrap();
  31. let (mut reader, mut writer) = smol::io::split(stream);
  32. io::copy(&mut reader, &mut writer).await.unwrap();
  33. });
  34. let payload = b"ohai tcp";
  35. let dialer = Dialer::new(url).await.unwrap();
  36. let mut client = dialer.dial(None).await.unwrap();
  37. client.write_all(payload).await.unwrap();
  38. let mut buf = vec![0u8; 8];
  39. client.read_exact(&mut buf).await.unwrap();
  40. assert_eq!(buf, payload);
  41. }
  42. #[async_std::test]
  43. async fn tcp_tls_transport() {
  44. let url = Url::parse("tcp+tls://127.0.0.1:5433").unwrap();
  45. let listener = Listener::new(url.clone()).await.unwrap().listen().await.unwrap();
  46. task::spawn(async move {
  47. let (stream, _) = listener.next().await.unwrap();
  48. let (mut reader, mut writer) = smol::io::split(stream);
  49. io::copy(&mut reader, &mut writer).await.unwrap();
  50. });
  51. let payload = b"ohai tls";
  52. let dialer = Dialer::new(url).await.unwrap();
  53. let mut client = dialer.dial(None).await.unwrap();
  54. client.write_all(payload).await.unwrap();
  55. let mut buf = vec![0u8; 8];
  56. client.read_exact(&mut buf).await.unwrap();
  57. assert_eq!(buf, payload);
  58. }