Function seec_channel::tcp::connect

source ·
pub async fn connect<T: RemoteSend>(
    remote_addr: impl ToSocketAddrs + Debug
) -> Result<TrackingChannel<T>, Error>
Examples found in repository?
crates/zappot/examples/co_base_ot.rs (line 54)
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
async fn receiver(args: Args) -> (Vec<Block>, BitVec) {
    // Create a secure RNG to use in the protocol
    let mut rng = OsRng;
    // Create the receiver. The struct holds no state
    let mut receiver = Receiver::new();
    // Connect to the sender on the listened on port
    let (mut base_sender, _, mut base_receiver, _) =
        seec_channel::tcp::connect::<seec_channel::Sender<_>>(("127.0.0.1", args.port))
            .await
            .expect("Error listening for channel connection");
    let (ch_sender, mut ch_receiver) = sub_channel(&mut base_sender, &mut base_receiver, 8)
        .await
        .expect("Establishing sub channel");

    // Randomly choose one of the blocks
    let choices: BitVec = rng
        .sample_iter::<bool, _>(distributions::Standard)
        .take(args.num_ots)
        .collect();

    // Perform the random ots
    let ots = receiver
        .receive_random(&choices, &mut rng, &ch_sender, &mut ch_receiver)
        .await
        .expect("Failed to generate ROTs");
    (ots, choices)
}
More examples
Hide additional examples
crates/zappot/examples/alsz_ot_extension.rs (line 61)
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
async fn receiver(args: Args) -> (Vec<Block>, BitVec) {
    // Create a secure RNG to use in the protocol
    let mut rng = OsRng;
    // Create the ot extension receiver. A base OT **sender** is passed as an argument and used
    // to create the base_ots
    let mut receiver = Receiver::new(base_ot::Sender);
    let (mut base_sender, _, mut base_receiver, _) =
        seec_channel::tcp::connect::<seec_channel::Sender<_>>(("127.0.0.1", args.port))
            .await
            .expect("Error listening for channel connection");
    let (ch_sender, mut ch_receiver) = sub_channel(&mut base_sender, &mut base_receiver, 128)
        .await
        .expect("Establishing sub channel");

    // Randomly choose one of the blocks
    let choices: BitVec = {
        let mut bv = bitvec![usize, Lsb0; 0; args.num_ots];
        rng.fill(bv.as_raw_mut_slice());
        bv
    };

    // Perform the random ot extension
    let ots = receiver
        .receive_random(&choices, &mut rng, &ch_sender, &mut ch_receiver)
        .await
        .expect("Failed to generate ROTs");
    (ots, choices)
}
crates/seec/examples/privmail.rs (line 229)
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
async fn main() -> anyhow::Result<()> {
    let args: Args = Args::parse();
    let search_query: SearchQuery =
        serde_yaml::from_reader(File::open(args.query_file_path).expect("Opening query file"))
            .expect("Deserializing query file");
    let mails: Vec<Mail> = fs::read_dir(args.mail_dir_path)
        .expect("Reading mail dir")
        .map(|entry| {
            let entry = entry.expect("Mail dir iteration");
            serde_yaml::from_reader(File::open(entry.path()).expect("Opening mail file"))
                .expect("Deserializing mail file")
        })
        .collect();

    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    let (input, _) = priv_mail_search(
        &search_query.keywords,
        &search_query.modifier_chain_share,
        &mails,
        args.duplication_factor,
    );

    let circuit: ExecutableCircuit<bool, _, _> =
        ExecutableCircuit::DynLayers(CircuitBuilder::global_into_circuit());
    // if args.save_circuit {
    //     circuit.save_dot("privmail.dot")?;
    // }

    let (mut sender, bytes_written, mut receiver, bytes_read) = match args.my_id {
        0 => seec_channel::tcp::listen(args.server).await?,
        1 => seec_channel::tcp::connect(args.server).await?,
        illegal => anyhow::bail!("Illegal party id {illegal}. Must be 0 or 1."),
    };

    let mut executor = {
        let mt_provider = InsecureMTProvider::default();
        BoolGmwExecutor::new(&circuit, args.my_id, mt_provider).await?
    };

    let (mut sender, mut receiver) =
        sub_channels_for!(&mut sender, &mut receiver, 16, Message<BooleanGmw>).await?;

    let output = executor
        .execute(Input::Scalar(input), &mut sender, &mut receiver)
        .await?;
    info!(
        my_id = %args.my_id,
        output = ?output,
        bytes_written = bytes_written.get(),
        bytes_read = bytes_read.get(),
        gate_count = circuit.gate_count()
    );
    Ok(())
}
crates/seec/examples/privmail_sc.rs (line 220)
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
async fn main() -> anyhow::Result<()> {
    let args: Args = Args::parse();
    let search_query: SearchQuery =
        serde_yaml::from_reader(File::open(args.query_file_path).expect("Opening query file"))
            .expect("Deserializing query file");
    let mails: Vec<Mail> = fs::read_dir(args.mail_dir_path)
        .expect("Reading mail dir")
        .map(|entry| {
            let entry = entry.expect("Mail dir iteration");
            serde_yaml::from_reader(File::open(entry.path()).expect("Opening mail file"))
                .expect("Deserializing mail file")
        })
        .collect();

    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    let now = Instant::now();
    let (input, _) = priv_mail_search(
        &search_query.keywords,
        &search_query.modifier_chain_share,
        &mails,
        args.duplication_factor,
    );
    let circuit = ExecutableCircuit::DynLayers(CircuitBuilder::global_into_circuit());
    info!("Building circuit took: {}", now.elapsed().as_secs_f32());
    // circuit = circuit.clone().into_base_circuit().into();
    // if args.save_circuit {
    //     bc.save_dot("privmail.dot")?;
    // }
    // dbg!(&circuit);
    let (mut sender, bytes_written, mut receiver, bytes_read) = match args.my_id {
        0 => seec_channel::tcp::listen(args.server).await?,
        1 => seec_channel::tcp::connect(args.server).await?,
        illegal => anyhow::bail!("Illegal party id {illegal}. Must be 0 or 1."),
    };

    let (ch1, mut ch2) = sub_channels_for!(
        &mut sender,
        &mut receiver,
        64,
        seec_channel::Sender<ot_ext::ExtOTMsg>,
        Message<BooleanGmw>
    )
    .await?;

    let mut executor = {
        let mt_provider = OtMTProvider::new(
            OsRng,
            ot_ext::Sender::default(),
            ot_ext::Receiver::default(),
            ch1.0,
            ch1.1,
        );
        BoolGmwExecutor::new(&circuit, args.my_id, mt_provider).await?
    };

    let output = executor
        .execute(Input::Scalar(input), &mut ch2.0, &mut ch2.1)
        .await?;
    info!(
        my_id = %args.my_id,
        output = ?output,
        bytes_written = bytes_written.get(),
        bytes_read = bytes_read.get(),
        gate_count = circuit.gate_count(),
    );
    Ok(())
}
crates/seec/examples/sha256.rs (line 62)
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
async fn main() -> Result<()> {
    let _guard = init_tracing()?;
    let args = Args::parse();
    let circuit: ExecutableCircuit<bool, BooleanGate, u32> = ExecutableCircuit::DynLayers(
        BaseCircuit::load_bristol(args.circuit, Load::Circuit)?.into(),
    );

    let (mut sender, bytes_written, mut receiver, bytes_read) = match args.id {
        0 => seec_channel::tcp::listen(args.server).await?,
        1 => seec_channel::tcp::connect(args.server).await?,
        illegal => anyhow::bail!("Illegal party id {illegal}. Must be 0 or 1."),
    };

    // Initialize the communication statistics tracker with the counters for the main channel
    let mut comm_stats = Statistics::new(bytes_written, bytes_read).without_unaccounted(true);

    let (mut sender, mut receiver) =
        sub_channels_for!(&mut sender, &mut receiver, 8, Message<BooleanGmw>).await?;

    let mut executor: Executor<BooleanGmw, _> = if let Some(addr) = args.mt_provider {
        let (mt_sender, bytes_written, mt_receiver, bytes_read) =
            seec_channel::tcp::connect(addr).await?;
        // Set the counters for the helper channel
        comm_stats.set_helper(bytes_written, bytes_read);
        let mt_provider = TrustedMTProviderClient::new("unique-id".into(), mt_sender, mt_receiver);
        // As the MTs are generated when the Executor is created, we record the communication
        // with the `record_helper` method and a custom category
        comm_stats
            .record_helper(
                Phase::Custom("Helper-Mts".into()),
                Executor::new(&circuit, args.id, mt_provider),
            )
            .await?
    } else {
        let mt_provider = InsecureMTProvider::default();
        comm_stats
            .record(
                Phase::FunctionDependentSetup,
                Executor::new(&circuit, args.id, mt_provider),
            )
            .await?
    };
    let input = BitVec::repeat(false, 768);
    let _out = comm_stats
        .record(
            Phase::Online,
            executor.execute(Input::Scalar(input), &mut sender, &mut receiver),
        )
        .await?;

    // Depending on whether a --stats file is set, create a file writer or stdout
    let mut writer: Box<dyn Write> = match 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.
    let mut res = comm_stats.into_run_result();
    res.add_metadata("circuit", "sha256.rs");
    serde_json::to_writer_pretty(&mut writer, &res)?;
    writeln!(writer)?;

    Ok(())
}
crates/seec/examples/aes_cbc.rs (line 147)
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
async fn execute(args: &ExecuteArgs) -> Result<()> {
    let (mut sender, bytes_written, mut receiver, bytes_read) = match args.id {
        0 => seec_channel::tcp::listen(args.server).await?,
        1 => seec_channel::tcp::connect(args.server).await?,
        illegal => anyhow::bail!("Illegal party id {illegal}. Must be 0 or 1."),
    };

    let (mut main_channel, executor_channel) =
        sub_channels_for!(&mut sender, &mut receiver, 8, Msg, Message<BooleanGmw>).await?;
    let mut sharing = XorSharing::new(ChaChaRng::from_rng(thread_rng()).context("Sharing RNG")?);

    let ot_channel = if args.insecure_setup.not() {
        let sub_channel = sub_channel_with(
            &mut main_channel.0,
            &mut main_channel.1,
            128,
            Msg::OtChannel,
            |msg| match msg {
                Msg::OtChannel(sender) => Some(sender),
                _ => None,
            },
        )
        .await
        .context("failed to create ot sub_channel")?;
        Some(sub_channel)
    } else {
        None
    };

    match args.id {
        0 => {
            let key: [u8; 16] = hex::decode(&args.key)
                .context("Decoding key")?
                .try_into()
                .ok()
                .context("Key must be 16 bytes long")?;
            let key: [usize; 2] = bytemuck::cast(key);
            // Apparently, the AES circuit wants it's arguments in Msb format. However,
            // the executor currently expects arguments to be in a BitVec with Lsb order.
            // The following changes the order of the bits manyally
            // TODO the following is likely wrong with the change to BitVec<usize>
            let msb_key: BitVec<usize> = key.iter().map(|bytes| bytes.reverse_bits()).collect();
            let iv = thread_rng().gen::<[usize; 2]>();
            let msb_iv: BitVec<usize> = iv.iter().map(|bytes| bytes.reverse_bits()).collect();

            let [key_share0, key_share1] = sharing.share(msb_key);
            let [iv_share0, iv_share1] = sharing.share(msb_iv);
            main_channel
                .0
                .send(Msg::ShareIvKey {
                    iv: iv_share1,
                    key: key_share1,
                })
                .await?;
            let Msg::ShareInput(input_share) = main_channel
                .1
                .recv()
                .await?
                .ok_or(anyhow::anyhow!("Remote closed"))?
            else {
                anyhow::bail!("Received wrong message. Expected ShareInput")
            };

            let out = encrypt(
                args,
                executor_channel,
                ot_channel,
                &input_share,
                &key_share0,
                &iv_share0,
            )
            .await?;

            main_channel
                .0
                .send(Msg::ReconstructAesCiphertext(out.clone()))
                .await?;
            if args.validate {
                main_channel.0.send(Msg::PlainIvKey { iv, key }).await?;
            }
            // Try to recv Ack but ignore errors
            let _ = main_channel.1.recv().await;

            info!(
                bytes_written = bytes_written.get(),
                bytes_read = bytes_read.get(),
            );
        }
        1 => {
            let (data, padded_data) = get_data(args).context("Loading data to encrypt")?;
            let mut padded_data_usize = vec![0_usize; padded_data.len() / mem::size_of::<usize>()];
            bytemuck::cast_slice_mut(&mut padded_data_usize).clone_from_slice(&padded_data);
            let padded_file_data = BitVec::from_vec(padded_data_usize);
            let [input_share0, input_share1] = sharing.share(padded_file_data);
            main_channel.0.send(Msg::ShareInput(input_share1)).await?;
            let Msg::ShareIvKey {
                iv: iv_share,
                key: key_share,
            } = main_channel
                .1
                .recv()
                .await
                .context("Receiving IvKeyShare")?
                .ok_or(anyhow::anyhow!("Remote closed"))?
            else {
                anyhow::bail!("Received wrong message. Expected IvKeyShare")
            };
            let out = encrypt(
                args,
                executor_channel,
                ot_channel,
                &input_share0,
                &key_share,
                &iv_share,
            )
            .await?;

            let Msg::ReconstructAesCiphertext(shared_out) = main_channel
                .1
                .recv()
                .await
                .context("Receiving ciphertext share")?
                .ok_or(anyhow::anyhow!("Remote closed"))?
            else {
                anyhow::bail!("Received wrong message. Expected IvKeyShare")
            };

            let ciphertext = match (out, shared_out) {
                (Output::Scalar(out), Output::Scalar(shared_out)) => {
                    XorSharing::<ThreadRng>::reconstruct([out, shared_out])
                }
                (Output::Simd(out), Output::Simd(shared_out)) => out
                    .into_iter()
                    .zip(shared_out)
                    .flat_map(|(a, b)| XorSharing::<ThreadRng>::reconstruct([a, b]))
                    .collect(),
                _ => unreachable!("Non compatible output"),
            };

            if args.validate {
                let Msg::PlainIvKey { iv, key } = main_channel
                    .1
                    .recv()
                    .await
                    .context("Reconstructing Iv/Key")?
                    .ok_or(anyhow::anyhow!("Remote closed"))?
                else {
                    anyhow::bail!("Received wrong message. Expected ReconstructIvKey")
                };
                validate(iv, key, &data, &ciphertext)?;
            }

            main_channel.0.send(Msg::Ack).await?;

            let encoded = hex::encode(bytemuck::cast_slice(ciphertext.as_raw_slice()));
            info!(
                bytes_written = bytes_written.get(),
                bytes_read = bytes_read.get(),
                ciphertext = encoded
            );
        }
        _ => unreachable!(),
    };
    Ok(())
}