Function seec_channel::sub_channel_with

source ·
pub async fn sub_channel_with<S, R, Msg, SubMsg>(
    sender: &mut S,
    receiver: &mut R,
    local_buffer: usize,
    wrap_fn: impl FnOnce(Sender<SubMsg>) -> Msg,
    extract_fn: impl FnOnce(Msg) -> Option<Sender<SubMsg>>
) -> Result<(Sender<SubMsg>, Receiver<SubMsg>), CommunicationError>
where S: SenderT<Msg>, R: ReceiverT<Msg>, Msg: RemoteSend, SubMsg: RemoteSend, CommunicationError: From<S::Error> + From<R::Error>,
Examples found in repository?
crates/seec/examples/aes_cbc.rs (lines 156-165)
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(())
}