bench_doram.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. use clap::{CommandFactory, Parser};
  2. use communicator::tcp::{make_tcp_communicator, NetworkOptions, NetworkPartyInfo};
  3. use communicator::{AbstractCommunicator, CommunicationStats};
  4. use cuckoo::hash::AesHashFunction;
  5. use dpf::mpdpf::SmartMpDpf;
  6. use dpf::spdpf::HalfTreeSpDpf;
  7. use ff::{Field, PrimeField};
  8. use oram::common::{InstructionShare, Operation};
  9. use oram::oram::{
  10. DistributedOram, DistributedOramProtocol, ProtocolStep as OramProtocolStep,
  11. Runtimes as OramRuntimes,
  12. };
  13. use oram::tools::BenchmarkMetaData;
  14. use rand::{Rng, SeedableRng};
  15. use rand_chacha::ChaChaRng;
  16. use rayon;
  17. use serde;
  18. use serde_json;
  19. use std::collections::HashMap;
  20. use std::process;
  21. use std::time::{Duration, Instant};
  22. use strum::IntoEnumIterator;
  23. use utils::field::Fp;
  24. type MPDPF = SmartMpDpf<Fp, HalfTreeSpDpf<Fp>, AesHashFunction<u16>>;
  25. type DOram = DistributedOramProtocol<Fp, MPDPF, HalfTreeSpDpf<Fp>>;
  26. #[derive(Debug, clap::Parser)]
  27. struct Cli {
  28. /// ID of this party
  29. #[arg(long, short = 'i', value_parser = clap::value_parser!(u32).range(0..3))]
  30. pub party_id: u32,
  31. /// Log2 of the database size, must be even
  32. #[arg(long, short = 's', value_parser = clap::value_parser!(u32).range(4..))]
  33. pub log_db_size: u32,
  34. /// Use preprocessing
  35. #[arg(long)]
  36. pub preprocess: bool,
  37. /// How many threads to use for the computation
  38. #[arg(long, short = 't', default_value_t = 1)]
  39. pub threads: usize,
  40. /// Output statistics in JSON
  41. #[arg(long, short = 'j')]
  42. pub json: bool,
  43. /// Which address to listen on for incoming connections
  44. #[arg(long, short = 'l')]
  45. pub listen_host: String,
  46. /// Which port to listen on for incoming connections
  47. #[arg(long, short = 'p', value_parser = clap::value_parser!(u16).range(1..))]
  48. pub listen_port: u16,
  49. /// Connection info for each party
  50. #[arg(long, short = 'c', value_name = "PARTY_ID>:<HOST>:<PORT", value_parser = parse_connect)]
  51. pub connect: Vec<(usize, String, u16)>,
  52. /// How long to try connecting before aborting
  53. #[arg(long, default_value_t = 10)]
  54. pub connect_timeout_seconds: usize,
  55. }
  56. #[derive(Debug, Clone, serde::Serialize)]
  57. struct BenchmarkResults {
  58. party_id: usize,
  59. log_db_size: u32,
  60. preprocess: bool,
  61. threads: usize,
  62. comm_stats_preprocess: HashMap<usize, CommunicationStats>,
  63. comm_stats_access: HashMap<usize, CommunicationStats>,
  64. runtimes: HashMap<String, Duration>,
  65. meta: BenchmarkMetaData,
  66. }
  67. impl BenchmarkResults {
  68. pub fn new(
  69. cli: &Cli,
  70. comm_stats_preprocess: &HashMap<usize, CommunicationStats>,
  71. comm_stats_access: &HashMap<usize, CommunicationStats>,
  72. runtimes: &OramRuntimes,
  73. ) -> Self {
  74. let mut runtime_map = HashMap::new();
  75. for step in OramProtocolStep::iter() {
  76. runtime_map.insert(step.to_string(), runtimes.get(step));
  77. }
  78. Self {
  79. party_id: cli.party_id as usize,
  80. log_db_size: cli.log_db_size,
  81. preprocess: cli.preprocess,
  82. threads: cli.threads,
  83. comm_stats_preprocess: comm_stats_preprocess.clone(),
  84. comm_stats_access: comm_stats_access.clone(),
  85. runtimes: runtime_map,
  86. meta: BenchmarkMetaData::collect(),
  87. }
  88. }
  89. }
  90. fn parse_connect(
  91. s: &str,
  92. ) -> Result<(usize, String, u16), Box<dyn std::error::Error + Send + Sync + 'static>> {
  93. let parts: Vec<_> = s.split(":").collect();
  94. if parts.len() != 3 {
  95. return Err(clap::Error::raw(
  96. clap::error::ErrorKind::ValueValidation,
  97. format!("'{}' has not the format '<party-id>:<host>:<post>'", s),
  98. )
  99. .into());
  100. }
  101. let party_id: usize = parts[0].parse()?;
  102. let host = parts[1];
  103. let port: u16 = parts[2].parse()?;
  104. if port == 0 {
  105. return Err(clap::Error::raw(
  106. clap::error::ErrorKind::ValueValidation,
  107. "the port needs to be positive",
  108. )
  109. .into());
  110. }
  111. Ok((party_id, host.to_owned(), port))
  112. }
  113. fn main() {
  114. let cli = Cli::parse();
  115. let mut netopts = NetworkOptions {
  116. listen_host: cli.listen_host.clone(),
  117. listen_port: cli.listen_port,
  118. connect_info: vec![NetworkPartyInfo::Listen; 3],
  119. connect_timeout_seconds: cli.connect_timeout_seconds,
  120. };
  121. rayon::ThreadPoolBuilder::new()
  122. .num_threads(cli.threads)
  123. .build_global()
  124. .unwrap();
  125. for c in cli.connect.iter() {
  126. if netopts.connect_info[c.0] != NetworkPartyInfo::Listen {
  127. println!(
  128. "{}",
  129. clap::Error::raw(
  130. clap::error::ErrorKind::ValueValidation,
  131. format!("multiple connect arguments for party {}", c.0),
  132. )
  133. .format(&mut Cli::command())
  134. );
  135. process::exit(1);
  136. }
  137. netopts.connect_info[c.0] = NetworkPartyInfo::Connect(c.1.clone(), c.2);
  138. }
  139. let mut comm = match make_tcp_communicator(3, cli.party_id as usize, &netopts) {
  140. Ok(comm) => comm,
  141. Err(e) => {
  142. eprintln!("network setup failed: {:?}", e);
  143. process::exit(1);
  144. }
  145. };
  146. let mut doram = DOram::new(cli.party_id as usize, 1 << cli.log_db_size);
  147. let db_size = 1 << cli.log_db_size;
  148. let db_share: Vec<_> = vec![Fp::ZERO; db_size];
  149. let stash_size = 1 << (cli.log_db_size >> 1);
  150. let instructions = if cli.party_id == 0 {
  151. let mut rng = ChaChaRng::from_seed([0u8; 32]);
  152. (0..stash_size)
  153. .map(|_| InstructionShare {
  154. operation: Operation::Write.encode(),
  155. address: Fp::from_u128(rng.gen_range(0..db_size) as u128),
  156. value: Fp::random(&mut rng),
  157. })
  158. .collect()
  159. } else {
  160. vec![
  161. InstructionShare {
  162. operation: Fp::ZERO,
  163. address: Fp::ZERO,
  164. value: Fp::ZERO
  165. };
  166. stash_size
  167. ]
  168. };
  169. doram.init(&mut comm, &db_share).expect("init failed");
  170. comm.reset_stats();
  171. let mut runtimes = OramRuntimes::default();
  172. let d_preprocess = if cli.preprocess {
  173. let t_start = Instant::now();
  174. runtimes = doram
  175. .preprocess_with_runtimes(&mut comm, 1, Some(runtimes))
  176. .expect("preprocess failed")
  177. .unwrap();
  178. t_start.elapsed()
  179. } else {
  180. Default::default()
  181. };
  182. let comm_stats_preprocess = comm.get_stats();
  183. comm.reset_stats();
  184. let t_start = Instant::now();
  185. for (_i, inst) in instructions.iter().enumerate() {
  186. // println!("executing instruction #{i}: {inst:?}");
  187. runtimes = doram
  188. .access_with_runtimes(&mut comm, *inst, Some(runtimes))
  189. .expect("access failed")
  190. .1
  191. .unwrap();
  192. }
  193. let d_accesses = Instant::now() - t_start;
  194. let comm_stats_access = comm.get_stats();
  195. comm.shutdown();
  196. let results =
  197. BenchmarkResults::new(&cli, &comm_stats_preprocess, &comm_stats_access, &runtimes);
  198. if cli.json {
  199. println!("{}", serde_json::to_string(&results).unwrap());
  200. } else {
  201. println!(
  202. "time preprocess: {:10.3} ms",
  203. d_preprocess.as_secs_f64() * 1000.0
  204. );
  205. println!(
  206. " per accesses: {:10.3} ms",
  207. d_preprocess.as_secs_f64() * 1000.0 / stash_size as f64
  208. );
  209. println!(
  210. "time accesses: {:10.3} ms{}",
  211. d_accesses.as_secs_f64() * 1000.0,
  212. if cli.preprocess {
  213. " (online only)"
  214. } else {
  215. ""
  216. }
  217. );
  218. println!(
  219. " per accesses: {:10.3} ms",
  220. d_accesses.as_secs_f64() * 1000.0 / stash_size as f64
  221. );
  222. runtimes.print(cli.party_id as usize + 1, stash_size);
  223. println!("communication preprocessing: {comm_stats_preprocess:#?}");
  224. println!("communication accesses: {comm_stats_access:#?}");
  225. }
  226. }