client.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. use rand::rngs::ThreadRng;
  2. use rand::RngCore;
  3. use std::sync::mpsc::*;
  4. use std::thread::*;
  5. use crate::params;
  6. use crate::VecData;
  7. enum Command {
  8. PreProc(usize),
  9. PreProcResp(Vec<u8>),
  10. }
  11. enum Response {
  12. PubParams(Vec<u8>),
  13. PreProcMsg(Vec<u8>),
  14. }
  15. pub struct Client {
  16. r: usize,
  17. thread_handle: JoinHandle<()>,
  18. incoming_cmd: SyncSender<Command>,
  19. outgoing_resp: Receiver<Response>,
  20. }
  21. impl Client {
  22. pub fn new(r: usize) -> (Self, Vec<u8>) {
  23. let (incoming_cmd, incoming_cmd_recv) = sync_channel(0);
  24. let (outgoing_resp_send, outgoing_resp) = sync_channel(0);
  25. let thread_handle = spawn(move || {
  26. let spiral_params = params::get_spiral_params(r);
  27. let mut clientrng = rand::thread_rng();
  28. let mut spiral_client = spiral_rs::client::Client::init(&spiral_params, &mut clientrng);
  29. // The first communication is the pub_params
  30. let pub_params = spiral_client.generate_keys().serialize();
  31. outgoing_resp_send
  32. .send(Response::PubParams(pub_params))
  33. .unwrap();
  34. // Wait for commands
  35. loop {
  36. println!("Client waiting");
  37. match incoming_cmd_recv.recv() {
  38. Err(_) => break,
  39. _ => panic!("Received something unexpected"),
  40. }
  41. }
  42. println!("Client ending");
  43. });
  44. let pub_params = match outgoing_resp.recv() {
  45. Ok(Response::PubParams(x)) => x,
  46. _ => panic!("Received something unexpected"),
  47. };
  48. (
  49. Client {
  50. r,
  51. thread_handle,
  52. incoming_cmd,
  53. outgoing_resp,
  54. },
  55. pub_params,
  56. )
  57. }
  58. }
  59. #[repr(C)]
  60. pub struct ClientNewRet {
  61. client: *mut Client,
  62. pub_params: VecData,
  63. }
  64. #[no_mangle]
  65. pub extern "C" fn spir_client_new(r: u8) -> ClientNewRet {
  66. let (client, pub_params) = Client::new(r as usize);
  67. let vecdata = VecData {
  68. data: pub_params.as_ptr(),
  69. len: pub_params.len(),
  70. cap: pub_params.capacity(),
  71. };
  72. std::mem::forget(pub_params);
  73. ClientNewRet {
  74. client: Box::into_raw(Box::new(client)),
  75. pub_params: vecdata,
  76. }
  77. }
  78. #[no_mangle]
  79. pub extern "C" fn spir_client_free(client: *mut Client) {
  80. if client.is_null() {
  81. return;
  82. }
  83. unsafe {
  84. Box::from_raw(client);
  85. }
  86. }