client.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. match incoming_cmd_recv.recv() {
  37. Err(_) => break,
  38. _ => panic!("Received something unexpected"),
  39. }
  40. }
  41. });
  42. let pub_params = match outgoing_resp.recv() {
  43. Ok(Response::PubParams(x)) => x,
  44. _ => panic!("Received something unexpected"),
  45. };
  46. (
  47. Client {
  48. r,
  49. thread_handle,
  50. incoming_cmd,
  51. outgoing_resp,
  52. },
  53. pub_params,
  54. )
  55. }
  56. }
  57. #[repr(C)]
  58. pub struct ClientNewRet {
  59. client: *mut Client,
  60. pub_params: VecData,
  61. }
  62. #[no_mangle]
  63. pub extern "C" fn spir_client_new(r: u8) -> ClientNewRet {
  64. let (client, pub_params) = Client::new(r as usize);
  65. let vecdata = VecData {
  66. data: pub_params.as_ptr(),
  67. len: pub_params.len(),
  68. cap: pub_params.capacity(),
  69. };
  70. std::mem::forget(pub_params);
  71. ClientNewRet {
  72. client: Box::into_raw(Box::new(client)),
  73. pub_params: vecdata,
  74. }
  75. }
  76. #[no_mangle]
  77. pub extern "C" fn spir_client_free(client: *mut Client) {
  78. if client.is_null() {
  79. return;
  80. }
  81. unsafe {
  82. Box::from_raw(client);
  83. }
  84. }