bench_doram.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 = parse_log_db_size)]
  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_log_db_size(s: &str) -> Result<u32, Box<dyn std::error::Error + Send + Sync + 'static>> {
  91. let log_db_size: u32 = s.parse()?;
  92. if log_db_size & 1 == 1 {
  93. return Err(clap::Error::raw(
  94. clap::error::ErrorKind::InvalidValue,
  95. format!("log_db_size must be even"),
  96. )
  97. .into());
  98. }
  99. Ok(log_db_size)
  100. }
  101. fn parse_connect(
  102. s: &str,
  103. ) -> Result<(usize, String, u16), Box<dyn std::error::Error + Send + Sync + 'static>> {
  104. let parts: Vec<_> = s.split(":").collect();
  105. if parts.len() != 3 {
  106. return Err(clap::Error::raw(
  107. clap::error::ErrorKind::ValueValidation,
  108. format!("'{}' has not the format '<party-id>:<host>:<post>'", s),
  109. )
  110. .into());
  111. }
  112. let party_id: usize = parts[0].parse()?;
  113. let host = parts[1];
  114. let port: u16 = parts[2].parse()?;
  115. if port == 0 {
  116. return Err(clap::Error::raw(
  117. clap::error::ErrorKind::ValueValidation,
  118. "the port needs to be positive",
  119. )
  120. .into());
  121. }
  122. Ok((party_id, host.to_owned(), port))
  123. }
  124. fn main() {
  125. let cli = Cli::parse();
  126. let mut netopts = NetworkOptions {
  127. listen_host: cli.listen_host.clone(),
  128. listen_port: cli.listen_port,
  129. connect_info: vec![NetworkPartyInfo::Listen; 3],
  130. connect_timeout_seconds: cli.connect_timeout_seconds,
  131. };
  132. rayon::ThreadPoolBuilder::new()
  133. .num_threads(cli.threads)
  134. .build_global()
  135. .unwrap();
  136. for c in cli.connect.iter() {
  137. if netopts.connect_info[c.0] != NetworkPartyInfo::Listen {
  138. println!(
  139. "{}",
  140. clap::Error::raw(
  141. clap::error::ErrorKind::ValueValidation,
  142. format!("multiple connect arguments for party {}", c.0),
  143. )
  144. .format(&mut Cli::command())
  145. );
  146. process::exit(1);
  147. }
  148. netopts.connect_info[c.0] = NetworkPartyInfo::Connect(c.1.clone(), c.2);
  149. }
  150. let mut comm = match make_tcp_communicator(3, cli.party_id as usize, &netopts) {
  151. Ok(comm) => comm,
  152. Err(e) => {
  153. eprintln!("network setup failed: {:?}", e);
  154. process::exit(1);
  155. }
  156. };
  157. let mut doram = DOram::new(cli.party_id as usize, cli.log_db_size);
  158. let db_size = 1 << cli.log_db_size;
  159. let db_share: Vec<_> = vec![Fp::ZERO; db_size];
  160. let stash_size = 1 << (cli.log_db_size >> 1);
  161. let instructions = if cli.party_id == 0 {
  162. let mut rng = ChaChaRng::from_seed([0u8; 32]);
  163. (0..stash_size)
  164. .map(|_| InstructionShare {
  165. operation: Operation::Write.encode(),
  166. address: Fp::from_u128(rng.gen_range(0..db_size) as u128),
  167. value: Fp::random(&mut rng),
  168. })
  169. .collect()
  170. } else {
  171. vec![
  172. InstructionShare {
  173. operation: Fp::ZERO,
  174. address: Fp::ZERO,
  175. value: Fp::ZERO
  176. };
  177. stash_size
  178. ]
  179. };
  180. doram.init(&mut comm, &db_share).expect("init failed");
  181. comm.reset_stats();
  182. let mut runtimes = OramRuntimes::default();
  183. let d_preprocess = if cli.preprocess {
  184. let t_start = Instant::now();
  185. runtimes = doram
  186. .preprocess_with_runtimes(&mut comm, 1, Some(runtimes))
  187. .expect("preprocess failed")
  188. .unwrap();
  189. t_start.elapsed()
  190. } else {
  191. Default::default()
  192. };
  193. let comm_stats_preprocess = comm.get_stats();
  194. comm.reset_stats();
  195. let t_start = Instant::now();
  196. for (_i, inst) in instructions.iter().enumerate() {
  197. // println!("executing instruction #{i}: {inst:?}");
  198. runtimes = doram
  199. .access_with_runtimes(&mut comm, *inst, Some(runtimes))
  200. .expect("access failed")
  201. .1
  202. .unwrap();
  203. }
  204. let d_accesses = Instant::now() - t_start;
  205. let comm_stats_access = comm.get_stats();
  206. comm.shutdown();
  207. let results =
  208. BenchmarkResults::new(&cli, &comm_stats_preprocess, &comm_stats_access, &runtimes);
  209. if cli.json {
  210. println!("{}", serde_json::to_string(&results).unwrap());
  211. } else {
  212. println!(
  213. "time preprocess: {:10.3} ms",
  214. d_preprocess.as_secs_f64() * 1000.0
  215. );
  216. println!(
  217. " per accesses: {:10.3} ms",
  218. d_preprocess.as_secs_f64() * 1000.0 / stash_size as f64
  219. );
  220. println!(
  221. "time accesses: {:10.3} ms{}",
  222. d_accesses.as_secs_f64() * 1000.0,
  223. if cli.preprocess {
  224. " (online only)"
  225. } else {
  226. ""
  227. }
  228. );
  229. println!(
  230. " per accesses: {:10.3} ms",
  231. d_accesses.as_secs_f64() * 1000.0 / stash_size as f64
  232. );
  233. runtimes.print(cli.party_id as usize + 1, stash_size);
  234. println!("communication preprocessing: {comm_stats_preprocess:#?}");
  235. println!("communication accesses: {comm_stats_access:#?}");
  236. }
  237. }