bench_doram.rs 9.5 KB

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