encryption.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. use std::{cell::Cell, rc::Rc};
  2. use crate::fleck_core;
  3. const SECRET : u32 = 0x12345678;
  4. #[derive(Debug, serde::Serialize, serde::Deserialize)]
  5. struct EncryptedMessage {
  6. secret_payload: u32
  7. }
  8. impl fleck_core::MessageParams for EncryptedMessage {
  9. const NAME: &'static str = "EncryptedMessage";
  10. const SIGNED: bool = false;
  11. const ENCRYPTED: bool = true;
  12. }
  13. #[derive(Default)]
  14. struct ReceiveService {
  15. counter: Cell<u32>,
  16. }
  17. impl crate::DefaultService for ReceiveService {
  18. fn setup(self: &Rc<Self>, api: Rc<crate::API>) {
  19. api.channel::<fleck_core::MessageChannel<EncryptedMessage>>().sub_eat(self, Self::message);
  20. }
  21. }
  22. impl ReceiveService {
  23. fn message(&self, msg: (fleck_core::msg::Metadata, EncryptedMessage)) {
  24. if msg.1 .secret_payload == SECRET {
  25. self.counter.set(self.counter.get() + 1);
  26. }
  27. }
  28. }
  29. #[test_log::test]
  30. fn one_way_test() {
  31. let skeleton = super::TestSkeleton::new();
  32. let span_f1 = tracing::span!(tracing::Level::TRACE, "f1");
  33. let span_f2 = tracing::span!(tracing::Level::TRACE, "f2");
  34. let fvec = skeleton.initialize_nodes(2);
  35. let f1 = fvec[0].clone();
  36. let f2 = fvec[1].clone();
  37. f1.with_service(|ms: &fleck_core::MessageService| {
  38. ms.add_message_type::<EncryptedMessage>();
  39. });
  40. f2.with_service(|ms: &fleck_core::MessageService| {
  41. ms.add_message_type::<EncryptedMessage>();
  42. });
  43. f2.add_service::<ReceiveService>();
  44. // let the encryption handshake happen
  45. for _ in 0..5 {
  46. {
  47. let _guard = span_f1.enter();
  48. f1.run_once();
  49. }
  50. {
  51. let _guard = span_f2.enter();
  52. f2.run_once();
  53. }
  54. }
  55. // grab f1's node for f2
  56. let node_for_f2 = f1.with_service(|ns: &fleck_core::NodeService|
  57. ns.node_by_pubkey(&f2.with_service(|ns: &fleck_core::NodeService| *ns.self_node().pubkey()))).expect("handshake failure?");
  58. log::info!("--- test triggering a message to be sent ---");
  59. // trigger f1 to send a packet
  60. f1.queue::<fleck_core::SendPacketChannel>(fleck_core::msg::Message::build(EncryptedMessage { secret_payload: SECRET }).with_peer(node_for_f2.peer().unwrap()).with_node(node_for_f2));
  61. // let the communication commence...
  62. for _ in 0..5 {
  63. {
  64. let _guard = span_f1.enter();
  65. f1.run_once();
  66. }
  67. {
  68. let _guard = span_f2.enter();
  69. f2.run_once();
  70. }
  71. }
  72. assert_eq!(1, f2.with_service(|rs: &ReceiveService| rs.counter.get()));
  73. }