1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! This example shows how to load a Bristol circuit (default sha256) and execute it,
//! optionally generating the multiplication triples via a third trusted party
//! (see the `trusted_party_mts.rs` example).
//!
//! It also demonstrates how to use the [`BenchParty`] API to track the communication of
//! different phases and write it to a file.

use anyhow::{Context, Result};
use clap::{Args, Parser};
use seec::bench::{BenchParty, ServerTlsConfig};
use seec::circuit::base_circuit::Load;
use seec::circuit::{BaseCircuit, ExecutableCircuit};
use seec::protocols::boolean_gmw::BooleanGmw;
use seec::secret::inputs;
use seec::SubCircuitOutput;
use seec::{BooleanGate, CircuitBuilder};
use std::fs::File;
use std::io;
use std::io::{stdout, BufReader, BufWriter, Write};
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::EnvFilter;

#[derive(Parser, Debug)]
enum ProgArgs {
    Compile(CompileArgs),
    Execute(ExecuteArgs),
}

#[derive(Args, Debug)]
/// Precompile a bristol circuit for faster execution
struct CompileArgs {
    #[arg(long)]
    simd: Option<NonZeroUsize>,

    /// Output path of the compile circuit.
    #[arg(short, long)]
    output: PathBuf,

    #[clap(short, long)]
    log: Option<PathBuf>,

    /// Use dynamic layers instead of static
    #[clap(short, long)]
    dyn_layers: bool,

    /// Circuit in bristol format
    circuit: PathBuf,
}

#[derive(Args, Debug)]
struct ExecuteArgs {
    /// Id of this party. If not provided, both parties will be spawned within this process.
    #[clap(long)]
    id: Option<usize>,

    /// Address of server to bind or connect to. Localhost if not provided
    #[clap(long)]
    server: Option<SocketAddr>,

    /// Only use if communication should be TLS encrypted.
    #[clap(long)]
    domain: Option<String>,
    /// Path to server TLS certificate.
    #[clap(long)]
    cert: Option<PathBuf>,
    /// Path to server TLS certificate private key.
    #[clap(long)]
    cert_pk: Option<PathBuf>,

    /// Performs insecure setup by randomly generating MTs based on fixed seed (no OTs)
    #[clap(long)]
    insecure_setup: bool,

    /// Use MTs stored in <FILE> generated via precompute_mts.rs
    #[clap(long)]
    stored_mts: Option<PathBuf>,

    /// Perform setup interleaved with the online phase
    #[clap(long)]
    interleave_setup: bool,

    #[clap(long, default_value = "1")]
    repeat: usize,

    /// File path for the communication statistics. Will overwrite existing files.
    #[clap(long)]
    stats: Option<PathBuf>,

    #[clap(short, long)]
    log: Option<PathBuf>,

    /// Circuit to execute. Must be compiled beforehand
    circuit: PathBuf,
}

#[tokio::main]
async fn main() -> Result<()> {
    let prog_args = ProgArgs::parse();
    init_tracing(&prog_args).context("failed to init logging")?;
    match prog_args {
        ProgArgs::Compile(args) => compile(args).context("failed to compile circuit"),
        ProgArgs::Execute(args) => execute(args).await.context("failed to execute circuit"),
    }
}

fn compile(compile_args: CompileArgs) -> Result<()> {
    let load = match compile_args.simd {
        Some(_) => Load::SubCircuit,
        None => Load::Circuit,
    };
    let mut bc: BaseCircuit = BaseCircuit::load_bristol(&compile_args.circuit, load)
        .expect("failed to load bristol circuit");

    let mut circ = match compile_args.simd {
        Some(size) => {
            bc.set_simd_size(size);
            let circ_input_size = bc.sub_circuit_input_count();
            let inputs = inputs::<u32>(circ_input_size);
            let bc = bc.into_shared();

            let (output, circ_id) = CircuitBuilder::with_global(|builder| {
                builder.get_main_circuit().lock().set_simd_size(size);
                let circ_id = builder.push_circuit(bc);
                let output = builder.connect_sub_circuit(&inputs, circ_id);
                (output, circ_id)
            });
            let main = output.connect_to_main(circ_id);
            main.iter().for_each(|s| {
                s.output();
            });
            let circ = CircuitBuilder::global_into_circuit();
            ExecutableCircuit::DynLayers(circ)
        }
        None => ExecutableCircuit::DynLayers(bc.into()),
    };
    if !compile_args.dyn_layers {
        circ = circ.precompute_layers();
    }
    let out =
        BufWriter::new(File::create(&compile_args.output).context("failed to create output file")?);
    bincode::serialize_into(out, &circ).context("failed to serialize circuit")?;
    Ok(())
}

impl ProgArgs {
    fn log(&self) -> Option<&PathBuf> {
        match self {
            ProgArgs::Compile(args) => args.log.as_ref(),
            ProgArgs::Execute(args) => args.log.as_ref(),
        }
    }
}

async fn execute(execute_args: ExecuteArgs) -> Result<()> {
    let circ_name = execute_args
        .circuit
        .file_stem()
        .unwrap()
        .to_string_lossy()
        .to_string();
    let circuit = load_circ(&execute_args).context("failed to load circuit")?;

    let create_party = |id, circ| {
        let mut party = BenchParty::<BooleanGmw, u32>::new(id)
            .explicit_circuit(circ)
            .repeat(execute_args.repeat)
            .insecure_setup(execute_args.insecure_setup)
            .interleave_setup(execute_args.interleave_setup)
            .metadata(circ_name.clone());
        if let Some(domain) = &execute_args.domain {
            party = party.tls_domain(domain.clone());
        }
        match (&execute_args.cert, &execute_args.cert_pk) {
            (Some(cert), Some(pk)) => {
                party = party.tls_config(ServerTlsConfig {
                    private_key_file: pk.clone(),
                    certificate_chain_file: cert.clone(),
                });
            }
            (Some(_), None) | (None, Some(_)) => {
                anyhow::bail!("Must provide both --cert and --cert-pk or neither")
            }
            _ => {}
        }
        if let Some(path) = &execute_args.stored_mts {
            party = party.stored_mts(path);
        }
        if let Some(server) = execute_args.server {
            party = party.server(server)
        }
        Ok(party)
    };

    let results = if let Some(id) = execute_args.id {
        let party = create_party(id, circuit)?;
        party.bench().await.context("Failed to run benchmark")?
    } else {
        let party0 = create_party(0, circuit.clone())?;
        let party1 = create_party(1, circuit)?;
        let bench0 = tokio::spawn(party0.bench());
        let bench1 = tokio::spawn(party1.bench());
        let (res0, _res1) = tokio::try_join!(bench0, bench1).context("Failed to join parties")?;
        res0.context("Failed to run benchmark")?
    };

    // Depending on whether a --stats file is set, create a file writer or stdout
    let mut writer: Box<dyn Write> = match execute_args.stats {
        Some(path) => {
            let file = File::create(path)?;
            Box::new(file)
        }
        None => Box::new(stdout()),
    };
    // serde_json is used to write the statistics in json format. `.csv` is currently not
    // supported.
    serde_json::to_writer_pretty(&mut writer, &results)?;
    writeln!(writer)?;

    Ok(())
}

fn load_circ(args: &ExecuteArgs) -> Result<ExecutableCircuit<bool, BooleanGate, u32>> {
    let res = bincode::deserialize_from(BufReader::new(
        File::open(&args.circuit).context("Failed to open circuit file")?,
    ));
    match res {
        Ok(circ) => Ok(circ),
        Err(_) => {
            // try to load as bristol
            Ok(ExecutableCircuit::DynLayers(
                BaseCircuit::load_bristol(&args.circuit, Load::Circuit)
                    .context("Circuit is neither .seec file or bristol")?
                    .into(),
            )
            .precompute_layers())
        }
    }
}

fn init_tracing(args: &ProgArgs) -> Result<Option<tracing_appender::non_blocking::WorkerGuard>> {
    let env_filter = EnvFilter::builder()
        .with_default_directive(LevelFilter::INFO.into())
        .from_env()
        .context("Invalid log directives")?;
    match args.log() {
        Some(path) => {
            let log_writer =
                BufWriter::new(File::create(path).context("failed to create log file")?);
            let (non_blocking, appender_guard) = tracing_appender::non_blocking(log_writer);
            tracing_subscriber::fmt()
                .json()
                .with_env_filter(env_filter)
                .with_writer(non_blocking)
                .init();
            Ok(Some(appender_guard))
        }
        None => {
            tracing_subscriber::fmt()
                .with_writer(io::stderr)
                .with_env_filter(env_filter)
                .init();
            Ok(None)
        }
    }
}