bench_doram.rs 11 KB

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