bench_doram.rs 9.4 KB

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