repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols-sys/src/client_cg.rs
rust/protocols-sys/src/client_cg.rs
use crate::*; use algebra::{fixed_point::*, fp_64::Fp64Parameters, FpParameters, PrimeField}; use crypto_primitives::additive_share::AdditiveShare; use neural_network::{ layers::{convolution::Padding, LinearLayerInfo}, tensors::{Input, Output}, }; use std::os::raw::c_char; pub struct Conv2D<'a> { data: Metadata, cfhe: &'a ClientFHE, shares: Option<ClientShares>, } pub struct FullyConnected<'a> { data: Metadata, cfhe: &'a ClientFHE, shares: Option<ClientShares>, } pub enum SealClientCG<'a> { Conv2D(Conv2D<'a>), FullyConnected(FullyConnected<'a>), } pub trait ClientCG { type Keys; fn new<F, C>( cfhe: Self::Keys, layer_info: &LinearLayerInfo<F, C>, input_dims: (usize, usize, usize, usize), output_dims: (usize, usize, usize, usize), ) -> Self where Self: std::marker::Sized; fn preprocess(&mut self, r: &Input<u64>) -> Vec<c_char>; fn decrypt(&mut self, linear_ct: Vec<c_char>); fn postprocess<P>(&self, linear_share: &mut Output<AdditiveShare<FixedPoint<P>>>) where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>; } impl<'a> SealClientCG<'a> { pub fn preprocess(&mut self, r: &Input<u64>) -> Vec<c_char> { match self { Self::Conv2D(s) => s.preprocess(r), Self::FullyConnected(s) => s.preprocess(r), } } pub fn decrypt(&mut self, linear_ct: Vec<c_char>) { match self { Self::Conv2D(s) => s.decrypt(linear_ct), Self::FullyConnected(s) => s.decrypt(linear_ct), }; } pub fn postprocess<P>(&self, linear_share: &mut Output<AdditiveShare<FixedPoint<P>>>) where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { match self { Self::Conv2D(s) => ClientCG::postprocess::<P>(s, linear_share), Self::FullyConnected(s) => ClientCG::postprocess::<P>(s, linear_share), }; } } impl<'a> ClientCG for Conv2D<'a> { type Keys = &'a ClientFHE; fn new<F, C>( cfhe: &'a ClientFHE, layer_info: &LinearLayerInfo<F, C>, input_dims: (usize, usize, usize, usize), _output_dims: (usize, usize, usize, usize), ) -> Self { let (kernel, padding, stride) = match layer_info { LinearLayerInfo::Conv2d { kernel, padding, stride, } => (kernel, padding, stride), _ => panic!("Incorrect Layer Type"), }; let data = unsafe { conv_metadata( cfhe.encoder, input_dims.2 as i32, input_dims.3 as i32, kernel.2 as i32, kernel.3 as i32, kernel.1 as i32, kernel.0 as i32, *stride as i32, *stride as i32, *padding == Padding::Valid, ) }; Self { data, cfhe, shares: None, } } fn preprocess(&mut self, r: &Input<u64>) -> Vec<c_char> { // Convert client secret share to raw pointers for C FFI let r_c: Vec<*const u64> = (0..self.data.inp_chans) .into_iter() .map(|inp_c| { r.slice(s![0, inp_c, .., ..]) .as_slice() .expect("Error converting client share") .as_ptr() }) .collect(); let shares = unsafe { client_conv_preprocess(self.cfhe, &self.data, r_c.as_ptr()) }; let ct_vec = unsafe { std::slice::from_raw_parts(shares.input_ct.inner, shares.input_ct.size as usize) .to_vec() }; self.shares = Some(shares); ct_vec } fn decrypt(&mut self, mut linear_ct: Vec<c_char>) { let mut shares = self.shares.unwrap(); // Copy the received ciphertexts into share struct shares.linear_ct = SerialCT { inner: linear_ct.as_mut_ptr(), size: linear_ct.len() as u64, }; // Decrypt everything unsafe { client_conv_decrypt(self.cfhe, &self.data, &mut shares) }; self.shares = Some(shares); } fn postprocess<P>(&self, linear_share: &mut Output<AdditiveShare<FixedPoint<P>>>) where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { let shares = self.shares.unwrap(); for chan in 0..self.data.out_chans as usize { for row in 0..self.data.output_h as usize { for col in 0..self.data.output_w as usize { let idx = (row * (self.data.output_w as usize) + col) as isize; let linear_val = unsafe { *(*(shares.linear.offset(chan as isize))).offset(idx as isize) }; linear_share[[0, chan, row, col]] = AdditiveShare::new( FixedPoint::with_num_muls(P::Field::from_repr(linear_val.into()), 1), ); } } } } } impl<'a> ClientCG for FullyConnected<'a> { type Keys = &'a ClientFHE; fn new<F, C>( cfhe: &'a ClientFHE, _layer_info: &LinearLayerInfo<F, C>, input_dims: (usize, usize, usize, usize), output_dims: (usize, usize, usize, usize), ) -> Self { let data = unsafe { fc_metadata( cfhe.encoder, (input_dims.1 * input_dims.2 * input_dims.3) as i32, output_dims.1 as i32, ) }; Self { data, cfhe, shares: None, } } fn preprocess(&mut self, r: &Input<u64>) -> Vec<c_char> { // Convert client secret share to raw pointers for C FFI let r_c: *const u64 = r .slice(s![0, .., .., ..]) .as_slice() .expect("Error converting client share") .as_ptr(); let shares = unsafe { client_fc_preprocess(self.cfhe, &self.data, r_c) }; let ct_vec = unsafe { std::slice::from_raw_parts(shares.input_ct.inner, shares.input_ct.size as usize) .to_vec() }; self.shares = Some(shares); ct_vec } fn decrypt(&mut self, mut linear_ct: Vec<c_char>) { let mut shares = self.shares.unwrap(); // Copy the received ciphertexts into share struct shares.linear_ct = SerialCT { inner: linear_ct.as_mut_ptr(), size: linear_ct.len() as u64, }; // Decrypt everything unsafe { client_fc_decrypt(self.cfhe, &self.data, &mut shares) }; self.shares = Some(shares); } fn postprocess<P>(&self, linear_share: &mut Output<AdditiveShare<FixedPoint<P>>>) where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { let shares = self.shares.unwrap(); for row in 0..self.data.filter_h as usize { let linear_val = unsafe { *(*(shares.linear.offset(0))).offset(row as isize) }; linear_share[[0, row, 0, 0]] = AdditiveShare::new(FixedPoint::with_num_muls( P::Field::from_repr(linear_val.into()), 1, )); } } } impl<'a> Drop for Conv2D<'a> { fn drop(&mut self) { unsafe { client_conv_free(&self.data, &mut self.shares.unwrap()) } } } impl<'a> Drop for FullyConnected<'a> { fn drop(&mut self) { unsafe { client_fc_free(&mut self.shares.unwrap()) }; } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols-sys/src/client_gen.rs
rust/protocols-sys/src/client_gen.rs
use crate::*; use std::os::raw::c_char; pub trait ClientGen { type Keys; /// The type of messages passed between client and server type MsgType; /// Create new ClientGen object fn new(keys: Self::Keys) -> Self; /// Preprocess `a` and `b` randomizers for sending to the server fn triples_preprocess( &self, a: &[u64], b: &[u64], ) -> (ClientTriples, Vec<Self::MsgType>, Vec<Self::MsgType>); /// Postprocess server's response and return `c` shares fn triples_postprocess( &self, shares: &mut ClientTriples, c_ct: &mut [Self::MsgType], ) -> Vec<u64>; } /// SEAL implementation of ClientGen pub struct SealClientGen<'a> { cfhe: &'a ClientFHE, } impl<'a> ClientGen for SealClientGen<'a> { type Keys = &'a ClientFHE; /// Messages are SEAL ciphertexts which are passed as opaque C pointers type MsgType = c_char; fn new(cfhe: Self::Keys) -> Self { Self { cfhe } } fn triples_preprocess( &self, a: &[u64], b: &[u64], ) -> (ClientTriples, Vec<c_char>, Vec<c_char>) { let shares = unsafe { client_triples_preprocess(self.cfhe, a.len() as u32, a.as_ptr(), b.as_ptr()) }; let a_ct = shares.a_ct.clone(); let b_ct = shares.b_ct.clone(); unsafe { ( shares, std::slice::from_raw_parts(a_ct.inner, a_ct.size as usize).to_vec(), std::slice::from_raw_parts(b_ct.inner, b_ct.size as usize).to_vec(), ) } } fn triples_postprocess(&self, shares: &mut ClientTriples, c: &mut [Self::MsgType]) -> Vec<u64> { let c_ct = SerialCT { inner: c.as_mut_ptr(), size: c.len() as u64, }; unsafe { client_triples_decrypt(self.cfhe, c_ct, shares); }; let result = unsafe { std::slice::from_raw_parts(shares.c_share, shares.num as usize).to_vec() }; result } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols-sys/tests/interface_test.rs
rust/protocols-sys/tests/interface_test.rs
use algebra::{ fields::{near_mersenne_64::F, PrimeField}, fixed_point::{FixedPoint, FixedPointParameters}, UniformRandom, }; use crypto_primitives::{additive_share::Share, beavers_mul::Triple}; use itertools::izip; use ndarray::s; use neural_network::{layers::*, tensors::*, Evaluate}; use protocols_sys::*; use rand::{Rng, SeedableRng}; use rand_chacha::ChaChaRng; type AdditiveShare<P> = crypto_primitives::AdditiveShare<FixedPoint<P>>; struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 3; const EXPONENT_CAPACITY: u8 = 8; } type TenBitExpFP = FixedPoint<TenBitExpParams>; type TenBitAS = AdditiveShare<TenBitExpParams>; const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let mut float: f64 = rng.gen(); float += 1.0; let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } fn print_output_f64(output: &Output<TenBitExpFP>) { output .slice(s![0, .., .., ..]) .outer_iter() .for_each(|out_c| { out_c.outer_iter().for_each(|inp_c| { inp_c.iter().for_each(|e| print!("{:.2}, ", f64::from(*e))); println!(""); }); }); } fn print_output_u64(output: &Output<TenBitExpFP>) { output .slice(s![0, .., .., ..]) .outer_iter() .for_each(|out_c| { out_c.outer_iter().for_each(|inp_c| { inp_c .iter() .for_each(|e| print!("{:.2}, ", e.inner.into_repr().0)); println!(""); }); }); } // Compares floats to 2 decimal points fn approx_equal(f1: f64, f2: f64) -> bool { f64::trunc(100. * f1) == f64::trunc(100. * f2) } fn interface<R: Rng + rand::CryptoRng>( client_cg: &mut SealClientCG, server_cg: &mut SealServerCG, input_dims: (usize, usize, usize, usize), output_dims: (usize, usize, usize, usize), pt_layer: &LinearLayer<TenBitExpFP, TenBitExpFP>, rng: &mut R, ) -> bool { // Client preprocessing let mut r = Input::zeros(input_dims); r.iter_mut() .for_each(|e| *e = generate_random_number(rng).1); let input_ct_vec = client_cg.preprocess(&r.to_repr()); // Server preprocessing let mut linear_share = Output::zeros(output_dims); linear_share .iter_mut() .for_each(|e| *e = generate_random_number(rng).1); server_cg.preprocess(&linear_share.to_repr()); // Server receive ciphertext and compute convolution let linear_ct = server_cg.process(input_ct_vec); // Client receives ciphertexts client_cg.decrypt(linear_ct); // The interface changed here after making this test so from here on // the code is very messy let mut linear = Output::zeros(output_dims); client_cg.postprocess::<TenBitExpParams>(&mut linear); let mut success = true; println!("\nPlaintext linear:"); let linear_pt = pt_layer.evaluate(&r); print_output_f64(&linear_pt); println!("Linear:"); let mut linear_result = Output::zeros(output_dims); linear_result .iter_mut() .zip(linear.iter().zip(linear_share.iter())) .zip(linear_pt.iter()) .for_each(|((r, (s1, s2)), p)| { *r = FixedPoint::randomize_local_share(s1, &s2.inner).inner; success &= approx_equal(f64::from(*r), f64::from(*p)); }); print_output_f64(&linear_result); success } #[test] fn test_convolution() { use neural_network::layers::convolution::*; let mut rng = ChaChaRng::from_seed(RANDOMNESS); // Set the parameters for the convolution. let input_dims = (1, 1, 28, 28); let kernel_dims = (16, 1, 5, 5); let stride = 1; let padding = Padding::Valid; // Sample a random kernel. let mut kernel = Kernel::zeros(kernel_dims); let mut bias = Kernel::zeros((kernel_dims.0, 1, 1, 1)); kernel .iter_mut() .for_each(|ker_i| *ker_i = generate_random_number(&mut rng).1); // Offline phase doesn't interact with bias so this can be 0 bias.iter_mut() .for_each(|bias_i| *bias_i = TenBitExpFP::from(0.0)); let layer_params = Conv2dParams::<TenBitAS, _>::new(padding, stride, kernel.clone(), bias.clone()); let pt_layer_params = Conv2dParams::<TenBitExpFP, _>::new(padding, stride, kernel.clone(), bias.clone()); let output_dims = layer_params.calculate_output_size(input_dims); let layer_dims = LayerDims { input_dims, output_dims, }; let layer = LinearLayer::Conv2d { dims: layer_dims, params: layer_params, }; let layer_info = (&layer).into(); let pt_layer = LinearLayer::Conv2d { dims: layer_dims, params: pt_layer_params, }; // Keygen let mut key_share = KeyShare::new(); let (cfhe, keys_vec) = key_share.generate(); let sfhe = key_share.receive(keys_vec); let input_dims = layer.input_dimensions(); let output_dims = layer.output_dimensions(); let mut client_cg = SealClientCG::Conv2D(client_cg::Conv2D::new( &cfhe, &layer_info, input_dims, output_dims, )); let mut server_cg = SealServerCG::Conv2D(server_cg::Conv2D::new(&sfhe, &layer, &kernel.to_repr())); assert_eq!( interface( &mut client_cg, &mut server_cg, input_dims, output_dims, &pt_layer, &mut rng ), true ); } #[test] fn test_fully_connected() { use neural_network::layers::fully_connected::*; let mut rng = ChaChaRng::from_seed(RANDOMNESS); // Set the parameters for the layer let input_dims = (1, 3, 32, 32); let kernel_dims = (10, 3, 32, 32); // Sample a random kernel. let mut kernel = Kernel::zeros(kernel_dims); let mut bias = Kernel::zeros((kernel_dims.0, 1, 1, 1)); kernel .iter_mut() .for_each(|ker_i| *ker_i = generate_random_number(&mut rng).1); // Offline phase doesn't interact with bias so this can be 0 bias.iter_mut() .for_each(|bias_i| *bias_i = TenBitExpFP::from(0.0)); let layer_params = FullyConnectedParams::<TenBitAS, _>::new(kernel.clone(), bias.clone()); let pt_layer_params = FullyConnectedParams::<TenBitExpFP, _>::new(kernel.clone(), bias.clone()); let output_dims = layer_params.calculate_output_size(input_dims); let layer_dims = LayerDims { input_dims, output_dims, }; let layer = LinearLayer::FullyConnected { dims: layer_dims, params: layer_params, }; let layer_info = (&layer).into(); let pt_layer = LinearLayer::FullyConnected { dims: layer_dims, params: pt_layer_params, }; // Keygen let mut key_share = KeyShare::new(); let (cfhe, keys_vec) = key_share.generate(); let sfhe = key_share.receive(keys_vec); let input_dims = layer.input_dimensions(); let output_dims = layer.output_dimensions(); let mut client_cg = SealClientCG::FullyConnected(client_cg::FullyConnected::new( &cfhe, &layer_info, input_dims, output_dims, )); let mut server_cg = SealServerCG::FullyConnected(server_cg::FullyConnected::new( &sfhe, &layer, &kernel.to_repr(), )); assert_eq!( interface( &mut client_cg, &mut server_cg, input_dims, output_dims, &pt_layer, &mut rng ), true ); } #[inline] fn to_u64(x: &Vec<F>) -> Vec<u64> { x.iter().map(|e| e.into_repr().0).collect() } #[test] fn test_triple_gen() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); let num = 100000; // Keygen let mut key_share = KeyShare::new(); let (cfhe, keys_vec) = key_share.generate(); let sfhe = key_share.receive(keys_vec); let mut client_gen = SealClientGen::new(&cfhe); let mut server_gen = SealServerGen::new(&sfhe); let mut client_a = Vec::with_capacity(num); let mut client_b = Vec::with_capacity(num); let mut server_a = Vec::with_capacity(num); let mut server_b = Vec::with_capacity(num); let mut server_c = Vec::with_capacity(num); let mut server_r = Vec::with_capacity(num); for i in 0..num { client_a.push(F::uniform(&mut rng)); client_b.push(F::uniform(&mut rng)); server_a.push(F::uniform(&mut rng)); server_b.push(F::uniform(&mut rng)); server_c.push(F::uniform(&mut rng)); server_r.push(server_a[i] * server_b[i] - server_c[i]); } let (mut client_triples, mut a_ct, mut b_ct) = client_gen.triples_preprocess(to_u64(&client_a).as_slice(), to_u64(&client_b).as_slice()); let mut server_triples = server_gen.triples_preprocess( to_u64(&server_a).as_slice(), to_u64(&server_b).as_slice(), to_u64(&server_r).as_slice(), ); let mut c_ct = server_gen.triples_online( &mut server_triples, a_ct.as_mut_slice(), b_ct.as_mut_slice(), ); let client_c = client_gen.triples_postprocess(&mut client_triples, c_ct.as_mut_slice()); let server_triples = izip!(server_a, server_b, server_c,).map(|(a, b, c)| Triple { a, b, c }); let client_triples = izip!(client_a, client_b, client_c,).map(|(a, b, c)| Triple { a: F::from_repr(a.into()), b: F::from_repr(b.into()), c: F::from_repr(c.into()), }); izip!(server_triples, client_triples).for_each(|(s, c)| { let a = s.a + &c.a; let b = s.b + &c.b; let c = s.c + &c.c; assert_eq!(c, a * b); }); }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/beavers_mul.rs
rust/protocols/src/beavers_mul.rs
#![allow(dead_code)] use crate::{AdditiveShare, InMessage, OutMessage}; use algebra::{ fields::PrimeField, fixed_point::{FixedPoint, FixedPointParameters}, fp_64::Fp64Parameters, FpParameters, UniformRandom, }; use crypto_primitives::{BeaversMul, BlindedSharedInputs}; use io_utils::imux::IMuxSync; use protocols_sys::{ client_gen::{ClientGen, SealClientGen}, server_gen::{SealServerGen, ServerGen}, ClientFHE, ServerFHE, }; use rand::{CryptoRng, RngCore}; use serde::{Deserialize, Serialize}; use std::{ io::{Read, Write}, marker::PhantomData, os::raw::c_char, }; pub struct BeaversMulProtocol<P: FixedPointParameters> { index: usize, _share: PhantomData<P>, } #[derive(Clone, Serialize, Deserialize)] pub struct BeaversOfflineMsg { pub a_shares: Vec<c_char>, pub b_shares: Vec<c_char>, } type Triple<P> = crypto_primitives::Triple<<P as FixedPointParameters>::Field>; pub struct BeaversMulProtocolType; pub type OfflineMsgSend<'a> = OutMessage<'a, BeaversOfflineMsg, BeaversMulProtocolType>; pub type OfflineMsgRcv = InMessage<BeaversOfflineMsg, BeaversMulProtocolType>; pub type OnlineMsgSend<'a, P> = OutMessage<'a, [BlindedSharedInputs<FixedPoint<P>>], BeaversMulProtocolType>; pub type OnlineMsgRcv<P> = InMessage<Vec<BlindedSharedInputs<FixedPoint<P>>>, BeaversMulProtocolType>; impl<P: FixedPointParameters> BeaversMulProtocol<P> where <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { pub(crate) fn offline_server_protocol<M, R, W, RNG>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, sfhe: &ServerFHE, num_triples: usize, rng: &mut RNG, ) -> Result<Vec<Triple<P>>, bincode::Error> where M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng, { let server_gen = SealServerGen::new(&sfhe); // Generate shares for a, b, and c let mut a = Vec::with_capacity(num_triples); let mut b = Vec::with_capacity(num_triples); let mut c = Vec::with_capacity(num_triples); let mut r = Vec::with_capacity(num_triples); for i in 0..num_triples { a.push(P::Field::uniform(rng)); b.push(P::Field::uniform(rng)); c.push(P::Field::uniform(rng)); r.push(a[i] * b[i] - c[i]); } let mut server_triples = server_gen.triples_preprocess( a.iter() .map(|e| e.into_repr().0) .collect::<Vec<_>>() .as_slice(), b.iter() .map(|e| e.into_repr().0) .collect::<Vec<_>>() .as_slice(), r.iter() .map(|e| e.into_repr().0) .collect::<Vec<_>>() .as_slice(), ); // Receive clients Enc(a1), Enc(b1) let recv_message: OfflineMsgRcv = crate::bytes::deserialize(reader)?; let recv_struct = recv_message.msg(); let mut a_ct = recv_struct.a_shares; let mut b_ct = recv_struct.b_shares; // Compute and send Enc(a1b2 + b1a2 + a2b2 - r) to client let c_ct = server_gen.triples_online( &mut server_triples, a_ct.as_mut_slice(), b_ct.as_mut_slice(), ); let client_msg = BeaversOfflineMsg { a_shares: c_ct, b_shares: Vec::new(), }; let send_message = OfflineMsgSend::new(&client_msg); crate::bytes::serialize(writer, &send_message)?; let mut server_triples: Vec<Triple<P>> = Vec::with_capacity(num_triples); for idx in 0..num_triples { server_triples.push(crypto_primitives::Triple { a: a[idx], b: b[idx], c: c[idx], }); } Ok(server_triples) } pub(crate) fn offline_client_protocol< M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng, >( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, cfhe: &ClientFHE, num_triples: usize, rng: &mut RNG, ) -> Result<Vec<Triple<P>>, bincode::Error> { let client_gen = SealClientGen::new(&cfhe); // Generate shares for a and b let mut a = Vec::with_capacity(num_triples); let mut b = Vec::with_capacity(num_triples); for _ in 0..num_triples { a.push(P::Field::uniform(rng)); b.push(P::Field::uniform(rng)); } // Compute Enc(a1), Enc(b1) let (mut client_triples, a_ct, b_ct) = client_gen.triples_preprocess( a.iter() .map(|e| e.into_repr().0) .collect::<Vec<_>>() .as_slice(), b.iter() .map(|e| e.into_repr().0) .collect::<Vec<_>>() .as_slice(), ); // Send Enc(a1), Enc(b1) to server let server_message = BeaversOfflineMsg { a_shares: a_ct, b_shares: b_ct, }; let send_message = OfflineMsgSend::new(&server_message); crate::bytes::serialize(writer, &send_message)?; // Receive Enc(a1b2 + b1a2 + a2b2 - r) from server let recv_message: OfflineMsgRcv = crate::bytes::deserialize(reader)?; let mut recv_struct = recv_message.msg(); // Compute and decrypt Enc(ab - r) and construct client triples let c_share_vec = client_gen .triples_postprocess(&mut client_triples, recv_struct.a_shares.as_mut_slice()); let mut client_triples: Vec<Triple<P>> = Vec::with_capacity(num_triples); for idx in 0..num_triples { client_triples.push(crypto_primitives::Triple { a: a[idx], b: b[idx], c: P::Field::from_repr(c_share_vec[idx].into()), }); } Ok(client_triples) } pub fn online_server_protocol<M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send>( party_index: usize, reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, x_s: &[AdditiveShare<P>], y_s: &[AdditiveShare<P>], triples: &[Triple<P>], ) -> Result<Vec<AdditiveShare<P>>, bincode::Error> { // Compute blinded shares using the triples. let self_blinded_and_shared = x_s .iter() .zip(y_s) .zip(triples.iter()) .map(|((x, y), triple)| M::share_and_blind_inputs(x, y, &triple)) .collect::<Vec<_>>(); let mut result = Vec::with_capacity(triples.len()); rayon::scope(|s| { s.spawn(|_| { for msg_contents in self_blinded_and_shared.chunks(8192) { let sent_message = OnlineMsgSend::new(&msg_contents); crate::bytes::serialize(writer, &sent_message).unwrap(); } }); s.spawn(|_| { let num_chunks = (triples.len() as f64 / 8192.0).ceil() as usize; for _ in 0..num_chunks { let in_msg: OnlineMsgRcv<_> = crate::bytes::deserialize(reader).unwrap(); let shares = in_msg.msg(); result.extend(shares); } }); }); // TODO: use rayon to spawn this on a different thread. Ok(result .into_iter() .zip(self_blinded_and_shared) .map(|(cur, other)| M::reconstruct_blinded_inputs(cur, other)) .zip(triples) .map(|(inp, triple)| M::multiply_blinded_inputs(party_index, inp, triple)) .collect()) } pub fn online_client_protocol<M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send>( party_index: usize, reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, x_s: &[AdditiveShare<P>], y_s: &[AdditiveShare<P>], triples: &[Triple<P>], ) -> Result<Vec<AdditiveShare<P>>, bincode::Error> { // Compute blinded shares using the triples. let self_blinded_and_shared = x_s .iter() .zip(y_s) .zip(triples.iter()) .map(|((x, y), triple)| M::share_and_blind_inputs(x, y, &triple)) .collect::<Vec<_>>(); let mut result = Vec::with_capacity(triples.len()); rayon::scope(|s| { s.spawn(|_| { let num_chunks = (triples.len() as f64 / 8192.0).ceil() as usize; for _ in 0..num_chunks { let in_msg: OnlineMsgRcv<_> = crate::bytes::deserialize(reader).unwrap(); let shares = in_msg.msg(); result.extend(shares); } }); s.spawn(|_| { // TODO: use rayon to spawn this on a different thread. for msg_contents in self_blinded_and_shared.chunks(8192) { let sent_message = OnlineMsgSend::new(&msg_contents); crate::bytes::serialize(writer, &sent_message).unwrap(); } }); }); // TODO: use rayon to spawn this on a different thread. Ok(result .into_iter() .zip(self_blinded_and_shared) .map(|(cur, other)| M::reconstruct_blinded_inputs(cur, other)) .zip(triples) .map(|(inp, triple)| M::multiply_blinded_inputs(party_index, inp, triple)) .collect()) } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/bytes.rs
rust/protocols/src/bytes.rs
use io_utils::imux::IMuxSync; #[inline] pub fn serialize<W: std::io::Write + Send, T: ?Sized>( writer: &mut IMuxSync<W>, value: &T, ) -> Result<(), bincode::Error> where T: serde::Serialize, { let bytes: Vec<u8> = bincode::serialize(value)?; let _ = writer.write(&bytes)?; writer.flush()?; Ok(()) } #[inline] pub fn deserialize<R, T>(reader: &mut IMuxSync<R>) -> bincode::Result<T> where R: std::io::Read + Send, T: serde::de::DeserializeOwned, { let bytes: Vec<u8> = reader.read()?; bincode::deserialize(&bytes[..]) }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/linear_layer.rs
rust/protocols/src/linear_layer.rs
use crate::{AdditiveShare, InMessage, OutMessage}; use algebra::{ fixed_point::{FixedPoint, FixedPointParameters}, fp_64::Fp64Parameters, FpParameters, PrimeField, UniformRandom, }; use crypto_primitives::additive_share::Share; use io_utils::imux::IMuxSync; use neural_network::{ layers::*, tensors::{Input, Output}, Evaluate, }; use protocols_sys::{SealClientCG, SealServerCG, *}; use rand::{CryptoRng, RngCore}; use std::{ io::{Read, Write}, marker::PhantomData, os::raw::c_char, }; pub struct LinearProtocol<P: FixedPointParameters> { _share: PhantomData<P>, } pub struct LinearProtocolType; pub type OfflineServerMsgSend<'a> = OutMessage<'a, Vec<c_char>, LinearProtocolType>; pub type OfflineServerMsgRcv = InMessage<Vec<c_char>, LinearProtocolType>; pub type OfflineServerKeyRcv = InMessage<Vec<c_char>, LinearProtocolType>; pub type OfflineClientMsgSend<'a> = OutMessage<'a, Vec<c_char>, LinearProtocolType>; pub type OfflineClientMsgRcv = InMessage<Vec<c_char>, LinearProtocolType>; pub type OfflineClientKeySend<'a> = OutMessage<'a, Vec<c_char>, LinearProtocolType>; pub type MsgSend<'a, P> = OutMessage<'a, Input<AdditiveShare<P>>, LinearProtocolType>; pub type MsgRcv<P> = InMessage<Input<AdditiveShare<P>>, LinearProtocolType>; impl<P: FixedPointParameters> LinearProtocol<P> where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { pub fn offline_server_protocol<R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, _input_dims: (usize, usize, usize, usize), output_dims: (usize, usize, usize, usize), server_cg: &mut SealServerCG, rng: &mut RNG, ) -> Result<Output<P::Field>, bincode::Error> { // TODO: Add batch size let start_time = timer_start!(|| "Server linear offline protocol"); let preprocess_time = timer_start!(|| "Preprocessing"); // Sample server's randomness `s` for randomizing the i+1-th layer's share. let mut server_randomness: Output<P::Field> = Output::zeros(output_dims); // TODO for r in &mut server_randomness { *r = P::Field::uniform(rng); } // Convert the secret share from P::Field -> u64 let mut server_randomness_c = Output::zeros(output_dims); server_randomness_c .iter_mut() .zip(&server_randomness) .for_each(|(e1, e2)| *e1 = e2.into_repr().0); // Preprocess filter rotations and noise masks server_cg.preprocess(&server_randomness_c); timer_end!(preprocess_time); // Receive client Enc(r_i) let rcv_time = timer_start!(|| "Receiving Input"); let client_share: OfflineServerMsgRcv = crate::bytes::deserialize(reader)?; let client_share_i = client_share.msg(); timer_end!(rcv_time); // Compute client's share for layer `i + 1`. // That is, compute -Lr + s let processing = timer_start!(|| "Processing Layer"); let enc_result_vec = server_cg.process(client_share_i); timer_end!(processing); let send_time = timer_start!(|| "Sending result"); let sent_message = OfflineServerMsgSend::new(&enc_result_vec); crate::bytes::serialize(writer, &sent_message)?; timer_end!(send_time); timer_end!(start_time); Ok(server_randomness) } // Output randomness to share the input in the online phase, and an additive // share of the output of after the linear function has been applied. // Basically, r and -(Lr + s). pub fn offline_client_protocol< 'a, R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng, >( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, input_dims: (usize, usize, usize, usize), output_dims: (usize, usize, usize, usize), client_cg: &mut SealClientCG, rng: &mut RNG, ) -> Result<(Input<P::Field>, Output<AdditiveShare<P>>), bincode::Error> { // TODO: Add batch size let start_time = timer_start!(|| "Linear offline protocol"); let preprocess_time = timer_start!(|| "Client preprocessing"); // Generate random share -> r2 = -r1 (because the secret being shared is zero). let client_share: Input<FixedPoint<P>> = Input::zeros(input_dims); let (r1, r2) = client_share.share(rng); // Preprocess and encrypt client secret share for sending let ct_vec = client_cg.preprocess(&r2.to_repr()); timer_end!(preprocess_time); // Send layer_i randomness for processing by server. let send_time = timer_start!(|| "Sending input"); let sent_message = OfflineClientMsgSend::new(&ct_vec); crate::bytes::serialize(writer, &sent_message)?; timer_end!(send_time); let rcv_time = timer_start!(|| "Receiving Result"); let enc_result: OfflineClientMsgRcv = crate::bytes::deserialize(reader)?; timer_end!(rcv_time); let post_time = timer_start!(|| "Post-processing"); let mut client_share_next = Input::zeros(output_dims); // Decrypt + reshape resulting ciphertext and free C++ allocations client_cg.decrypt(enc_result.msg()); client_cg.postprocess(&mut client_share_next); // Should be equal to -(L*r1 - s) assert_eq!(client_share_next.dim(), output_dims); // Extract the inner field element. let layer_randomness = r1 .iter() .map(|r: &AdditiveShare<P>| r.inner.inner) .collect::<Vec<_>>(); let layer_randomness = ndarray::Array1::from_vec(layer_randomness) .into_shape(input_dims) .unwrap(); timer_end!(post_time); timer_end!(start_time); Ok((layer_randomness.into(), client_share_next)) } pub fn online_client_protocol<W: Write + Send>( writer: &mut IMuxSync<W>, x_s: &Input<AdditiveShare<P>>, layer: &LinearLayerInfo<AdditiveShare<P>, FixedPoint<P>>, next_layer_input: &mut Output<AdditiveShare<P>>, ) -> Result<(), bincode::Error> { let start = timer_start!(|| "Linear online protocol"); match layer { LinearLayerInfo::Conv2d { .. } | LinearLayerInfo::FullyConnected => { let sent_message = MsgSend::new(x_s); crate::bytes::serialize(writer, &sent_message)?; } _ => { layer.evaluate_naive(x_s, next_layer_input); for elem in next_layer_input.iter_mut() { elem.inner.signed_reduce_in_place(); } } } timer_end!(start); Ok(()) } pub fn online_server_protocol<R: Read + Send>( reader: &mut IMuxSync<R>, layer: &LinearLayer<AdditiveShare<P>, FixedPoint<P>>, output_rerandomizer: &Output<P::Field>, input_derandomizer: &Input<P::Field>, output: &mut Output<AdditiveShare<P>>, ) -> Result<(), bincode::Error> { let start = timer_start!(|| "Linear online protocol"); // Receive client share and compute layer if conv or fc let mut input: Input<AdditiveShare<P>> = match &layer { LinearLayer::Conv2d { .. } | LinearLayer::FullyConnected { .. } => { let recv: MsgRcv<P> = crate::bytes::deserialize(reader).unwrap(); recv.msg() } _ => Input::zeros(input_derandomizer.dim()), }; input.randomize_local_share(input_derandomizer); *output = layer.evaluate(&input); output.zip_mut_with(output_rerandomizer, |out, s| { *out = FixedPoint::randomize_local_share(out, s) }); timer_end!(start); Ok(()) } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/lib.rs
rust/protocols/src/lib.rs
use algebra::fixed_point::FixedPoint; use io_utils::imux::IMuxSync; use protocols_sys::{ClientFHE, KeyShare, ServerFHE}; use serde::{Deserialize, Serialize}; use std::{ io::{Read, Write}, marker::PhantomData, }; #[macro_use] extern crate bench_utils; extern crate ndarray; pub mod beavers_mul; pub mod gc; pub mod linear_layer; pub mod neural_network; pub mod quad_approx; pub mod bytes; #[cfg(test)] mod tests; pub type AdditiveShare<P> = crypto_primitives::AdditiveShare<FixedPoint<P>>; pub struct KeygenType; pub type ServerKeyRcv = InMessage<Vec<std::os::raw::c_char>, KeygenType>; pub type ClientKeySend<'a> = OutMessage<'a, Vec<std::os::raw::c_char>, KeygenType>; pub fn client_keygen<W: Write + Send>( writer: &mut IMuxSync<W>, ) -> Result<ClientFHE, bincode::Error> { let mut key_share = KeyShare::new(); let gen_time = timer_start!(|| "Generating keys"); let (cfhe, keys_vec) = key_share.generate(); timer_end!(gen_time); let send_time = timer_start!(|| "Sending keys"); let sent_message = ClientKeySend::new(&keys_vec); crate::bytes::serialize(writer, &sent_message)?; timer_end!(send_time); Ok(cfhe) } pub fn server_keygen<R: Read + Send>( reader: &mut IMuxSync<R>, ) -> Result<ServerFHE, bincode::Error> { let recv_time = timer_start!(|| "Receiving keys"); let keys: ServerKeyRcv = crate::bytes::deserialize(reader)?; timer_end!(recv_time); let mut key_share = KeyShare::new(); Ok(key_share.receive(keys.msg())) } #[derive(Serialize)] pub struct OutMessage<'a, T: 'a + ?Sized, Type> { msg: &'a T, protocol_type: PhantomData<Type>, } impl<'a, T: 'a + ?Sized, Type> OutMessage<'a, T, Type> { pub fn new(msg: &'a T) -> Self { Self { msg, protocol_type: PhantomData, } } pub fn msg(&self) -> &T { self.msg } } #[derive(Deserialize)] pub struct InMessage<T, Type> { msg: T, protocol_type: PhantomData<Type>, } impl<T, Type> InMessage<T, Type> { pub fn msg(self) -> T { self.msg } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/gc.rs
rust/protocols/src/gc.rs
use crate::{AdditiveShare, InMessage, OutMessage}; use algebra::{ fields::PrimeField, fixed_point::{FixedPoint, FixedPointParameters}, fp_64::Fp64Parameters, BigInteger64, FpParameters, UniformRandom, }; use crypto_primitives::{ gc::{ fancy_garbling, fancy_garbling::{ circuit::{Circuit, CircuitBuilder}, Encoder, GarbledCircuit, Wire, }, }, Share, }; use io_utils::imux::IMuxSync; use ocelot::ot::{AlszReceiver as OTReceiver, AlszSender as OTSender, Receiver, Sender}; use rand::{CryptoRng, RngCore}; use rayon::prelude::*; use scuttlebutt::Channel; use std::{ convert::TryFrom, io::{Read, Write}, marker::PhantomData, }; #[derive(Default)] pub struct ReluProtocol<P: FixedPointParameters> { _share: PhantomData<P>, } pub struct ReluProtocolType; pub type ServerGcMsgSend<'a> = OutMessage<'a, (&'a [GarbledCircuit], &'a [Wire]), ReluProtocolType>; pub type ClientGcMsgRcv = InMessage<(Vec<GarbledCircuit>, Vec<Wire>), ReluProtocolType>; // The message is a slice of (vectors of) input labels; pub type ServerLabelMsgSend<'a> = OutMessage<'a, [Vec<Wire>], ReluProtocolType>; pub type ClientLabelMsgRcv = InMessage<Vec<Vec<Wire>>, ReluProtocolType>; pub fn make_relu<P: FixedPointParameters>() -> Circuit where <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { let mut b = CircuitBuilder::new(); crypto_primitives::gc::relu::<P>(&mut b, 1).unwrap(); b.finish() } pub fn u128_from_share<P: FixedPointParameters>(s: AdditiveShare<P>) -> u128 where <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = BigInteger64>, { let s: u64 = s.inner.inner.into_repr().into(); s.into() } pub struct ServerState<P: FixedPointParameters> { pub encoders: Vec<Encoder>, pub output_randomizers: Vec<P::Field>, } pub struct ClientState { pub gc_s: Vec<GarbledCircuit>, pub server_randomizer_labels: Vec<Wire>, pub client_input_labels: Vec<Wire>, } impl<P: FixedPointParameters> ReluProtocol<P> where <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = BigInteger64>, { #[inline] pub fn size_of_client_inputs() -> usize { make_relu::<P>().num_evaluator_inputs() } pub fn offline_server_protocol<R: Read + Send, W: Write + Send, RNG: CryptoRng + RngCore>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, number_of_relus: usize, rng: &mut RNG, ) -> Result<ServerState<P>, bincode::Error> { let start_time = timer_start!(|| "ReLU offline protocol"); let mut gc_s = Vec::with_capacity(number_of_relus); let mut encoders = Vec::with_capacity(number_of_relus); let p = (<<P::Field as PrimeField>::Params>::MODULUS.0).into(); let c = make_relu::<P>(); let garble_time = timer_start!(|| "Garbling"); (0..number_of_relus) .into_par_iter() .map(|_| { let mut c = c.clone(); let (en, gc) = fancy_garbling::garble(&mut c).unwrap(); (en, gc) }) .unzip_into_vecs(&mut encoders, &mut gc_s); timer_end!(garble_time); let encode_time = timer_start!(|| "Encoding inputs"); let num_garbler_inputs = c.num_garbler_inputs(); let num_evaluator_inputs = c.num_evaluator_inputs(); let zero_inputs = vec![0u16; num_evaluator_inputs]; let one_inputs = vec![1u16; num_evaluator_inputs]; let mut labels = Vec::with_capacity(number_of_relus * num_evaluator_inputs); let mut randomizer_labels = Vec::with_capacity(number_of_relus); let mut output_randomizers = Vec::with_capacity(number_of_relus); for enc in encoders.iter() { let r = P::Field::uniform(rng); output_randomizers.push(r); let r_bits: u64 = ((-r).into_repr()).into(); let r_bits = fancy_garbling::util::u128_to_bits( r_bits.into(), crypto_primitives::gc::num_bits(p), ); for w in ((num_garbler_inputs / 2)..num_garbler_inputs) .zip(r_bits) .map(|(i, r_i)| enc.encode_garbler_input(r_i, i)) { randomizer_labels.push(w); } let all_zeros = enc.encode_evaluator_inputs(&zero_inputs); let all_ones = enc.encode_evaluator_inputs(&one_inputs); all_zeros .into_iter() .zip(all_ones) .for_each(|(label_0, label_1)| { labels.push((label_0.as_block(), label_1.as_block())) }); } timer_end!(encode_time); let send_gc_time = timer_start!(|| "Sending GCs"); let randomizer_label_per_relu = if number_of_relus == 0 { 8192 } else { randomizer_labels.len() / number_of_relus }; for msg_contents in gc_s .chunks(8192) .zip(randomizer_labels.chunks(randomizer_label_per_relu * 8192)) { let sent_message = ServerGcMsgSend::new(&msg_contents); crate::bytes::serialize(writer, &sent_message)?; } timer_end!(send_gc_time); if number_of_relus != 0 { let r = reader.get_mut_ref().remove(0); let w = writer.get_mut_ref().remove(0); let ot_time = timer_start!(|| "OTs"); let mut channel = Channel::new(r, w); let mut ot = OTSender::init(&mut channel, rng).unwrap(); ot.send(&mut channel, labels.as_slice(), rng).unwrap(); timer_end!(ot_time); } timer_end!(start_time); Ok(ServerState { encoders, output_randomizers, }) } pub fn offline_client_protocol<R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, number_of_relus: usize, shares: &[AdditiveShare<P>], rng: &mut RNG, ) -> Result<ClientState, bincode::Error> { use fancy_garbling::util::*; let start_time = timer_start!(|| "ReLU offline protocol"); let p = u128::from(<<P::Field as PrimeField>::Params>::MODULUS.0); let field_size = crypto_primitives::gc::num_bits(p); let rcv_gc_time = timer_start!(|| "Receiving GCs"); let mut gc_s = Vec::with_capacity(number_of_relus); let mut r_wires = Vec::with_capacity(number_of_relus); let num_chunks = (number_of_relus as f64 / 8192.0).ceil() as usize; for i in 0..num_chunks { let in_msg: ClientGcMsgRcv = crate::bytes::deserialize(reader)?; let (gc_chunks, r_wire_chunks) = in_msg.msg(); if i < (num_chunks - 1) { assert_eq!(gc_chunks.len(), 8192); } gc_s.extend(gc_chunks); r_wires.extend(r_wire_chunks); } timer_end!(rcv_gc_time); assert_eq!(gc_s.len(), number_of_relus); let bs = shares .iter() .flat_map(|s| u128_to_bits(u128_from_share(*s), field_size)) .map(|b| b == 1) .collect::<Vec<_>>(); let labels = if number_of_relus != 0 { let r = reader.get_mut_ref().remove(0); let w = writer.get_mut_ref().remove(0); let ot_time = timer_start!(|| "OTs"); let mut channel = Channel::new(r, w); let mut ot = OTReceiver::init(&mut channel, rng).expect("should work"); let labels = ot .receive(&mut channel, bs.as_slice(), rng) .expect("should work"); let labels = labels .into_iter() .map(|l| Wire::from_block(l, 2)) .collect::<Vec<_>>(); timer_end!(ot_time); labels } else { Vec::new() }; timer_end!(start_time); Ok(ClientState { gc_s, server_randomizer_labels: r_wires, client_input_labels: labels, }) } pub fn online_server_protocol<'a, W: Write + Send>( writer: &mut IMuxSync<W>, shares: &[AdditiveShare<P>], encoders: &[Encoder], ) -> Result<(), bincode::Error> { let p = u128::from(u64::from(P::Field::characteristic())); let start_time = timer_start!(|| "ReLU online protocol"); let encoding_time = timer_start!(|| "Encoding inputs"); let field_size = (p.next_power_of_two() * 2).trailing_zeros() as usize; let wires = shares .iter() .map(|share| { let share = u128_from_share(*share); fancy_garbling::util::u128_to_bits(share, field_size) }) .zip(encoders) .map(|(share_bits, encoder)| encoder.encode_garbler_inputs(&share_bits)) .collect::<Vec<Vec<_>>>(); timer_end!(encoding_time); let send_time = timer_start!(|| "Sending inputs"); let sent_message = ServerLabelMsgSend::new(wires.as_slice()); timer_end!(send_time); timer_end!(start_time); crate::bytes::serialize(writer, &sent_message) } /// Outputs shares for the next round's input. pub fn online_client_protocol<R: Read + Send>( reader: &mut IMuxSync<R>, num_relus: usize, server_input_wires: &[Wire], client_input_wires: &[Wire], evaluators: &[GarbledCircuit], next_layer_randomizers: &[P::Field], ) -> Result<Vec<AdditiveShare<P>>, bincode::Error> { let start_time = timer_start!(|| "ReLU online protocol"); let rcv_time = timer_start!(|| "Receiving inputs"); let in_msg: ClientLabelMsgRcv = crate::bytes::deserialize(reader)?; let mut garbler_wires = in_msg.msg(); timer_end!(rcv_time); let eval_time = timer_start!(|| "Evaluating GCs"); let c = make_relu::<P>(); let num_evaluator_inputs = c.num_evaluator_inputs(); let num_garbler_inputs = c.num_garbler_inputs(); garbler_wires .iter_mut() .zip(server_input_wires.chunks(num_garbler_inputs / 2)) .for_each(|(w1, w2)| w1.extend_from_slice(w2)); assert_eq!(num_relus, garbler_wires.len()); assert_eq!(num_evaluator_inputs * num_relus, client_input_wires.len()); // We access the input wires in reverse. let c = make_relu::<P>(); let mut results = client_input_wires .par_chunks(num_evaluator_inputs) .zip(garbler_wires) .zip(evaluators) .map(|((eval_inps, garbler_inps), gc)| { let mut c = c.clone(); let result = gc .eval(&mut c, &garbler_inps, eval_inps) .expect("evaluation failed"); let result = fancy_garbling::util::u128_from_bits(result.as_slice()); FixedPoint::new(P::Field::from_repr(u64::try_from(result).unwrap().into())).into() }) .collect::<Vec<AdditiveShare<P>>>(); results .iter_mut() .zip(next_layer_randomizers) .for_each(|(s, r)| *s = FixedPoint::<P>::randomize_local_share(s, r)); timer_end!(eval_time); timer_end!(start_time); Ok(results) } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/quad_approx.rs
rust/protocols/src/quad_approx.rs
use crate::{beavers_mul::BeaversMulProtocol, AdditiveShare}; use algebra::{ fields::PrimeField, fixed_point::{FixedPoint, FixedPointParameters}, fp_64::Fp64Parameters, FpParameters, Polynomial, }; use crypto_primitives::{BeaversMul, Triple}; use io_utils::imux::IMuxSync; use protocols_sys::*; use rand::{CryptoRng, RngCore}; use std::{ io::{Read, Write}, marker::PhantomData, }; pub struct QuadApproxProtocol<P: FixedPointParameters> { _share: PhantomData<P>, } impl<P: FixedPointParameters> QuadApproxProtocol<P> where <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { pub fn offline_server_protocol< M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng, >( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, sfhe: &ServerFHE, num_approx: usize, rng: &mut RNG, ) -> Result<Vec<Triple<P::Field>>, bincode::Error> { if num_approx != 0 { BeaversMulProtocol::offline_server_protocol::<M, _, _, _>( reader, writer, sfhe, num_approx, rng, ) } else { Ok(Vec::new()) } } pub fn offline_client_protocol< M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng, >( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, cfhe: &ClientFHE, num_approx: usize, rng: &mut RNG, ) -> Result<Vec<Triple<P::Field>>, bincode::Error> { if num_approx != 0 { BeaversMulProtocol::offline_client_protocol::<M, _, _, _>( reader, writer, cfhe, num_approx, rng, ) } else { Ok(Vec::new()) } } pub fn online_server_protocol<M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send>( party_index: usize, reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, polynomial: &Polynomial<FixedPoint<P>>, x_s: &[AdditiveShare<P>], triples: &[Triple<P::Field>], ) -> Result<Vec<AdditiveShare<P>>, bincode::Error> { let mut x_squared = BeaversMulProtocol::online_server_protocol::<M, R, W>( party_index, reader, writer, x_s, x_s, &triples, )?; let coeffs = polynomial.coeffs(); assert_eq!(coeffs.len(), 3); let a_0 = coeffs[0]; let a_1 = coeffs[1]; let a_2 = coeffs[2]; // Reduce down to correct size. for (x2, x) in x_squared.iter_mut().zip(x_s) { x2.inner.signed_reduce_in_place(); *x2 *= a_2; x2.inner.signed_reduce_in_place(); let mut a_1_x = *x * a_1; a_1_x.inner.signed_reduce_in_place(); *x2 += a_1_x; // Only add the constant if we are the client. // (Both parties adding it would mean that the constant is doubled.) if party_index == crate::neural_network::CLIENT { x2.add_constant_in_place(a_0); } } Ok(x_squared) } pub fn online_client_protocol<M: BeaversMul<FixedPoint<P>>, R: Read + Send, W: Write + Send>( party_index: usize, reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, polynomial: &Polynomial<FixedPoint<P>>, x_s: &[AdditiveShare<P>], triples: &[Triple<P::Field>], ) -> Result<Vec<AdditiveShare<P>>, bincode::Error> { let mut x_squared = BeaversMulProtocol::online_client_protocol::<M, R, W>( party_index, reader, writer, x_s, x_s, &triples, )?; let coeffs = polynomial.coeffs(); assert_eq!(coeffs.len(), 3); let a_0 = coeffs[0]; let a_1 = coeffs[1]; let a_2 = coeffs[2]; // Reduce down to correct size. for (x2, x) in x_squared.iter_mut().zip(x_s) { x2.inner.signed_reduce_in_place(); *x2 *= a_2; x2.inner.signed_reduce_in_place(); let mut a_1_x = *x * a_1; a_1_x.inner.signed_reduce_in_place(); *x2 += a_1_x; // Only add the constant if we are the client. // (Both parties adding it would mean that the constant is doubled.) if party_index == crate::neural_network::CLIENT { x2.add_constant_in_place(a_0); } } Ok(x_squared) } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/tests.rs
rust/protocols/src/tests.rs
use crate::AdditiveShare; use algebra::{ fields::near_mersenne_64::F, fixed_point::{FixedPoint, FixedPointParameters}, }; use crypto_primitives::{additive_share::Share, beavers_mul::FPBeaversMul}; use io_utils::imux::IMuxSync; use protocols_sys::*; use rand::{Rng, SeedableRng}; use rand_chacha::ChaChaRng; use std::net::{TcpListener, TcpStream}; struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 3; const EXPONENT_CAPACITY: u8 = 7; } type TenBitExpFP = FixedPoint<TenBitExpParams>; type TenBitBM = FPBeaversMul<TenBitExpParams>; type TenBitAS = AdditiveShare<TenBitExpParams>; const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let mut float: f64 = rng.gen(); float += 1.0; let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } fn generate_random_weight<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let float: f64 = rng.gen_range(-0.9, 0.9); let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } mod beavers_mul { use super::*; use crate::beavers_mul::BeaversMulProtocol; use crypto_primitives::Share; #[test] fn test_beavers_mul() { let num_triples = 10000; let mut rng = ChaChaRng::from_seed(RANDOMNESS); let mut plain_x_s = Vec::with_capacity(num_triples); let mut plain_y_s = Vec::with_capacity(num_triples); let mut plain_results = Vec::with_capacity(num_triples); // Shares for party 1 let mut x_s_1 = Vec::with_capacity(num_triples); let mut y_s_1 = Vec::with_capacity(num_triples); // Shares for party 2 let mut x_s_2 = Vec::with_capacity(num_triples); let mut y_s_2 = Vec::with_capacity(num_triples); // Give shares to each party for _ in 0..num_triples { let (f1, n1) = (2.0, TenBitExpFP::from(2.0)); let (f2, n2) = (5.0, TenBitExpFP::from(5.0)); plain_x_s.push(n1); plain_y_s.push(n2); let f3 = f1 * f2; let n3 = TenBitExpFP::from(f3); plain_results.push(n3); let (s11, s12) = n1.share(&mut rng); let (s21, s22) = n2.share(&mut rng); x_s_1.push(s11); x_s_2.push(s12); y_s_1.push(s21); y_s_2.push(s22); } // Keygen let mut key_share = KeyShare::new(); let (cfhe, keys_vec) = key_share.generate(); let sfhe = key_share.receive(keys_vec); // Party 1 acts as the server, Party 2 as the client let addr = "127.0.0.1:8005"; let party_1_listener = TcpListener::bind(&addr).unwrap(); let (triples_1, triples_2) = crossbeam::thread::scope(|s| { let triples_1 = s.spawn(|_| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for stream in party_1_listener.incoming() { match stream { Ok(read_stream) => { return BeaversMulProtocol::offline_server_protocol::<TenBitBM, _, _, _>( &mut IMuxSync::new(vec![read_stream.try_clone().unwrap()]), &mut IMuxSync::new(vec![read_stream]), &sfhe, num_triples, &mut rng, ) } Err(_) => panic!("Connection failed"), } } unreachable!("we should never exit server's loop") }); let triples_2 = s.spawn(|_| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); let party_2_stream = TcpStream::connect(&addr).unwrap(); BeaversMulProtocol::offline_client_protocol::<TenBitBM, _, _, _>( &mut IMuxSync::new(vec![party_2_stream.try_clone().unwrap()]), &mut IMuxSync::new(vec![party_2_stream]), &cfhe, num_triples, &mut rng, ) }); ( triples_1.join().unwrap().unwrap(), triples_2.join().unwrap().unwrap(), ) }) .unwrap(); let (p1, p2) = crossbeam::thread::scope(|s| { let p1 = s.spawn(|_| { for stream in party_1_listener.incoming() { match stream { Ok(read_stream) => { return BeaversMulProtocol::online_client_protocol::<TenBitBM, _, _>( 1, // party index &mut IMuxSync::new(vec![read_stream.try_clone().unwrap()]), &mut IMuxSync::new(vec![read_stream]), &x_s_1, &y_s_1, &triples_1, ); } Err(_) => panic!("Connection failed"), } } unreachable!("we should never exit server's loop") }); let p2 = s.spawn(|_| { let party_2_stream = TcpStream::connect(&addr).unwrap(); BeaversMulProtocol::online_server_protocol::<TenBitBM, _, _>( 2, // party index &mut IMuxSync::new(vec![party_2_stream.try_clone().unwrap()]), &mut IMuxSync::new(vec![party_2_stream]), &x_s_2, &y_s_2, &triples_2, ) }); (p1.join().unwrap().unwrap(), p2.join().unwrap().unwrap()) }) .unwrap(); for (i, ((mut s1, mut s2), n3)) in p1.into_iter().zip(p2).zip(plain_results).enumerate() { s1.inner.signed_reduce_in_place(); s2.inner.signed_reduce_in_place(); let n4 = s1.combine(&s2); assert_eq!(n4, n3, "iteration {} failed", i); } } } // TODO: Some APIs got out of sync here //mod gc { // use super::*; // use crate::gc::*; // // #[test] // fn test_gc_relu() { // let mut rng = ChaChaRng::from_seed(RANDOMNESS); // let mut plain_x_s = Vec::with_capacity(1001); // let mut plain_results = Vec::with_capacity(1001); // // // Shares for server // let mut server_x_s = Vec::with_capacity(1001); // let mut randomizer = Vec::with_capacity(1001); // // // Shares for client // let mut client_x_s = Vec::with_capacity(1001); // let mut client_results = Vec::with_capacity(1001); // // for _ in 0..1000 { // let (f1, n1) = generate_random_number(&mut rng); // plain_x_s.push(n1); // let f2 = if f1 < 0.0 { // 0.0 // } else if f1 > 6.0 { // 6.0 // } else { // f1 // }; // let n2 = TenBitExpFP::from(f2); // plain_results.push(n2); // // let (s11, s12) = n1.share(&mut rng); // let (_, s22) = n2.share(&mut rng); // server_x_s.push(s11); // client_x_s.push(s12); // // randomizer.push(-s22.inner.inner); // client_results.push(s22); // } // // let server_addr = "127.0.0.1:8003"; // let client_addr = "127.0.0.1:8004"; // let num_relus = 1000; // let server_listener = TcpListener::bind(server_addr).unwrap(); // // let (server_offline, client_offline) = crossbeam::thread::scope(|s| { // let server_offline_result = s.spawn(|_| { // let mut rng = ChaChaRng::from_seed(RANDOMNESS); // // for stream in server_listener.incoming() { // let stream = stream.expect("server connection failed!"); // let mut read_stream = IMuxSync::new(vec![stream.try_clone().unwrap()]); // let mut write_stream = IMuxSync::new(vec![stream]); // return ReluProtocol::<TenBitExpParams>::offline_server_protocol( // &mut read_stream, // &mut write_stream, // num_relus, // &mut rng, // ); // } // unreachable!("we should never exit server's loop") // }); // // let client_offline_result = s.spawn(|_| { // let mut rng = ChaChaRng::from_seed(RANDOMNESS); // // // client's connection to server. // let stream = TcpStream::connect(server_addr).expect("connecting to server failed"); // let mut read_stream = IMuxSync::new(vec![stream.try_clone().unwrap()]); // let mut write_stream = IMuxSync::new(vec![stream]); // // return ReluProtocol::offline_client_protocol( // &mut read_stream, // &mut write_stream, // num_relus, // &client_x_s, // &mut rng, // ); // }); // ( // server_offline_result.join().unwrap().unwrap(), // client_offline_result.join().unwrap().unwrap(), // ) // }) // .unwrap(); // let client_listener = TcpListener::bind(client_addr).unwrap(); // // let client_online = crossbeam::thread::scope(|s| { // // Start thread for client. // let result = s.spawn(|_| { // let gc_s = &client_offline.gc_s; // let server_labels = &client_offline.server_randomizer_labels; // let client_labels = &client_offline.client_input_labels; // for stream in client_listener.incoming() { // let mut read_stream = // IMuxSync::new(vec![stream.expect("client connection failed!")]); // return ReluProtocol::online_client_protocol( // &mut read_stream, // num_relus, // &server_labels, // &client_labels, // &gc_s, // &randomizer, // ); // } // unreachable!("we should never reach here") // }); // // // Start thread for the server to make a connection. // let _ = s // .spawn(|_| { // let mut write_stream = // IMuxSync::new(vec![TcpStream::connect(client_addr).unwrap()]); // // ReluProtocol::online_server_protocol( // &mut write_stream, // &server_x_s, // &server_offline.encoders, // ) // }) // .join() // .unwrap(); // // result.join().unwrap().unwrap() // }) // .unwrap(); // for i in 0..1000 { // let server_randomizer = server_offline.output_randomizers[i]; // let server_share = // TenBitExpFP::randomize_local_share(&client_online[i], &server_randomizer); // let client_share = client_results[i]; // let result = plain_results[i]; // assert_eq!(server_share.combine(&client_share), result); // } // } //} mod linear { use super::*; use crate::linear_layer::*; use ndarray::s; use neural_network::{layers::*, tensors::*, Evaluate}; use std::io::{BufReader, BufWriter}; #[test] fn test_convolution() { use neural_network::layers::convolution::*; const RANDOMNESS: [u8; 32] = [ 0x14, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; let mut rng = ChaChaRng::from_seed(RANDOMNESS); // Set the parameters for the convolution. let input_dims = (1, 64, 8, 8); let kernel_dims = (64, 64, 3, 3); let stride = 1; let padding = Padding::Same; // Sample a random kernel. let mut kernel = Kernel::zeros(kernel_dims); let mut bias = Kernel::zeros((kernel_dims.0, 1, 1, 1)); kernel .iter_mut() .for_each(|ker_i| *ker_i = generate_random_number(&mut rng).1); bias.iter_mut() .for_each(|bias_i| *bias_i = generate_random_number(&mut rng).1); let layer_params = Conv2dParams::<TenBitAS, _>::new(padding, stride, kernel.clone(), bias.clone()); let output_dims = layer_params.calculate_output_size(input_dims); let pt_layer_params = Conv2dParams::<TenBitExpFP, _>::new(padding, stride, kernel.clone(), bias.clone()); let layer_dims = LayerDims { input_dims, output_dims, }; let layer = Layer::LL(LinearLayer::Conv2d { dims: layer_dims, params: layer_params, }); let layer_info = (&layer).into(); let layer = match layer { Layer::LL(l) => l, Layer::NLL(_) => unreachable!(), }; let pt_layer = LinearLayer::Conv2d { dims: layer_dims, params: pt_layer_params, }; // Done setting up parameters for the convolution // Sample a random input. let mut input = Input::zeros(input_dims); input .iter_mut() .for_each(|in_i| *in_i = generate_random_number(&mut rng).1); // Evaluate convolution layer on plaintext, so that we can check results later. let output = pt_layer.evaluate(&input); let server_addr = "127.0.0.1:8001"; let server_listener = TcpListener::bind(server_addr).unwrap(); let layer_input_dims = layer.input_dimensions(); let layer_output_dims = layer.output_dimensions(); let layer = std::sync::Arc::new(std::sync::Mutex::new(layer)); let ((layer_randomizer, client_next_layer_share), server_offline) = crossbeam::thread::scope(|s| { let server_offline_result = s.spawn(|_| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for stream in server_listener.incoming() { let stream = stream.expect("server connection failed!"); let mut reader = IMuxSync::new(vec![BufReader::new(&stream)]); let mut writer = IMuxSync::new(vec![BufWriter::new(&stream)]); let sfhe: ServerFHE = crate::server_keygen(&mut reader)?; let layer = layer.lock().unwrap(); let mut cg_handler = SealServerCG::Conv2D(server_cg::Conv2D::new( &sfhe, &layer, &layer.kernel_to_repr(), )); return LinearProtocol::<TenBitExpParams>::offline_server_protocol( &mut reader, &mut writer, layer_input_dims, layer_output_dims, &mut cg_handler, &mut rng, ); } unreachable!("we should never exit server's loop") }); let client_offline_result = s.spawn(|_| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); // client's connection to server. let stream = TcpStream::connect(server_addr).expect("connecting to server failed"); let mut reader = IMuxSync::new(vec![stream.try_clone().unwrap()]); let mut writer = IMuxSync::new(vec![stream]); let cfhe: ClientFHE = crate::client_keygen(&mut writer)?; match &layer_info { LayerInfo::LL(_, info) => { let mut cg_handler = SealClientCG::Conv2D(client_cg::Conv2D::new( &cfhe, info, layer_input_dims, layer_output_dims, )); LinearProtocol::offline_client_protocol( &mut reader, &mut writer, layer_input_dims, layer_output_dims, &mut cg_handler, &mut rng, ) } LayerInfo::NLL(..) => unreachable!(), } }); ( client_offline_result.join().unwrap().unwrap(), server_offline_result.join().unwrap().unwrap(), ) }) .unwrap(); // Share the input for layer `1`, computing // server_share_1 = x + r. // client_share_1 = -r; let (server_current_layer_share, _) = input.share_with_randomness(&layer_randomizer); let server_next_layer_share = crossbeam::thread::scope(|s| { // Start thread for client. let result = s.spawn(|_| { let mut write_stream = IMuxSync::new(vec![TcpStream::connect(server_addr).unwrap()]); let mut result = Output::zeros(layer_output_dims); match &layer_info { LayerInfo::LL(_, info) => LinearProtocol::online_client_protocol( &mut write_stream, &server_current_layer_share, &info, &mut result, ), LayerInfo::NLL(..) => unreachable!(), } }); // Start thread for the server to make a connection. let server_result = s .spawn(move |_| { for stream in server_listener.incoming() { let mut read_stream = IMuxSync::new(vec![stream.expect("server connection failed!")]); let mut output = Output::zeros(output_dims); return LinearProtocol::online_server_protocol( &mut read_stream, // we only receive here, no messages to client &layer.lock().unwrap(), // layer parameters &server_offline, // this is our `s` from above. &Input::zeros(layer_input_dims), &mut output, // this is where the result will go. ) .map(|_| output); } unreachable!("Server should not exit loop"); }) .join() .unwrap() .unwrap(); let _ = result.join(); server_result }) .unwrap(); let mut result: Input<TenBitExpFP> = Input::zeros(client_next_layer_share.dim()); result .iter_mut() .zip(client_next_layer_share.iter()) .zip(server_next_layer_share.iter()) .for_each(|((r, s1), s2)| { *r = (*s1).combine(s2); }); println!("Result:"); println!("DIM: {:?}", result.dim()); let chan_size = result.dim().2 * result.dim().3; let row_size = result.dim().2; let mut success = true; result .slice(s![0, .., .., ..]) .outer_iter() .zip(output.slice(s![0, .., .., ..]).outer_iter()) .enumerate() .for_each(|(chan_idx, (res_c, out_c))| { println!("Channel {}: ", chan_idx); res_c .outer_iter() .zip(out_c.outer_iter()) .enumerate() .for_each(|(inp_idx, (inp_r, inp_out))| { println!(" Row {}: ", inp_idx); inp_r .iter() .zip(inp_out.iter()) .enumerate() .for_each(|(i, (r, out))| { println!( "IDX {}: {} {}", i + inp_idx * row_size + chan_idx * chan_size, r, out ); let delta = f64::from(*r) - f64::from(*out); if delta.abs() > 0.5 { println!( "{:?}-th index failed {:?} {:?} {} {}", i, r.signed_reduce(), out.signed_reduce(), r, out ); println!( "{} + {} = {}", client_next_layer_share[[0, chan_idx, inp_idx, i]].inner, server_next_layer_share[[0, chan_idx, inp_idx, i]].inner, r ); success = false; } }); }); }); assert!(success); } #[test] fn test_fully_connected() { use neural_network::layers::fully_connected::*; let mut rng = ChaChaRng::from_seed(RANDOMNESS); // Set the parameters for the layer let input_dims = (1, 3, 32, 32); let kernel_dims = (10, 3, 32, 32); // Sample a random kernel. let mut kernel = Kernel::zeros(kernel_dims); let mut bias = Kernel::zeros((kernel_dims.0, 1, 1, 1)); kernel .iter_mut() .for_each(|ker_i| *ker_i = generate_random_weight(&mut rng).1); bias.iter_mut() .for_each(|bias_i| *bias_i = generate_random_weight(&mut rng).1); let layer_params = FullyConnectedParams::<TenBitAS, _>::new(kernel.clone(), bias.clone()); let pt_layer_params = FullyConnectedParams::<TenBitExpFP, _>::new(kernel.clone(), bias.clone()); let output_dims = layer_params.calculate_output_size(input_dims); let layer_dims = LayerDims { input_dims, output_dims, }; let layer = Layer::LL(LinearLayer::FullyConnected { dims: layer_dims, params: layer_params, }); let layer_info = (&layer).into(); let layer = match layer { Layer::LL(l) => l, Layer::NLL(_) => unreachable!(), }; let pt_layer = LinearLayer::FullyConnected { dims: layer_dims, params: pt_layer_params, }; // Sample a random input. let mut input = Input::zeros(input_dims); input .iter_mut() .for_each(|in_i| *in_i = generate_random_weight(&mut rng).1); // input.iter_mut().for_each(|in_i| *in_i = TenBitExpFP::from(1.0)); // Evaluate convolution layer on plaintext, so that we can check results later. let output = pt_layer.evaluate(&input); let server_addr = "127.0.0.1:8002"; let server_listener = TcpListener::bind(server_addr).unwrap(); let layer_input_dims = layer.input_dimensions(); let layer_output_dims = layer.output_dimensions(); let layer = std::sync::Arc::new(std::sync::Mutex::new(layer)); let ((layer_randomizer, client_next_layer_share), server_offline) = crossbeam::thread::scope(|s| { let server_offline_result = s.spawn(|_| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); let mut sfhe_op: Option<ServerFHE> = None; for stream in server_listener.incoming() { let stream = stream.expect("server connection failed!"); let mut reader = IMuxSync::new(vec![BufReader::new(&stream)]); let mut writer = IMuxSync::new(vec![BufWriter::new(&stream)]); let sfhe: ServerFHE = crate::server_keygen(&mut reader)?; let layer = layer.lock().unwrap(); let mut cg_handler = SealServerCG::FullyConnected( server_cg::FullyConnected::new(&sfhe, &layer, &layer.kernel_to_repr()), ); return LinearProtocol::<TenBitExpParams>::offline_server_protocol( &mut reader, &mut writer, layer_input_dims, layer_output_dims, &mut cg_handler, &mut rng, ); } unreachable!("we should never exit server's loop") }); let client_offline_result = s.spawn(|_| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); let mut cfhe_op: Option<ClientFHE> = None; // client's connection to server. let stream = TcpStream::connect(server_addr).expect("connecting to server failed"); let mut reader = IMuxSync::new(vec![stream.try_clone().unwrap()]); let mut writer = IMuxSync::new(vec![stream]); let cfhe: ClientFHE = crate::client_keygen(&mut writer)?; match &layer_info { LayerInfo::LL(_, info) => { let mut cg_handler = SealClientCG::FullyConnected(client_cg::FullyConnected::new( &cfhe, info, layer_input_dims, layer_output_dims, )); LinearProtocol::offline_client_protocol( &mut reader, &mut writer, layer_input_dims, layer_output_dims, &mut cg_handler, &mut rng, ) } LayerInfo::NLL(..) => unreachable!(), } }); ( client_offline_result.join().unwrap().unwrap(), server_offline_result.join().unwrap().unwrap(), ) }) .unwrap(); println!("\nSERVER'S SHARE: "); server_offline.iter().for_each(|e| { let as_share: FixedPoint<TenBitExpParams> = -(FixedPoint::with_num_muls(*e, 1)); println!("{} {}", as_share.inner, as_share); }); println!("\n"); println!("CLIENT'S NEXT LAYER SHARE:"); client_next_layer_share.iter().for_each(|e| { println!("{}, {}", e.inner.inner, e.inner); }); println!("\n"); println!("CLIENT'S LAYER RANDOMIZER:"); layer_randomizer.iter().for_each(|e: &F| { let as_share: FixedPoint<TenBitExpParams> = FixedPoint::with_num_muls(*e, 0); println!("{}, {}", e, as_share); }); println!("\n"); // Share the input for layer `1`, computing // server_share_1 = x + r. // client_share_1 = -r; let (server_current_layer_share, _) = input.share_with_randomness(&layer_randomizer); println!("CLIENT ONLINE INPUT:"); server_current_layer_share.iter().for_each(|e| { println!("{}, {}", e.inner.inner, e.inner); }); println!("\n"); let server_next_layer_share = crossbeam::thread::scope(|s| { // Start thread for client. let result = s.spawn(|_| { let mut write_stream = IMuxSync::new(vec![TcpStream::connect(server_addr).unwrap()]); let mut result = Output::zeros(layer_output_dims); match &layer_info { LayerInfo::LL(_, info) => LinearProtocol::online_client_protocol( &mut write_stream, &server_current_layer_share, &info, &mut result, ), LayerInfo::NLL(..) => unreachable!(), } }); // Start thread for the server to make a connection. let server_result = s .spawn(move |_| { for stream in server_listener.incoming() { let mut read_stream = IMuxSync::new(vec![stream.expect("server connection failed!")]); let mut output = Output::zeros(output_dims); return LinearProtocol::online_server_protocol( &mut read_stream, // we only receive here, no messages to client &layer.lock().unwrap(), // layer parameters &server_offline, // this is our `s` from above. &Input::zeros(layer_input_dims), &mut output, // this is where the result will go. ) .map(|_| output); } unreachable!("Server should not exit loop"); }) .join() .unwrap() .unwrap(); let _ = result.join(); server_result }) .unwrap(); println!("\nSERVER ONLINE OUTPUT:"); server_next_layer_share.iter().for_each(|e| { println!("{}, {}", e.inner.inner, e.inner); }); println!("\n"); println!("CLIENT UNMASKING:"); for (i, ((s1, s2), &n3)) in client_next_layer_share .iter() .zip(server_next_layer_share.iter()) .zip(output.iter()) .enumerate() { let s1 = *s1; let s2 = *s2; let n4 = s1.combine(&s2); println!("{} + {} = {}", s1.inner, s2.inner, n4); assert_eq!(n4, n3, "{:?}-th index failed", i); } } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/protocols/src/neural_network.rs
rust/protocols/src/neural_network.rs
use crate::AdditiveShare; use bench_utils::{timer_end, timer_start}; use neural_network::{ layers::{Layer, LayerInfo, NonLinearLayer, NonLinearLayerInfo}, NeuralArchitecture, NeuralNetwork, }; use rand::{CryptoRng, RngCore}; use std::{ io::{Read, Write}, marker::PhantomData, }; use algebra::{ fixed_point::{FixedPoint, FixedPointParameters}, fp_64::Fp64Parameters, FpParameters, PrimeField, }; use io_utils::imux::IMuxSync; use neural_network::{ layers::*, tensors::{Input, Output}, }; use crypto_primitives::{ beavers_mul::{FPBeaversMul, Triple}, gc::fancy_garbling::{Encoder, GarbledCircuit, Wire}, }; use crate::{gc::ReluProtocol, linear_layer::LinearProtocol, quad_approx::QuadApproxProtocol}; use protocols_sys::*; use std::collections::BTreeMap; pub struct NNProtocol<P: FixedPointParameters> { _share: PhantomData<P>, } pub const CLIENT: usize = 1; pub const SERVER: usize = 2; pub struct ServerState<P: FixedPointParameters> { pub linear_state: BTreeMap<usize, Output<P::Field>>, pub relu_encoders: Vec<Encoder>, pub relu_output_randomizers: Vec<P::Field>, pub approx_state: Vec<Triple<P::Field>>, } // This is a hack since Send + Sync aren't implemented for the raw pointer types // Not sure if there's a cleaner way to guarantee this unsafe impl<P: FixedPointParameters> Send for ServerState<P> {} unsafe impl<P: FixedPointParameters> Sync for ServerState<P> {} pub struct ClientState<P: FixedPointParameters> { pub relu_circuits: Vec<GarbledCircuit>, pub relu_server_labels: Vec<Vec<Wire>>, pub relu_client_labels: Vec<Vec<Wire>>, pub relu_next_layer_randomizers: Vec<P::Field>, pub approx_state: Vec<Triple<P::Field>>, /// Randomizers for the input of a linear layer. pub linear_randomizer: BTreeMap<usize, Input<P::Field>>, /// Shares of the output of a linear layer pub linear_post_application_share: BTreeMap<usize, Output<AdditiveShare<P>>>, } pub struct NNProtocolType; // The final message from the server to the client, contains a share of the // output. pub type MsgSend<'a, P> = crate::OutMessage<'a, Output<AdditiveShare<P>>, NNProtocolType>; pub type MsgRcv<P> = crate::InMessage<Output<AdditiveShare<P>>, NNProtocolType>; /// ```markdown /// Client Server /// -------------------------------------------------------------------------- /// -------------------------------------------------------------------------- /// Offline: /// 1. Linear: /// 1. Sample randomizers r /// for each layer. /// /// ------- Enc(r) ------> /// 1. Sample randomness s_1. /// 2. Compute Enc(Mr + s_1) /// <--- Enc(Mr + s_1) --- /// 2. Store -(Mr + s1) /// /// 2. ReLU: /// 1. Sample online output randomizers s_2 /// 2. Garble ReLU circuit with s_2 as input. /// <-------- GC --------- /// 1. OT input: /// Mr_i + s_(1, i), /// r_{i + 1} /// <-------- OT --------> /// /// 3. Quadratic approx: /// <- Beaver's Triples -> /// /// -------------------------------------------------------------------------- /// /// Online: /// /// 1. Linear: /// -- x_i + r_i + s_{2, i} -> /// /// /// 1. Derandomize the input /// 1. Compute y_i = M(x_i + r_i) + s_{1, i} /// /// 2. ReLU: /// 2. Compute garbled labels for y_i /// <- garbled labels ----- /// 1. Evaluate garbled circuit, /// 2. Set next layer input to /// be output of GC. /// /// 3. Quad Approx /// ---- (multiplication protocol) ---- /// | | /// ▼ ▼ /// y_i + a a /// /// ------ y_i + a + r_i --> /// ``` impl<P: FixedPointParameters> NNProtocol<P> where <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { pub fn offline_server_protocol<R: Read + Send, W: Write + Send, RNG: CryptoRng + RngCore>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, neural_network: &NeuralNetwork<AdditiveShare<P>, FixedPoint<P>>, rng: &mut RNG, ) -> Result<ServerState<P>, bincode::Error> { let mut num_relu = 0; let mut num_approx = 0; let mut linear_state = BTreeMap::new(); let sfhe: ServerFHE = crate::server_keygen(reader)?; let start_time = timer_start!(|| "Server offline phase"); let linear_time = timer_start!(|| "Linear layers offline phase"); for (i, layer) in neural_network.layers.iter().enumerate() { match layer { Layer::NLL(NonLinearLayer::ReLU(dims)) => { let (b, c, h, w) = dims.input_dimensions(); num_relu += b * c * h * w; } Layer::NLL(NonLinearLayer::PolyApprox { dims, .. }) => { let (b, c, h, w) = dims.input_dimensions(); num_approx += b * c * h * w; } Layer::LL(layer) => { let randomizer = match &layer { LinearLayer::Conv2d { .. } | LinearLayer::FullyConnected { .. } => { let mut cg_handler = match &layer { LinearLayer::Conv2d { .. } => SealServerCG::Conv2D( server_cg::Conv2D::new(&sfhe, layer, &layer.kernel_to_repr()), ), LinearLayer::FullyConnected { .. } => { SealServerCG::FullyConnected(server_cg::FullyConnected::new( &sfhe, layer, &layer.kernel_to_repr(), )) } _ => unreachable!(), }; LinearProtocol::<P>::offline_server_protocol( reader, writer, layer.input_dimensions(), layer.output_dimensions(), &mut cg_handler, rng, )? } // AvgPool and Identity don't require an offline phase LinearLayer::AvgPool { dims, .. } => { Output::zeros(dims.output_dimensions()) } LinearLayer::Identity { dims } => Output::zeros(dims.output_dimensions()), }; linear_state.insert(i, randomizer); } } } timer_end!(linear_time); let relu_time = timer_start!(|| format!("ReLU layers offline phase, with {:?} activations", num_relu)); let crate::gc::ServerState { encoders: relu_encoders, output_randomizers: relu_output_randomizers, } = ReluProtocol::<P>::offline_server_protocol(reader, writer, num_relu, rng)?; timer_end!(relu_time); let approx_time = timer_start!(|| format!( "Approx layers offline phase, with {:?} activations", num_approx )); let approx_state = QuadApproxProtocol::offline_server_protocol::<FPBeaversMul<P>, _, _, _>( reader, writer, &sfhe, num_approx, rng, )?; timer_end!(approx_time); timer_end!(start_time); Ok(ServerState { linear_state, relu_encoders, relu_output_randomizers, approx_state, }) } pub fn offline_client_protocol<R: Read + Send, W: Write + Send, RNG: RngCore + CryptoRng>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, neural_network_architecture: &NeuralArchitecture<AdditiveShare<P>, FixedPoint<P>>, rng: &mut RNG, ) -> Result<ClientState<P>, bincode::Error> { let mut num_relu = 0; let mut num_approx = 0; let mut in_shares = BTreeMap::new(); let mut out_shares = BTreeMap::new(); let mut relu_layers = Vec::new(); let mut approx_layers = Vec::new(); let cfhe: ClientFHE = crate::client_keygen(writer)?; let start_time = timer_start!(|| "Client offline phase"); let linear_time = timer_start!(|| "Linear layers offline phase"); for (i, layer) in neural_network_architecture.layers.iter().enumerate() { match layer { LayerInfo::NLL(dims, NonLinearLayerInfo::ReLU) => { relu_layers.push(i); let (b, c, h, w) = dims.input_dimensions(); num_relu += b * c * h * w; } LayerInfo::NLL(dims, NonLinearLayerInfo::PolyApprox { .. }) => { approx_layers.push(i); let (b, c, h, w) = dims.input_dimensions(); num_approx += b * c * h * w; } LayerInfo::LL(dims, linear_layer_info) => { let input_dims = dims.input_dimensions(); let output_dims = dims.output_dimensions(); let (in_share, mut out_share) = match &linear_layer_info { LinearLayerInfo::Conv2d { .. } | LinearLayerInfo::FullyConnected => { let mut cg_handler = match &linear_layer_info { LinearLayerInfo::Conv2d { .. } => { SealClientCG::Conv2D(client_cg::Conv2D::new( &cfhe, linear_layer_info, input_dims, output_dims, )) } LinearLayerInfo::FullyConnected => { SealClientCG::FullyConnected(client_cg::FullyConnected::new( &cfhe, linear_layer_info, input_dims, output_dims, )) } _ => unreachable!(), }; LinearProtocol::<P>::offline_client_protocol( reader, writer, layer.input_dimensions(), layer.output_dimensions(), &mut cg_handler, rng, )? } _ => { // AvgPool and Identity don't require an offline communication if out_shares.keys().any(|k| k == &(i - 1)) { // If the layer comes after a linear layer, apply the function to // the last layer's output share let prev_output_share = out_shares.get(&(i - 1)).unwrap(); let mut output_share = Output::zeros(dims.output_dimensions()); linear_layer_info .evaluate_naive(prev_output_share, &mut output_share); (Input::zeros(dims.input_dimensions()), output_share) } else { // Otherwise, just return randomizers of 0 ( Input::zeros(dims.input_dimensions()), Output::zeros(dims.output_dimensions()), ) } } }; // We reduce here becase the input to future layers requires // shares to already be reduced correctly; for example, // `online_server_protocol` reduces at the end of each layer. for share in &mut out_share { share.inner.signed_reduce_in_place(); } // r in_shares.insert(i, in_share); // -(Lr + s) out_shares.insert(i, out_share); } } } timer_end!(linear_time); // Preprocessing for next step with ReLUs; if a ReLU is layer i, // we want to take output shares for the (linear) layer i - 1, // and input shares for the (linear) layer i + 1. let mut current_layer_shares = Vec::new(); let mut relu_next_layer_randomizers = Vec::new(); let relu_time = timer_start!(|| format!("ReLU layers offline phase with {} ReLUs", num_relu)); for &i in &relu_layers { let current_layer_output_shares = out_shares .get(&(i - 1)) .expect("should exist because every ReLU should be preceeded by a linear layer"); current_layer_shares.extend_from_slice(current_layer_output_shares.as_slice().unwrap()); let next_layer_randomizers = in_shares .get(&(i + 1)) .expect("should exist because every ReLU should be succeeded by a linear layer"); relu_next_layer_randomizers .extend_from_slice(next_layer_randomizers.as_slice().unwrap()); } let crate::gc::ClientState { gc_s: relu_circuits, server_randomizer_labels: randomizer_labels, client_input_labels: relu_labels, } = ReluProtocol::<P>::offline_client_protocol( reader, writer, num_relu, current_layer_shares.as_slice(), rng, )?; let (relu_client_labels, relu_server_labels) = if num_relu != 0 { let size_of_client_input = relu_labels.len() / num_relu; let size_of_server_input = randomizer_labels.len() / num_relu; assert_eq!( size_of_client_input, ReluProtocol::<P>::size_of_client_inputs(), "number of inputs unequal" ); let client_labels = relu_labels .chunks(size_of_client_input) .map(|chunk| chunk.to_vec()) .collect(); let server_labels = randomizer_labels .chunks(size_of_server_input) .map(|chunk| chunk.to_vec()) .collect(); (client_labels, server_labels) } else { (vec![], vec![]) }; timer_end!(relu_time); let approx_time = timer_start!(|| format!( "Approx layers offline phase with {} approximations", num_approx )); let approx_state = QuadApproxProtocol::offline_client_protocol::<FPBeaversMul<P>, _, _, _>( reader, writer, &cfhe, num_approx, rng, )?; timer_end!(approx_time); timer_end!(start_time); Ok(ClientState { relu_circuits, relu_server_labels, relu_client_labels, relu_next_layer_randomizers, approx_state, linear_randomizer: in_shares, linear_post_application_share: out_shares, }) } pub fn online_server_protocol<R: Read + Send, W: Write + Send + Send>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, neural_network: &NeuralNetwork<AdditiveShare<P>, FixedPoint<P>>, state: &ServerState<P>, ) -> Result<(), bincode::Error> { let (first_layer_in_dims, first_layer_out_dims) = { let layer = neural_network.layers.first().unwrap(); assert!( layer.is_linear(), "first layer of the network should always be linear." ); (layer.input_dimensions(), layer.output_dimensions()) }; let mut num_consumed_relus = 0; let mut num_consumed_triples = 0; let mut next_layer_input = Output::zeros(first_layer_out_dims); let mut next_layer_derandomizer = Input::zeros(first_layer_in_dims); let start_time = timer_start!(|| "Server online phase"); for (i, layer) in neural_network.layers.iter().enumerate() { match layer { Layer::NLL(NonLinearLayer::ReLU(dims)) => { let start_time = timer_start!(|| "ReLU layer"); // Have the server encode the current input, via the garbled circuit, // and then send the labels over to the other party. let layer_size = next_layer_input.len(); assert_eq!(dims.input_dimensions(), next_layer_input.dim()); let layer_encoders = &state.relu_encoders[num_consumed_relus..(num_consumed_relus + layer_size)]; ReluProtocol::online_server_protocol( writer, &next_layer_input.as_slice().unwrap(), layer_encoders, )?; let relu_output_randomizers = state.relu_output_randomizers [num_consumed_relus..(num_consumed_relus + layer_size)] .to_vec(); num_consumed_relus += layer_size; next_layer_derandomizer = ndarray::Array1::from_iter(relu_output_randomizers) .into_shape(dims.output_dimensions()) .expect("shape should be correct") .into(); timer_end!(start_time); } Layer::NLL(NonLinearLayer::PolyApprox { dims, poly, .. }) => { let start_time = timer_start!(|| "Approx layer"); let layer_size = next_layer_input.len(); assert_eq!(dims.input_dimensions(), next_layer_input.dim()); let triples = &state.approx_state [num_consumed_triples..(num_consumed_triples + layer_size)]; num_consumed_triples += layer_size; let shares_of_eval = QuadApproxProtocol::online_server_protocol::<FPBeaversMul<P>, _, _>( SERVER, // party_index: 2 reader, writer, &poly, next_layer_input.as_slice().unwrap(), triples, )?; let shares_of_eval: Vec<_> = shares_of_eval.into_iter().map(|s| s.inner.inner).collect(); next_layer_derandomizer = ndarray::Array1::from_iter(shares_of_eval) .into_shape(dims.output_dimensions()) .expect("shape should be correct") .into(); timer_end!(start_time); } Layer::LL(layer) => { let start_time = timer_start!(|| "Linear layer"); // Input for the next layer. let layer_randomizer = state.linear_state.get(&i).unwrap(); // The idea here is that the previous layer was linear. // Hence the input we're receiving from the client is if i != 0 && neural_network.layers.get(i - 1).unwrap().is_linear() { next_layer_derandomizer .iter_mut() .zip(&next_layer_input) .for_each(|(l_r, inp)| { *l_r += &inp.inner.inner; }); } next_layer_input = Output::zeros(layer.output_dimensions()); LinearProtocol::online_server_protocol( reader, layer, layer_randomizer, &next_layer_derandomizer, &mut next_layer_input, )?; next_layer_derandomizer = Output::zeros(layer.output_dimensions()); // Since linear operations involve multiplications // by fixed-point constants, we want to truncate here to // ensure that we don't overflow. for share in next_layer_input.iter_mut() { share.inner.signed_reduce_in_place(); } timer_end!(start_time); } } } let sent_message = MsgSend::new(&next_layer_input); crate::bytes::serialize(writer, &sent_message)?; timer_end!(start_time); Ok(()) } /// Outputs shares for the next round's input. pub fn online_client_protocol<R: Read + Send, W: Write + Send + Send>( reader: &mut IMuxSync<R>, writer: &mut IMuxSync<W>, input: &Input<FixedPoint<P>>, architecture: &NeuralArchitecture<AdditiveShare<P>, FixedPoint<P>>, state: &ClientState<P>, ) -> Result<Output<FixedPoint<P>>, bincode::Error> { let first_layer_in_dims = { let layer = architecture.layers.first().unwrap(); assert!( layer.is_linear(), "first layer of the network should always be linear." ); assert_eq!(layer.input_dimensions(), input.dim()); layer.input_dimensions() }; assert_eq!(first_layer_in_dims, input.dim()); let mut num_consumed_relus = 0; let mut num_consumed_triples = 0; let start_time = timer_start!(|| "Client online phase"); let (mut next_layer_input, _) = input.share_with_randomness(&state.linear_randomizer[&0]); for (i, layer) in architecture.layers.iter().enumerate() { match layer { LayerInfo::NLL(dims, nll_info) => { match nll_info { NonLinearLayerInfo::ReLU => { let start_time = timer_start!(|| "ReLU layer"); // The client receives the garbled circuits from the server, // uses its already encoded inputs to get the next linear // layer's input. let layer_size = next_layer_input.len(); assert_eq!(dims.input_dimensions(), next_layer_input.dim()); let layer_client_labels = &state.relu_client_labels [num_consumed_relus..(num_consumed_relus + layer_size)]; let layer_server_labels = &state.relu_server_labels [num_consumed_relus..(num_consumed_relus + layer_size)]; let next_layer_randomizers = &state.relu_next_layer_randomizers [num_consumed_relus..(num_consumed_relus + layer_size)]; let layer_circuits = &state.relu_circuits [num_consumed_relus..(num_consumed_relus + layer_size)]; num_consumed_relus += layer_size; let layer_client_labels = layer_client_labels .into_iter() .flat_map(|l| l.clone()) .collect::<Vec<_>>(); let layer_server_labels = layer_server_labels .into_iter() .flat_map(|l| l.clone()) .collect::<Vec<_>>(); let output = ReluProtocol::online_client_protocol( reader, layer_size, // num_relus &layer_server_labels, // Labels for layer &layer_client_labels, // Labels for layer &layer_circuits, // circuits for layer. &next_layer_randomizers, // circuits for layer. )?; next_layer_input = ndarray::Array1::from_iter(output) .into_shape(dims.output_dimensions()) .expect("shape should be correct") .into(); timer_end!(start_time); } NonLinearLayerInfo::PolyApprox { poly, .. } => { let start_time = timer_start!(|| "Approx layer"); let layer_size = next_layer_input.len(); assert_eq!(dims.input_dimensions(), next_layer_input.dim()); let triples = &state.approx_state [num_consumed_triples..(num_consumed_triples + layer_size)]; num_consumed_triples += layer_size; let output = QuadApproxProtocol::online_client_protocol::< FPBeaversMul<P>, _, _, >( CLIENT, // party_index: 1 reader, writer, &poly, next_layer_input.as_slice().unwrap(), triples, )?; next_layer_input = ndarray::Array1::from_iter(output) .into_shape(dims.output_dimensions()) .expect("shape should be correct") .into(); next_layer_input .randomize_local_share(&state.linear_randomizer[&(i + 1)]); timer_end!(start_time); } } } LayerInfo::LL(_, layer_info) => { let start_time = timer_start!(|| "Linear layer"); // Send server secret share if required by the layer let input = next_layer_input; next_layer_input = state.linear_post_application_share[&i].clone(); LinearProtocol::online_client_protocol( writer, &input, &layer_info, &mut next_layer_input, )?; // If this is not the last layer, and if the next layer // is also linear, randomize the output correctly. if i != (architecture.layers.len() - 1) && architecture.layers[i + 1].is_linear() { next_layer_input.randomize_local_share(&state.linear_randomizer[&(i + 1)]); } timer_end!(start_time); } } } let result = crate::bytes::deserialize(reader).map(|output: MsgRcv<P>| { let server_output_share = output.msg(); server_output_share.combine(&next_layer_input) })?; timer_end!(start_time); Ok(result) } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/bytes.rs
rust/algebra/src/bytes.rs
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::io::{Read, Result as IoResult, Write}; pub trait ToBytes { /// Serializes `self` into `writer`. fn write<W: Write>(&self, writer: W) -> IoResult<()>; } pub trait FromBytes: Sized { /// Reads `Self` from `reader`. fn read<R: Read>(reader: R) -> IoResult<Self>; } macro_rules! array_bytes { ($N:expr) => { impl ToBytes for [u8; $N] { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { writer.write_all(self) } } impl FromBytes for [u8; $N] { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { let mut arr = [0u8; $N]; reader.read_exact(&mut arr)?; Ok(arr) } } impl ToBytes for [u16; $N] { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { for num in self { writer.write_u16::<LittleEndian>(*num)?; } Ok(()) } } impl FromBytes for [u16; $N] { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { let mut res = [0u16; $N]; reader.read_u16_into::<LittleEndian>(&mut res)?; Ok(res) } } impl ToBytes for [u32; $N] { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { for num in self { writer.write_u32::<LittleEndian>(*num)?; } Ok(()) } } impl FromBytes for [u32; $N] { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { let mut res = [0u32; $N]; reader.read_u32_into::<LittleEndian>(&mut res)?; Ok(res) } } impl ToBytes for [u64; $N] { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { for num in self { writer.write_u64::<LittleEndian>(*num)?; } Ok(()) } } impl FromBytes for [u64; $N] { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { let mut res = [0u64; $N]; reader.read_u64_into::<LittleEndian>(&mut res)?; Ok(res) } } }; } array_bytes!(0); array_bytes!(1); array_bytes!(2); array_bytes!(3); array_bytes!(4); array_bytes!(5); array_bytes!(6); array_bytes!(7); array_bytes!(8); array_bytes!(9); array_bytes!(10); array_bytes!(11); array_bytes!(12); array_bytes!(13); array_bytes!(14); array_bytes!(15); array_bytes!(16); array_bytes!(17); array_bytes!(18); array_bytes!(19); array_bytes!(20); array_bytes!(21); array_bytes!(22); array_bytes!(23); array_bytes!(24); array_bytes!(25); array_bytes!(26); array_bytes!(27); array_bytes!(28); array_bytes!(29); array_bytes!(30); array_bytes!(31); array_bytes!(32); /// Takes as input a sequence of structs, and converts them to a series of /// bytes. All traits that implement `Bytes` can be automatically converted to /// bytes in this manner. #[macro_export] macro_rules! to_bytes { ($($x:expr),*) => ({ use std::io::Cursor; let mut buf = Cursor::new(vec![0u8; 1]); {$crate::push_to_vec!(buf, $($x),*)}.map(|_| buf.into_inner()) }); } #[macro_export] macro_rules! push_to_vec { ($buf:expr, $y:expr, $($x:expr),*) => ({ { ToBytes::write(&$y, &mut $buf) }.and({$crate::push_to_vec!($buf, $($x),*)}) }); ($buf:expr, $x:expr) => ({ ToBytes::write(&$x, &mut $buf) }) } impl ToBytes for u8 { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { writer.write_u8(*self) } } impl FromBytes for u8 { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { reader.read_u8() } } impl ToBytes for u16 { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { writer.write_u16::<LittleEndian>(*self) } } impl FromBytes for u16 { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { reader.read_u16::<LittleEndian>() } } impl ToBytes for u32 { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { writer.write_u32::<LittleEndian>(*self) } } impl FromBytes for u32 { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { reader.read_u32::<LittleEndian>() } } impl ToBytes for u64 { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { writer.write_u64::<LittleEndian>(*self) } } impl FromBytes for u64 { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { reader.read_u64::<LittleEndian>() } } impl ToBytes for () { #[inline] fn write<W: Write>(&self, _writer: W) -> IoResult<()> { Ok(()) } } impl FromBytes for () { #[inline] fn read<R: Read>(_bytes: R) -> IoResult<Self> { Ok(()) } } impl ToBytes for bool { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { u8::write(&(*self as u8), writer) } } impl FromBytes for bool { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { match u8::read(reader) { Ok(0) => Ok(false), Ok(1) => Ok(true), Ok(_) => Err(::std::io::ErrorKind::Other.into()), Err(err) => Err(err), } } } impl<T: ToBytes> ToBytes for [T] { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { for item in self { item.write(&mut writer)?; } Ok(()) } } impl<T: ToBytes> ToBytes for Vec<T> { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { for item in self { item.write(&mut writer)?; } Ok(()) } } impl<'a, T: 'a + ToBytes> ToBytes for &'a [T] { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { for item in *self { item.write(&mut writer)?; } Ok(()) } } impl<'a, T: 'a + ToBytes> ToBytes for &'a T { #[inline] fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { (*self).write(&mut writer) } } impl FromBytes for Vec<u8> { #[inline] fn read<R: Read>(mut reader: R) -> IoResult<Self> { let mut buf = Vec::new(); let _ = reader.read_to_end(&mut buf)?; Ok(buf) } } #[cfg(test)] mod test { use super::ToBytes; #[test] fn test_macro() { let array1 = [1u8; 32]; let array2 = [2u8; 16]; let array3 = [3u8; 8]; let bytes = to_bytes![array1, array2, array3].unwrap(); assert_eq!(bytes.len(), 56); let mut actual_bytes = Vec::new(); actual_bytes.extend_from_slice(&array1); actual_bytes.extend_from_slice(&array2); actual_bytes.extend_from_slice(&array3); assert_eq!(bytes, actual_bytes); } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/lib.rs
rust/algebra/src/lib.rs
#![deny( unused_import_braces, unused_qualifications, trivial_casts, trivial_numeric_casts )] #![deny(unused_qualifications, variant_size_differences, stable_features)] #![deny( non_shorthand_field_patterns, unused_attributes, unused_imports, unused_extern_crates )] #![deny( renamed_and_removed_lints, stable_features, unused_allocation, unused_comparisons )] #![deny( unused_must_use, unused_mut, unused_unsafe, private_in_public, unsafe_code )] #![deny(unsafe_code)] #[macro_use] extern crate derivative; use rand::{CryptoRng, RngCore}; #[cfg_attr(test, macro_use)] pub mod bytes; pub use self::bytes::*; pub mod biginteger; pub use self::biginteger::*; pub mod fields; pub use self::fields::*; pub mod fixed_point; pub use fixed_point::*; pub mod polynomial; pub use polynomial::*; pub trait UniformRandom { /// Samples a uniformly random field element. fn uniform<R: RngCore + CryptoRng>(r: &mut R) -> Self; }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fixed_point.rs
rust/algebra/src/fixed_point.rs
use derivative::Derivative; use num_traits::{One, Zero}; use serde::{Deserialize, Serialize}; use std::{ fmt::{Display, Formatter, Result as FmtResult}, marker::PhantomData, ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, }; use crate::{ biginteger::BigInteger, fields::{Field, FpParameters, PrimeField}, UniformRandom, }; use rand::{CryptoRng, RngCore}; /// `FixedPointParameters` represents the parameters for a fixed-point number. /// `MANTISSA_CAPACITY + EXPONENT_CAPACITY` must be less than 64. pub trait FixedPointParameters: Send + Sync { type Field: PrimeField; const MANTISSA_CAPACITY: u8; const EXPONENT_CAPACITY: u8; fn truncate_float(f: f64) -> f64 { let max_exp = f64::from(1 << Self::EXPONENT_CAPACITY); (f * max_exp).round() / max_exp } } #[derive(Derivative, Serialize, Deserialize)] #[derivative( Default(bound = "P: FixedPointParameters"), Hash(bound = "P: FixedPointParameters"), Clone(bound = "P: FixedPointParameters"), Copy(bound = "P: FixedPointParameters"), Debug(bound = "P: FixedPointParameters"), Eq(bound = "P: FixedPointParameters") )] #[serde(bound = "P: FixedPointParameters")] #[must_use] pub struct FixedPoint<P: FixedPointParameters> { pub inner: P::Field, num_muls: u8, #[serde(skip)] #[derivative(Debug = "ignore")] _params: PhantomData<P>, } impl<P: FixedPointParameters> Zero for FixedPoint<P> { fn zero() -> Self { Self::zero() } fn is_zero(&self) -> bool { self.is_zero() } } impl<P: FixedPointParameters> One for FixedPoint<P> { fn one() -> Self { Self::one() } fn is_one(&self) -> bool { self.is_one() } } impl<P: FixedPointParameters> FixedPoint<P> { #[inline] pub fn new(inner: P::Field) -> Self { Self::with_num_muls(inner, 0) } #[inline] pub fn with_num_muls(inner: P::Field, num_muls: u8) -> Self { if Self::max_mul_capacity() < 1 { panic!( "cannot multiply or add because `P::MANTISSA_CAPACITY + P::EXPONENT_CAPACITY` is \ too large." ); } Self { inner, num_muls, _params: PhantomData, } } #[inline] pub fn uniform<R: RngCore + CryptoRng>(r: &mut R) -> Self { Self::new(P::Field::uniform(r)) } #[inline] pub fn truncate_float(f: f64) -> f64 { P::truncate_float(f) } #[inline] pub fn is_negative(&self) -> bool { let cur = self.inner.into_repr(); let modulus_div_2 = <P::Field as PrimeField>::Params::MODULUS_MINUS_ONE_DIV_TWO; cur >= modulus_div_2 } // We divide the space in half, with the top half representing negative numbers, // and the bottom half representing positive numbers. #[inline] const fn inner_capacity() -> u8 { (<P::Field as PrimeField>::Params::CAPACITY - 1) as u8 } #[inline] const fn max_mul_capacity() -> u8 { Self::inner_capacity() / Self::size_in_bits() } #[inline] pub const fn num_muls(&self) -> u8 { self.num_muls } #[inline] const fn remaining_mul_capacity(&self) -> u8 { Self::max_mul_capacity() - self.num_muls } #[inline] pub const fn should_reduce(&self) -> bool { // Will multiplying further cause overflow? self.num_muls == Self::max_mul_capacity() } #[inline] pub const fn size_in_bits() -> u8 { P::MANTISSA_CAPACITY + P::EXPONENT_CAPACITY } #[inline] pub fn zero() -> Self { Self::new(P::Field::zero()) } #[inline] pub fn one() -> Self { let mut one_repr = P::Field::one().into_repr(); one_repr.muln(P::EXPONENT_CAPACITY as u32); let one = P::Field::from_repr(one_repr); Self { inner: one, num_muls: 0, _params: PhantomData, } } #[inline] pub fn is_zero(&self) -> bool { self.inner.is_zero() } #[inline] pub fn is_one(&self) -> bool { *self == Self::one() } #[inline] pub fn double(&self) -> Self { let mut result = *self; result.double_in_place(); result } #[inline] pub fn double_in_place(&mut self) -> &mut Self { self.inner.double_in_place(); self } #[inline] pub fn signed_reduce(&self) -> Self { let mut result = *self; result.signed_reduce_in_place(); result } #[inline] pub fn signed_reduce_in_place(&mut self) -> &mut Self { let cur_is_neg = self.is_negative(); if cur_is_neg { *self = -*self; } self.reduce_in_place(); if cur_is_neg { *self = -*self; } self } #[inline] pub fn signed_truncate_by(&self, by: usize) -> Self { let mut result = *self; result.signed_truncate_by_in_place(by); result } #[inline] pub fn signed_truncate_by_in_place(&mut self, by: usize) -> &mut Self { let cur_is_neg = self.is_negative(); if cur_is_neg { *self = -*self; } self.truncate_in_place(by); if cur_is_neg { *self = -*self; } self } #[inline] fn reduce_in_place(&mut self) { self.truncate_in_place(usize::from(self.num_muls * P::EXPONENT_CAPACITY)); } #[inline] fn truncate_in_place(&mut self, n_bits: usize) -> &mut Self { let mut repr = self.inner.into_repr(); // We should shift down by the number of consumed bits, leaving only // the top (P::MANTISSA_CAPACITY + P::EXPONENT_CAPACITY) bits. repr.divn((n_bits) as u32); self.inner = P::Field::from_repr(repr); self.num_muls = 0; self } } pub fn discretized_cos<P: FixedPointParameters>(inp: FixedPoint<P>) -> FixedPoint<P> { let mut sum = FixedPoint::zero(); for i in 0..4 { let mut res = inp.signed_truncate_by(i); for _ in 0..i { res.inner.double_in_place(); } if i % 2 == 0 { sum.inner += &res.inner; } else { sum.inner -= &res.inner; } } // let mut smallest = FixedPoint::one(); // smallest.truncate_in_place(usize::from(P::EXPONENT_CAPACITY - 1)); // (sum.signed_truncate_by(7)).double() // sum // TODO: fix for arbitrary sizes (mostly wrt doubling) sum.signed_truncate_by(2) } impl<P: FixedPointParameters> Display for FixedPoint<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "{}", f64::from(*self)) } } impl<P: FixedPointParameters> Add for FixedPoint<P> { type Output = Self; #[inline] fn add(mut self, mut other: Self) -> Self { if self.num_muls > other.num_muls { let shift = (self.num_muls - other.num_muls) * P::EXPONENT_CAPACITY; for _ in 0..shift { other.double_in_place(); } other.num_muls = self.num_muls; self + other } else if other.num_muls > self.num_muls { other + self } else { self.inner += &other.inner; self } } } impl<P: FixedPointParameters> AddAssign for FixedPoint<P> { #[inline] fn add_assign(&mut self, other: Self) { *self = *self + other } } impl<P: FixedPointParameters> Sub for FixedPoint<P> { type Output = Self; #[inline] fn sub(mut self, mut other: Self) -> Self { if self.num_muls > other.num_muls { let mut other_repr = other.inner.into_repr(); let shift = (self.num_muls - other.num_muls) * P::EXPONENT_CAPACITY; other_repr.muln(shift.into()); other = Self::new(P::Field::from_repr(other_repr)); other.num_muls = self.num_muls; self - other } else if other.num_muls > self.num_muls { -(other - self) } else { self.inner -= &other.inner; self } } } impl<P: FixedPointParameters> SubAssign for FixedPoint<P> { #[inline] fn sub_assign(&mut self, other: Self) { *self = *self - other } } impl<P: FixedPointParameters> Neg for FixedPoint<P> { type Output = Self; #[inline] fn neg(mut self) -> Self { self.inner = -self.inner; self } } impl<P: FixedPointParameters> Mul for FixedPoint<P> { type Output = Self; #[inline] fn mul(mut self, mut other: Self) -> Self { if self.remaining_mul_capacity() > other.num_muls { self.inner *= &other.inner; self.num_muls += other.num_muls + 1; self } else if other.remaining_mul_capacity() > self.num_muls { other * self } else { // self.num_muls + other.num_muls > Self::max_mul_capacity() // That is, multiplying will overflow and wrap around. if other.remaining_mul_capacity() < self.remaining_mul_capacity() { other.signed_reduce_in_place(); other * self } else { self.signed_reduce_in_place(); self * other } } } } impl<P: FixedPointParameters> MulAssign for FixedPoint<P> { #[inline] fn mul_assign(&mut self, other: Self) { *self = *self * other } } impl<P: FixedPointParameters> From<f64> for FixedPoint<P> { #[inline] fn from(other: f64) -> Self { if other.is_nan() { panic!("other is NaN: {:?}", other); } let val = (other.abs() * f64::from(1u32 << P::EXPONENT_CAPACITY)).round() as u64; let val = <P::Field as PrimeField>::BigInt::from(val); let mut val = P::Field::from_repr(val); if other.is_sign_negative() { val = -val } Self::new(val) } } impl<P: FixedPointParameters> From<f32> for FixedPoint<P> { #[inline] fn from(other: f32) -> Self { f64::from(other).into() } } impl<P: FixedPointParameters> From<FixedPoint<P>> for f64 { #[inline] fn from(mut other: FixedPoint<P>) -> Self { let is_negative = other.is_negative(); if is_negative { other = -other } other.reduce_in_place(); let inner = other.inner.into_repr(); let mut inner = inner.into_iter(); let len = inner.size_hint().0; let first = inner.next(); if len == 1 || inner.all(|e| e == 0) { let ans = (first.unwrap() as f64) / f64::from(1 << P::EXPONENT_CAPACITY); if is_negative { -ans } else { ans } } else { panic!("other is too large to fit in f64 {:?}", other) } } } impl<P: FixedPointParameters> From<FixedPoint<P>> for f32 { #[inline] fn from(other: FixedPoint<P>) -> Self { f64::from(other) as f32 } } pub struct FPIterator<F: FixedPointParameters> { int: <<F::Field as PrimeField>::BigInt as IntoIterator>::IntoIter, } impl<F: FixedPointParameters> Iterator for FPIterator<F> { type Item = u64; fn next(&mut self) -> Option<Self::Item> { self.int.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.int.size_hint() } } impl<F: FixedPointParameters> ExactSizeIterator for FPIterator<F> {} impl<F: FixedPointParameters> IntoIterator for FixedPoint<F> { type Item = u64; type IntoIter = FPIterator<F>; #[inline] fn into_iter(self) -> Self::IntoIter { Self::IntoIter { int: self.inner.into_repr().into_iter(), } } } impl<F: FixedPointParameters> std::iter::FromIterator<u64> for FixedPoint<F> { /// Creates a FixedPoint from an iterator over limbs in little-endian order #[inline] fn from_iter<I: IntoIterator<Item = u64>>(iter: I) -> Self { let big_int = <F::Field as PrimeField>::BigInt::from_iter(iter); Self::new(F::Field::from_repr(big_int)) } } impl<P: FixedPointParameters> PartialEq for FixedPoint<P> { #[inline] fn eq(&self, other: &Self) -> bool { let cur_is_neg = self.is_negative(); let other_is_neg = other.is_negative(); if cur_is_neg ^ other_is_neg { false } else { let mut cur = if cur_is_neg { -*self } else { *self }; let mut other = if other_is_neg { -*other } else { *other }; cur.reduce_in_place(); other.reduce_in_place(); let cur_repr = cur.inner.into_repr(); let other_repr = other.inner.into_repr(); let cur = cur_repr.into_iter().next().unwrap(); let other = other_repr.into_iter().next().unwrap(); cur.checked_sub(other) .map_or_else(|| (other - cur) <= 1, |res| res <= 1) } } } impl<P: FixedPointParameters> PartialOrd for FixedPoint<P> { #[inline] fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { use std::cmp::Ordering; let cur_is_neg = self.is_negative(); let other_is_neg = other.is_negative(); if cur_is_neg && !other_is_neg { Some(Ordering::Less) } else if !cur_is_neg && other_is_neg { Some(Ordering::Greater) } else { let mut cur = if cur_is_neg { -*self } else { *self }; let mut other = if other_is_neg { -*other } else { *other }; cur.reduce_in_place(); other.reduce_in_place(); let cur_repr = cur.inner.into_repr(); let other_repr = other.inner.into_repr(); let cur = cur_repr.into_iter().next().unwrap(); let other = other_repr.into_iter().next().unwrap(); if cur .checked_sub(other) .map_or_else(|| (other - cur) <= 1, |res| res <= 1) { Some(Ordering::Equal) } else { cur_repr.partial_cmp(&other_repr) } } } } impl<P: FixedPointParameters> Ord for FixedPoint<P> { #[inline] fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.partial_cmp(other).unwrap() } } impl<P: FixedPointParameters> Into<u64> for FixedPoint<P> where <P::Field as PrimeField>::Params: crate::Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { #[inline] fn into(self) -> u64 { self.inner.into_repr().into() } } #[cfg(test)] mod tests { use super::*; use crate::fields::near_mersenne_64::F; use rand::{Rng, SeedableRng}; use rand_chacha::ChaChaRng; struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 5; const EXPONENT_CAPACITY: u8 = 5; } type TenBitExpFP = FixedPoint<TenBitExpParams>; const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mut mul = if is_neg { -10.0 } else { 10.0 }; let is_hundreds: bool = rng.gen(); mul *= if is_hundreds { 10.0 } else { 1.0 }; let float: f64 = rng.gen(); let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } #[test] fn test_from_float() { let num_float = 17.5; let num_fixed = TenBitExpFP::from(num_float); let num_fixed_double = TenBitExpFP::from(num_float * 2.0); let one = TenBitExpFP::one(); let two = one + one; let num_plus_one_fixed = TenBitExpFP::from(num_float + 1.0); let neg_num = TenBitExpFP::from(-num_float); assert_eq!(num_plus_one_fixed, one + num_fixed); assert_eq!(num_fixed + num_fixed, num_fixed_double); assert_eq!(num_fixed.double(), num_fixed_double); assert_eq!(num_fixed * two, num_fixed_double); assert_eq!(num_fixed + neg_num, TenBitExpFP::zero()); } #[test] fn test_double() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..1000 { let (f1, n1) = generate_random_number(&mut rng); let f2 = f1 * 2.0; let n2 = TenBitExpFP::from(f2); let error_msg = format!("test failed with f1 = {:?}, f2 = {:?}", f1, f2,); assert_eq!(n1.double(), n2, "{}", error_msg); } } #[test] fn test_is_negative() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..1000 { let (f, n) = generate_random_number(&mut rng); let error_msg = format!("test failed with f = {:?}, n = {}", f, n); let f_is_neg = f.is_sign_negative() & (f != 0.0); assert_eq!(f_is_neg, n.is_negative(), "{}", error_msg); } } #[test] fn test_neg() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..1000 { let (f1, n1) = generate_random_number(&mut rng); let f2 = -f1; let n2 = TenBitExpFP::from(f2); let error_msg = format!("test failed with f1 = {:?}, f2 = {:?}", f1, f2,); assert_eq!(-n1, n2, "{}", error_msg); } } #[test] fn test_add() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..1000 { let (f1, n1) = generate_random_number(&mut rng); let (f2, n2) = generate_random_number(&mut rng); let f3 = f1 + f2; let n3 = TenBitExpFP::from(f3); let error_msg = format!( "test failed with f1 = {:?}, f2 = {:?}, f3 = {:?}", f1, f2, f3 ); assert_eq!(n1 + n2, n3, "{}", error_msg); } } #[test] fn test_sub() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..1000 { let (f1, n1) = generate_random_number(&mut rng); let (f2, n2) = generate_random_number(&mut rng); let f3 = f1 - f2; let n3 = TenBitExpFP::from(f3); let error_msg = format!( "test failed with\nf1 = {:?}, f2 = {:?}, f3 = {:?}\nn1 = {}, n2 = {}, n3 = {}\n", f1, f2, f3, n1, n2, n3, ); assert_eq!(n1 - n2, n3, "{}", error_msg); } } #[test] fn test_mul() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..1000 { let (f1, n1) = generate_random_number(&mut rng); let (f2, n2) = generate_random_number(&mut rng); let f3 = TenBitExpFP::truncate_float(f1 * f2); let n3 = TenBitExpFP::from(f3); let error_msg = format!( "test failed with\nf1 = {:?}, f2 = {:?}, f3 = {:?}\nn1 = {}, n2 = {}, n3 = {}\n", f1, f2, f3, n1, n2, n3, ); assert_eq!(n1 * n2, n3, "{}", error_msg); } } #[test] fn test_reduce_positive() { let one = TenBitExpFP::one(); assert_eq!(one, one * one, "one is not equal to 1 * 1"); let reduced_one = (one * one * one).signed_reduce(); assert_eq!(one, reduced_one); } #[test] fn test_reduce_neg() { let one = TenBitExpFP::one(); let neg_one = -one; assert_eq!( neg_one, one * neg_one, "negative one ({}) is not equal to -1 * 1 ({})", neg_one, one * neg_one, ); let reduced_neg_one = (-one * one * one).signed_reduce(); assert_eq!(neg_one, reduced_neg_one); } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/polynomial.rs
rust/algebra/src/polynomial.rs
use num_traits::{One, Zero}; use std::ops::{AddAssign, Mul, MulAssign}; /// A polynomial with coefficients in `F`. #[derive(Debug, Clone)] pub struct Polynomial<F> { coeffs: Vec<F>, } impl<C> Polynomial<C> { /// Constructs a new polynomial p(x) = a_0 + a_1 * x + ... + a_n x^n /// when given as inputs the coefficients `coeffs` /// such that `coeffs[i] = a_i`. pub fn new(coeffs: Vec<C>) -> Self { Self { coeffs } } pub fn evaluate<F>(&self, point: F) -> F where F: AddAssign + MulAssign + Mul<C, Output = F> + Zero + One + Copy, C: Copy, { let mut sum = F::zero(); let mut power = F::one(); for coeff in &self.coeffs { sum += power * (*coeff); power *= point; } sum } pub fn coeffs(&self) -> &[C] { &self.coeffs } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/utils.rs
rust/algebra/src/utils.rs
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/biginteger/bigint_32.rs
rust/algebra/src/biginteger/bigint_32.rs
use crate::{ biginteger::BigInteger, bytes::{FromBytes, ToBytes}, fields::BitIterator, }; use rand::{CryptoRng, Rng, RngCore}; use serde::{Deserialize, Serialize}; use std::{ fmt::Display, io::{Read, Result as IoResult, Write}, }; #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash, Serialize, Deserialize)] pub struct BigInteger32(pub u32); impl BigInteger32 { pub fn new(value: u32) -> Self { BigInteger32(value) } } impl BigInteger for BigInteger32 { #[inline] fn add_nocarry(&mut self, other: &Self) -> bool { let res = (self.0 as u64) + (other.0 as u64); let carry = (res & (1 << 33)) == 1; *self = BigInteger32(res as u32); carry } #[inline] fn sub_noborrow(&mut self, other: &Self) -> bool { let tmp = (1u64 << 32) + u64::from(self.0) - u64::from(other.0); let borrow = if tmp >> 32 == 0 { 1 } else { 0 }; *self = BigInteger32(tmp as u32); borrow == 1 } #[inline] fn mul2(&mut self) { *(&mut self.0) <<= 1; } #[inline] fn muln(&mut self, n: u32) { *(&mut self.0) <<= n; } #[inline] fn div2(&mut self) { *(&mut self.0) >>= 1; } #[inline] fn divn(&mut self, n: u32) { *(&mut self.0) >>= n; } #[inline] fn is_odd(&self) -> bool { self.0 & 1 == 1 } #[inline] fn is_even(&self) -> bool { !self.is_odd() } #[inline] fn is_zero(&self) -> bool { self.0 == 0 } #[inline] fn num_bits(&self) -> u32 { 32 - self.0.leading_zeros() } #[inline] fn from_bits(bits: &[bool]) -> Self { assert!(bits.len() <= 32); let mut acc: u32 = 0; let mut bits = bits.to_vec(); bits.reverse(); for bit in bits { acc <<= 1; acc += bit as u32; } Self::new(acc) } #[inline] fn to_bits(&self) -> Vec<bool> { let mut res = Vec::with_capacity(32); for b in BitIterator::new([self.0 as u64]) { res.push(b); } res } #[inline] fn find_wnaf(&self) -> Vec<i64> { vec![] } #[inline] fn uniform<R: RngCore + CryptoRng>(rng: &mut R) -> Self { BigInteger32(rng.gen()) } } impl std::iter::FromIterator<u64> for BigInteger32 { /// Creates a BigInteger from an iterator over limbs in little-endian order #[inline] fn from_iter<I: IntoIterator<Item = u64>>(iter: I) -> Self { let mut cur = Self::default(); let next = iter.into_iter().next().unwrap(); cur.0 = next as u32; cur } } impl ToBytes for BigInteger32 { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.0.write(writer) } } impl FromBytes for BigInteger32 { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { u32::read(reader).map(Self::new) } } pub struct IntoIter32 { int: BigInteger32, iterated: bool, } impl Iterator for IntoIter32 { type Item = u64; fn next(&mut self) -> Option<Self::Item> { if self.iterated { None } else { self.iterated = true; Some(self.int.0 as u64) } } fn size_hint(&self) -> (usize, Option<usize>) { (1, Some(1)) } } impl ExactSizeIterator for IntoIter32 {} impl IntoIterator for BigInteger32 { type Item = u64; type IntoIter = IntoIter32; #[inline] fn into_iter(self) -> Self::IntoIter { Self::IntoIter { int: self, iterated: false, } } } impl Display for BigInteger32 { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "0x")?; write!(f, "{:016x}", self.0) } } impl Ord for BigInteger32 { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { self.0.cmp(&other.0) } } impl PartialOrd for BigInteger32 { #[inline] fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> { Some(self.cmp(other)) } } impl From<u64> for BigInteger32 { #[inline] fn from(val: u64) -> BigInteger32 { Self::new(val as u32) } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/biginteger/tests.rs
rust/algebra/src/biginteger/tests.rs
use crate::biginteger::BigInteger; use rand::{self, CryptoRng, RngCore, SeedableRng}; use rand_chacha::ChaChaRng; const RANDOMNESS: [u8; 32] = [ 0x99, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0x62, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn biginteger_arithmetic_test<B: BigInteger>(a: B, b: B, zero: B) { // zero == zero assert_eq!(zero, zero); // zero.is_zero() == true assert_eq!(zero.is_zero(), true); // a == a assert_eq!(a, a); // a + 0 = a let mut a0_add = a.clone(); a0_add.add_nocarry(&zero); assert_eq!(a0_add, a); // a - 0 = a let mut a0_sub = a.clone(); a0_sub.sub_noborrow(&zero); assert_eq!(a0_sub, a); // a - a = 0 let mut aa_sub = a.clone(); aa_sub.sub_noborrow(&a); assert_eq!(aa_sub, zero); // a + b = b + a let mut ab_add = a.clone(); ab_add.add_nocarry(&b); let mut ba_add = b.clone(); ba_add.add_nocarry(&a); assert_eq!(ab_add, ba_add); } fn biginteger_bytes_test<B: BigInteger, R: RngCore + CryptoRng>(r: &mut R) { let mut bytes = [0u8; 256]; let x = B::uniform(r); x.write(bytes.as_mut()).unwrap(); let y = B::read(bytes.as_ref()).unwrap(); assert_eq!(x, y); } fn test_biginteger<B: BigInteger, R: RngCore + CryptoRng>(zero: B, r: &mut R) { let a = B::uniform(r); let b = B::uniform(r); biginteger_arithmetic_test(a, b, zero); biginteger_bytes_test::<B, R>(r); } #[test] fn test_biginteger32() { use crate::biginteger::BigInteger32 as B; let mut rng = ChaChaRng::from_seed(RANDOMNESS); test_biginteger(B::new(0u32), &mut rng); } #[test] fn test_biginteger64() { use crate::biginteger::BigInteger64 as B; let mut rng = ChaChaRng::from_seed(RANDOMNESS); test_biginteger(B::new(0u64), &mut rng); } #[test] fn test_biginteger128() { use crate::biginteger::BigInteger128 as B; let mut rng = ChaChaRng::from_seed(RANDOMNESS); test_biginteger(B::new([0u64; 2]), &mut rng); } #[test] fn test_biginteger256() { use crate::biginteger::BigInteger256 as B; let mut rng = ChaChaRng::from_seed(RANDOMNESS); test_biginteger(B::new([0u64; 4]), &mut rng); } #[test] fn test_biginteger384() { use crate::biginteger::BigInteger384 as B; let mut rng = ChaChaRng::from_seed(RANDOMNESS); test_biginteger(B::new([0u64; 6]), &mut rng); }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/biginteger/bigint_64.rs
rust/algebra/src/biginteger/bigint_64.rs
use crate::{ biginteger::BigInteger, bytes::{FromBytes, ToBytes}, fields::BitIterator, }; use rand::{CryptoRng, Rng, RngCore}; use serde::{Deserialize, Serialize}; use std::{ fmt::Display, io::{Read, Result as IoResult, Write}, }; #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash, Serialize, Deserialize)] pub struct BigInteger64(pub u64); impl BigInteger64 { pub fn new(value: u64) -> Self { BigInteger64(value) } } impl BigInteger for BigInteger64 { #[inline] fn add_nocarry(&mut self, other: &Self) -> bool { let res = (self.0 as u128) + (other.0 as u128); let carry = (res & (1 << 65)) == 1; *self = BigInteger64(res as u64); carry } #[inline] fn sub_noborrow(&mut self, other: &Self) -> bool { let tmp = (1u128 << 64) + u128::from(self.0) - u128::from(other.0); let borrow = if tmp >> 64 == 0 { 1 } else { 0 }; *self = BigInteger64(tmp as u64); borrow == 1 } #[inline] fn mul2(&mut self) { *(&mut self.0) <<= 1; } #[inline] fn muln(&mut self, n: u32) { *(&mut self.0) <<= n; } #[inline] fn div2(&mut self) { *(&mut self.0) >>= 1; } #[inline] fn divn(&mut self, n: u32) { *(&mut self.0) >>= n; } #[inline] fn is_odd(&self) -> bool { self.0 & 1 == 1 } #[inline] fn is_even(&self) -> bool { !self.is_odd() } #[inline] fn is_zero(&self) -> bool { self.0 == 0 } #[inline] fn num_bits(&self) -> u32 { 64 - self.0.leading_zeros() } #[inline] fn from_bits(bits: &[bool]) -> Self { assert!(bits.len() <= 64); let mut acc: u64 = 0; let mut bits = bits.to_vec(); bits.reverse(); for bit in bits { acc <<= 1; acc += bit as u64; } Self::new(acc) } #[inline] fn to_bits(&self) -> Vec<bool> { let mut res = Vec::with_capacity(64); for b in BitIterator::new([self.0]) { res.push(b); } res } #[inline] fn find_wnaf(&self) -> Vec<i64> { vec![] } #[inline] fn uniform<R: RngCore + CryptoRng>(rng: &mut R) -> Self { BigInteger64(rng.gen()) } } impl std::iter::FromIterator<u64> for BigInteger64 { /// Creates a BigInteger from an iterator over limbs in little-endian order #[inline] fn from_iter<I: IntoIterator<Item = u64>>(iter: I) -> Self { let mut cur = Self::default(); let next = iter.into_iter().next().unwrap(); cur.0 = next; cur } } impl ToBytes for BigInteger64 { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.0.write(writer) } } impl FromBytes for BigInteger64 { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { u64::read(reader).map(Self::new) } } pub struct IntoIter64 { int: BigInteger64, iterated: bool, } impl Iterator for IntoIter64 { type Item = u64; fn next(&mut self) -> Option<Self::Item> { if self.iterated { None } else { self.iterated = true; Some(self.int.0) } } fn size_hint(&self) -> (usize, Option<usize>) { (1, Some(1)) } } impl ExactSizeIterator for IntoIter64 {} impl IntoIterator for BigInteger64 { type Item = u64; type IntoIter = IntoIter64; #[inline] fn into_iter(self) -> Self::IntoIter { Self::IntoIter { int: self, iterated: false, } } } impl Display for BigInteger64 { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "0x")?; write!(f, "{:016x}", self.0) } } impl Ord for BigInteger64 { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { self.0.cmp(&other.0) } } impl PartialOrd for BigInteger64 { #[inline] fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> { Some(self.cmp(other)) } } impl From<BigInteger64> for u64 { #[inline] fn from(val: BigInteger64) -> Self { val.0 } } impl From<u64> for BigInteger64 { #[inline] fn from(val: u64) -> BigInteger64 { Self::new(val) } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/biginteger/macros.rs
rust/algebra/src/biginteger/macros.rs
macro_rules! bigint_impl { ($name:ident, $num_limbs:expr, $iter_name:ident) => { #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash, Serialize, Deserialize)] pub struct $name(pub [u64; $num_limbs]); impl $name { pub fn new(value: [u64; $num_limbs]) -> Self { $name(value) } } impl BigInteger for $name { #[inline] fn add_nocarry(&mut self, other: &Self) -> bool { let mut carry = 0; for (a, b) in self.0.iter_mut().zip(other.0.iter()) { *a = arithmetic::adc(*a, *b, &mut carry); } carry != 0 } #[inline] fn sub_noborrow(&mut self, other: &Self) -> bool { let mut borrow = 0; for (a, b) in self.0.iter_mut().zip(other.0.iter()) { *a = arithmetic::sbb(*a, *b, &mut borrow); } borrow != 0 } #[inline] fn mul2(&mut self) { let mut last = 0; for i in &mut self.0 { let tmp = *i >> 63; *i <<= 1; *i |= last; last = tmp; } } #[inline] fn muln(&mut self, mut n: u32) { if n >= 64 * $num_limbs { *self = Self::from(0); return; } while n >= 64 { let mut t = 0; for i in &mut self.0 { ::std::mem::swap(&mut t, i); } n -= 64; } if n > 0 { let mut t = 0; for i in &mut self.0 { let t2 = *i >> (64 - n); *i <<= n; *i |= t; t = t2; } } } #[inline] fn div2(&mut self) { let mut t = 0; for i in self.0.iter_mut().rev() { let t2 = *i << 63; *i >>= 1; *i |= t; t = t2; } } #[inline] fn divn(&mut self, mut n: u32) { if n >= 64 * $num_limbs { *self = Self::from(0); return; } while n >= 64 { let mut t = 0; for i in self.0.iter_mut().rev() { ::std::mem::swap(&mut t, i); } n -= 64; } if n > 0 { let mut t = 0; for i in self.0.iter_mut().rev() { let t2 = *i << (64 - n); *i >>= n; *i |= t; t = t2; } } } #[inline] fn is_odd(&self) -> bool { self.0[0] & 1 == 1 } #[inline] fn is_even(&self) -> bool { !self.is_odd() } #[inline] fn is_zero(&self) -> bool { self.0.iter().all(|&e| e == 0) } #[inline] fn num_bits(&self) -> u32 { let mut ret = $num_limbs * 64; for i in self.0.iter().rev() { let leading = i.leading_zeros(); ret -= leading; if leading != 64 { break; } } ret } #[inline] fn from_bits(bits: &[bool]) -> Self { let mut res = Self::default(); let mut acc: u64 = 0; let mut bits = bits.to_vec(); bits.reverse(); for (i, bits64) in bits.chunks(64).enumerate() { for bit in bits64.iter().rev() { acc <<= 1; acc += *bit as u64; } res.0[i] = acc; acc = 0; } res } #[inline] fn to_bits(&self) -> Vec<bool> { let mut res = Vec::with_capacity(256); for b in BitIterator::new(self.0) { res.push(b); } res } #[inline] fn find_wnaf(&self) -> Vec<i64> { let mut res = vec![]; let mut e = self.clone(); while !e.is_zero() { let z: i64; if e.is_odd() { z = 2 - (e.0[0] % 4) as i64; if z >= 0 { e.sub_noborrow(&Self::from(z as u64)); } else { e.add_nocarry(&Self::from((-z) as u64)); } } else { z = 0; } res.push(z); e.div2(); } res } #[inline] fn uniform<R: RngCore + CryptoRng>(rng: &mut R) -> Self { $name(rng.gen()) } } impl ToBytes for $name { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.0.write(writer) } } impl FromBytes for $name { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { <[u64; $num_limbs]>::read(reader).map(Self::new) } } pub struct $iter_name { int: $name, index: usize, } impl Iterator for $iter_name { type Item = u64; fn next(&mut self) -> Option<Self::Item> { let result = self.int.0.get(self.index).map(|&l| l); self.index += 1; result } fn size_hint(&self) -> (usize, Option<usize>) { let len = self.int.0.len(); (len, Some(len)) } } impl ExactSizeIterator for $iter_name {} impl IntoIterator for $name { type Item = u64; type IntoIter = $iter_name; #[inline] fn into_iter(self) -> Self::IntoIter { Self::IntoIter { int: self, index: 0, } } } impl FromIterator<u64> for $name { /// Creates a BigInteger from an iterator over limbs in little-endian order #[inline] fn from_iter<I: IntoIterator<Item = u64>>(iter: I) -> $name { let mut cur = Self::default(); for (i, limb) in iter.into_iter().enumerate() { cur.0[i] = limb } cur } } impl Display for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "0x")?; for i in self.0.iter().rev() { write!(f, "{:016x}", *i)?; } Ok(()) } } impl Ord for $name { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { for (a, b) in self.0.iter().rev().zip(other.0.iter().rev()) { if a < b { return ::std::cmp::Ordering::Less; } else if a > b { return ::std::cmp::Ordering::Greater; } } ::std::cmp::Ordering::Equal } } impl PartialOrd for $name { #[inline] fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> { Some(self.cmp(other)) } } impl AsMut<[u64]> for $name { #[inline] fn as_mut(&mut self) -> &mut [u64] { &mut self.0 } } impl AsRef<[u64]> for $name { #[inline] fn as_ref(&self) -> &[u64] { &self.0 } } impl From<u64> for $name { #[inline] fn from(val: u64) -> $name { let mut repr = Self::default(); repr.0[0] = val; repr } } }; }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/biginteger/mod.rs
rust/algebra/src/biginteger/mod.rs
use crate::{ bytes::{FromBytes, ToBytes}, fields::BitIterator, }; use rand::{CryptoRng, Rng, RngCore}; use serde::{Deserialize, Serialize}; use std::{ fmt::{Debug, Display}, io::{Read, Result as IoResult, Write}, iter::FromIterator, }; #[macro_use] mod macros; mod bigint_32; pub use bigint_32::*; mod bigint_64; pub use bigint_64::*; // bigint_impl!(BigInteger64, 1, IntoIter64); bigint_impl!(BigInteger128, 2, IntoIter128); bigint_impl!(BigInteger256, 4, IntoIter256); bigint_impl!(BigInteger384, 6, IntoIter384); #[cfg(test)] mod tests; /// This defines a `BigInteger`, a smart wrapper around a /// sequence of `u64` limbs, least-significant digit first. pub trait BigInteger: ToBytes + FromBytes + Copy + Clone + Debug + Default + Display + Eq + Ord + Send + Sized + Sync + 'static + From<u64> + IntoIterator<Item = u64> + FromIterator<u64> { /// Add another representation to this one, returning the carry bit. fn add_nocarry(&mut self, other: &Self) -> bool; /// Subtract another representation from this one, returning the borrow bit. fn sub_noborrow(&mut self, other: &Self) -> bool; /// Performs a leftwise bitshift of this number, effectively multiplying /// it by 2. Overflow is ignored. fn mul2(&mut self); /// Performs a leftwise bitshift of this number by some amount. fn muln(&mut self, amt: u32); /// Performs a rightwise bitshift of this number, effectively dividing /// it by 2. fn div2(&mut self); /// Performs a rightwise bitshift of this number by some amount. fn divn(&mut self, amt: u32); /// Returns true iff this number is odd. fn is_odd(&self) -> bool; /// Returns true iff this number is even. fn is_even(&self) -> bool; /// Returns true iff this number is zero. fn is_zero(&self) -> bool; /// Compute the number of bits needed to encode this number. Always a /// multiple of 64. fn num_bits(&self) -> u32; /// Returns the big integer representation of a given big endian boolean /// array. fn from_bits(bits: &[bool]) -> Self; /// Returns the bit representation in a big endian boolean array, without /// leading zeros. fn to_bits(&self) -> Vec<bool>; /// Returns a vector for wnaf. fn find_wnaf(&self) -> Vec<i64>; /// Samples a uniformly random instance of `Self`. fn uniform<R: RngCore + CryptoRng>(rng: &mut R) -> Self; /// Writes this `BigInteger` as a big endian integer. Always writes /// `(num_bits` / 8) bytes. fn write_le<W: Write>(&self, writer: &mut W) -> IoResult<()> { self.write(writer) } /// Reads a big endian integer occupying (`num_bits` / 8) bytes into this /// representation. fn read_le<R: Read>(&mut self, reader: &mut R) -> IoResult<()> { *self = Self::read(reader)?; Ok(()) } } pub mod arithmetic { /// Calculate a + b + carry, returning the sum and modifying the /// carry value. #[inline(always)] pub(crate) fn adc(a: u64, b: u64, carry: &mut u64) -> u64 { let tmp = u128::from(a) + u128::from(b) + u128::from(*carry); *carry = (tmp >> 64) as u64; tmp as u64 } /// Calculate a - b - borrow, returning the result and modifying /// the borrow value. #[inline(always)] pub(crate) fn sbb(a: u64, b: u64, borrow: &mut u64) -> u64 { let tmp = (1u128 << 64) + u128::from(a) - u128::from(b) - u128::from(*borrow); *borrow = if tmp >> 64 == 0 { 1 } else { 0 }; tmp as u64 } /// Calculate a + (b * c) + carry, returning the least significant digit /// and setting carry to the most significant digit. #[inline(always)] pub(crate) fn mac_with_carry(a: u64, b: u64, c: u64, carry: &mut u64) -> u64 { let tmp = (u128::from(a)) + u128::from(b) * u128::from(c) + u128::from(*carry); *carry = (tmp >> 64) as u64; tmp as u64 } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/tests.rs
rust/algebra/src/fields/tests.rs
use crate::fields::{Field, LegendreSymbol, PrimeField, SquareRootField}; use rand::{CryptoRng, Rng, RngCore, SeedableRng}; use rand_chacha::ChaChaRng; pub const ITERATIONS: u32 = 40; const RANDOMNESS: [u8; 32] = [ 0x99, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8e, 0x63, 0x03, 0xf4, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn random_negation_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { for _ in 0..ITERATIONS { let a = F::uniform(rng); let mut b = -a; b += &a; assert!(b.is_zero()); } } fn random_addition_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { for _ in 0..ITERATIONS { let a = F::uniform(rng); let b = F::uniform(rng); let c = F::uniform(rng); let t0 = (a + &b) + &c; // (a + b) + c let t1 = (a + &c) + &b; // (a + c) + b let t2 = (b + &c) + &a; // (b + c) + a assert_eq!(t0, t1); assert_eq!(t1, t2); } } fn random_subtraction_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { for _ in 0..ITERATIONS { let a = F::uniform(rng); let b = F::uniform(rng); let t0 = a - &b; // (a - b) let mut t1 = b; // (b - a) t1 -= &a; let mut t2 = t0; // (a - b) + (b - a) = 0 t2 += &t1; assert!(t2.is_zero()); } } fn random_multiplication_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { for _ in 0..ITERATIONS { let a = F::uniform(rng); let b = F::uniform(rng); let c = F::uniform(rng); let mut t0 = a; // (a * b) * c t0 *= &b; t0 *= &c; let mut t1 = a; // (a * c) * b t1 *= &c; t1 *= &b; let mut t2 = b; // (b * c) * a t2 *= &c; t2 *= &a; assert_eq!(t0, t1); assert_eq!(t1, t2); } } fn random_inversion_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { assert!(F::zero().inverse().is_none()); for _ in 0..ITERATIONS { let mut a = F::uniform(rng); let b = a.inverse().unwrap(); // probablistically nonzero a *= &b; assert_eq!(a, F::one()); } } fn random_doubling_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { for _ in 0..ITERATIONS { let mut a = F::uniform(rng); let mut b = a; a += &b; b.double_in_place(); assert_eq!(a, b); } } fn random_squaring_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { for _ in 0..ITERATIONS { let mut a = F::uniform(rng); let mut b = a; a *= &b; b.square_in_place(); assert_eq!(a, b); } } fn random_expansion_tests<F: Field, R: CryptoRng + RngCore>(rng: &mut R) { for _ in 0..ITERATIONS { // Compare (a + b)(c + d) and (a*c + b*c + a*d + b*d) let a = F::uniform(rng); let b = F::uniform(rng); let c = F::uniform(rng); let d = F::uniform(rng); let mut t0 = a; t0 += &b; let mut t1 = c; t1 += &d; t0 *= &t1; let mut t2 = a; t2 *= &c; let mut t3 = b; t3 *= &c; let mut t4 = a; t4 *= &d; let mut t5 = b; t5 *= &d; t2 += &t3; t2 += &t4; t2 += &t5; assert_eq!(t0, t2); } for _ in 0..ITERATIONS { // Compare (a + b)c and (a*c + b*c) let a = F::uniform(rng); let b = F::uniform(rng); let c = F::uniform(rng); let t0 = (a + &b) * &c; let t2 = a * &c + &(b * &c); assert_eq!(t0, t2); } } fn random_field_tests<F: Field>() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); random_negation_tests::<F, _>(&mut rng); random_addition_tests::<F, _>(&mut rng); random_subtraction_tests::<F, _>(&mut rng); random_multiplication_tests::<F, _>(&mut rng); random_inversion_tests::<F, _>(&mut rng); random_doubling_tests::<F, _>(&mut rng); random_squaring_tests::<F, _>(&mut rng); random_expansion_tests::<F, _>(&mut rng); assert!(F::zero().is_zero()); { let z = -F::zero(); assert!(z.is_zero()); } assert!(F::zero().inverse().is_none()); // Multiplication by zero { let a = F::uniform(&mut rng) * &F::zero(); assert!(a.is_zero()); } // Addition by zero { let mut a = F::uniform(&mut rng); let copy = a; a += &F::zero(); assert_eq!(a, copy); } } fn random_sqrt_tests<F: SquareRootField>() { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..ITERATIONS { let a = F::uniform(&mut rng); let b = a.square(); assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue); let b = b.sqrt().unwrap(); assert!(a == b || a == -b); } let mut c = F::one(); for _ in 0..ITERATIONS { let mut b = c.square(); assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue); b = b.sqrt().unwrap(); if b != c { b = -b; } assert_eq!(b, c); c += &F::one(); } } pub fn from_str_test<F: PrimeField>() { { let a = "84395729384759238745923745892374598234705297301958723458712394587103249587213984572934750213947582345792304758273458972349582734958273495872304598234"; let b = "38495729084572938457298347502349857029384609283450692834058293405982304598230458230495820394850293845098234059823049582309485203948502938452093482039"; let c = "3248875134290623212325429203829831876024364170316860259933542844758450336418538569901990710701240661702808867062612075657861768196242274635305077449545396068598317421057721935408562373834079015873933065667961469731886739181625866970316226171512545167081793907058686908697431878454091011239990119126"; let mut a = F::from_str(a).map_err(|_| ()).unwrap(); let b = F::from_str(b).map_err(|_| ()).unwrap(); let c = F::from_str(c).map_err(|_| ()).unwrap(); a *= &b; assert_eq!(a, c); } { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..ITERATIONS { let n: u64 = rng.gen(); let a = F::from_str(&format!("{}", n)).map_err(|_| ()).unwrap(); let b = F::from_repr(n.into()); assert_eq!(a, b); } } assert!(F::from_str("").is_err()); assert!(F::from_str("0").map_err(|_| ()).unwrap().is_zero()); assert!(F::from_str("00").is_err()); assert!(F::from_str("00000000000").is_err()); } pub fn field_test<F: Field>(a: F, b: F) { let zero = F::zero(); assert_eq!(zero, zero); assert_eq!(zero.is_zero(), true); assert_eq!(zero.is_one(), false); let one = F::one(); assert_eq!(one, one); println!("One: {:?}", one); println!("Zero: {:?}", zero); assert!(!one.is_zero()); assert!(one.is_one()); assert!((zero + &one).is_one()); let two = one + &one; assert_eq!(two, two); assert_ne!(zero, two); assert_ne!(one, two); // a == a assert_eq!(a, a); // a + 0 = a assert_eq!(a + &zero, a); // a - 0 = a assert_eq!(a - &zero, a); // a - a = 0 assert_eq!(a - &a, zero); // 0 - a = -a assert_eq!(zero - &a, -a); // a.double() = a + a assert_eq!(a.double(), a + &a); // b.double() = b + b assert_eq!(b.double(), b + &b); // a + b = b + a assert_eq!(a + &b, b + &a); // a - b = -(b - a) assert_eq!(a - &b, -(b - &a)); // (a + b) + a = a + (b + a) assert_eq!((a + &b) + &a, a + &(b + &a)); // (a + b).double() = (a + b) + (b + a) assert_eq!((a + &b).double(), (a + &b) + &(b + &a)); // a * 0 = 0 assert_eq!(a * &zero, zero); // a * 1 = a assert_eq!(a * &one, a); // a * 2 = a.double() assert_eq!(a * &two, a.double()); // a * a^-1 = 1 assert_eq!(a * &a.inverse().unwrap(), one); // a * a = a^2 assert_eq!(a * &a, a.square()); // a * a * a = a^3 assert_eq!(a * &(a * &a), a.pow([0x3, 0x0, 0x0, 0x0])); // a * b = b * a assert_eq!(a * &b, b * &a); // (a * b) * a = a * (b * a) assert_eq!((a * &b) * &a, a * &(b * &a)); // (a + b)^2 = a^2 + 2ab + b^2 assert_eq!( (a + &b).square(), a.square() + &((a * &b) + &(a * &b)) + &b.square() ); // (a - b)^2 = (-(b - a))^2 assert_eq!((a - &b).square(), (-(b - &a)).square()); random_field_tests::<F>(); } pub fn primefield_test<F: PrimeField>() { let one = F::one(); assert_eq!(F::from_repr(one.into_repr()), one); assert_eq!(F::from_str("1").ok().unwrap(), one); } pub fn sqrt_field_test<F: SquareRootField>(elem: F) { let square = elem.square(); let sqrt = square.sqrt().unwrap(); assert!(sqrt == elem || sqrt == -elem); if let Some(sqrt) = elem.sqrt() { assert!(sqrt.square() == elem || sqrt.square() == -elem); } random_sqrt_tests::<F>(); } pub fn frobenius_test<F: Field, C: AsRef<[u64]>>(characteristic: C, maxpower: usize) { let mut rng = ChaChaRng::from_seed(RANDOMNESS); for _ in 0..ITERATIONS { let a = F::uniform(&mut rng); let mut a_0 = a; a_0.frobenius_map(0); assert_eq!(a, a_0); let mut a_q = a.pow(&characteristic); for power in 1..maxpower { let mut a_qi = a; a_qi.frobenius_map(power); assert_eq!(a_qi, a_q); a_q = a_q.pow(&characteristic); } } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/macros.rs
rust/algebra/src/fields/macros.rs
macro_rules! impl_field_into_bigint { ($field: ident, $bigint: ident, $params: ident) => { impl<P: $params> From<$field<P>> for $bigint { fn from(val: $field<P>) -> Self { val.into_repr() } } }; } macro_rules! impl_ops_traits { ($field: ident, $params: ident) => { impl<P: $params> Add<Self> for $field<P> { type Output = $field<P>; #[inline] fn add(self, other: Self) -> Self { self + &other } } impl<P: $params> Sub<Self> for $field<P> { type Output = $field<P>; #[inline] fn sub(self, other: Self) -> Self { self - &other } } impl<P: $params> Mul<Self> for $field<P> { type Output = $field<P>; #[inline] fn mul(self, other: Self) -> Self { self * &other } } impl<P: $params> Div<Self> for $field<P> { type Output = $field<P>; #[inline] fn div(self, other: Self) -> Self { self / &other } } impl<P: $params> AddAssign<Self> for $field<P> { #[inline] fn add_assign(&mut self, other: Self) { *self += &other } } impl<P: $params> SubAssign<Self> for $field<P> { #[inline] fn sub_assign(&mut self, other: Self) { *self -= &other } } impl<P: $params> MulAssign<Self> for $field<P> { #[inline] fn mul_assign(&mut self, other: Self) { *self *= &other } } impl<P: $params> DivAssign<Self> for $field<P> { #[inline] fn div_assign(&mut self, other: Self) { *self /= &other } } }; } macro_rules! sqrt_impl { ($Self:ident, $P:tt, $self:expr) => {{ use crate::fields::LegendreSymbol::*; // https://eprint.iacr.org/2012/685.pdf (page 12, algorithm 5) // Actually this is just normal Tonelli-Shanks; since `P::Generator` // is a quadratic non-residue, `P::ROOT_OF_UNITY = P::GENERATOR ^ t` // is also a quadratic non-residue (since `t` is odd). match $self.legendre() { Zero => Some(*$self), QuadraticNonResidue => None, QuadraticResidue => { let mut z = $Self::qnr_to_t(); let mut w = $self.pow($P::T_MINUS_ONE_DIV_TWO); let mut x = w * $self; let mut b = x * &w; let mut v = $P::TWO_ADICITY as usize; // t = self^t #[cfg(debug_assertions)] { let mut check = b; for _ in 0..(v - 1) { check.square_in_place(); } if !check.is_one() { panic!("Input is not a square root, but it passed the QR test") } } while !b.is_one() { let mut k = 0usize; let mut b2k = b; while !b2k.is_one() { // invariant: b2k = b^(2^k) after entering this loop b2k.square_in_place(); k += 1; } let j = v - k - 1; w = z; for _ in 0..j { w.square_in_place(); } z = w.square(); b *= &z; x *= &w; v = k; } Some(x) } } }}; }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/mod.rs
rust/algebra/src/fields/mod.rs
use crate::{ biginteger::BigInteger, bytes::{FromBytes, ToBytes}, UniformRandom, }; use num_traits::{One, Zero}; use serde::{Deserialize, Serialize}; use std::{ fmt::{Debug, Display}, hash::Hash, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, str::FromStr, }; #[macro_use] mod macros; pub mod models; pub mod near_mersenne_64; #[cfg(test)] pub mod tests; pub use self::models::*; /// The interface for a generic field. pub trait Field: ToBytes + FromBytes + Copy + Clone + Debug + Display + Default + Send + Sync + 'static + Eq + Ord + Neg<Output = Self> + Sized + Hash + Serialize + for<'de> Deserialize<'de> + UniformRandom + Zero + One + for<'a> Add<&'a Self, Output = Self> + for<'a> Sub<&'a Self, Output = Self> + for<'a> Mul<&'a Self, Output = Self> + for<'a> Div<&'a Self, Output = Self> + Add<Self, Output = Self> + Sub<Self, Output = Self> + Mul<Self, Output = Self> + Div<Self, Output = Self> + for<'a> AddAssign<&'a Self> + for<'a> SubAssign<&'a Self> + for<'a> MulAssign<&'a Self> + for<'a> DivAssign<&'a Self> { /// Returns `self + self`. #[must_use] fn double(&self) -> Self; /// Doubles `self` in place. fn double_in_place(&mut self) -> &mut Self; /// Returns `self * self`. #[must_use] fn square(&self) -> Self; /// Squares `self` in place. fn square_in_place(&mut self) -> &mut Self; /// Computes the multiplicative inverse of `self` if `self` is nonzero. #[must_use] fn inverse(&self) -> Option<Self>; // Sets `self` to `self`'s inverse if it exists. Otherwise it is a no-op. fn inverse_in_place(&mut self) -> Option<&mut Self>; /// Exponentiates this element by a power of the base prime modulus via /// the Frobenius automorphism. fn frobenius_map(&mut self, power: usize); /// Exponentiates this element by a number represented with `u64` limbs, /// least significant limb first. fn pow<S: AsRef<[u64]>>(&self, exp: S) -> Self { let mut res = Self::one(); let mut found_one = false; for i in BitIterator::new(exp) { if !found_one { if i { found_one = true; } else { continue; } } res.square_in_place(); if i { res *= self; } } res } } /// A trait that defines parameters for a prime field. pub trait FpParameters: 'static + Send + Sync + Sized { type BigInt: BigInteger; /// The modulus of the field. const MODULUS: Self::BigInt; /// The number of bits needed to represent the `Self::MODULUS`. const MODULUS_BITS: u32; /// The number of bits that must be shaved from the beginning of /// the representation when randomly sampling. const REPR_SHAVE_BITS: u32; /// R = 2^256 % Self::MODULUS const R: Self::BigInt; /// R2 = R^2 % Self::MODULUS const R2: Self::BigInt; /// INV = -(MODULUS^{-1} mod MODULUS) mod MODULUS const INV: u64; /// A multiplicative generator that is also a quadratic nonresidue. /// `Self::GENERATOR` is an element having multiplicative order /// `Self::MODULUS - 1`. /// There also does not exist `x` such that `Self::GENERATOR = x^2 % /// Self::MODULUS` const GENERATOR: Self::BigInt; /// The number of bits that can be reliably stored. /// (Should equal `SELF::MODULUS_BITS - 1`) const CAPACITY: u32; /// 2^s * t = MODULUS - 1 with t odd. This is the two-adicity of the prime. const TWO_ADICITY: u32; /// 2^s root of unity computed by GENERATOR^t const ROOT_OF_UNITY: Self::BigInt; /// t for 2^s * t = MODULUS - 1 const T: Self::BigInt; /// (t - 1) / 2 const T_MINUS_ONE_DIV_TWO: Self::BigInt; /// (Self::MODULUS - 1) / 2 const MODULUS_MINUS_ONE_DIV_TWO: Self::BigInt; } /// The interface for a prime field. pub trait PrimeField: Field + FromStr { type Params: FpParameters<BigInt = Self::BigInt>; type BigInt: BigInteger; /// Returns a prime field element from its underlying representation. fn from_repr(repr: <Self::Params as FpParameters>::BigInt) -> Self; /// Returns the underlying representation of the prime field element. fn into_repr(&self) -> Self::BigInt; /// Returns a field element if the set of bytes forms a valid field element, /// otherwise returns None. fn from_random_bytes(bytes: &[u8]) -> Option<Self>; /// Returns the characteristic of the prime field. fn characteristic() -> Self::BigInt { Self::Params::MODULUS } /// Returns the multiplicative generator of `char()` - 1 order. fn multiplicative_generator() -> Self; /// Returns the 2^s root of unity. fn root_of_unity() -> Self; /// Return the a QNR^T fn qnr_to_t() -> Self { Self::root_of_unity() } /// Returns the field size in bits. fn size_in_bits() -> usize { Self::Params::MODULUS_BITS as usize } /// Returns the trace. fn trace() -> Self::BigInt { Self::Params::T } /// Returns the trace minus one divided by two. fn trace_minus_one_div_two() -> Self::BigInt { Self::Params::T_MINUS_ONE_DIV_TWO } /// Returns the modulus minus one divided by two. fn modulus_minus_one_div_two() -> Self::BigInt { Self::Params::MODULUS_MINUS_ONE_DIV_TWO } } /// The interface for a field that supports an efficient square-root operation. pub trait SquareRootField: Field { /// Returns the Legendre symbol. fn legendre(&self) -> LegendreSymbol; /// Returns the square root of self, if it exists. #[must_use] fn sqrt(&self) -> Option<Self>; /// Sets `self` to be the square root of `self`, if it exists. fn sqrt_in_place(&mut self) -> Option<&mut Self>; } #[derive(Debug, PartialEq)] pub enum LegendreSymbol { Zero = 0, QuadraticResidue = 1, QuadraticNonResidue = -1, } impl LegendreSymbol { pub fn is_zero(&self) -> bool { *self == LegendreSymbol::Zero } pub fn is_qnr(&self) -> bool { *self == LegendreSymbol::QuadraticNonResidue } pub fn is_qr(&self) -> bool { *self == LegendreSymbol::QuadraticResidue } } #[derive(Debug)] pub struct BitIterator<E> { t: E, n: usize, } impl<E: AsRef<[u64]>> BitIterator<E> { pub fn new(t: E) -> Self { let n = t.as_ref().len() * 64; BitIterator { t, n } } } impl<E: AsRef<[u64]>> Iterator for BitIterator<E> { type Item = bool; fn next(&mut self) -> Option<bool> { if self.n == 0 { None } else { self.n -= 1; let part = self.n / 64; let bit = self.n - (64 * part); Some(self.t.as_ref()[part] & (1 << bit) > 0) } } } use crate::biginteger::{BigInteger256, BigInteger384, BigInteger64}; impl_field_into_bigint!(Fp64, BigInteger64, Fp64Parameters); impl_field_into_bigint!(Fp256, BigInteger256, Fp256Parameters); impl_field_into_bigint!(Fp384, BigInteger384, Fp384Parameters); pub fn batch_inversion<F: Field>(v: &mut [F]) { // Montgomery’s Trick and Fast Implementation of Masked AES // Genelle, Prouff and Quisquater // Section 3.2 // First pass: compute [a, ab, abc, ...] let mut prod = Vec::with_capacity(v.len()); let mut tmp = F::one(); for f in v.iter().filter(|f| !f.is_zero()) { tmp.mul_assign(&f); prod.push(tmp); } // Invert `tmp`. tmp = tmp.inverse().unwrap(); // Guaranteed to be nonzero. // Second pass: iterate backwards to compute inverses for (f, s) in v.iter_mut() // Backwards .rev() // Ignore normalized elements .filter(|f| !f.is_zero()) // Backwards, skip last element, fill in one for last term. .zip(prod.into_iter().rev().skip(1).chain(Some(F::one()))) { // tmp := tmp * g.z; g.z := tmp * s = 1/z let newtmp = tmp * &*f; *f = tmp * &s; tmp = newtmp; } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/models/fp_384.rs
rust/algebra/src/fields/models/fp_384.rs
use num_traits::{One, Zero}; use rand::{CryptoRng, RngCore}; use std::{ cmp::{Ord, Ordering, PartialOrd}, fmt::{Display, Formatter, Result as FmtResult}, io::{Read, Result as IoResult, Write}, marker::PhantomData, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, str::FromStr, }; use serde::{Deserialize, Serialize}; use crate::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger384 as BigInteger}, bytes::{FromBytes, ToBytes}, fields::{Field, FpParameters, LegendreSymbol, PrimeField, SquareRootField}, UniformRandom, }; pub trait Fp384Parameters: FpParameters<BigInt = BigInteger> {} #[derive(Derivative, Serialize, Deserialize)] #[derivative( Default(bound = "P: Fp384Parameters"), Hash(bound = "P: Fp384Parameters"), Clone(bound = "P: Fp384Parameters"), Copy(bound = "P: Fp384Parameters"), Debug(bound = "P: Fp384Parameters"), PartialEq(bound = "P: Fp384Parameters"), Eq(bound = "P: Fp384Parameters") )] #[serde(bound = "P: Fp384Parameters")] pub struct Fp384<P: Fp384Parameters>(pub(crate) BigInteger, #[serde(skip)] PhantomData<P>); impl<P: Fp384Parameters> Fp384<P> { #[inline] pub const fn new(element: BigInteger) -> Self { Fp384::<P>(element, PhantomData) } #[inline] pub(crate) fn is_valid(&self) -> bool { self.0 < P::MODULUS } #[inline] fn reduce(&mut self) { if !self.is_valid() { self.0.sub_noborrow(&P::MODULUS); } } #[inline] fn mont_reduce( &mut self, r0: u64, mut r1: u64, mut r2: u64, mut r3: u64, mut r4: u64, mut r5: u64, mut r6: u64, mut r7: u64, mut r8: u64, mut r9: u64, mut r10: u64, mut r11: u64, ) { // The Montgomery reduction here is based on Algorithm 14.32 in // Handbook of Applied Cryptography // <http://cacr.uwaterloo.ca/hac/about/chap14.pdf>. let k = r0.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry); r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry); r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry); r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry); r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[4], &mut carry); r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[5], &mut carry); r6 = fa::adc(r6, 0, &mut carry); let carry2 = carry; let k = r1.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry); r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry); r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry); r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry); r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[4], &mut carry); r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[5], &mut carry); r7 = fa::adc(r7, carry2, &mut carry); let carry2 = carry; let k = r2.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry); r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry); r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry); r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry); r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[4], &mut carry); r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[5], &mut carry); r8 = fa::adc(r8, carry2, &mut carry); let carry2 = carry; let k = r3.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry); r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry); r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry); r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry); r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[4], &mut carry); r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[5], &mut carry); r9 = fa::adc(r9, carry2, &mut carry); let carry2 = carry; let k = r4.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r4, k, P::MODULUS.0[0], &mut carry); r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[1], &mut carry); r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[2], &mut carry); r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[3], &mut carry); r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[4], &mut carry); r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[5], &mut carry); r10 = fa::adc(r10, carry2, &mut carry); let carry2 = carry; let k = r5.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r5, k, P::MODULUS.0[0], &mut carry); r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[1], &mut carry); r7 = fa::mac_with_carry(r7, k, P::MODULUS.0[2], &mut carry); r8 = fa::mac_with_carry(r8, k, P::MODULUS.0[3], &mut carry); r9 = fa::mac_with_carry(r9, k, P::MODULUS.0[4], &mut carry); r10 = fa::mac_with_carry(r10, k, P::MODULUS.0[5], &mut carry); r11 = fa::adc(r11, carry2, &mut carry); (self.0).0[0] = r6; (self.0).0[1] = r7; (self.0).0[2] = r8; (self.0).0[3] = r9; (self.0).0[4] = r10; (self.0).0[5] = r11; self.reduce(); } } impl<P: Fp384Parameters> Zero for Fp384<P> { #[inline] fn zero() -> Self { Fp384::<P>(BigInteger::from(0), PhantomData) } #[inline] fn is_zero(&self) -> bool { self.0.is_zero() } } impl<P: Fp384Parameters> One for Fp384<P> { #[inline] fn one() -> Self { Fp384::<P>(P::R, PhantomData) } #[inline] fn is_one(&self) -> bool { self == &Self::one() } } impl<P: Fp384Parameters> Field for Fp384<P> { #[inline] fn double(&self) -> Self { let mut temp = *self; temp.double_in_place(); temp } #[inline] fn double_in_place(&mut self) -> &mut Self { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); self } #[inline] fn square(&self) -> Self { let mut temp = self.clone(); temp.square_in_place(); temp } #[inline] fn square_in_place(&mut self) -> &mut Self { let mut carry = 0; let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry); let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry); let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry); let r4 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[4], &mut carry); let r5 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[5], &mut carry); let r6 = carry; let mut carry = 0; let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry); let r5 = fa::mac_with_carry(r5, (self.0).0[1], (self.0).0[4], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[1], (self.0).0[5], &mut carry); let r7 = carry; let mut carry = 0; let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[2], (self.0).0[4], &mut carry); let r7 = fa::mac_with_carry(r7, (self.0).0[2], (self.0).0[5], &mut carry); let r8 = carry; let mut carry = 0; let r7 = fa::mac_with_carry(r7, (self.0).0[3], (self.0).0[4], &mut carry); let r8 = fa::mac_with_carry(r8, (self.0).0[3], (self.0).0[5], &mut carry); let r9 = carry; let mut carry = 0; let r9 = fa::mac_with_carry(r9, (self.0).0[4], (self.0).0[5], &mut carry); let r10 = carry; let r11 = r10 >> 63; let r10 = (r10 << 1) | (r9 >> 63); let r9 = (r9 << 1) | (r8 >> 63); let r8 = (r8 << 1) | (r7 >> 63); let r7 = (r7 << 1) | (r6 >> 63); let r6 = (r6 << 1) | (r5 >> 63); let r5 = (r5 << 1) | (r4 >> 63); let r4 = (r4 << 1) | (r3 >> 63); let r3 = (r3 << 1) | (r2 >> 63); let r2 = (r2 << 1) | (r1 >> 63); let r1 = r1 << 1; let mut carry = 0; let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry); let r1 = fa::adc(r1, 0, &mut carry); let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry); let r3 = fa::adc(r3, 0, &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry); let r5 = fa::adc(r5, 0, &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry); let r7 = fa::adc(r7, 0, &mut carry); let r8 = fa::mac_with_carry(r8, (self.0).0[4], (self.0).0[4], &mut carry); let r9 = fa::adc(r9, 0, &mut carry); let r10 = fa::mac_with_carry(r10, (self.0).0[5], (self.0).0[5], &mut carry); let r11 = fa::adc(r11, 0, &mut carry); self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11); self } #[inline] fn inverse(&self) -> Option<Self> { if self.is_zero() { None } else { // Guajardo Kumar Paar Pelzl // Efficient Software-Implementation of Finite Fields with Applications to // Cryptography // Algorithm 16 (BEA for Inversion in Fp) let one = BigInteger::from(1); let mut u = self.0; let mut v = P::MODULUS; let mut b = Fp384::<P>(P::R2, PhantomData); // Avoids unnecessary reduction step. let mut c = Self::zero(); while u != one && v != one { while u.is_even() { u.div2(); if b.0.is_even() { b.0.div2(); } else { b.0.add_nocarry(&P::MODULUS); b.0.div2(); } } while v.is_even() { v.div2(); if c.0.is_even() { c.0.div2(); } else { c.0.add_nocarry(&P::MODULUS); c.0.div2(); } } if v < u { u.sub_noborrow(&v); b.sub_assign(&c); } else { v.sub_noborrow(&u); c.sub_assign(&b); } } if u == one { Some(b) } else { Some(c) } } } fn inverse_in_place(&mut self) -> Option<&mut Self> { if let Some(inverse) = self.inverse() { *self = inverse; Some(self) } else { None } } #[inline] fn frobenius_map(&mut self, _: usize) { // No-op: No effect in a prime field. } } impl<P: Fp384Parameters> UniformRandom for Fp384<P> { /// Samples a uniformly random field element. #[inline] fn uniform<R: RngCore + CryptoRng>(r: &mut R) -> Self { loop { let mut tmp = Fp384::<P>(BigInteger::uniform(r), PhantomData); // Mask away the unused bits at the beginning. tmp.0.as_mut()[5] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; if tmp.is_valid() { return tmp; } } } } impl<P: Fp384Parameters> PrimeField for Fp384<P> { type Params = P; type BigInt = BigInteger; #[inline] fn from_repr(r: BigInteger) -> Self { let mut r = Fp384(r, PhantomData); if r.is_valid() { r.mul_assign(&Fp384(P::R2, PhantomData)); r } else { Self::zero() } } #[inline] fn into_repr(&self) -> BigInteger { let mut r = *self; r.mont_reduce( (self.0).0[0], (self.0).0[1], (self.0).0[2], (self.0).0[3], (self.0).0[4], (self.0).0[5], 0, 0, 0, 0, 0, 0, ); r.0 } #[inline] fn from_random_bytes(bytes: &[u8]) -> Option<Self> { let mut result_bytes = vec![0u8; (Self::zero().0).0.len() * 8]; for (result_byte, in_byte) in result_bytes.iter_mut().zip(bytes.iter()) { *result_byte = *in_byte; } BigInteger::read(result_bytes.as_slice()) .ok() .and_then(|mut res| { res.as_mut()[5] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; let result = Self::new(res); if result.is_valid() { Some(result) } else { None } }) } #[inline] fn multiplicative_generator() -> Self { Fp384::<P>(P::GENERATOR, PhantomData) } #[inline] fn root_of_unity() -> Self { Fp384::<P>(P::ROOT_OF_UNITY, PhantomData) } } impl<P: Fp384Parameters> SquareRootField for Fp384<P> { #[inline] fn legendre(&self) -> LegendreSymbol { use crate::fields::LegendreSymbol::*; // s = self^((MODULUS - 1) // 2) let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO); if s.is_zero() { Zero } else if s.is_one() { QuadraticResidue } else { QuadraticNonResidue } } #[inline] fn sqrt(&self) -> Option<Self> { sqrt_impl!(Self, P, self) } fn sqrt_in_place(&mut self) -> Option<&mut Self> { (*self).sqrt().map(|sqrt| { *self = sqrt; self }) } } impl<P: Fp384Parameters> Ord for Fp384<P> { #[inline(always)] fn cmp(&self, other: &Self) -> Ordering { self.into_repr().cmp(&other.into_repr()) } } impl<P: Fp384Parameters> PartialOrd for Fp384<P> { #[inline(always)] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<P: Fp384Parameters> ToBytes for Fp384<P> { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.into_repr().write(writer) } } impl<P: Fp384Parameters> FromBytes for Fp384<P> { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { BigInteger::read(reader).map(Fp384::from_repr) } } impl<P: Fp384Parameters> FromStr for Fp384<P> { type Err = (); /// Interpret a string of numbers as a (congruent) prime field element. /// Does not accept unnecessary leading zeroes or a blank string. fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { println!("Is empty!"); return Err(()); } if s == "0" { return Ok(Self::zero()); } let mut res = Self::zero(); let ten = Self::from_repr(<Self as PrimeField>::BigInt::from(10)); let mut first_digit = true; for c in s.chars() { match c.to_digit(10) { Some(c) => { if first_digit { if c == 0 { return Err(()); } first_digit = false; } res.mul_assign(&ten); res.add_assign(&Self::from_repr(<Self as PrimeField>::BigInt::from( u64::from(c), ))); } None => { println!("Not valid digit!"); return Err(()); } } } if !res.is_valid() { Err(()) } else { Ok(res) } } } impl<P: Fp384Parameters> Display for Fp384<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "Fp384({})", self.0) } } impl<P: Fp384Parameters> Neg for Fp384<P> { type Output = Self; #[inline] #[must_use] fn neg(self) -> Self { if !self.is_zero() { let mut tmp = P::MODULUS.clone(); tmp.sub_noborrow(&self.0); Fp384::<P>(tmp, PhantomData) } else { self } } } impl<'a, P: Fp384Parameters> Add<&'a Fp384<P>> for Fp384<P> { type Output = Self; #[inline] fn add(self, other: &Self) -> Self { let mut result = self.clone(); result.add_assign(other); result } } impl<'a, P: Fp384Parameters> Sub<&'a Fp384<P>> for Fp384<P> { type Output = Self; #[inline] fn sub(self, other: &Self) -> Self { let mut result = self.clone(); result.sub_assign(other); result } } impl<'a, P: Fp384Parameters> Mul<&'a Fp384<P>> for Fp384<P> { type Output = Self; #[inline] fn mul(self, other: &Self) -> Self { let mut result = self.clone(); result.mul_assign(other); result } } impl<'a, P: Fp384Parameters> Div<&'a Fp384<P>> for Fp384<P> { type Output = Self; #[inline] fn div(self, other: &Self) -> Self { let mut result = self.clone(); result.mul_assign(&other.inverse().unwrap()); result } } impl<'a, P: Fp384Parameters> AddAssign<&'a Self> for Fp384<P> { #[inline] fn add_assign(&mut self, other: &Self) { // This cannot exceed the backing capacity. self.0.add_nocarry(&other.0); // However, it may need to be reduced self.reduce(); } } impl<'a, P: Fp384Parameters> SubAssign<&'a Self> for Fp384<P> { #[inline] fn sub_assign(&mut self, other: &Self) { // If `other` is larger than `self`, add the modulus to self first. if other.0 > self.0 { self.0.add_nocarry(&P::MODULUS); } self.0.sub_noborrow(&other.0); } } impl<'a, P: Fp384Parameters> MulAssign<&'a Self> for Fp384<P> { #[inline] fn mul_assign(&mut self, other: &Self) { let mut carry = 0; let r0 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[0], &mut carry); let r1 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[1], &mut carry); let r2 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[2], &mut carry); let r3 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[3], &mut carry); let r4 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[4], &mut carry); let r5 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[5], &mut carry); let r6 = carry; let mut carry = 0; let r1 = fa::mac_with_carry(r1, (self.0).0[1], (other.0).0[0], &mut carry); let r2 = fa::mac_with_carry(r2, (self.0).0[1], (other.0).0[1], &mut carry); let r3 = fa::mac_with_carry(r3, (self.0).0[1], (other.0).0[2], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[1], (other.0).0[3], &mut carry); let r5 = fa::mac_with_carry(r5, (self.0).0[1], (other.0).0[4], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[1], (other.0).0[5], &mut carry); let r7 = carry; let mut carry = 0; let r2 = fa::mac_with_carry(r2, (self.0).0[2], (other.0).0[0], &mut carry); let r3 = fa::mac_with_carry(r3, (self.0).0[2], (other.0).0[1], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[2], (other.0).0[2], &mut carry); let r5 = fa::mac_with_carry(r5, (self.0).0[2], (other.0).0[3], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[2], (other.0).0[4], &mut carry); let r7 = fa::mac_with_carry(r7, (self.0).0[2], (other.0).0[5], &mut carry); let r8 = carry; let mut carry = 0; let r3 = fa::mac_with_carry(r3, (self.0).0[3], (other.0).0[0], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[3], (other.0).0[1], &mut carry); let r5 = fa::mac_with_carry(r5, (self.0).0[3], (other.0).0[2], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[3], (other.0).0[3], &mut carry); let r7 = fa::mac_with_carry(r7, (self.0).0[3], (other.0).0[4], &mut carry); let r8 = fa::mac_with_carry(r8, (self.0).0[3], (other.0).0[5], &mut carry); let r9 = carry; let mut carry = 0; let r4 = fa::mac_with_carry(r4, (self.0).0[4], (other.0).0[0], &mut carry); let r5 = fa::mac_with_carry(r5, (self.0).0[4], (other.0).0[1], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[4], (other.0).0[2], &mut carry); let r7 = fa::mac_with_carry(r7, (self.0).0[4], (other.0).0[3], &mut carry); let r8 = fa::mac_with_carry(r8, (self.0).0[4], (other.0).0[4], &mut carry); let r9 = fa::mac_with_carry(r9, (self.0).0[4], (other.0).0[5], &mut carry); let r10 = carry; let mut carry = 0; let r5 = fa::mac_with_carry(r5, (self.0).0[5], (other.0).0[0], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[5], (other.0).0[1], &mut carry); let r7 = fa::mac_with_carry(r7, (self.0).0[5], (other.0).0[2], &mut carry); let r8 = fa::mac_with_carry(r8, (self.0).0[5], (other.0).0[3], &mut carry); let r9 = fa::mac_with_carry(r9, (self.0).0[5], (other.0).0[4], &mut carry); let r10 = fa::mac_with_carry(r10, (self.0).0[5], (other.0).0[5], &mut carry); let r11 = carry; self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11); } } impl<'a, P: Fp384Parameters> DivAssign<&'a Self> for Fp384<P> { #[inline] fn div_assign(&mut self, other: &Self) { self.mul_assign(&other.inverse().unwrap()); } } impl_ops_traits!(Fp384, Fp384Parameters);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/models/fp_32.rs
rust/algebra/src/fields/models/fp_32.rs
use num_traits::{One, Zero}; use rand::{CryptoRng, RngCore}; use std::{ cmp::{Ord, Ordering, PartialOrd}, fmt::{Display, Formatter, Result as FmtResult}, io::{Read, Result as IoResult, Write}, marker::PhantomData, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, str::FromStr, }; use serde::{Deserialize, Serialize}; use crate::{ biginteger::{BigInteger as _BigInteger, BigInteger32 as BigInteger}, bytes::{FromBytes, ToBytes}, fields::{Field, FpParameters, PrimeField}, UniformRandom, }; pub trait Fp32Parameters: FpParameters<BigInt = BigInteger> {} #[derive(Derivative, Serialize, Deserialize)] #[derivative( Default(bound = "P: Fp32Parameters"), Hash(bound = "P: Fp32Parameters"), Clone(bound = "P: Fp32Parameters"), Copy(bound = "P: Fp32Parameters"), Debug(bound = "P: Fp32Parameters"), PartialEq(bound = "P: Fp32Parameters"), Eq(bound = "P: Fp32Parameters") )] #[serde(bound = "P: Fp32Parameters")] /// Does *not* use Montgomery reduction. pub struct Fp32<P: Fp32Parameters>( pub(crate) BigInteger, #[serde(skip)] #[derivative(Debug = "ignore")] PhantomData<P>, ); impl<P: Fp32Parameters> Fp32<P> { #[inline] pub const fn new(element: BigInteger) -> Self { Fp32::<P>(element, PhantomData) } #[inline] fn is_valid(&self) -> bool { self.0 < P::MODULUS } #[inline] fn reduce(&mut self) { if !self.is_valid() { self.0.sub_noborrow(&P::MODULUS); } } } impl<P: Fp32Parameters> Zero for Fp32<P> { #[inline] fn zero() -> Self { Fp32::<P>(BigInteger::from(0), PhantomData) } #[inline] fn is_zero(&self) -> bool { self.0.is_zero() } } impl<P: Fp32Parameters> One for Fp32<P> { #[inline] fn one() -> Self { Fp32::new(BigInteger::from(1)) } #[inline] fn is_one(&self) -> bool { self == &Self::one() } } impl<P: Fp32Parameters> Field for Fp32<P> { #[inline] fn double(&self) -> Self { let mut temp = *self; temp.double_in_place(); temp } #[inline] fn double_in_place(&mut self) -> &mut Self { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); self } #[inline] fn square(&self) -> Self { let mut temp = self.clone(); temp.square_in_place(); temp } #[inline] fn square_in_place(&mut self) -> &mut Self { let cur = *self; *self *= &cur; self } #[inline] fn inverse(&self) -> Option<Self> { if self.is_zero() { None } else { Some(self.pow(&[u64::from(P::MODULUS.0 - 2)])) } } fn inverse_in_place(&mut self) -> Option<&mut Self> { if let Some(inverse) = self.inverse() { *self = inverse; Some(self) } else { None } } #[inline] fn frobenius_map(&mut self, _: usize) { // No-op: No effect in a prime field. } } impl<P: Fp32Parameters> UniformRandom for Fp32<P> { /// Samples a uniformly random field element. #[inline] fn uniform<R: RngCore + CryptoRng>(r: &mut R) -> Self { loop { let mut tmp = Fp32::<P>(BigInteger::uniform(r), PhantomData); // Mask away the unused bits at the beginning. (&mut tmp.0).0 &= std::u32::MAX >> P::REPR_SHAVE_BITS; if tmp.is_valid() { return tmp; } } } } impl<P: Fp32Parameters> PrimeField for Fp32<P> { type Params = P; type BigInt = BigInteger; #[inline] fn from_repr(r: BigInteger) -> Self { let r = Fp32::new(r); if r.is_valid() { r } else { Self::zero() } } #[inline] fn into_repr(&self) -> BigInteger { self.0 } #[inline] fn from_random_bytes(bytes: &[u8]) -> Option<Self> { let mut result = Self::zero(); if result.0.read_le((&bytes[..]).by_ref()).is_ok() { (&mut result.0).0 &= std::u32::MAX >> P::REPR_SHAVE_BITS; if result.is_valid() { Some(result) } else { None } } else { None } } #[inline] fn multiplicative_generator() -> Self { Fp32::<P>(P::GENERATOR, PhantomData) } #[inline] fn root_of_unity() -> Self { Fp32::<P>(P::ROOT_OF_UNITY, PhantomData) } } impl<P: Fp32Parameters> ToBytes for Fp32<P> { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.into_repr().write(writer) } } impl<P: Fp32Parameters> FromBytes for Fp32<P> { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { BigInteger::read(reader).map(Fp32::from_repr) } } /// `Fp` elements are ordered lexicographically. impl<P: Fp32Parameters> Ord for Fp32<P> { #[inline(always)] fn cmp(&self, other: &Self) -> Ordering { self.into_repr().cmp(&other.into_repr()) } } impl<P: Fp32Parameters> PartialOrd for Fp32<P> { #[inline(always)] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<P: Fp32Parameters> FromStr for Fp32<P> { type Err = (); /// Interpret a string of numbers as a (congruent) prime field element. /// Does not accept unnecessary leading zeroes or a blank string. fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { return Err(()); } if s == "0" { return Ok(Self::zero()); } let mut res = Self::zero(); let ten = Self::from_repr(<Self as PrimeField>::BigInt::from(10)); let mut first_digit = true; for c in s.chars() { match c.to_digit(10) { Some(c) => { if first_digit { if c == 0 { return Err(()); } first_digit = false; } res.mul_assign(&ten); res.add_assign(&Self::from_repr(<Self as PrimeField>::BigInt::from( u64::from(c), ))); } None => { return Err(()); } } } if !res.is_valid() { Err(()) } else { Ok(res) } } } impl<P: Fp32Parameters> Display for Fp32<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "Fp32({})", self.0) } } impl<P: Fp32Parameters> Neg for Fp32<P> { type Output = Self; #[inline] #[must_use] fn neg(self) -> Self { if !self.is_zero() { let mut tmp = P::MODULUS; tmp.sub_noborrow(&self.0); Fp32::<P>(tmp, PhantomData) } else { self } } } impl<'a, P: Fp32Parameters> Add<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn add(self, other: &Self) -> Self { let mut result = self; result.add_assign(other); result } } impl<'a, P: Fp32Parameters> Sub<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn sub(self, other: &Self) -> Self { let mut result = self; result.sub_assign(other); result } } impl<'a, P: Fp32Parameters> Mul<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn mul(self, other: &Self) -> Self { let mut result = self; result.mul_assign(other); result } } impl<'a, P: Fp32Parameters> Div<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn div(self, other: &Self) -> Self { let mut result = self; result.mul_assign(&other.inverse().unwrap()); result } } impl<'a, P: Fp32Parameters> AddAssign<&'a Self> for Fp32<P> { #[inline] fn add_assign(&mut self, other: &Self) { // This cannot exceed the backing capacity. self.0.add_nocarry(&other.0); // However, it may need to be reduced self.reduce(); } } impl<'a, P: Fp32Parameters> SubAssign<&'a Self> for Fp32<P> { #[inline] fn sub_assign(&mut self, other: &Self) { // If `other` is larger than `self`, add the modulus to self first. if other.0 > self.0 { self.0.add_nocarry(&P::MODULUS); } self.0.sub_noborrow(&other.0); } } impl<'a, P: Fp32Parameters> MulAssign<&'a Self> for Fp32<P> { #[inline] fn mul_assign(&mut self, other: &Self) { let res = ((self.0).0 as u64) * ((other.0).0 as u64) % (P::MODULUS.0 as u64); (&mut self.0).0 = res as u32; } } impl<'a, P: Fp32Parameters> DivAssign<&'a Self> for Fp32<P> { #[inline] fn div_assign(&mut self, other: &Self) { self.mul_assign(&other.inverse().unwrap()); } } impl_ops_traits!(Fp32, Fp32Parameters);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/models/fp_32_lazy.rs
rust/algebra/src/fields/models/fp_32_lazy.rs
use num_traits::{One, Zero}; use rand::{CryptoRng, RngCore}; use std::{ cmp::{Ord, Ordering, PartialOrd}, fmt::{Display, Formatter, Result as FmtResult}, io::{Read, Result as IoResult, Write}, marker::PhantomData, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, str::FromStr, }; use serde::{Deserialize, Serialize}; use crate::{ biginteger::{BigInteger as _BigInteger, BigInteger64 as BigInteger}, bytes::{FromBytes, ToBytes}, fields::{Field, FpParameters, PrimeField}, UniformRandom, }; pub trait Fp32Parameters: FpParameters<BigInt = BigInteger> {} #[derive(Derivative, Serialize, Deserialize)] #[derivative( Default(bound = "P: Fp32Parameters"), Hash(bound = "P: Fp32Parameters"), Clone(bound = "P: Fp32Parameters"), Copy(bound = "P: Fp32Parameters"), PartialEq(bound = "P: Fp32Parameters"), Eq(bound = "P: Fp32Parameters") )] #[serde(bound = "P: Fp32Parameters")] // #[serde(from = "Fp32Slow<P>")] // #[serde(into = "Fp32Slow<P>")] /// Does *not* use Montgomery reduction. pub struct Fp32<P: Fp32Parameters>(pub(crate) BigInteger, #[serde(skip)] PhantomData<P>); // impl<P: Fp32Parameters> Serialize for Fp32<P> { // #[inline] // fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> // where // S: serde::Serializer // { // serializer.serialize_u32((self.0).0 as u32) // } // } // struct Fp32Visitor<P>(PhantomData<P>); // impl<'de, P: Fp32Parameters> serde::de::Visitor<'de> for Fp32Visitor<P> { // type Value = Fp32<P>; // fn expecting(&self, formatter: &mut Formatter) -> FmtResult { // formatter.write_str("an integer between -2^31 and 2^31") // } // fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E> // where // E: serde::de::Error, // { // Ok(Fp32::from_repr(BigInteger::from(value as u64))) // } // } // impl<'de, P: Fp32Parameters> Deserialize<'de> for Fp32<P> { // fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> // where // D: serde::Deserializer<'de>, // { // deserializer.deserialize_u32(Fp32Visitor(PhantomData)) // } // } impl<P: Fp32Parameters> Fp32<P> { #[inline] pub const fn new(element: BigInteger) -> Self { Fp32::<P>(element, PhantomData) } #[inline] fn is_valid(&self) -> bool { self.0 < P::MODULUS } #[inline] fn reduce(&mut self) { if !self.is_valid() { self.0.sub_noborrow(&P::MODULUS); } } } impl<P: Fp32Parameters> Zero for Fp32<P> { #[inline] fn zero() -> Self { Fp32::<P>(BigInteger::from(0), PhantomData) } #[inline] fn is_zero(&self) -> bool { self.0.is_zero() } } impl<P: Fp32Parameters> One for Fp32<P> { #[inline] fn one() -> Self { Fp32::new(BigInteger::from(1)) } #[inline] fn is_one(&self) -> bool { self == &Self::one() } } impl<P: Fp32Parameters> Field for Fp32<P> { #[inline] fn double(&self) -> Self { let mut temp = *self; temp.double_in_place(); temp } #[inline] fn double_in_place(&mut self) -> &mut Self { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); self } #[inline] fn square(&self) -> Self { let mut temp = self.clone(); temp.square_in_place(); temp } #[inline] fn square_in_place(&mut self) -> &mut Self { let cur = *self; *self *= &cur; self } #[inline] fn inverse(&self) -> Option<Self> { if self.is_zero() { None } else { // Guajardo Kumar Paar Pelzl // Efficient Software-Implementation of Finite Fields with Applications to // Cryptography // Algorithm 16 (BEA for Inversion in Fp) let one = BigInteger::from(1); let mut u = self.0; let mut v = P::MODULUS; let mut b = Fp32::<P>(P::R2, PhantomData); // Avoids unnecessary reduction step. let mut c = Self::zero(); while u != one && v != one { while u.is_even() { u.div2(); if b.0.is_even() { b.0.div2(); } else { b.0.add_nocarry(&P::MODULUS); b.0.div2(); } } while v.is_even() { v.div2(); if c.0.is_even() { c.0.div2(); } else { c.0.add_nocarry(&P::MODULUS); c.0.div2(); } } if v < u { u.sub_noborrow(&v); b.sub_assign(&c); } else { v.sub_noborrow(&u); c.sub_assign(&b); } } if u == one { Some(b) } else { Some(c) } } } fn inverse_in_place(&mut self) -> Option<&mut Self> { if let Some(inverse) = self.inverse() { *self = inverse; Some(self) } else { None } } #[inline] fn frobenius_map(&mut self, _: usize) { // No-op: No effect in a prime field. } } impl<P: Fp32Parameters> UniformRandom for Fp32<P> { /// Samples a uniformly random field element. #[inline] fn uniform<R: RngCore + CryptoRng>(r: &mut R) -> Self { loop { let mut tmp = Fp32::<P>(BigInteger::uniform(r), PhantomData); // Mask away the unused bits at the beginning. (&mut tmp.0).0 &= std::u64::MAX >> P::REPR_SHAVE_BITS; if tmp.is_valid() { return tmp; } } } } impl<P: Fp32Parameters> PrimeField for Fp32<P> { type Params = P; type BigInt = P::BigInt; #[inline] fn from_repr(r: BigInteger) -> Self { let r = Fp32::new(r); if r.is_valid() { r } else { Self::zero() } } #[inline] fn into_repr(&self) -> BigInteger { self.0 } #[inline] fn from_random_bytes(bytes: &[u8]) -> Option<Self> { let mut result = Self::zero(); if result.0.read_le((&bytes[..]).by_ref()).is_ok() { (&mut result.0).0 &= std::u64::MAX >> P::REPR_SHAVE_BITS; if result.is_valid() { Some(result) } else { None } } else { None } } #[inline] fn multiplicative_generator() -> Self { Fp32::<P>(P::GENERATOR, PhantomData) } #[inline] fn root_of_unity() -> Self { Fp32::<P>(P::ROOT_OF_UNITY, PhantomData) } } impl<P: Fp32Parameters> ToBytes for Fp32<P> { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.into_repr().write(writer) } } impl<P: Fp32Parameters> FromBytes for Fp32<P> { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { BigInteger::read(reader).map(Fp32::from_repr) } } /// `Fp` elements are ordered lexicographically. impl<P: Fp32Parameters> Ord for Fp32<P> { #[inline(always)] fn cmp(&self, other: &Self) -> Ordering { self.into_repr().cmp(&other.into_repr()) } } impl<P: Fp32Parameters> PartialOrd for Fp32<P> { #[inline(always)] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<P: Fp32Parameters> FromStr for Fp32<P> { type Err = (); /// Interpret a string of numbers as a (congruent) prime field element. /// Does not accept unnecessary leading zeroes or a blank string. fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { return Err(()); } if s == "0" { return Ok(Self::zero()); } let mut res = Self::zero(); let ten = Self::from_repr(<Self as PrimeField>::BigInt::from(10)); let mut first_digit = true; for c in s.chars() { match c.to_digit(10) { Some(c) => { if first_digit { if c == 0 { return Err(()); } first_digit = false; } res.mul_assign(&ten); res.add_assign(&Self::from_repr(<Self as PrimeField>::BigInt::from( u64::from(c), ))); } None => { return Err(()); } } } if !res.is_valid() { Err(()) } else { Ok(res) } } } impl<P: Fp32Parameters> Display for Fp32<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "Fp32({})", self.0) } } impl<P: Fp32Parameters> std::fmt::Debug for Fp32<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { let big_int = self.into_repr(); if big_int.0 > (P::MODULUS.0 / 2) { write!(f, "Fp32({})", (P::MODULUS.0 as i64) - (big_int.0 as i64)) } else { write!(f, "Fp32({})", big_int.0) } } } impl<P: Fp32Parameters> Neg for Fp32<P> { type Output = Self; #[inline] #[must_use] fn neg(self) -> Self { if !self.is_zero() { let mut tmp = P::MODULUS; tmp.sub_noborrow(&self.0); Fp32::<P>(tmp, PhantomData) } else { self } } } impl<'a, P: Fp32Parameters> Add<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn add(self, other: &Self) -> Self { let mut result = self; result.add_assign(other); result } } impl<'a, P: Fp32Parameters> Sub<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn sub(self, other: &Self) -> Self { let mut result = self; result.sub_assign(other); result } } impl<'a, P: Fp32Parameters> Mul<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn mul(self, other: &Self) -> Self { let mut result = self; result.mul_assign(other); result } } impl<'a, P: Fp32Parameters> Div<&'a Fp32<P>> for Fp32<P> { type Output = Self; #[inline] fn div(self, other: &Self) -> Self { let mut result = self; result.mul_assign(&other.inverse().unwrap()); result } } impl<'a, P: Fp32Parameters> AddAssign<&'a Self> for Fp32<P> { #[inline] fn add_assign(&mut self, other: &Self) { // This cannot exceed the backing capacity. self.0.add_nocarry(&other.0); // However, it may need to be reduced self.reduce(); } } impl<'a, P: Fp32Parameters> SubAssign<&'a Self> for Fp32<P> { #[inline] fn sub_assign(&mut self, other: &Self) { // If `other` is larger than `self`, add the modulus to self first. if other.0 > self.0 { self.0.add_nocarry(&P::MODULUS); } self.0.sub_noborrow(&other.0); } } impl<'a, P: Fp32Parameters> MulAssign<&'a Self> for Fp32<P> { #[inline] fn mul_assign(&mut self, other: &Self) { let res = (self.0).0 * (other.0).0 % P::MODULUS.0; (&mut self.0).0 = res; } } impl<'a, P: Fp32Parameters> DivAssign<&'a Self> for Fp32<P> { #[inline] fn div_assign(&mut self, other: &Self) { self.mul_assign(&other.inverse().unwrap()); } } impl_ops_traits!(Fp32, Fp32Parameters);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/models/fp_256.rs
rust/algebra/src/fields/models/fp_256.rs
use num_traits::{One, Zero}; use rand::{CryptoRng, RngCore}; use std::{ cmp::{Ord, Ordering, PartialOrd}, fmt::{Display, Formatter, Result as FmtResult}, io::{Read, Result as IoResult, Write}, marker::PhantomData, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, str::FromStr, }; use serde::{Deserialize, Serialize}; use crate::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger256 as BigInteger}, bytes::{FromBytes, ToBytes}, fields::{Field, FpParameters, LegendreSymbol, PrimeField, SquareRootField}, UniformRandom, }; pub trait Fp256Parameters: FpParameters<BigInt = BigInteger> {} #[derive(Derivative, Serialize, Deserialize)] #[derivative( Default(bound = "P: Fp256Parameters"), Hash(bound = "P: Fp256Parameters"), Clone(bound = "P: Fp256Parameters"), Copy(bound = "P: Fp256Parameters"), Debug(bound = "P: Fp256Parameters"), PartialEq(bound = "P: Fp256Parameters"), Eq(bound = "P: Fp256Parameters") )] #[serde(bound = "P: Fp256Parameters")] pub struct Fp256<P: Fp256Parameters>(pub(crate) BigInteger, #[serde(skip)] PhantomData<P>); impl<P: Fp256Parameters> Fp256<P> { #[inline] pub const fn new(element: BigInteger) -> Self { Fp256::<P>(element, PhantomData) } #[inline] fn is_valid(&self) -> bool { self.0 < P::MODULUS } #[inline] fn reduce(&mut self) { if !self.is_valid() { self.0.sub_noborrow(&P::MODULUS); } } #[inline] fn mont_reduce( &mut self, r0: u64, mut r1: u64, mut r2: u64, mut r3: u64, mut r4: u64, mut r5: u64, mut r6: u64, mut r7: u64, ) { // The Montgomery reduction here is based on Algorithm 14.32 in // Handbook of Applied Cryptography // <http://cacr.uwaterloo.ca/hac/about/chap14.pdf>. let k = r0.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry); r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry); r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry); r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry); r4 = fa::adc(r4, 0, &mut carry); let carry2 = carry; let k = r1.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry); r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry); r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry); r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry); r5 = fa::adc(r5, carry2, &mut carry); let carry2 = carry; let k = r2.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry); r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry); r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry); r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry); r6 = fa::adc(r6, carry2, &mut carry); let carry2 = carry; let k = r3.wrapping_mul(P::INV); let mut carry = 0; fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry); r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry); r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry); r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry); r7 = fa::adc(r7, carry2, &mut carry); (self.0).0[0] = r4; (self.0).0[1] = r5; (self.0).0[2] = r6; (self.0).0[3] = r7; self.reduce(); } } impl<P: Fp256Parameters> Zero for Fp256<P> { #[inline] fn zero() -> Self { Fp256::<P>(BigInteger::from(0), PhantomData) } #[inline] fn is_zero(&self) -> bool { self.0.is_zero() } } impl<P: Fp256Parameters> One for Fp256<P> { #[inline] fn one() -> Self { Fp256::<P>(P::R, PhantomData) } #[inline] fn is_one(&self) -> bool { self == &Self::one() } } impl<P: Fp256Parameters> Field for Fp256<P> { #[inline] fn double(&self) -> Self { let mut temp = *self; temp.double_in_place(); temp } #[inline] fn double_in_place(&mut self) -> &mut Self { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); self } #[inline] fn square(&self) -> Self { let mut temp = self.clone(); temp.square_in_place(); temp } #[inline] fn square_in_place(&mut self) -> &mut Self { let mut carry = 0; let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry); let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry); let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry); let r4 = carry; let mut carry = 0; let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry); let r5 = carry; let mut carry = 0; let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry); let r6 = carry; let r7 = r6 >> 63; let r6 = (r6 << 1) | (r5 >> 63); let r5 = (r5 << 1) | (r4 >> 63); let r4 = (r4 << 1) | (r3 >> 63); let r3 = (r3 << 1) | (r2 >> 63); let r2 = (r2 << 1) | (r1 >> 63); let r1 = r1 << 1; let mut carry = 0; let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry); let r1 = fa::adc(r1, 0, &mut carry); let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry); let r3 = fa::adc(r3, 0, &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry); let r5 = fa::adc(r5, 0, &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry); let r7 = fa::adc(r7, 0, &mut carry); self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7); self } #[inline] fn inverse(&self) -> Option<Self> { if self.is_zero() { None } else { // Guajardo Kumar Paar Pelzl // Efficient Software-Implementation of Finite Fields with Applications to // Cryptography // Algorithm 16 (BEA for Inversion in Fp) let one = BigInteger::from(1); let mut u = self.0; let mut v = P::MODULUS; let mut b = Fp256::<P>(P::R2, PhantomData); // Avoids unnecessary reduction step. let mut c = Self::zero(); while u != one && v != one { while u.is_even() { u.div2(); if b.0.is_even() { b.0.div2(); } else { b.0.add_nocarry(&P::MODULUS); b.0.div2(); } } while v.is_even() { v.div2(); if c.0.is_even() { c.0.div2(); } else { c.0.add_nocarry(&P::MODULUS); c.0.div2(); } } if v < u { u.sub_noborrow(&v); b.sub_assign(&c); } else { v.sub_noborrow(&u); c.sub_assign(&b); } } if u == one { Some(b) } else { Some(c) } } } fn inverse_in_place(&mut self) -> Option<&mut Self> { if let Some(inverse) = self.inverse() { *self = inverse; Some(self) } else { None } } #[inline] fn frobenius_map(&mut self, _: usize) { // No-op: No effect in a prime field. } } impl<P: Fp256Parameters> UniformRandom for Fp256<P> { /// Samples a uniformly random field element. #[inline] fn uniform<R: RngCore + CryptoRng>(r: &mut R) -> Self { loop { let mut tmp = Fp256::<P>(BigInteger::uniform(r), PhantomData); // Mask away the unused bits at the beginning. tmp.0.as_mut()[3] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; if tmp.is_valid() { return tmp; } } } } impl<P: Fp256Parameters> PrimeField for Fp256<P> { type Params = P; type BigInt = BigInteger; #[inline] fn from_repr(r: BigInteger) -> Self { let mut r = Fp256(r, PhantomData); if r.is_valid() { r.mul_assign(&Fp256(P::R2, PhantomData)); r } else { Self::zero() } } #[inline] fn into_repr(&self) -> BigInteger { let mut r = *self; r.mont_reduce( (self.0).0[0], (self.0).0[1], (self.0).0[2], (self.0).0[3], 0, 0, 0, 0, ); r.0 } #[inline] fn from_random_bytes(bytes: &[u8]) -> Option<Self> { let mut result = Self::zero(); if result.0.read_le((&bytes[..]).by_ref()).is_ok() { result.0.as_mut()[3] &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; if result.is_valid() { Some(result) } else { None } } else { None } } #[inline] fn multiplicative_generator() -> Self { Fp256::<P>(P::GENERATOR, PhantomData) } #[inline] fn root_of_unity() -> Self { Fp256::<P>(P::ROOT_OF_UNITY, PhantomData) } } impl<P: Fp256Parameters> SquareRootField for Fp256<P> { #[inline] fn legendre(&self) -> LegendreSymbol { use crate::fields::LegendreSymbol::*; // s = self^((MODULUS - 1) // 2) let s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO); if s.is_zero() { Zero } else if s.is_one() { QuadraticResidue } else { QuadraticNonResidue } } // Only works for p = 1 (mod 16). #[inline] fn sqrt(&self) -> Option<Self> { sqrt_impl!(Self, P, self) } fn sqrt_in_place(&mut self) -> Option<&mut Self> { if let Some(sqrt) = self.sqrt() { *self = sqrt; Some(self) } else { None } } } impl<P: Fp256Parameters> ToBytes for Fp256<P> { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.into_repr().write(writer) } } impl<P: Fp256Parameters> FromBytes for Fp256<P> { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { BigInteger::read(reader).map(Fp256::from_repr) } } /// `Fp` elements are ordered lexicographically. impl<P: Fp256Parameters> Ord for Fp256<P> { #[inline(always)] fn cmp(&self, other: &Self) -> Ordering { self.into_repr().cmp(&other.into_repr()) } } impl<P: Fp256Parameters> PartialOrd for Fp256<P> { #[inline(always)] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<P: Fp256Parameters> FromStr for Fp256<P> { type Err = (); /// Interpret a string of numbers as a (congruent) prime field element. /// Does not accept unnecessary leading zeroes or a blank string. fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { return Err(()); } if s == "0" { return Ok(Self::zero()); } let mut res = Self::zero(); let ten = Self::from_repr(<Self as PrimeField>::BigInt::from(10)); let mut first_digit = true; for c in s.chars() { match c.to_digit(10) { Some(c) => { if first_digit { if c == 0 { return Err(()); } first_digit = false; } res.mul_assign(&ten); res.add_assign(&Self::from_repr(<Self as PrimeField>::BigInt::from( u64::from(c), ))); } None => { return Err(()); } } } if !res.is_valid() { Err(()) } else { Ok(res) } } } impl<P: Fp256Parameters> Display for Fp256<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "Fp256({})", self.0) } } impl<P: Fp256Parameters> Neg for Fp256<P> { type Output = Self; #[inline] #[must_use] fn neg(self) -> Self { if !self.is_zero() { let mut tmp = P::MODULUS; tmp.sub_noborrow(&self.0); Fp256::<P>(tmp, PhantomData) } else { self } } } impl<'a, P: Fp256Parameters> Add<&'a Fp256<P>> for Fp256<P> { type Output = Self; #[inline] fn add(self, other: &Self) -> Self { let mut result = self; result.add_assign(other); result } } impl<'a, P: Fp256Parameters> Sub<&'a Fp256<P>> for Fp256<P> { type Output = Self; #[inline] fn sub(self, other: &Self) -> Self { let mut result = self; result.sub_assign(other); result } } impl<'a, P: Fp256Parameters> Mul<&'a Fp256<P>> for Fp256<P> { type Output = Self; #[inline] fn mul(self, other: &Self) -> Self { let mut result = self; result.mul_assign(other); result } } impl<'a, P: Fp256Parameters> Div<&'a Fp256<P>> for Fp256<P> { type Output = Self; #[inline] fn div(self, other: &Self) -> Self { let mut result = self; result.mul_assign(&other.inverse().unwrap()); result } } impl<'a, P: Fp256Parameters> AddAssign<&'a Self> for Fp256<P> { #[inline] fn add_assign(&mut self, other: &Self) { // This cannot exceed the backing capacity. self.0.add_nocarry(&other.0); // However, it may need to be reduced self.reduce(); } } impl<'a, P: Fp256Parameters> SubAssign<&'a Self> for Fp256<P> { #[inline] fn sub_assign(&mut self, other: &Self) { // If `other` is larger than `self`, add the modulus to self first. if other.0 > self.0 { self.0.add_nocarry(&P::MODULUS); } self.0.sub_noborrow(&other.0); } } impl<'a, P: Fp256Parameters> MulAssign<&'a Self> for Fp256<P> { #[inline] fn mul_assign(&mut self, other: &Self) { let mut carry = 0; let r0 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[0], &mut carry); let r1 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[1], &mut carry); let r2 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[2], &mut carry); let r3 = fa::mac_with_carry(0, (self.0).0[0], (other.0).0[3], &mut carry); let r4 = carry; let mut carry = 0; let r1 = fa::mac_with_carry(r1, (self.0).0[1], (other.0).0[0], &mut carry); let r2 = fa::mac_with_carry(r2, (self.0).0[1], (other.0).0[1], &mut carry); let r3 = fa::mac_with_carry(r3, (self.0).0[1], (other.0).0[2], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[1], (other.0).0[3], &mut carry); let r5 = carry; let mut carry = 0; let r2 = fa::mac_with_carry(r2, (self.0).0[2], (other.0).0[0], &mut carry); let r3 = fa::mac_with_carry(r3, (self.0).0[2], (other.0).0[1], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[2], (other.0).0[2], &mut carry); let r5 = fa::mac_with_carry(r5, (self.0).0[2], (other.0).0[3], &mut carry); let r6 = carry; let mut carry = 0; let r3 = fa::mac_with_carry(r3, (self.0).0[3], (other.0).0[0], &mut carry); let r4 = fa::mac_with_carry(r4, (self.0).0[3], (other.0).0[1], &mut carry); let r5 = fa::mac_with_carry(r5, (self.0).0[3], (other.0).0[2], &mut carry); let r6 = fa::mac_with_carry(r6, (self.0).0[3], (other.0).0[3], &mut carry); let r7 = carry; self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7); } } impl<'a, P: Fp256Parameters> DivAssign<&'a Self> for Fp256<P> { #[inline] fn div_assign(&mut self, other: &Self) { self.mul_assign(&other.inverse().unwrap()); } } impl_ops_traits!(Fp256, Fp256Parameters);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/models/fp_64.rs
rust/algebra/src/fields/models/fp_64.rs
use num_traits::{One, Zero}; use rand::{CryptoRng, RngCore}; use std::{ cmp::{Ord, Ordering, PartialOrd}, fmt::{Display, Formatter, Result as FmtResult}, io::{Read, Result as IoResult, Write}, marker::PhantomData, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, str::FromStr, }; use serde::{Deserialize, Serialize}; use crate::{ biginteger::{BigInteger as _BigInteger, BigInteger64 as BigInteger}, bytes::{FromBytes, ToBytes}, fields::{Field, FpParameters, PrimeField}, UniformRandom, }; pub trait Fp64Parameters: FpParameters<BigInt = BigInteger> {} #[derive(Derivative, Serialize, Deserialize)] #[derivative( Default(bound = "P: Fp64Parameters"), Hash(bound = "P: Fp64Parameters"), Clone(bound = "P: Fp64Parameters"), Copy(bound = "P: Fp64Parameters"), PartialEq(bound = "P: Fp64Parameters"), Eq(bound = "P: Fp64Parameters") )] #[serde(bound = "P: Fp64Parameters")] pub struct Fp64<P: Fp64Parameters>(pub(crate) BigInteger, #[serde(skip)] PhantomData<P>); impl<P: Fp64Parameters> Fp64<P> { #[inline] pub const fn new(element: BigInteger) -> Self { Fp64::<P>(element, PhantomData) } #[inline] fn is_valid(&self) -> bool { self.0 < P::MODULUS } #[inline] fn reduce(&mut self) { if !self.is_valid() { self.0.sub_noborrow(&P::MODULUS); } } #[inline] fn mont_reduce(&mut self, mul_result: u128) { let m = (mul_result as u64).wrapping_mul(P::INV) as u128; (self.0).0 = ((mul_result + m * u128::from(P::MODULUS.0)) >> 64) as u64; self.reduce(); } } impl<P: Fp64Parameters> Zero for Fp64<P> { #[inline] fn zero() -> Self { Fp64::<P>(BigInteger::from(0), PhantomData) } #[inline] fn is_zero(&self) -> bool { self.0.is_zero() } } impl<P: Fp64Parameters> One for Fp64<P> { #[inline] fn one() -> Self { Fp64::new(BigInteger::from(P::R)) } #[inline] fn is_one(&self) -> bool { self == &Self::one() } } impl<P: Fp64Parameters> Field for Fp64<P> { #[inline] fn double(&self) -> Self { let mut temp = *self; temp.double_in_place(); temp } #[inline] fn double_in_place(&mut self) -> &mut Self { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); self } #[inline] fn square(&self) -> Self { let mut temp = self.clone(); temp.square_in_place(); temp } #[inline] fn square_in_place(&mut self) -> &mut Self { let cur = *self; *self *= &cur; self } #[inline] fn inverse(&self) -> Option<Self> { if self.is_zero() { None } else { Some(self.pow(&[P::MODULUS.0 - 2])) } } fn inverse_in_place(&mut self) -> Option<&mut Self> { if let Some(inverse) = self.inverse() { *self = inverse; Some(self) } else { None } } #[inline] fn frobenius_map(&mut self, _: usize) { // No-op: No effect in a prime field. } } impl<P: Fp64Parameters> UniformRandom for Fp64<P> { /// Samples a uniformly random field element. #[inline] fn uniform<R: RngCore + CryptoRng>(r: &mut R) -> Self { loop { let mut tmp = Fp64::<P>(BigInteger::uniform(r), PhantomData); // Mask away the unused bits at the beginning. (&mut tmp.0).0 &= std::u64::MAX >> P::REPR_SHAVE_BITS; if tmp.is_valid() { return tmp; } } } } impl<P: Fp64Parameters> PrimeField for Fp64<P> { type Params = P; type BigInt = BigInteger; #[inline] fn from_repr(r: BigInteger) -> Self { let mut r = Fp64(r, PhantomData); if r.is_valid() { r.mul_assign(&Fp64(P::R2, PhantomData)); r } else { Self::zero() } } #[inline] fn into_repr(&self) -> BigInteger { let mut r = *self; r.mont_reduce((self.0).0 as u128); r.0 } #[inline] fn from_random_bytes(bytes: &[u8]) -> Option<Self> { let mut result = Self::zero(); if result.0.read_le((&bytes[..]).by_ref()).is_ok() { (result.0).0 &= 0xffffffffffffffff >> P::REPR_SHAVE_BITS; if result.is_valid() { Some(result) } else { None } } else { None } } #[inline] fn multiplicative_generator() -> Self { Fp64::<P>(P::GENERATOR, PhantomData) } #[inline] fn root_of_unity() -> Self { Fp64::<P>(P::ROOT_OF_UNITY, PhantomData) } } impl<P: Fp64Parameters> ToBytes for Fp64<P> { #[inline] fn write<W: Write>(&self, writer: W) -> IoResult<()> { self.into_repr().write(writer) } } impl<P: Fp64Parameters> FromBytes for Fp64<P> { #[inline] fn read<R: Read>(reader: R) -> IoResult<Self> { BigInteger::read(reader).map(Fp64::from_repr) } } /// `Fp` elements are ordered lexicographically. impl<P: Fp64Parameters> Ord for Fp64<P> { #[inline(always)] fn cmp(&self, other: &Self) -> Ordering { self.into_repr().cmp(&other.into_repr()) } } impl<P: Fp64Parameters> PartialOrd for Fp64<P> { #[inline(always)] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<P: Fp64Parameters> FromStr for Fp64<P> { type Err = (); /// Interpret a string of numbers as a (congruent) prime field element. /// Does not accept unnecessary leading zeroes or a blank string. fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { return Err(()); } if s == "0" { return Ok(Self::zero()); } let mut res = Self::zero(); let ten = Self::from_repr(<Self as PrimeField>::BigInt::from(10)); let mut first_digit = true; for c in s.chars() { match c.to_digit(10) { Some(c) => { if first_digit { if c == 0 { return Err(()); } first_digit = false; } res.mul_assign(&ten); res.add_assign(&Self::from_repr(<Self as PrimeField>::BigInt::from( u64::from(c), ))); } None => { return Err(()); } } } if !res.is_valid() { Err(()) } else { Ok(res) } } } impl<P: Fp64Parameters> Display for Fp64<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { write!(f, "Fp64({})", self.0) } } impl<P: Fp64Parameters> std::fmt::Debug for Fp64<P> { #[inline] fn fmt(&self, f: &mut Formatter) -> FmtResult { let big_int = self.into_repr(); if big_int.0 > (P::MODULUS_MINUS_ONE_DIV_TWO.0) { write!(f, "Fp64({})", (P::MODULUS.0 as i64) - (big_int.0 as i64)) } else { write!(f, "Fp64({})", big_int.0) } } } impl<P: Fp64Parameters> Neg for Fp64<P> { type Output = Self; #[inline] #[must_use] fn neg(self) -> Self { if !self.is_zero() { let mut tmp = P::MODULUS; tmp.sub_noborrow(&self.0); Fp64::<P>(tmp, PhantomData) } else { self } } } impl<'a, P: Fp64Parameters> Add<&'a Fp64<P>> for Fp64<P> { type Output = Self; #[inline] fn add(self, other: &Self) -> Self { let mut result = self; result.add_assign(other); result } } impl<'a, P: Fp64Parameters> Sub<&'a Fp64<P>> for Fp64<P> { type Output = Self; #[inline] fn sub(self, other: &Self) -> Self { let mut result = self; result.sub_assign(other); result } } impl<'a, P: Fp64Parameters> Mul<&'a Fp64<P>> for Fp64<P> { type Output = Self; #[inline] fn mul(self, other: &Self) -> Self { let mut result = self; result.mul_assign(other); result } } impl<'a, P: Fp64Parameters> Div<&'a Fp64<P>> for Fp64<P> { type Output = Self; #[inline] fn div(self, other: &Self) -> Self { let mut result = self; result.mul_assign(&other.inverse().unwrap()); result } } impl<'a, P: Fp64Parameters> AddAssign<&'a Self> for Fp64<P> { #[inline] fn add_assign(&mut self, other: &Self) { // This cannot exceed the backing capacity. self.0.add_nocarry(&other.0); // However, it may need to be reduced self.reduce(); } } impl<'a, P: Fp64Parameters> SubAssign<&'a Self> for Fp64<P> { #[inline] fn sub_assign(&mut self, other: &Self) { // If `other` is larger than `self`, add the modulus to self first. if other.0 > self.0 { self.0.add_nocarry(&P::MODULUS); } self.0.sub_noborrow(&other.0); } } impl<'a, P: Fp64Parameters> MulAssign<&'a Self> for Fp64<P> { #[inline] fn mul_assign(&mut self, other: &Self) { let prod = (self.0).0 as u128 * (other.0).0 as u128; self.mont_reduce(prod); } } impl<'a, P: Fp64Parameters> DivAssign<&'a Self> for Fp64<P> { #[inline] fn div_assign(&mut self, other: &Self) { self.mul_assign(&other.inverse().unwrap()); } } impl_ops_traits!(Fp64, Fp64Parameters);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/models/mod.rs
rust/algebra/src/fields/models/mod.rs
pub mod fp_32_lazy; pub mod fp_32; pub use self::fp_32::*; pub mod fp_64; pub use self::fp_64::*; pub mod fp_256; pub use self::fp_256::*; pub mod fp_384; pub use self::fp_384::*;
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/near_mersenne_64/tests.rs
rust/algebra/src/fields/near_mersenne_64/tests.rs
#[cfg(test)] mod tests { use crate::fields::{ tests::{field_test, primefield_test}, UniformRandom, }; use rand::SeedableRng; use rand_chacha::ChaChaRng; const RANDOMNESS: [u8; 32] = [ 0x99, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0x62, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; #[test] fn test_f() { use crate::fields::near_mersenne_64::F; let mut rng = ChaChaRng::from_seed(RANDOMNESS); let a = F::uniform(&mut rng); let b = F::uniform(&mut rng); field_test(a, b); primefield_test::<F>(); } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/algebra/src/fields/near_mersenne_64/mod.rs
rust/algebra/src/fields/near_mersenne_64/mod.rs
use crate::{ biginteger::BigInteger64 as BigInteger, fields::{Fp64, Fp64Parameters, FpParameters}, }; pub type F = Fp64<FParameters>; pub struct FParameters; impl Fp64Parameters for FParameters {} impl FpParameters for FParameters { type BigInt = BigInteger; const MODULUS: BigInteger = BigInteger(2061584302081); const MODULUS_BITS: u32 = 41u32; const CAPACITY: u32 = Self::MODULUS_BITS - 1; const REPR_SHAVE_BITS: u32 = 23; const R: BigInteger = BigInteger(1099502679928); const R2: BigInteger = BigInteger(1824578462277); const INV: u64 = 2061584302079; const GENERATOR: BigInteger = BigInteger(7u64); const TWO_ADICITY: u32 = 37; const ROOT_OF_UNITY: BigInteger = BigInteger(624392905781); const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger(1030792151040); const T: BigInteger = BigInteger(15); const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger(7); } #[cfg(test)] mod tests;
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/bench-utils/src/lib.rs
rust/bench-utils/src/lib.rs
#[cfg(feature = "timer")] extern crate colored; pub use self::inner::*; #[cfg(feature = "timer")] #[macro_use] pub mod inner { pub use colored::Colorize; // print-trace requires std, so these imports are well-defined pub use std::{ format, println, string::{String, ToString}, sync::atomic::{AtomicUsize, Ordering}, time::Instant, }; pub static NUM_INDENT: AtomicUsize = AtomicUsize::new(0); pub const PAD_CHAR: &'static str = "·"; #[macro_export] macro_rules! timer_start { ($msg:expr) => {{ use std::{sync::atomic::Ordering, time::Instant}; use $crate::{compute_indent, Colorize, NUM_INDENT}; let result = $msg(); let start_info = "Start:".yellow().bold(); let indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed); let indent = compute_indent(indent_amount); if NUM_INDENT.fetch_add(0, Ordering::Relaxed) <= 10 { println!("{}{:8} {}", indent, start_info, result); } NUM_INDENT.fetch_add(1, Ordering::Relaxed); (result, Instant::now()) }}; } #[macro_export] macro_rules! timer_end { ($time:expr) => {{ use std::{io::Write, sync::atomic::Ordering}; use $crate::{compute_indent, Colorize, NUM_INDENT}; let time = $time.1; let final_time = time.elapsed(); if let Ok(file_name) = std::env::var("BENCH_OUTPUT_FILE") { let mut file = std::fs::OpenOptions::new() .append(true) .create(true) .open(file_name) .unwrap(); writeln!(&mut file, "{}, {:?}", $time.0, final_time).unwrap(); } let final_time = { let secs = final_time.as_secs(); let millis = final_time.subsec_millis(); let micros = final_time.subsec_micros() % 1000; let nanos = final_time.subsec_nanos() % 1000; if secs != 0 { format!("{}.{}s", secs, millis).bold() } else if millis > 0 { format!("{}.{}ms", millis, micros).bold() } else if micros > 0 { format!("{}.{}µs", micros, nanos).bold() } else { format!("{}ns", final_time.subsec_nanos()).bold() } }; let end_info = "End:".green().bold(); let message = format!("{}", $time.0); if NUM_INDENT.fetch_add(0, Ordering::Relaxed) <= 10 { NUM_INDENT.fetch_sub(1, Ordering::Relaxed); let indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed); let indent = compute_indent(indent_amount); // Todo: Recursively ensure that *entire* string is of appropriate // width (not just message). println!( "{}{:8} {:.<pad$}{}", indent, end_info, message, final_time, pad = 75 - indent_amount ); } }}; } #[macro_export] macro_rules! add_to_trace { ($title:expr, $msg:expr) => {{ use std::io::Write; use $crate::{ compute_indent, compute_indent_whitespace, format, Colorize, Ordering, ToString, NUM_INDENT, }; let start_msg = "StartMsg".yellow().bold(); let end_msg = "EndMsg".green().bold(); let title = $title(); let start_msg = format!("{}: {}", start_msg, title); let end_msg = format!("{}: {}", end_msg, title); let start_indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed); let start_indent = compute_indent(start_indent_amount); let msg_indent_amount = 2 * NUM_INDENT.fetch_add(0, Ordering::Relaxed) + 2; let msg_indent = compute_indent_whitespace(msg_indent_amount); let mut final_message = "\n".to_string(); for line in $msg().lines() { final_message += &format!("{}{}\n", msg_indent, line,); } if let Ok(file_name) = std::env::var("BENCH_OUTPUT_FILE") { let mut file = std::fs::OpenOptions::new() .append(true) .create(true) .open(file_name) .unwrap(); writeln!(&mut file, "{}, {:?}", title, final_message).unwrap(); } // Todo: Recursively ensure that *entire* string is of appropriate // width (not just message). println!("{}{}", start_indent, start_msg); println!("{}{}", msg_indent, final_message,); println!("{}{}", start_indent, end_msg); }}; } pub fn compute_indent(indent_amount: usize) -> String { use std::env::var; let mut indent = String::new(); let pad_string = match var("CLICOLOR") { Ok(val) => { if val == "0" { " " } else { PAD_CHAR } } Err(_) => PAD_CHAR, }; for _ in 0..indent_amount { indent.push_str(&pad_string.white()); } indent } pub fn compute_indent_whitespace(indent_amount: usize) -> String { let mut indent = String::new(); for _ in 0..indent_amount { indent.push_str(" "); } indent } } #[cfg(not(feature = "timer"))] #[macro_use] mod inner { #[macro_export] macro_rules! timer_start { ($msg:expr) => { () }; } #[macro_export] macro_rules! add_to_trace { ($title:expr, $msg:expr) => { let _ = $msg; }; } #[macro_export] macro_rules! timer_end { ($time:expr) => { let _ = $time; }; } } mod tests { #[test] fn print_start_end() { let start = timer_start!(|| "Hello"); add_to_trace!(|| "HelloMsg", || "Hello, I\nAm\nA\nMessage"); timer_end!(start); } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/lib.rs
rust/neural-network/src/lib.rs
#![allow(incomplete_features)] #![feature(specialization)] use crate::tensors::{Input, Output}; use ndarray::ArrayView; use num_traits::{One, Zero}; use std::{ io::Read, ops::{AddAssign, Mul, MulAssign}, }; #[macro_use] pub extern crate ndarray; pub extern crate npy; extern crate npy_derive; pub mod layers; pub mod tensors; use layers::{ Layer, LayerInfo, LinearLayer::{Conv2d, FullyConnected}, }; use npy::NpyData; pub trait Evaluate<F> { #[inline] fn evaluate(&self, input: &Input<F>) -> Output<F> { self.evaluate_with_method(EvalMethod::default(), input) } fn evaluate_with_method(&self, method: EvalMethod, input: &Input<F>) -> Output<F>; } #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum EvalMethod { Naive, TorchDevice(tch::Device), } impl Default for EvalMethod { fn default() -> Self { EvalMethod::Naive } } impl EvalMethod { #[inline] pub fn with_tch_device(dev: tch::Device) -> Self { EvalMethod::TorchDevice(dev) } #[inline] pub fn with_var_store(vs: &tch::nn::Path) -> Self { EvalMethod::TorchDevice(vs.device()) } } /// `NeuralNetwork` represents a neural network as a sequence of `Layer`s that /// are to be evaluated sequentially. // TODO: add residual layers. // Probably by generalizing to a DAG instead of a Vec. #[derive(Debug, Default)] pub struct NeuralNetwork<F, C = F> { pub eval_method: EvalMethod, pub layers: Vec<Layer<F, C>>, } /// Describes the architecture and topology of the network #[derive(Clone, Debug, Default)] pub struct NeuralArchitecture<F, C = F> { pub layers: Vec<LayerInfo<F, C>>, } impl<F, C> NeuralNetwork<F, C> where C: std::convert::From<f64>, { /// `validate` ensures that the layers of `self` from a valid sequence. /// That is, `validate` checks that the output dimensions of the i-th layer /// are equal to the input dimensions of the (i+1)-th layer. // TODO: make this work with residual layers. // When we switch to DAGs, check that for every layer, the parent layer(s) // have matching output dimensions. pub fn validate(&self) -> bool { let len = self.layers.len(); if len == 0 || len == 1 { true } else { let mut result = true; for (i, (layer, next_layer)) in self.layers.iter().zip(&self.layers[1..]).enumerate() { if layer.output_dimensions() != next_layer.input_dimensions() { eprintln!( "layer {} is incorrect: expected {:?}, got {:?}", i, layer.output_dimensions(), next_layer.input_dimensions(), ); } result &= layer.output_dimensions() == next_layer.input_dimensions() } result } } pub fn from_numpy(&mut self, weights_path: &str) -> Result<(), ndarray::ShapeError> { // Deserialize numpy weights into a 1-d vector let mut buf = vec![]; std::fs::File::open(weights_path) .unwrap() .read_to_end(&mut buf) .unwrap(); let weights: Vec<f64> = NpyData::from_bytes(&buf).unwrap().to_vec(); let mut weights_idx = 0; // npy can't do multi-dimensional numpy serialization so all the weights are // stored as a single flattened array. for layer in self.layers.iter_mut() { let (kernel, bias) = match layer { Layer::LL(Conv2d { dims: _, params }) => (&params.kernel, &params.bias), Layer::LL(FullyConnected { dims: _, params }) => (&params.weights, &params.bias), _ => continue, }; let kernel_dims = kernel.dim(); let kernel_size = kernel_dims.0 * kernel_dims.1 * kernel_dims.2 * kernel_dims.3; let new_kernel = ArrayView::from_shape( kernel_dims, &weights[weights_idx..(weights_idx + kernel_size)], )?; weights_idx += kernel_size; let bias_dims = bias.dim(); let bias_size = bias_dims.0; let new_bias = ArrayView::from_shape(bias_dims, &weights[weights_idx..(weights_idx + bias_size)])?; weights_idx += bias_size; match layer { Layer::LL(Conv2d { dims: _, params }) => params.kernel.iter_mut(), Layer::LL(FullyConnected { dims: _, params }) => params.weights.iter_mut(), _ => unreachable!(), } .zip(new_kernel.iter()) .for_each(|(o, n)| *o = (*n).into()); match layer { Layer::LL(Conv2d { dims: _, params }) => params.bias.iter_mut(), Layer::LL(FullyConnected { dims: _, params }) => params.bias.iter_mut(), _ => unreachable!(), } .zip(new_bias.iter()) .for_each(|(o, n)| *o = (*n).into()); } Ok(()) } } impl<'a, F, C: Clone> From<&'a NeuralNetwork<F, C>> for NeuralArchitecture<F, C> { fn from(other: &'a NeuralNetwork<F, C>) -> Self { let layers = other.layers.iter().map(|layer| layer.into()).collect(); Self { layers } } } impl<F> Evaluate<F> for NeuralNetwork<F, F> where F: One + Zero + Mul<Output = F> + AddAssign + MulAssign + PartialOrd + Copy + From<f64> + std::fmt::Debug, { #[inline] fn evaluate(&self, input: &Input<F>) -> Output<F> { self.evaluate_with_method(self.eval_method, input) } /// `evaluate` takes an `input`, evaluates `self` over `input`, and returns /// the result. Panics if `self.validate() == false`. // TODO: make this work with residual layers. // When we switch to DAGs, check that for every layer, the parent layer(s) // have matching output dimensions. default fn evaluate_with_method(&self, method: EvalMethod, input: &Input<F>) -> Output<F> { assert!(self.validate()); if self.layers.len() == 0 { input.clone() } else { let mut input = input.clone(); for layer in &self.layers { let output = layer.evaluate_with_method(method, &input); input = output; } input } } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/layers/non_linear.rs
rust/neural-network/src/layers/non_linear.rs
use crate::{ layers::LayerDims, tensors::{Input, Output}, }; use algebra::Polynomial; use num_traits::{One, Zero}; use std::{ marker::PhantomData, ops::{AddAssign, Mul, MulAssign}, }; use crate::Evaluate; use NonLinearLayer::*; #[derive(Debug, Clone)] pub enum NonLinearLayer<F, C = F> { ReLU(LayerDims), PolyApprox { dims: LayerDims, poly: Polynomial<C>, _v: PhantomData<F>, }, } #[derive(Debug, Clone)] pub enum NonLinearLayerInfo<F, C> { ReLU, PolyApprox { poly: Polynomial<C>, _v: PhantomData<F>, }, } impl<F, C> NonLinearLayer<F, C> { pub fn dimensions(&self) -> LayerDims { match self { ReLU(dims) | PolyApprox { dims, .. } => *dims, } } pub fn input_dimensions(&self) -> (usize, usize, usize, usize) { self.dimensions().input_dimensions() } pub fn output_dimensions(&self) -> (usize, usize, usize, usize) { self.dimensions().input_dimensions() } } impl<F, C> Evaluate<F> for NonLinearLayer<F, C> where F: One + Zero + Mul<C, Output = F> + AddAssign + MulAssign + PartialOrd<C> + Copy, C: Copy + From<f64> + Zero, { fn evaluate_with_method(&self, _: crate::EvalMethod, input: &Input<F>) -> Output<F> { assert_eq!(self.input_dimensions(), input.dim()); let mut output = Output::zeros(self.output_dimensions()); match self { ReLU(_) => { let zero = C::zero(); let f_zero = F::zero(); for (&inp, out) in input.iter().zip(&mut output) { *out = if inp > zero { inp } else { f_zero }; } } PolyApprox { dims: _d, poly, .. } => { for (&inp, out) in input.iter().zip(&mut output) { *out = poly.evaluate(inp); } } }; output } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/layers/mod.rs
rust/neural-network/src/layers/mod.rs
use crate::{ tensors::{Input, Output}, Evaluate, }; use num_traits::{One, Zero}; use std::ops::{AddAssign, Mul, MulAssign}; mod linear; mod non_linear; pub use linear::*; pub use non_linear::*; use Layer::*; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct LayerDims { /// Dimension of the input to a layer: `(batch_size, channels, height, /// width)` pub input_dims: (usize, usize, usize, usize), /// Dimension of the output of a layer: `(batch_size, channels, height, /// width)` pub output_dims: (usize, usize, usize, usize), } impl LayerDims { pub fn input_dimensions(&self) -> (usize, usize, usize, usize) { self.input_dims } pub fn output_dimensions(&self) -> (usize, usize, usize, usize) { self.output_dims } } #[derive(Debug)] pub enum Layer<F, C> { LL(LinearLayer<F, C>), NLL(NonLinearLayer<F, C>), } impl<F, C> Layer<F, C> { #[inline] pub fn is_linear(&self) -> bool { match self { LL(_) => true, NLL(_) => false, } } #[inline] pub fn is_non_linear(&self) -> bool { !self.is_linear() } pub fn input_dimensions(&self) -> (usize, usize, usize, usize) { match self { LL(l) => l.input_dimensions(), NLL(l) => l.input_dimensions(), } } pub fn output_dimensions(&self) -> (usize, usize, usize, usize) { match self { LL(l) => l.output_dimensions(), NLL(l) => l.output_dimensions(), } } } impl<F, C> Evaluate<F> for Layer<F, C> where F: Zero + One + MulAssign + Mul<C, Output = F> + AddAssign + PartialOrd<C> + Copy, C: std::fmt::Debug + Copy + Into<F> + From<f64> + Zero + One, { fn evaluate(&self, input: &Input<F>) -> Output<F> { match self { LL(l) => l.evaluate(input), NLL(l) => l.evaluate(input), } } fn evaluate_with_method(&self, method: crate::EvalMethod, input: &Input<F>) -> Output<F> { match self { LL(l) => l.evaluate_with_method(method, input), NLL(l) => l.evaluate_with_method(method, input), } } } #[derive(Debug, Clone)] pub enum LayerInfo<F, C> { LL(LayerDims, LinearLayerInfo<F, C>), NLL(LayerDims, NonLinearLayerInfo<F, C>), } impl<F, C> LayerInfo<F, C> { #[inline] pub fn is_linear(&self) -> bool { match self { LayerInfo::LL(..) => true, LayerInfo::NLL(..) => false, } } #[inline] pub fn is_non_linear(&self) -> bool { !self.is_linear() } pub fn input_dimensions(&self) -> (usize, usize, usize, usize) { match self { LayerInfo::LL(l, _) => l.input_dimensions(), LayerInfo::NLL(l, _) => l.input_dimensions(), } } pub fn output_dimensions(&self) -> (usize, usize, usize, usize) { match self { LayerInfo::LL(l, _) => l.output_dimensions(), LayerInfo::NLL(l, _) => l.output_dimensions(), } } } impl<'a, F, C: Clone> From<&'a Layer<F, C>> for LayerInfo<F, C> { fn from(other: &'a Layer<F, C>) -> Self { match other { LL(LinearLayer::Conv2d { dims, params }) => LayerInfo::LL( *dims, LinearLayerInfo::Conv2d { kernel: params.kernel.dim(), padding: params.padding, stride: params.stride, }, ), // TODO: Is there a way to match all of these with one statement LL(LinearLayer::FullyConnected { dims, params: _ }) => { LayerInfo::LL(*dims, LinearLayerInfo::FullyConnected) } LL(LinearLayer::AvgPool { dims, params }) => LayerInfo::LL( *dims, LinearLayerInfo::AvgPool { pool_h: params.pool_h, pool_w: params.pool_w, stride: params.stride, normalizer: params.normalizer.clone(), _variable: std::marker::PhantomData, }, ), LL(LinearLayer::Identity { dims }) => { LayerInfo::LL(*dims, LinearLayerInfo::FullyConnected) } NLL(NonLinearLayer::ReLU(dims)) => LayerInfo::NLL(*dims, NonLinearLayerInfo::ReLU), NLL(NonLinearLayer::PolyApprox { dims, poly, .. }) => LayerInfo::NLL( *dims, NonLinearLayerInfo::PolyApprox { poly: poly.clone(), _v: std::marker::PhantomData, }, ), } } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/layers/linear/tests.rs
rust/neural-network/src/layers/linear/tests.rs
use super::*; use crate::*; use algebra::fields::near_mersenne_64::F; use rand::Rng; use rand_chacha::ChaChaRng; struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 3; const EXPONENT_CAPACITY: u8 = 5; } type TenBitExpFP = FixedPoint<TenBitExpParams>; pub const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x84, 0xbc, 0x89, 0xa7, 0x94, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x43, 0x72, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd1, ]; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let float: f64 = rng.gen(); let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } mod convolution { use super::*; use rand::SeedableRng; use tch::nn; #[test] fn test_torch() { println!("CUDA device is available: {:?}", tch::Cuda::is_available()); let vs = nn::VarStore::new(tch::Device::cuda_if_available()); println!("VS Device: {:?}", vs.device()); let mut rng = ChaChaRng::from_seed(RANDOMNESS); // Set the parameters for the convolution. let input_dims = (1, 1, 3, 3); let kernel_dims = (1, 1, 3, 3); let stride = 1; let padding = Padding::Same; // Sample a random kernel. let mut kernel = Kernel::zeros(kernel_dims); let mut bias = Kernel::zeros((kernel_dims.0, 1, 1, 1)); kernel .iter_mut() .for_each(|ker_i| *ker_i = generate_random_number(&mut rng).1); bias.iter_mut() .for_each(|bias_i| *bias_i = generate_random_number(&mut rng).1); let conv_params = Conv2dParams::<TenBitExpFP, _>::new_with_gpu(&vs.root(), padding, stride, kernel, bias); let output_dims = conv_params.calculate_output_size(input_dims); let layer_dims = LayerDims { input_dims, output_dims, }; let layer = LinearLayer::Conv2d { dims: layer_dims, params: conv_params, }; let mut input = Input::zeros(input_dims); input .iter_mut() .for_each(|in_i| *in_i = generate_random_number(&mut rng).1); let naive_method = crate::EvalMethod::Naive; let torch_method = crate::EvalMethod::TorchDevice(vs.device()); let result_1 = layer.evaluate_with_method(torch_method, &input); let result_2 = layer.evaluate_with_method(naive_method, &input); println!("Naive result: ["); for result in &result_2 { println!(" {},", result); } println!("]"); println!("Torch result: ["); for result in &result_1 { println!(" {},", result); } println!("]"); assert_eq!(result_1, result_2); } #[test] fn load_conv2d_weights() { let input: Input<TenBitExpFP> = ndarray::Array4::from_shape_vec( (1, 1, 3, 3), vec![ 1.0, 1.0, 1.0, // 1.0, 1.0, 0.0, // 1.0, 1.0, 1.0, // ], ) .expect("Should be of correct shape") .into(); let fp_kernel = ndarray::Array4::from_shape_vec( (1, 1, 3, 3), vec![ 1.0, 1.0, 1.0, // 0.0, 0.0, 0.0, // 1.0, 1.0, 1.0, // ], ) .expect("Should be of correct shape"); let kernel: Kernel<TenBitExpFP> = fp_kernel.into(); let mut bias: Kernel<TenBitExpFP> = Kernel::zeros((1, 1, 1, 1)); bias.iter_mut().for_each(|ker_i| { *ker_i = TenBitExpFP::from(1.0); }); let conv_params = Conv2dParams::<TenBitExpFP, _>::new(Padding::Same, 1, kernel, bias); let mut output = Output::zeros((1, 1, 3, 3)); conv_params.conv2d_naive(&input, &mut output); output.iter_mut().for_each(|e| { e.signed_reduce_in_place(); }); let expected_output: Output<TenBitExpFP> = ndarray::Array4::from_shape_vec( (1, 1, 3, 3), vec![ 3.0, 3.0, 2.0, // 5.0, 7.0, 5.0, // 3.0, 3.0, 2.0, ], ) .unwrap() .into(); output .iter() .for_each(|e| println!("e: {:?}", e.signed_reduce())); expected_output.iter().for_each(|e| println!("e: {:?}", e)); assert_eq!(output, expected_output); } #[test] fn check_naive_conv2d() { let input: Input<TenBitExpFP> = ndarray::Array4::from_shape_vec( (1, 3, 5, 5), vec![ 0.0, 0.0, 0.0, 0.0, 1.0f64, // 1.0, 2.0, 0.0, 1.0, 0.0, // 0.0, 1.0, 2.0, 0.0, 0.0, // 1.0, 0.0, 0.0, 2.0, 1.0, // 1.0, 2.0, 1.0, 0.0, 0.0, // // 1.0, 1.0, 1.0, 1.0, 1.0, // 2.0, 2.0, 2.0, 1.0, 0.0, // 1.0, 0.0, 0.0, 0.0, 2.0, // 0.0, 1.0, 2.0, 1.0, 0.0, // 1.0, 1.0, 2.0, 0.0, 1.0, // // 0.0, 0.0, 2.0, 2.0, 2.0, // 1.0, 2.0, 0.0, 1.0, 2.0, // 1.0, 0.0, 2.0, 2.0, 1.0, // 0.0, 2.0, 0.0, 1.0, 0.0, // 2.0, 1.0, 1.0, 1.0, 0.0, // ], ) .expect("Should be of correct shape") .into(); let fp_kernel = ndarray::Array4::from_shape_vec( (1, 3, 3, 3), vec![ -1.0, 1.0, 0.0f64, // 0.0, 0.0, 0.0, // -1.0, 0.0, 0.0, // // 1.0, -1.0, -1.0, // -1.0, 0.0, 1.0, // 1.0, 1.0, -1.0, // // -1.0, -1.0, 1.0, // 0.0, 1.0, 0.0, // 1.0, -1.0, 1.0, // ], ) .expect("Should be of correct shape"); let kernel: Kernel<TenBitExpFP> = fp_kernel.into(); let mut bias: Kernel<TenBitExpFP> = Kernel::zeros((1, 1, 1, 1)); bias.iter_mut().for_each(|ker_i| { *ker_i = TenBitExpFP::from(1.0); }); let conv_params = Conv2dParams::<TenBitExpFP, _>::new(Padding::Same, 2, kernel.clone(), bias.clone()); let mut output = Output::zeros((1, 1, 3, 3)); conv_params.conv2d_naive(&input, &mut output); let mut expected_output: Output<TenBitExpFP> = ndarray::Array4::from_shape_vec( (1, 1, 3, 3), vec![ 2.0, 6.0, 0.0f64, // 0.0, 3.0, -2.0, // 5.0, -3.0, -1.0, // ], ) .unwrap() .into(); expected_output .iter_mut() .for_each(|e| *e += TenBitExpFP::from(1.0)); assert_eq!(output, expected_output); let conv_params = Conv2dParams::<TenBitExpFP, _>::new(Padding::Valid, 1, kernel.clone(), bias.clone()); output = Output::zeros((1, 1, 3, 3)); conv_params.conv2d_naive(&input, &mut output); expected_output = ndarray::Array4::from_shape_vec( (1, 1, 3, 3), vec![ 7.0, -3.0, -7.0f64, // -9.0, 3.0, 9.0, // 8.0, 3.0, -8.0, // ], ) .unwrap() .into(); expected_output .iter_mut() .for_each(|e| *e += TenBitExpFP::from(1.0)); assert_eq!(output, expected_output); let input: Input<TenBitExpFP> = ndarray::Array4::from_shape_vec( (1, 1, 3, 3), vec![ 1.0, 2.0, 1.0, // 2.0, 1.0, 2.0, // 1.0, 1.0, 1.0, // ], ) .expect("Should be of correct shape") .into(); let fp_kernel = ndarray::Array4::from_shape_vec((3, 1, 1, 1), vec![1.0, 2.0, 3.0]) .expect("Should be of correct shape"); let fp_bias = ndarray::Array4::from_shape_vec((3, 1, 1, 1), vec![7.0, 3.0, 9.0]) .expect("Should be of correct shape"); let kernel: Kernel<TenBitExpFP> = fp_kernel.into(); let bias: Kernel<TenBitExpFP> = fp_bias.into(); let conv_params = Conv2dParams::<TenBitExpFP, _>::new(Padding::Valid, 1, kernel.clone(), bias.clone()); let mut output = Output::zeros((1, 3, 3, 3)); conv_params.conv2d_naive(&input, &mut output); expected_output = ndarray::Array4::from_shape_vec( (1, 3, 3, 3), vec![ 1.0, 2.0, 1.0f64, // 2.0, 1.0, 2.0, // 1.0, 1.0, 1.0, // // 2.0, 4.0, 2.0f64, // 4.0, 2.0, 4.0, // 2.0, 2.0, 2.0, // // 3.0, 6.0, 3.0f64, // 6.0, 3.0, 6.0, // 3.0, 3.0, 3.0, // ], ) .unwrap() .into(); expected_output .slice_mut(s![0, .., .., ..]) .outer_iter_mut() .enumerate() .for_each(|(i, mut view)| { view.iter_mut().for_each(|e| *e += bias[[i, 0, 0, 0]]); }); assert_eq!(output, expected_output); } } mod pooling { use super::*; #[test] fn check_naive_avg_pool() { let input: Input<TenBitExpFP> = ndarray::Array4::from_shape_vec( (1, 2, 4, 4), vec![ 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 0.0, 1.0, 0.0, 1.0, 2.0, 0.0, 1.0, 0.0, 0.0, 2.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 1.0, ], ) .unwrap() .into(); let mut output = Output::zeros((1, 2, 2, 2)); let normalizer = TenBitExpFP::from(1.0 / (2.0 * 2.0)); let pool_params = AvgPoolParams::<TenBitExpFP, _>::new(2, 2, 2, normalizer); pool_params.avg_pool_naive(&input, &mut output); let expected_output = ndarray::Array4::from_shape_vec( (1, 2, 2, 2), vec![0.75, 0.25, 0.5, 1.0, 1.5, 1.25, 0.5, 0.75], ) .unwrap() .into(); assert_eq!(output, expected_output); } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/layers/linear/fully_connected.rs
rust/neural-network/src/layers/linear/fully_connected.rs
use crate::tensors::{Input, Kernel, Output}; use algebra::{fp_64::Fp64Parameters, FixedPoint, FixedPointParameters, FpParameters, PrimeField}; use crypto_primitives::AdditiveShare; use num_traits::Zero; use std::{ marker::PhantomData, ops::{Add, AddAssign, Mul}, }; use tch::nn; #[derive(Debug)] pub struct FullyConnectedParams<F, C> { pub weights: Kernel<C>, pub bias: Kernel<C>, pub tch_config: Option<nn::Linear>, pub eval_method: crate::EvalMethod, _variable: PhantomData<F>, } unsafe impl<F, C> Send for FullyConnectedParams<F, C> {} unsafe impl<F, C> Sync for FullyConnectedParams<F, C> {} impl<F, C> FullyConnectedParams<F, C> where F: Zero + Mul<C, Output = F> + AddAssign + Add<Output = F> + Copy, C: Copy + Into<F>, { pub fn new(weights: Kernel<C>, bias: Kernel<C>) -> Self { let kernel_dims = weights.dim(); let bias_dims = bias.dim(); assert!( (bias_dims.0 == kernel_dims.0) && (bias_dims.1 == 1) && (bias_dims.2 == 1) && (bias_dims.3 == 1) ); Self { weights, bias, tch_config: None, eval_method: crate::EvalMethod::Naive, _variable: PhantomData, } } pub fn calculate_output_size( &self, (batch_size, in_channels, in_height, in_width): (usize, usize, usize, usize), ) -> (usize, usize, usize, usize) { let (num, w_channels, w_height, w_width) = self.weights.dim(); assert_eq!(w_height, in_height); assert_eq!(w_width, in_width); assert_eq!(w_channels, in_channels); let out_height = 1; let out_width = 1; let out_channels = num; (batch_size, out_channels, out_height, out_width) } pub fn fully_connected_naive(&self, input: &Input<F>, out: &mut Output<F>) { let (batch_size, in_channels, in_height, in_width) = input.dim(); let (num, w_channels, w_height, w_width) = self.weights.dim(); let (o_batch_size, o_channels, ..) = out.dim(); assert!( (o_batch_size == batch_size) & (w_height == in_height) & (w_width == in_width) & (in_channels == w_channels) & (o_channels == num), "Shape doesn't match: input: {:?}, weights: {:?}, output: {:?}", input.dim(), self.weights.dim(), out.dim() ); let k = in_height * in_width; let in_slice = s![0..batch_size, 0..in_channels, 0..in_height, 0..in_width]; let w_slice = s![0..num, 0..w_channels, 0..w_height, 0..w_width]; let inp = input .slice(&in_slice) .into_shape((batch_size, in_channels, k)) .expect("Reshape should work"); let weights = self .weights .slice(&w_slice) .into_shape((num, w_channels, k)) .expect("Reshape should work"); let i_zero = ndarray::Axis(0); out.axis_iter_mut(i_zero) .zip(inp.axis_iter(i_zero)) .for_each(|(mut out, inp)| { // for each output-input pair in batch weights .axis_iter(i_zero) .zip(out.axis_iter_mut(i_zero)) .for_each(|(weight, mut out)| { weight .axis_iter(i_zero) .zip(inp.axis_iter(i_zero)) .for_each(|(weight, inp)| unsafe { let elt = out.uget_mut((0, 0)); *elt = (0..k) .fold(*elt, move |s, x| s + *inp.uget(x) * *weight.uget(x)); }) }); }); // Add the appropiate bias to each channel of output out.outer_iter_mut().for_each(|mut batch| { batch .outer_iter_mut() .enumerate() .for_each(|(i, mut view)| { let b = unsafe { *self.bias.uget((i, 0, 0, 0)) }; view.iter_mut().for_each(|e| *e += b.into()); }); }); } } impl<P: FixedPointParameters> FullyConnectedParams<AdditiveShare<FixedPoint<P>>, FixedPoint<P>> where <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { pub fn new_with_gpu( vs: &nn::Path, weights: Kernel<FixedPoint<P>>, bias: Kernel<FixedPoint<P>>, ) -> Self { let (out_channels, in_channels, ..) = weights.dim(); let device = vs.device(); let weights_tensor = weights.to_tensor().to_device(device); let bias_tensor = bias .to_tensor() .reshape(&[bias.dim().0 as i64]) .to_device(device); let mut out = Self::new(weights, bias); out.eval_method = crate::EvalMethod::TorchDevice(device); let mut tch_config = nn::linear( vs, in_channels as i64, out_channels as i64, Default::default(), ); tch_config.ws = weights_tensor; tch_config.bs = bias_tensor; out.tch_config = Some(tch_config); out } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/layers/linear/mod.rs
rust/neural-network/src/layers/linear/mod.rs
use crate::{ tensors::{Input, Kernel, Output}, EvalMethod, Evaluate, }; use algebra::{fixed_point::*, fp_64::Fp64Parameters, FpParameters, PrimeField}; use crypto_primitives::AdditiveShare; use num_traits::{One, Zero}; use std::{ marker::PhantomData, ops::{AddAssign, Mul}, }; use tch::nn::Module; use crate::layers::LayerDims; use LinearLayer::*; pub mod convolution; use convolution::*; pub mod average_pooling; use average_pooling::*; pub mod fully_connected; use fully_connected::*; #[cfg(test)] mod tests; #[derive(Debug)] pub enum LinearLayer<F, C> { Conv2d { dims: LayerDims, params: Conv2dParams<F, C>, }, FullyConnected { dims: LayerDims, params: FullyConnectedParams<F, C>, }, AvgPool { dims: LayerDims, params: AvgPoolParams<F, C>, }, Identity { dims: LayerDims, }, } #[derive(Debug, Clone)] pub enum LinearLayerInfo<F, C> { Conv2d { kernel: (usize, usize, usize, usize), padding: Padding, stride: usize, }, FullyConnected, AvgPool { pool_h: usize, pool_w: usize, stride: usize, normalizer: C, _variable: PhantomData<F>, }, Identity, } impl<F, C> LinearLayer<F, C> { pub fn dimensions(&self) -> LayerDims { match self { Conv2d { dims, .. } | FullyConnected { dims, .. } | AvgPool { dims, .. } | Identity { dims, .. } => *dims, } } pub fn input_dimensions(&self) -> (usize, usize, usize, usize) { self.dimensions().input_dimensions() } pub fn output_dimensions(&self) -> (usize, usize, usize, usize) { self.dimensions().output_dimensions() } pub fn all_dimensions( &self, ) -> ( (usize, usize, usize, usize), (usize, usize, usize, usize), (usize, usize, usize, usize), ) { let input_dims = self.input_dimensions(); let output_dims = self.output_dimensions(); let kernel_dims = match self { Conv2d { dims: _, params: p } => p.kernel.dim(), FullyConnected { dims: _, params: p } => p.weights.dim(), _ => panic!("Identity/AvgPool layers do not have a kernel"), }; (input_dims, output_dims, kernel_dims) } pub fn kernel_to_repr<P>(&self) -> Kernel<u64> where C: Copy + Into<FixedPoint<P>>, P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { match self { Conv2d { dims: _, params: p } => p.kernel.to_repr(), FullyConnected { dims: _, params: p } => p.weights.to_repr(), _ => panic!("Identity/AvgPool layers do not have a kernel"), } } pub fn eval_method(&self) -> crate::EvalMethod { match self { Conv2d { dims: _, params } => params.eval_method, FullyConnected { dims: _, params } => params.eval_method, _ => crate::EvalMethod::Naive, } } fn evaluate_naive(&self, input: &Input<F>, output: &mut Output<F>) where F: Zero + Mul<C, Output = F> + AddAssign + Copy, C: Copy + Into<F> + One + std::fmt::Debug, { match self { Conv2d { dims: _, params: p } => { p.conv2d_naive(input, output); } AvgPool { dims: _, params: p } => p.avg_pool_naive(input, output), FullyConnected { dims: _, params: p } => p.fully_connected_naive(input, output), Identity { dims: _ } => { *output = input.clone(); let one = C::one(); for elem in output.iter_mut() { *elem = *elem * one; } } } } pub fn batch_evaluate(&self, input: &[Input<F>], output: &mut [Output<F>]) where Self: Evaluate<F>, { for (inp, out) in input.iter().zip(output.iter_mut()) { *out = self.evaluate(inp); } } } impl<F, C> Evaluate<F> for LinearLayer<F, C> where F: Zero + Mul<C, Output = F> + AddAssign + Copy, C: Copy + Into<F> + One + std::fmt::Debug, { fn evaluate(&self, input: &Input<F>) -> Output<F> { self.evaluate_with_method(self.eval_method(), input) } default fn evaluate_with_method(&self, method: EvalMethod, input: &Input<F>) -> Output<F> { let mut output = Output::zeros(self.output_dimensions()); match method { EvalMethod::Naive => self.evaluate_naive(input, &mut output), EvalMethod::TorchDevice(_) => { unimplemented!("cannot evaluate general networks with torch") } } output } } impl<P: FixedPointParameters> Evaluate<FixedPoint<P>> for LinearLayer<FixedPoint<P>, FixedPoint<P>> { default fn evaluate_with_method( &self, method: EvalMethod, input: &Input<FixedPoint<P>>, ) -> Output<FixedPoint<P>> { let mut output = Output::zeros(self.output_dimensions()); match method { EvalMethod::Naive => self.evaluate_naive(input, &mut output), EvalMethod::TorchDevice(_) => { unimplemented!("cannot evaluate general networks with torch") } } for elem in output.iter_mut() { elem.signed_reduce_in_place(); } output } } impl<P> Evaluate<AdditiveShare<FixedPoint<P>>> for LinearLayer<AdditiveShare<FixedPoint<P>>, FixedPoint<P>> where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { fn evaluate_with_method( &self, method: EvalMethod, input: &Input<AdditiveShare<FixedPoint<P>>>, ) -> Output<AdditiveShare<FixedPoint<P>>> { let mut output = Output::zeros(self.output_dimensions()); match method { EvalMethod::Naive => self.evaluate_naive(input, &mut output), EvalMethod::TorchDevice(m) => { match self { Conv2d { dims: _, params: p } => { let conv2d = &p.tch_config; // Send the tensor to the appropriate PyTorch device let input_tensor = input.to_tensor().to_device(m); output = conv2d .as_ref() .and_then(|cfg| Output::from_tensor(cfg.forward(&input_tensor))) .expect("shape should be correct"); } // FullyConnected { dims: _, params: p } => { // let fc = &p.tch_config; // let input_tensor = input.to_tensor(); // // Send the tensor to the appropriate PyTorch device // input_tensor.to_device(m); // output = fc.as_ref().and_then(|cfg| // Output::from_tensor(cfg.forward(&input_tensor))).expect("shape should be // correct"); }, _ => self.evaluate_naive(input, &mut output), } } } output } } impl<P> Evaluate<FixedPoint<P>> for LinearLayer<FixedPoint<P>, FixedPoint<P>> where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { fn evaluate_with_method( &self, method: EvalMethod, input: &Input<FixedPoint<P>>, ) -> Output<FixedPoint<P>> { let mut output = Output::zeros(self.output_dimensions()); match method { EvalMethod::Naive => self.evaluate_naive(input, &mut output), EvalMethod::TorchDevice(m) => { match self { Conv2d { dims: _, params: p } => { let conv2d = &p.tch_config; // Send the input to the appropriate PyTorch device let input_tensor = input.to_tensor().to_device(m); output = conv2d .as_ref() .and_then(|cfg| Output::from_tensor(cfg.forward(&input_tensor))) .expect("shape should be correct"); } // FullyConnected { dims: _, params: p } => { // let fc = &p.tch_config; // // Send the input to the appropriate PyTorch device // let input_tensor = input.to_tensor().to_device(m); // output = fc.as_ref().and_then(|cfg| // Output::from_tensor(cfg.forward(&input_tensor))).expect("shape should be // correct"); }, _ => self.evaluate_naive(input, &mut output), } } } output } } impl<F, C> LinearLayerInfo<F, C> { pub fn evaluate_naive(&self, input: &Input<F>, output: &mut Output<F>) where F: Zero + Mul<C, Output = F> + AddAssign + Copy, C: Copy + One + std::fmt::Debug, { match self { LinearLayerInfo::AvgPool { pool_h, pool_w, stride, normalizer, .. } => { let params = AvgPoolParams::new(*pool_h, *pool_w, *stride, *normalizer); params.avg_pool_naive(input, output) } LinearLayerInfo::Identity => { *output = input.clone(); let one = C::one(); for elem in output.iter_mut() { *elem = *elem * one; } } _ => unreachable!(), } } } impl<'a, F, C: Clone> From<&'a LinearLayer<F, C>> for LinearLayerInfo<F, C> { fn from(other: &'a LinearLayer<F, C>) -> Self { match other { LinearLayer::Conv2d { params, .. } => LinearLayerInfo::Conv2d { kernel: params.kernel.dim(), padding: params.padding, stride: params.stride, }, LinearLayer::FullyConnected { .. } => LinearLayerInfo::FullyConnected, LinearLayer::AvgPool { params, .. } => LinearLayerInfo::AvgPool { pool_h: params.pool_h, pool_w: params.pool_w, stride: params.stride, normalizer: params.normalizer.clone(), _variable: std::marker::PhantomData, }, LinearLayer::Identity { .. } => LinearLayerInfo::Identity, } } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/layers/linear/average_pooling.rs
rust/neural-network/src/layers/linear/average_pooling.rs
use crate::tensors::{Input, Output}; use num_traits::Zero; use std::{ marker::PhantomData, ops::{AddAssign, Mul}, }; #[derive(Debug, Clone)] pub struct AvgPoolParams<F, C> { pub pool_h: usize, pub pool_w: usize, pub stride: usize, pub normalizer: C, _variable: PhantomData<F>, } impl<F, C> AvgPoolParams<F, C> where F: Zero + Mul<C, Output = F> + AddAssign + Copy, C: Copy, { pub fn new(pool_h: usize, pool_w: usize, stride: usize, normalizer: C) -> Self { Self { pool_h, pool_w, stride, normalizer, _variable: PhantomData, } } pub fn calculate_output_size( &self, (batch_size, in_channels, in_height, in_width): (usize, usize, usize, usize), ) -> (usize, usize, usize, usize) { assert_eq!(in_height % (self.pool_h), 0); assert_eq!(in_width % (self.pool_w), 0); let out_height = (in_height - self.pool_h) / self.stride + 1; let out_width = (in_width - self.pool_w) / self.stride + 1; let out_channels = in_channels; (batch_size, out_channels, out_height, out_width) } pub fn avg_pool_naive(&self, input: &Input<F>, out: &mut Output<F>) { let (batch_size, in_channels, in_height, in_width) = input.dim(); assert_eq!(in_height % (self.pool_h), 0); assert_eq!(in_width % (self.pool_w), 0); let out_dim = self.calculate_output_size(input.dim()); assert_eq!(out.dim(), out_dim); for b_i in 0..batch_size { for (out_i, i) in (0..in_height).step_by(self.stride).enumerate() { for (out_j, j) in (0..in_width).step_by(self.stride).enumerate() { for chan in 0..in_channels { let mut sum = F::zero(); for k_i in 0..self.pool_h { for k_j in 0..self.pool_w { sum += input[(b_i, chan, (i + k_i), (j + k_j))]; } } out[(b_i, chan, out_i, out_j)] = sum * self.normalizer; } } } } } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/layers/linear/convolution.rs
rust/neural-network/src/layers/linear/convolution.rs
use crate::tensors::{Input, Kernel, Output}; use algebra::{fp_64::Fp64Parameters, FixedPoint, FixedPointParameters, FpParameters, PrimeField}; use num_traits::Zero; use std::{ marker::PhantomData, ops::{AddAssign, Mul}, }; use tch::nn; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Padding { Same, Valid, } #[derive(Debug)] pub struct Conv2dParams<F, C> { pub padding: Padding, pub stride: usize, pub kernel: Kernel<C>, pub bias: Kernel<C>, pub tch_config: Option<nn::Conv2D>, pub eval_method: crate::EvalMethod, _variable: PhantomData<F>, } unsafe impl<F, C> Send for Conv2dParams<F, C> {} unsafe impl<F, C> Sync for Conv2dParams<F, C> {} impl<F, C> Conv2dParams<F, C> where F: Zero + Copy + Mul<C, Output = F> + AddAssign, C: Copy + Into<F>, { pub fn new(padding: Padding, stride: usize, kernel: Kernel<C>, bias: Kernel<C>) -> Self { // Check whether the bias dimension are correct - it should have one element per // out_chan let kernel_dims = kernel.dim(); let bias_dims = bias.dim(); assert!( (bias_dims.0 == kernel_dims.0) && (bias_dims.1 == 1) && (bias_dims.2 == 1) && (bias_dims.3 == 1) ); Self { padding, stride, kernel, bias, tch_config: None, eval_method: crate::EvalMethod::Naive, _variable: PhantomData, } } pub fn calculate_output_size( &self, (batch_size, in_channels, in_height, in_width): (usize, usize, usize, usize), ) -> (usize, usize, usize, usize) { let (num, k_channels, k_height, _) = self.kernel.dim(); let padding = match self.padding { Padding::Same => (k_height - 1) / 2, Padding::Valid => 0, }; assert_eq!(k_channels, in_channels); let k_size = k_height; let out_height = (in_height - k_size + 2 * padding) / self.stride + 1; let out_width = (in_width - k_size + 2 * padding) / self.stride + 1; let out_channels = num; (batch_size, out_channels, out_height, out_width) } #[inline] fn get_with_padding( &self, input: &Input<F>, batch: usize, mut row: isize, mut col: isize, chan: usize, p: u8, ) -> F { let (_, _, in_height, in_width) = input.dim(); let in_height = in_height as isize; let in_width = in_width as isize; row -= p as isize; col -= p as isize; if row < 0 || col < 0 || row >= in_height || col >= in_width { F::zero() } else { unsafe { *input.uget((batch, chan, row as usize, col as usize)) } } } pub fn conv2d_naive(&self, input: &Input<F>, out: &mut Output<F>) { let (batch_size, in_channels, in_height, in_width) = input.dim(); let (num, k_channels, k_height, k_width) = self.kernel.dim(); assert_eq!(k_channels, in_channels); let p = match self.padding { Padding::Same => (k_height - 1) / 2, Padding::Valid => 0, }; let out_dim = self.calculate_output_size(input.dim()); // Check that we will always be in bounds during access: assert_eq!(out.dim(), out_dim); let ((in_h_start, in_h_end), (in_w_start, in_w_end)) = match self.padding { Padding::Same => ((0, in_height), (0, in_width)), Padding::Valid => ((0, out_dim.2), (0, out_dim.3)), }; for b_i in 0..batch_size { for (out_i, i) in (in_h_start..in_h_end).step_by(self.stride).enumerate() { for (out_j, j) in (in_w_start..in_w_end).step_by(self.stride).enumerate() { for in_chan in 0..in_channels { for num_f in 0..num { let mut sum = F::zero(); for k_i in 0..k_height { for k_j in 0..k_width { let in_ij = self.get_with_padding( input, b_i, (i + k_i) as isize, (j + k_j) as isize, in_chan, p as u8, ); let k_ij = unsafe { *self.kernel.uget((num_f, in_chan, k_i, k_j)) }; sum += in_ij * k_ij; } } unsafe { *out.uget_mut((b_i, num_f, out_i, out_j)) += sum; } } } } } // Add the appropiate bias to each channel of output out.outer_iter_mut().for_each(|mut batch| { batch .outer_iter_mut() .enumerate() .for_each(|(i, mut view)| { let b = unsafe { *self.bias.uget((i, 0, 0, 0)) }; view.iter_mut().for_each(|e| *e += b.into()); }); }); } } } impl<P: FixedPointParameters, I> Conv2dParams<I, FixedPoint<P>> where I: Zero + Copy + Into<FixedPoint<P>> + AddAssign + Mul<FixedPoint<P>, Output = I>, FixedPoint<P>: Into<I>, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, { pub fn new_with_gpu( vs: &nn::Path, padding: Padding, stride: usize, kernel: Kernel<FixedPoint<P>>, mut bias: Kernel<FixedPoint<P>>, ) -> Self { let (out_channels, in_channels, k_h, _) = kernel.dim(); let device = vs.device(); let kernel_tensor = kernel.to_tensor().to_device(device); let one = FixedPoint::one(); for b in &mut bias { *b *= one; } let bias_tensor = bias .to_tensor() .reshape(&[out_channels as i64]) .to_device(device); let mut out = Self::new(padding, stride, kernel, bias); out.eval_method = crate::EvalMethod::TorchDevice(device); assert_eq!(kernel_tensor.kind(), tch::Kind::Double); assert_eq!(bias_tensor.kind(), tch::Kind::Double); let p = match padding { Padding::Same => (k_h - 1) / 2, Padding::Valid => 0, }; let conv2d_cfg = nn::ConvConfig { stride: stride as i64, padding: p as i64, bias: true, ..Default::default() }; let mut tch_config = nn::conv2d( vs, in_channels as i64, out_channels as i64, k_h as i64, conv2d_cfg, ); tch_config.ws = kernel_tensor; tch_config.bs = Some(bias_tensor); out.tch_config = Some(tch_config); out } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/tensors/macros.rs
rust/neural-network/src/tensors/macros.rs
macro_rules! ndarray_impl { ($name:ident, $inner:ident, $dims:ty) => { #[derive(Clone, PartialEq, Eq, Debug, Default, Hash, Serialize, Deserialize)] pub struct $name<F>($inner<F>); impl<F> $name<F> { #[inline] pub fn from_elem(dim: $dims, elem: F) -> Self where F: Clone, { $name($inner::from_elem(dim, elem)) } #[inline] pub fn zeros(dim: $dims) -> Self where F: Zero + Clone, { $name($inner::zeros(dim)) } #[inline] pub fn from_shape_vec(dim: $dims, v: Vec<F>) -> Result<Self, ndarray::ShapeError> { $inner::from_shape_vec(dim, v).map($name) } #[inline] pub fn iter(&self) -> impl Iterator<Item = &F> { self.0.iter() } #[inline] pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut F> { self.0.iter_mut() } } impl<T: From<I>, I: Copy> From<$inner<I>> for $name<T> { #[inline] fn from(other: $inner<I>) -> Self { let inp_vec: Vec<T> = other.iter().map(|e| T::from(*e)).collect(); $name( ndarray::Array1::from_vec(inp_vec) .into_shape(other.dim()) .unwrap(), ) } } impl<F> std::ops::Deref for $name<F> { type Target = $inner<F>; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl<F> std::ops::DerefMut for $name<F> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<'a, F> IntoIterator for &'a $name<F> { type Item = &'a F; type IntoIter = <&'a $inner<F> as IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { (&self.0).into_iter() } } impl<'a, F> IntoIterator for &'a mut $name<F> { type Item = &'a mut F; type IntoIter = <&'a mut $inner<F> as IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { (&mut self.0).into_iter() } } }; }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/src/tensors/mod.rs
rust/neural-network/src/tensors/mod.rs
use algebra::{fp_64::Fp64Parameters, FixedPoint, FixedPointParameters, FpParameters, PrimeField}; use crypto_primitives::{AdditiveShare, Share}; use ndarray::Array4; use num_traits::Zero; use rand::{CryptoRng, RngCore}; use serde::{Deserialize, Serialize}; use tch::Tensor; #[macro_use] mod macros; type Quadruple = (usize, usize, usize, usize); ndarray_impl!(Input, Array4, Quadruple); ndarray_impl!(Kernel, Array4, Quadruple); pub type Output<F> = Input<F>; impl<T: Share> Input<T> { pub fn share<R: RngCore + CryptoRng>( &self, rng: &mut R, ) -> (Input<AdditiveShare<T>>, Input<AdditiveShare<T>>) { let mut share_1 = Vec::with_capacity(self.len()); let mut share_2 = Vec::with_capacity(self.len()); for inp in self.iter() { let (s1, s2) = inp.share(rng); share_1.push(s1); share_2.push(s2); } let s1 = Input::from_shape_vec(self.dim(), share_1).expect("Shapes should be same"); let s2 = Input::from_shape_vec(self.dim(), share_2).expect("Shapes should be same"); (s1, s2) } pub fn share_with_randomness( &self, r: &Input<T::Ring>, ) -> (Input<AdditiveShare<T>>, Input<AdditiveShare<T>>) { assert_eq!(r.dim(), self.dim()); let mut share_1 = Vec::with_capacity(r.len()); let mut share_2 = Vec::with_capacity(r.len()); self.iter() .zip(r.iter()) .map(|(elem, r)| T::share_with_randomness(elem, r)) .for_each(|(s1, s2)| { share_1.push(s1); share_2.push(s2); }); let s1 = Input::from_shape_vec(r.dim(), share_1).expect("Shapes should be same"); let s2 = Input::from_shape_vec(r.dim(), share_2).expect("Shapes should be same"); (s1, s2) } } impl<I> Input<I> { /// If the underlying elements of `Input` are `FixedPoint` elements having /// base field `Fp32` backed by a `u64` (thus allowing lazy reduction), /// then we can convert it to an equivalent `nn::Tensor` containing `i64`s. pub fn to_tensor<P>(&self) -> Tensor where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, I: Copy + Into<FixedPoint<P>>, { let (b, c, h, w) = self.dim(); let mut result = vec![0.0; self.len()]; let mut all_num_muls_are_zero = true; result.iter_mut().zip(self.iter()).for_each(|(e1, e2)| { let fp: FixedPoint<P> = Into::<FixedPoint<P>>::into(*e2); let big_int = fp.inner.into_repr(); *e1 = if big_int >= <P::Field as PrimeField>::Params::MODULUS_MINUS_ONE_DIV_TWO { -((<P::Field as PrimeField>::Params::MODULUS.0 as i64) - big_int.0 as i64) as f64 } else { big_int.0 as f64 }; all_num_muls_are_zero &= fp.num_muls() == 0; }); assert!(all_num_muls_are_zero); let result = Tensor::of_slice(&result).reshape(&[b as i64, c as i64, h as i64, w as i64]); result } /// If the underlying elements of `Input` are `FixedPoint` elements having /// base field `Fp64` backed by a `u64` we can convert to Input<u64> pub fn to_repr<P>(&self) -> Input<u64> where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, I: Copy + Into<FixedPoint<P>>, { let mut input: Input<u64> = Input::zeros(self.dim()); input.iter_mut().zip(self).for_each(|(e1, e2)| { let fp: FixedPoint<P> = Into::<FixedPoint<P>>::into(*e2); *e1 = fp.inner.into_repr().0; }); input } pub fn from_tensor<P>(tensor: Tensor) -> Option<Self> where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, I: Copy + From<FixedPoint<P>>, { let shape = tensor .size4() .ok() .map(|(b, c, h, w)| (b as usize, c as usize, h as usize, w as usize))?; let mut output: Vec<f64> = tensor.into(); let output = output .iter_mut() .map(|e| { let e = *e as i64 % <P::Field as PrimeField>::Params::MODULUS.0 as i64; let reduced = if e < 0 { ((<P::Field as PrimeField>::Params::MODULUS.0 as i64) + e as i64) as u64 } else { e as u64 }; FixedPoint::with_num_muls(P::Field::from_repr(reduced.into()), 1).into() }) .collect::<Vec<_>>(); Input::from_shape_vec(shape, output).ok() } } impl<T: Share> Input<AdditiveShare<T>> { pub fn randomize_local_share(&mut self, r: &Input<T::Ring>) { for (inp, r) in self.iter_mut().zip(r.iter()) { *inp = T::randomize_local_share(inp, r); } } pub fn combine(&self, other: &Input<AdditiveShare<T>>) -> Input<T> { assert_eq!(self.dim(), other.dim()); let combined = self .iter() .zip(other.iter()) .map(|(s1, s2)| AdditiveShare::combine(s1, s2)) .collect(); Input::from_shape_vec(self.dim(), combined).expect("Shapes should be same") } } impl<I> Kernel<I> { /// If the underlying elements of `Kernel` are `FixedPoint` elements having /// base field `Fp64` backed by a `u64` then we can convert to an equivalent /// 'nn::Tensor' containing `i64`s. pub fn to_tensor<P>(&self) -> Tensor where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, I: Copy + Into<FixedPoint<P>>, { let (c_out, c_in, h, w) = self.dim(); let mut result = vec![0.0; self.len()]; result.iter_mut().zip(self.iter()).for_each(|(e1, e2)| { let fp: FixedPoint<P> = Into::<FixedPoint<P>>::into(*e2); let big_int = fp.inner.into_repr(); *e1 = if big_int >= <P::Field as PrimeField>::Params::MODULUS_MINUS_ONE_DIV_TWO { -((<P::Field as PrimeField>::Params::MODULUS.0 as i64) - big_int.0 as i64) as f64 } else { big_int.0 as f64 }; *e1 = fp.inner.into_repr().0 as f64; }); Tensor::of_slice(&result).reshape(&[c_out as i64, c_in as i64, h as i64, w as i64]) } /// If the underlying elements of `Kernel` are `FixedPoint` elements having /// base field `Fp64` backed by a `u64` we can convert to Kernel<u64> pub fn to_repr<P>(&self) -> Kernel<u64> where P: FixedPointParameters, <P::Field as PrimeField>::Params: Fp64Parameters, P::Field: PrimeField<BigInt = <<P::Field as PrimeField>::Params as FpParameters>::BigInt>, I: Copy + Into<FixedPoint<P>>, { let mut kernel: Kernel<u64> = Kernel::zeros(self.dim()); kernel.iter_mut().zip(self).for_each(|(e1, e2)| { let fp: FixedPoint<P> = Into::<FixedPoint<P>>::into(*e2); *e1 = fp.inner.into_repr().0; }); kernel } }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/benches/torch.rs
rust/neural-network/benches/torch.rs
#![feature(test)] extern crate test; use algebra::{fields::near_mersenne_64::F, *}; use neural_network::{ layers::{convolution::*, *}, tensors::*, }; use rand::Rng; use rand_chacha::ChaChaRng; use test::Bencher; struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 8; const EXPONENT_CAPACITY: u8 = 6; } type TenBitExpFP = FixedPoint<TenBitExpParams>; pub const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x84, 0xbc, 0x89, 0xa7, 0x94, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x43, 0x72, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd1, ]; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let float: f64 = rng.gen(); let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } use neural_network::*; use rand::SeedableRng; use tch::nn; #[bench] fn test_torch_cpu(b: &mut Bencher) { println!("CUDA device is available: {:?}", tch::Cuda::is_available()); let vs = nn::VarStore::new(tch::Device::cuda_if_available()); println!("VS Device: {:?}", vs.device()); let mut rng = ChaChaRng::from_seed(RANDOMNESS); // Set the parameters for the convolution. let input_dims = (10, 16, 32, 32); let kernel_dims = (16, 16, 3, 3); let stride = 1; let padding = Padding::Same; // Sample a random kernel. let mut kernel = Kernel::zeros(kernel_dims); let mut bias = Kernel::zeros((kernel_dims.0, 1, 1, 1)); kernel .iter_mut() .for_each(|ker_i| *ker_i = generate_random_number(&mut rng).1); bias.iter_mut() .for_each(|bias_i| *bias_i = generate_random_number(&mut rng).1); let conv_params = Conv2dParams::<TenBitExpFP, _>::new_with_gpu(&vs.root(), padding, stride, kernel, bias); let output_dims = conv_params.calculate_output_size(input_dims); let layer_dims = LayerDims { input_dims, output_dims, }; let layer = LinearLayer::Conv2d { dims: layer_dims, params: conv_params, }; let mut input = Input::zeros(input_dims); input .iter_mut() .for_each(|in_i| *in_i = generate_random_number(&mut rng).1); let naive_method = neural_network::EvalMethod::Naive; b.iter(|| layer.evaluate_with_method(naive_method, &input)) } #[bench] fn test_torch_gpu(b: &mut Bencher) { println!("CUDA device is available: {:?}", tch::Cuda::is_available()); let vs = nn::VarStore::new(tch::Device::cuda_if_available()); println!("VS Device: {:?}", vs.device()); let mut rng = ChaChaRng::from_seed(RANDOMNESS); // Set the parameters for the convolution. let input_dims = (10, 16, 32, 32); let kernel_dims = (16, 16, 3, 3); let stride = 1; let padding = Padding::Same; // Sample a random kernel. let mut kernel = Kernel::zeros(kernel_dims); let mut bias = Kernel::zeros((kernel_dims.0, 1, 1, 1)); kernel .iter_mut() .for_each(|ker_i| *ker_i = generate_random_number(&mut rng).1); bias.iter_mut() .for_each(|bias_i| *bias_i = generate_random_number(&mut rng).1); let conv_params = Conv2dParams::<TenBitExpFP, _>::new_with_gpu(&vs.root(), padding, stride, kernel, bias); let output_dims = conv_params.calculate_output_size(input_dims); let layer_dims = LayerDims { input_dims, output_dims, }; let layer = LinearLayer::Conv2d { dims: layer_dims, params: conv_params, }; let mut input = Input::zeros(input_dims); input .iter_mut() .for_each(|in_i| *in_i = generate_random_number(&mut rng).1); let torch_method = neural_network::EvalMethod::TorchDevice(vs.device()); b.iter(|| layer.evaluate_with_method(torch_method, &input)) }
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/benches/fully_connected.rs
rust/neural-network/benches/fully_connected.rs
use criterion::{criterion_group, criterion_main, Criterion}; use std::time::Duration; use algebra::{fields::near_mersenne_64::F, fixed_point::*}; use neural_network::{layers::fully_connected::*, tensors::*}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaChaRng; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let float: f64 = rng.gen(); let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 5; const EXPONENT_CAPACITY: u8 = 5; } type TenBitExpFP = FixedPoint<TenBitExpParams>; const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn make_fc( c: &mut Criterion, input_dim: (usize, usize, usize, usize), kernel_dim: (usize, usize, usize, usize), ) { c.bench_function( &format!("fully_connected_{:?}_{:?}", input_dim, kernel_dim), move |bench| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); let mut input = Input::zeros(input_dim); for in_i in input.iter_mut() { let (_, n) = generate_random_number(&mut rng); *in_i = n; } let mut kernel = Kernel::zeros(kernel_dim); for ker_i in kernel.iter_mut() { let (_, n) = generate_random_number(&mut rng); *ker_i = n; } let mut bias = Kernel::zeros((kernel_dim.0, 1, 1, 1)); for b_i in bias.iter_mut() { let (_, n) = generate_random_number(&mut rng); *b_i = n; } let fc_params = FullyConnectedParams::<TenBitExpFP, _>::new(kernel, bias); let output_dims = fc_params.calculate_output_size(input_dim); let mut output = Input::zeros(output_dims); bench.iter(|| fc_params.fully_connected_naive(&input, &mut output)); }, ); } fn bench_fc_16x8x8_to_100x1x1(c: &mut Criterion) { let input_dim = (1, 16, 8, 8); let kernel_dim = (100, 16, 8, 8); make_fc(c, input_dim, kernel_dim); } fn bench_fc_32x16x16_to_4096x1x1(c: &mut Criterion) { let input_dim = (1, 32, 16, 16); let kernel_dim = (4096, 32, 16, 16); make_fc(c, input_dim, kernel_dim); } criterion_group! { name = fully_connected; config = Criterion::default().warm_up_time(Duration::from_millis(100)); targets = bench_fc_16x8x8_to_100x1x1 } criterion_group! { name = fully_connected_slow; config = Criterion::default().warm_up_time(Duration::from_millis(100)).sample_size(2); targets = bench_fc_32x16x16_to_4096x1x1 } criterion_main!(fully_connected, fully_connected_slow);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/benches/average_pooling.rs
rust/neural-network/benches/average_pooling.rs
use criterion::{criterion_group, criterion_main, Criterion}; use std::time::Duration; use algebra::{fields::near_mersenne_64::F, fixed_point::*}; use neural_network::{layers::average_pooling::*, tensors::*}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaChaRng; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let float: f64 = rng.gen(); let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 5; const EXPONENT_CAPACITY: u8 = 5; } type TenBitExpFP = FixedPoint<TenBitExpParams>; const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn make_avg_pool( c: &mut Criterion, input_dim: (usize, usize, usize, usize), pool_h: usize, pool_w: usize, stride: usize, ) { c.bench_function( &format!("Avg pooling {:?} ({:?}x{:?})", input_dim, pool_h, pool_w), move |bench| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); let mut input = Input::zeros(input_dim); for in_i in input.iter_mut() { let (_, n) = generate_random_number(&mut rng); *in_i = n; } let normalizer = TenBitExpFP::from(1.0 / (2.0 * 2.0)); let pool_params = AvgPoolParams::<TenBitExpFP, _>::new(pool_h, pool_w, stride, normalizer); let output_dims = pool_params.calculate_output_size(input.dim()); let mut output = Input::zeros(output_dims); bench.iter(|| pool_params.avg_pool_naive(&input, &mut output)); }, ); } fn bench_avg_pool_128x16x16_by_2x2(c: &mut Criterion) { let input_dim = (1, 128, 16, 16); let stride = 2; make_avg_pool(c, input_dim, 2, 2, stride); } fn bench_avg_pool_1x28x28_by_2x2(c: &mut Criterion) { let input_dim = (1, 1, 28, 28); let stride = 2; make_avg_pool(c, input_dim, 2, 2, stride); } criterion_group! { name = pooling; config = Criterion::default().warm_up_time(Duration::from_millis(100)); targets = bench_avg_pool_128x16x16_by_2x2, bench_avg_pool_1x28x28_by_2x2 } criterion_main!(pooling);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
mc2-project/delphi
https://github.com/mc2-project/delphi/blob/92bc0071fa11570df6b048ae0f6937ced249bb5a/rust/neural-network/benches/convolution.rs
rust/neural-network/benches/convolution.rs
use criterion::{criterion_group, criterion_main, Criterion}; use std::time::Duration; use algebra::{fields::near_mersenne_64::F, fixed_point::*}; use neural_network::{layers::convolution::*, tensors::*}; use rand::{Rng, SeedableRng}; use rand_chacha::ChaChaRng; fn generate_random_number<R: Rng>(rng: &mut R) -> (f64, TenBitExpFP) { let is_neg: bool = rng.gen(); let mul = if is_neg { -10.0 } else { 10.0 }; let float: f64 = rng.gen(); let f = TenBitExpFP::truncate_float(float * mul); let n = TenBitExpFP::from(f); (f, n) } struct TenBitExpParams {} impl FixedPointParameters for TenBitExpParams { type Field = F; const MANTISSA_CAPACITY: u8 = 5; const EXPONENT_CAPACITY: u8 = 5; } type TenBitExpFP = FixedPoint<TenBitExpParams>; const RANDOMNESS: [u8; 32] = [ 0x11, 0xe0, 0x8f, 0xbc, 0x89, 0xa7, 0x34, 0x01, 0x45, 0x86, 0x82, 0xb6, 0x51, 0xda, 0xf4, 0x76, 0x5d, 0xc9, 0x8d, 0xea, 0x23, 0xf2, 0x90, 0x8f, 0x9d, 0x03, 0xf2, 0x77, 0xd3, 0x4a, 0x52, 0xd2, ]; fn make_conv2d( c: &mut Criterion, input_dim: (usize, usize, usize, usize), kernel_dim: (usize, usize, usize, usize), stride: usize, padding: Padding, ) { c.bench_function( &format!("convolution_{:?}_{:?}", input_dim, kernel_dim), move |bench| { let mut rng = ChaChaRng::from_seed(RANDOMNESS); let mut input = Input::zeros(input_dim); for in_i in input.iter_mut() { let (_, n) = generate_random_number(&mut rng); *in_i = n; } let mut kernel = Kernel::zeros(kernel_dim); for ker_i in kernel.iter_mut() { let (_, n) = generate_random_number(&mut rng); *ker_i = n; } let mut bias = Kernel::zeros((kernel_dim.0, 1, 1, 1)); for b_i in bias.iter_mut() { let (_, n) = generate_random_number(&mut rng); *b_i = n; } let conv_params = Conv2dParams::<TenBitExpFP, _>::new(padding, stride, kernel, bias); let output_dims = conv_params.calculate_output_size(input_dim); let mut output = Output::zeros(output_dims); bench.iter(|| conv_params.conv2d_naive(&input, &mut output)); }, ); } fn bench_conv2d_resnet32_2_1(c: &mut Criterion) { let input_dim = (1, 32, 16, 16); let kernel_dim = (32, 32, 3, 3); let stride = 1; let padding = Padding::Same; make_conv2d(c, input_dim, kernel_dim, stride, padding); } fn bench_conv2d_resnet32_3_3(c: &mut Criterion) { let input_dim = (1, 64, 8, 8); let kernel_dim = (64, 64, 3, 3); let stride = 1; let padding = Padding::Same; make_conv2d(c, input_dim, kernel_dim, stride, padding); } fn bench_conv2d_resnet32_1_1(c: &mut Criterion) { let input_dim = (1, 16, 32, 32); let kernel_dim = (16, 16, 3, 3); let stride = 1; let padding = Padding::Same; make_conv2d(c, input_dim, kernel_dim, stride, padding); } criterion_group! { name = convolution; config = Criterion::default().warm_up_time(Duration::from_millis(100)); targets = bench_conv2d_resnet32_3_3, bench_conv2d_resnet32_1_1, bench_conv2d_resnet32_2_1 } criterion_main!(convolution);
rust
Apache-2.0
92bc0071fa11570df6b048ae0f6937ced249bb5a
2026-01-04T20:24:11.030795Z
false
cshuaimin/scd
https://github.com/cshuaimin/scd/blob/9b243ffc37a64797d56ede4e29dc7704bb0702ed/src/app.rs
src/app.rs
use std::io; use std::thread; use std::time::{Duration, Instant}; use anyhow::{bail, Result}; use crossbeam_channel::{self as channel, select, Receiver}; use notify::RecommendedWatcher; use termion::{event::Key, input::TermRead, raw::IntoRawMode, screen::AlternateScreen}; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::Terminal; use crate::file_manager::FileManager; use crate::shell; use crate::status_bar::{Mode, StatusBar}; use crate::system_monitor::SystemMonitor; use crate::task_manager::{self, TaskManager}; enum InputFocus { FileManager, TaskManager, } pub struct App { system_monitor: SystemMonitor, file_manager: FileManager<RecommendedWatcher>, task_manager: TaskManager, status_bar: StatusBar, input_focus: InputFocus, keys: channel::Receiver<Key>, ticks: Receiver<Instant>, watch_events: Receiver<notify::Event>, task_events: Receiver<task_manager::Event>, shell_events: Receiver<shell::Event>, } impl App { pub fn new() -> Result<App> { let system_monitor = SystemMonitor::new(); let (file_manager, watch_events) = FileManager::new()?; let (task_manager, task_events) = TaskManager::new()?; let status_bar = StatusBar::new(); let (tx, keys) = channel::bounded(0); thread::spawn(move || { io::stdin() .keys() .map(Result::unwrap) .for_each(|k| tx.send(k).unwrap()); }); let (tx, shell_events) = channel::bounded(0); thread::spawn(move || shell::receive_events(tx)); Ok(App { system_monitor, file_manager, task_manager, status_bar, input_focus: InputFocus::FileManager, keys, ticks: channel::tick(Duration::from_secs(2)), watch_events, task_events, shell_events, }) } pub fn run(&mut self) -> Result<()> { let mut terminal = { let stdout = io::stdout().into_raw_mode()?; let stdout = AlternateScreen::from(stdout); let backend = TermionBackend::new(stdout); Terminal::new(backend)? }; loop { terminal.draw(|mut frame| { // + 3: seperator, title, seperator let task_height = (self.task_manager.tasks.len() as u16 + 3).min(frame.size().height / 3); let chunks = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Length(8), Constraint::Min(0), Constraint::Length(task_height), Constraint::Length(1), ] .as_ref(), ) .split(frame.size()); self.system_monitor.draw(&mut frame, chunks[0]); self.file_manager.draw(&mut frame, chunks[1]); if !self.task_manager.tasks.is_empty() { self.task_manager.draw(&mut frame, chunks[2]); } self.status_bar .draw(&mut self.file_manager, &mut frame, chunks[3]); })?; let bottom = terminal.size()?.bottom() - 1; match &self.status_bar.mode { Mode::Ask { prompt, .. } => { terminal.set_cursor(prompt.len() as u16, bottom)?; terminal.show_cursor()?; } Mode::Edit { prompt, cursor, .. } => { terminal.set_cursor((prompt.len() + cursor) as u16, bottom)?; terminal.show_cursor()?; } _ => terminal.hide_cursor()?, } macro_rules! catch_error { ($r:expr) => { if let Err(e) = $r { self.status_bar.show_message(e.to_string()); } }; } select! { recv(self.keys) -> key => { let key = key.unwrap(); match self.status_bar.mode { Mode::Ask { .. } | Mode::Edit { .. } => { catch_error!(self.status_bar.on_key(key, &mut self.file_manager, &mut self.task_manager)); } _ => match key { Key::Char('q') => { if self.file_manager.shell_pid.as_raw() > 0 { shell::deinit(self.file_manager.shell_pid)?; } break; } Key::Char('\t') => match self.input_focus { InputFocus::FileManager => self.input_focus = InputFocus::TaskManager, InputFocus::TaskManager => self.input_focus = InputFocus::FileManager, } key => catch_error!(match self.input_focus { InputFocus::FileManager => self.file_manager.on_key(key, &mut self.status_bar), InputFocus::TaskManager => self.task_manager.on_key(key, &mut self.status_bar), }) } } } recv(self.ticks) -> tick => { let tick = tick.unwrap(); self.system_monitor.on_tick(tick); self.status_bar.on_tick(tick); } recv(self.watch_events) -> watch => catch_error!(self.file_manager.on_notify(watch.unwrap())), recv(self.task_events) -> task_event => self.task_manager.on_event(task_event.unwrap()), recv(self.shell_events) -> shell_event => { catch_error!(match shell_event.unwrap() { shell::Event::Exit => break, shell::Event::Task { command, rendered } => self.task_manager.new_task(command, rendered), event => self.file_manager.on_shell_event(event), }) } } } Ok(()) } } pub trait ListExt { type Item; fn get_index(&self) -> Option<usize>; fn get_list(&self) -> &[Self::Item]; fn select(&mut self, index: Option<usize>); fn selected(&self) -> Option<&Self::Item> { if self.get_list().is_empty() { None } else { let idx = self.get_index().unwrap_or(0); Some(&self.get_list()[idx]) } } fn select_first(&mut self) { let index = if self.get_list().is_empty() { None } else { Some(0) }; self.select(index); } fn select_last(&mut self) { let index = match self.get_list().len() { 0 => None, len => Some(len - 1), }; self.select(index); } fn select_next(&mut self) { let index = self.get_index().map(|i| (i + 1) % self.get_list().len()); self.select(index); } fn select_prev(&mut self) { let index = match self.get_index() { None => None, Some(0) if self.get_list().is_empty() => None, Some(0) => Some(self.get_list().len() - 1), Some(i) => Some(i - 1), }; self.select(index); } fn on_list_key(&mut self, key: Key) -> Result<()> { match key { Key::Char('j') | Key::Ctrl('n') | Key::Down => self.select_next(), Key::Char('k') | Key::Ctrl('p') | Key::Up => self.select_prev(), Key::Char('g') | Key::Home => self.select_first(), Key::Char('G') | Key::End => self.select_last(), uk => bail!("Unknown key: {:?}", uk), } Ok(()) } }
rust
MIT
9b243ffc37a64797d56ede4e29dc7704bb0702ed
2026-01-04T20:24:43.087867Z
false
cshuaimin/scd
https://github.com/cshuaimin/scd/blob/9b243ffc37a64797d56ede4e29dc7704bb0702ed/src/system_monitor.rs
src/system_monitor.rs
use std::fmt::Write; use std::time::Instant; use sysinfo::{ProcessorExt, RefreshKind, System, SystemExt}; use tui::backend::Backend; use tui::buffer::Buffer; use tui::layout::{Constraint, Direction, Layout, Rect}; use tui::style::{Color, Modifier, Style}; use tui::widgets::{Paragraph, Text, Widget}; use tui::Frame; fn format_time(mut secs: u64) -> String { const UNITS: &[(u64, &str)] = &[ (60 * 60 * 24 * 31, "month"), (60 * 60 * 24 * 7, "week"), (60 * 60 * 24, "day"), ]; let mut res = String::new(); for &(div, unit) in UNITS { if secs >= div { let n = secs / div; let p = if n > 1 { "s" } else { "" }; write!(res, "{} {}{}, ", n, unit, p).unwrap(); secs %= div; } } let hours = secs / (60 * 60); secs %= 60 * 60; let minutes = secs / 60; secs %= 60; write!(res, "{:0>2}:{:0>2}:{:0>2}", hours, minutes, secs).unwrap(); res } struct Meter<'a> { label: &'a str, percentage: u16, style: Style, } impl<'a> Widget for Meter<'a> { fn render(mut self, area: Rect, buf: &mut Buffer) { if self.percentage > 100 { self.percentage = 0; } if area.width <= 5 { return; } let width = area.width - 5; // space + 100% let sep = area.left() + width * self.percentage / 100; let end = area.left() + width; buf.set_string(area.left(), area.top(), self.label, Style::default()); for x in area.left()..sep { buf.get_mut(x, area.top() + 1) .set_fg(self.style.fg) .set_symbol("▆"); } for x in sep..end { buf.get_mut(x, area.top() + 1) .set_fg(Color::DarkGray) .set_symbol("▆"); } buf.set_string( end + 1, area.top() + 1, format!("{:>3}%", self.percentage), self.style, ); } } pub struct SystemMonitor { system: System, } impl SystemMonitor { pub fn new() -> SystemMonitor { SystemMonitor { system: System::new_with_specifics(RefreshKind::new().with_cpu().with_memory()), } } pub fn on_tick(&mut self, _tick: Instant) { self.system.refresh_cpu(); self.system.refresh_memory(); } pub fn draw(&self, frame: &mut Frame<impl Backend>, area: Rect) { let chunks = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Length(1), // load average Constraint::Length(1), // uptime Constraint::Length(1), // blank Constraint::Length(2), // CPU meter Constraint::Length(2), // memory meter ] .as_ref(), ) .split(area); let value_style = Style::default() .fg(Color::LightCyan) .modifier(Modifier::BOLD); let avg = self.system.get_load_average(); let load_average = format!("{:.2} {:.2} {:.2}", avg.one, avg.five, avg.fifteen); frame.render_widget( Paragraph::new([Text::raw("LA "), Text::styled(load_average, value_style)].iter()), chunks[0], ); let uptime = format_time(self.system.get_uptime()); frame.render_widget( Paragraph::new([Text::raw("UP "), Text::styled(uptime, value_style)].iter()), chunks[1], ); let cpu_usage = self .system .get_global_processor_info() .get_cpu_usage() .round() as u16; frame.render_widget( Meter { label: "CPU", percentage: cpu_usage, style: value_style, }, chunks[3], ); let mem_usage = (100 * self.system.get_used_memory() / self.system.get_total_memory()) as u16; frame.render_widget( Meter { label: "Memory", percentage: mem_usage, style: value_style, }, chunks[4], ); } }
rust
MIT
9b243ffc37a64797d56ede4e29dc7704bb0702ed
2026-01-04T20:24:43.087867Z
false
cshuaimin/scd
https://github.com/cshuaimin/scd/blob/9b243ffc37a64797d56ede4e29dc7704bb0702ed/src/status_bar.rs
src/status_bar.rs
use std::os::unix::fs::PermissionsExt; use std::time::{Duration, Instant}; use anyhow::Result; use notify::Watcher; use strmode::strmode; use termion::event::Key; use tui::backend::Backend; use tui::layout::{Alignment, Rect}; use tui::style::{Color, Style}; use tui::widgets::{Paragraph, Text}; use tui::Frame; use crate::app::ListExt; use crate::file_manager::FileManager; use crate::task_manager::TaskManager; pub enum Mode { /// Show some properties of selected file/task. Normal, /// Display a short lived message. Message { text: String, expire_at: Instant }, /// Ask a yes/no question. Ask { prompt: String, on_yes: Box<dyn Fn(&mut FileManager, &mut TaskManager) -> Result<()>>, }, /// Edit some text. Edit { prompt: String, text: String, cursor: usize, on_change: Box<dyn Fn(&str, &mut FileManager, &mut TaskManager) -> Result<()>>, on_enter: Box<dyn Fn(&str, &mut FileManager, &mut TaskManager) -> Result<()>>, }, } pub struct StatusBar { pub mode: Mode, } impl StatusBar { pub fn new() -> StatusBar { StatusBar { mode: Mode::Normal } } pub fn show_message(&mut self, text: impl Into<String>) { self.mode = Mode::Message { text: text.into(), expire_at: Instant::now() + Duration::from_secs(4), }; } pub fn ask( &mut self, prompt: impl Into<String>, on_yes: impl Fn(&mut FileManager, &mut TaskManager) -> Result<()> + 'static, ) { self.mode = Mode::Ask { prompt: prompt.into(), on_yes: Box::new(on_yes), } } pub fn edit( &mut self, prompt: impl Into<String>, text: impl Into<String>, on_change: impl Fn(&str, &mut FileManager, &mut TaskManager) -> Result<()> + 'static, on_enter: impl Fn(&str, &mut FileManager, &mut TaskManager) -> Result<()> + 'static, ) { let text = text.into(); let cursor = text.len(); self.mode = Mode::Edit { prompt: prompt.into(), text, cursor, on_change: Box::new(on_change), on_enter: Box::new(on_enter), }; } pub fn on_tick(&mut self, now: Instant) { if let Mode::Message { expire_at, .. } = self.mode { if expire_at >= now { self.mode = Mode::Normal; } } } pub fn on_key( &mut self, key: Key, file_manager: &mut FileManager, task_manager: &mut TaskManager, ) -> Result<()> { match &mut self.mode { Mode::Normal => panic!(), Mode::Message { .. } => self.mode = Mode::Normal, Mode::Ask { on_yes, .. } => { if key == Key::Char('y') { on_yes(file_manager, task_manager)?; } self.mode = Mode::Normal; } Mode::Edit { text, cursor, on_change, on_enter, .. } => match key { Key::Char('\n') => { on_enter(text, file_manager, task_manager)?; self.mode = Mode::Normal; } Key::Esc | Key::Ctrl('[') => { on_change("", file_manager, task_manager)?; self.mode = Mode::Normal; } Key::Home | Key::Ctrl('a') => *cursor = 0, Key::End | Key::Ctrl('e') => *cursor = text.len(), Key::Left | Key::Ctrl('b') => { if *cursor > 0 { *cursor -= 1; } } Key::Right | Key::Ctrl('f') => { if *cursor < text.len() { *cursor += 1; } } Key::Backspace | Key::Ctrl('h') => { if *cursor > 0 { text.remove(*cursor - 1); *cursor -= 1; on_change(text, file_manager, task_manager)?; } } Key::Delete | Key::Ctrl('d') => { if *cursor < text.len() { text.remove(*cursor); on_change(text, file_manager, task_manager)?; } } Key::Ctrl('u') => { text.clear(); *cursor = 0; on_change(text, file_manager, task_manager)?; } Key::Char(ch) => { text.insert(*cursor, ch); *cursor += 1; on_change(text, file_manager, task_manager)?; } _ => {} }, } Ok(()) } pub fn draw( &self, file_manager: &FileManager<impl Watcher>, frame: &mut Frame<impl Backend>, area: Rect, ) { let prompt_style = Style::default().fg(Color::LightYellow); match &self.mode { Mode::Normal => { if let Some(file) = file_manager.selected() { let mode = strmode(file.metadata.permissions().mode()); let size = format_size(file.metadata.len()); let texts = [ Text::styled(mode, Style::default().fg(Color::LightGreen)), Text::raw(" "), Text::raw(size), ]; frame.render_widget( Paragraph::new(texts.iter()).alignment(Alignment::Left), area, ); } let mut text = String::new(); if !file_manager.files_marked.is_empty() { text.push_str("M:"); text.push_str(&file_manager.files_marked.len().to_string()); } text.push_str(&format!( " {}/{}", file_manager .list_state .selected() .map(|i| i + 1) .unwrap_or(0), file_manager.files.len() )); frame.render_widget( Paragraph::new([Text::raw(text)].iter()).alignment(Alignment::Right), area, ); } Mode::Message { text, .. } => { let texts = [Text::styled(text, prompt_style)]; frame.render_widget(Paragraph::new(texts.iter()), area); } Mode::Ask { prompt, .. } => { let texts = [Text::styled(prompt, prompt_style)]; frame.render_widget(Paragraph::new(texts.iter()), area); } Mode::Edit { prompt, text, .. } => { let texts = [ Text::styled(prompt, prompt_style), Text::styled(text, Style::default().fg(Color::LightCyan)), ]; frame.render_widget(Paragraph::new(texts.iter()), area); } } } } fn format_size(size: u64) -> String { const UNITS: &[(u64, &str)] = &[ (1024 * 1024 * 1024 * 1024, "T"), (1024 * 1024 * 1024, "G"), (1024 * 1024, "M"), (1024, "K"), (1, "B"), ]; for &(div, unit) in UNITS { if size >= div { return format!("{:.1}{}", size as f32 / div as f32, unit); } } "0B".to_string() }
rust
MIT
9b243ffc37a64797d56ede4e29dc7704bb0702ed
2026-01-04T20:24:43.087867Z
false
cshuaimin/scd
https://github.com/cshuaimin/scd/blob/9b243ffc37a64797d56ede4e29dc7704bb0702ed/src/file_manager.rs
src/file_manager.rs
use std::cmp; use std::convert::TryFrom; use std::env; use std::fs::{self, DirEntry, Metadata}; use std::io; use std::mem; use std::os::unix::fs::PermissionsExt; use std::{ collections::HashMap, path::{Path, PathBuf}, }; use anyhow::Result; use crossbeam_channel::{self as channel, Receiver}; use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use termion::event::Key; use tui::backend::Backend; use tui::layout::{Constraint, Direction, Layout, Rect}; use tui::style::{Color, Modifier, Style}; use tui::widgets::{List, ListState, Paragraph, Text}; use tui::Frame; use crate::app::ListExt; use crate::shell; use crate::status_bar::StatusBar; use nix::unistd::Pid; #[derive(Debug, Clone)] pub struct FileInfo { pub path: PathBuf, pub name: String, pub extension: Option<String>, pub metadata: Metadata, } impl TryFrom<DirEntry> for FileInfo { type Error = io::Error; fn try_from(entry: DirEntry) -> Result<Self, Self::Error> { let path = entry.path(); let name = entry.file_name().to_str().unwrap().to_owned(); let extension = path.extension().map(|e| e.to_str().unwrap().to_owned()); Ok(Self { path, name, extension, metadata: entry.metadata()?, }) } } pub struct FileManager<W = RecommendedWatcher> where W: Watcher, { dir: PathBuf, all_files: Vec<FileInfo>, pub files: Vec<FileInfo>, // filtered pub files_marked: Vec<PathBuf>, pub filter: String, show_hidden: bool, pub list_state: ListState, watcher: W, pub shell_pid: Pid, open_methods: HashMap<String, String>, } impl<W> FileManager<W> where W: Watcher, { pub fn new() -> Result<(FileManager<W>, Receiver<notify::Event>)> { let (tx, rx) = channel::bounded(0); let watcher = W::new_immediate(move |event: notify::Result<notify::Event>| { tx.send(event.unwrap()).unwrap() })?; let mut file_manager = FileManager { dir: PathBuf::new(), all_files: vec![], files: vec![], files_marked: vec![], filter: "".to_string(), show_hidden: false, list_state: ListState::default(), watcher, shell_pid: Pid::from_raw(0), open_methods: load_open_methods()?, }; file_manager.cd(env::current_dir()?)?; Ok((file_manager, rx)) } pub fn cd(&mut self, mut dir: PathBuf) -> Result<()> { if dir != self.dir { if self.dir != Path::new("") { self.watcher.unwatch(&self.dir)?; } mem::swap(&mut self.dir, &mut dir); match self.read_dir() { Ok(res) => { self.all_files = res; self.apply_filter(); self.select_first(); self.watcher.watch(&self.dir, RecursiveMode::NonRecursive)?; } Err(e) => { self.dir = dir; self.watcher.watch(&self.dir, RecursiveMode::NonRecursive)?; return Err(e.into()); } } } Ok(()) } pub fn read_dir(&self) -> io::Result<Vec<FileInfo>> { let mut res = vec![]; for entry in fs::read_dir(&self.dir)? { res.push(FileInfo::try_from(entry?)?); } res.sort_unstable_by(|a, b| match (a.metadata.is_dir(), b.metadata.is_dir()) { (true, false) => cmp::Ordering::Less, (false, true) => cmp::Ordering::Greater, _ => a.name.cmp(&b.name), }); Ok(res) } pub fn apply_filter(&mut self) { let selected = self.selected().map(|f| f.name.clone()); self.files = self .all_files .iter() .filter(|f| self.show_hidden || !f.name.starts_with('.')) .filter(|f| f.name.to_lowercase().contains(&self.filter.to_lowercase())) .cloned() .collect(); // Keep selection after filter. if let Some(name) = selected { self.select_file(name); } } pub fn select_file(&mut self, name: String) { let index = self.files.iter().position(|f| f.name == name).unwrap_or(0); self.list_state.select(Some(index)); } pub fn on_notify(&mut self, event: notify::Event) -> io::Result<()> { match event.kind { EventKind::Create(_) | EventKind::Remove(_) | EventKind::Modify(_) => { self.read_dir().map(|res| { self.all_files = res; self.apply_filter(); }) } _ => Ok(()), } } pub fn on_shell_event(&mut self, shell_event: shell::Event) -> Result<()> { match shell_event { shell::Event::Pid(pid) => self.shell_pid = Pid::from_raw(pid), shell::Event::ChangeDirectory(dir) => self.cd(dir)?, _ => {} } Ok(()) } pub fn on_key(&mut self, key: Key, status_bar: &mut StatusBar) -> Result<()> { match key { Key::Char('l') | Key::Char('\n') => { if let Some(file) = self.selected() { if file.metadata.is_dir() { let path = file.path.clone(); self.cd(path.clone())?; shell::run(self.shell_pid, "cd", &[path.to_str().unwrap()], false)?; } else { let open_cmd = match &file.extension { None => "xdg-open", Some(ext) => self .open_methods .get(ext) .map(String::as_str) .unwrap_or("xdg-open"), }; shell::run(self.shell_pid, open_cmd, &[&file.name], true)?; } } } Key::Char('h') | Key::Esc => { if let Some(parent) = self.dir.parent() { let parent = parent.to_owned(); let current = self.dir.file_name().unwrap().to_str().unwrap().to_owned(); self.cd(parent.clone())?; self.select_file(current); shell::run(self.shell_pid, "cd", &[parent.to_str().unwrap()], false)?; } } Key::Char('.') => { self.show_hidden = !self.show_hidden; self.apply_filter(); } Key::Char(' ') => { if let Some(file) = self.selected() { if let Some(index) = self.files_marked.iter().position(|p| p == &file.path) { self.files_marked.remove(index); } else { let path = file.path.clone(); self.files_marked.push(path); } if self.list_state.selected().unwrap() != self.files.len() - 1 { self.select_next(); } } } Key::Char('p') => { if self.files_marked.is_empty() { status_bar.show_message("No files marked"); } else { let files = mem::take(&mut self.files_marked); let files: Vec<&str> = files.iter().map(|f| f.to_str().unwrap()).collect(); shell::run(self.shell_pid, "cp -r {} .", &files, true)?; } } Key::Char('m') => { if self.files_marked.is_empty() { status_bar.show_message("No files marked"); } else { let files = mem::take(&mut self.files_marked); let files: Vec<&str> = files.iter().map(|f| f.to_str().unwrap()).collect(); shell::run(self.shell_pid, "mv {} .", &files, true)?; } } Key::Char('d') => { if let Some(selected) = self.selected() { let tp = if selected.metadata.is_file() { "file" } else { "directory" }; let file = selected.path.to_str().unwrap().to_owned(); status_bar.ask( format!("Delete {} {}? [y/N]", tp, selected.name), move |this, _| shell::run(this.shell_pid, "rm -r", &[&file], true), ); } } Key::Char('r') => { if let Some(file) = self.selected() { let path = file.path.clone(); status_bar.edit( "Rename: ", &file.name, |_, _, _| Ok(()), move |new_name, this, _| { shell::run( this.shell_pid, "mv", &[ path.to_str().unwrap(), path.with_file_name(new_name).to_str().unwrap(), ], true, ) }, ); } } Key::Char('/') => { status_bar.edit( "/", "", |filter, this, _| { this.filter = filter.to_owned(); this.apply_filter(); Ok(()) }, |_, this, _| { this.filter.clear(); this.apply_filter(); Ok(()) }, ); } key => self.on_list_key(key)?, } Ok(()) } pub fn draw(&mut self, frame: &mut Frame<impl Backend>, area: Rect) { let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Length(1), Constraint::Min(0)].as_ref()) .split(area); frame.render_widget( Paragraph::new( [Text::styled( self.dir.to_str().unwrap(), Style::default().modifier(Modifier::UNDERLINED), )] .iter(), ), chunks[0], ); let items = self .files .iter() .map(|file| { let color = if file.metadata.is_dir() { Color::Blue } else if file.metadata.permissions().mode() & 0o1 != 0 { Color::Green } else { Color::White }; let is_selected = if self.files_marked.contains(&file.path) { "+" } else { " " }; let icon = ""; //self.icons.get(file); let suffix = if file.metadata.is_dir() { "/" } else { "" }; Text::styled( format!("{}{} {}{}", is_selected, icon, file.name, suffix), Style::default().fg(color), ) }) .collect::<Vec<_>>() .into_iter(); let list = List::new(items).highlight_style(Style::default().fg(Color::Black).bg(Color::Blue)); frame.render_stateful_widget(list, chunks[1], &mut self.list_state); } } fn load_open_methods() -> Result<HashMap<String, String>> { let config = &env::var("HOME")?; let config = Path::new(&config); let config = config.join(".config/scd/open.yml"); let mut res = HashMap::new(); match fs::read_to_string(config) { Ok(buf) => { let raw: HashMap<String, String> = serde_yaml::from_str(&buf)?; for (exts, cmd) in raw { for ext in exts.split(',').map(str::trim) { res.insert(ext.to_string(), cmd.clone()); } } } Err(e) => { if e.kind() != io::ErrorKind::NotFound { return Err(e.into()); } } } Ok(res) } impl<W> ListExt for FileManager<W> where W: Watcher, { type Item = FileInfo; fn get_index(&self) -> Option<usize> { self.list_state.selected() } fn get_list(&self) -> &[Self::Item] { &self.files } fn select(&mut self, index: Option<usize>) { self.list_state.select(index) } }
rust
MIT
9b243ffc37a64797d56ede4e29dc7704bb0702ed
2026-01-04T20:24:43.087867Z
false
cshuaimin/scd
https://github.com/cshuaimin/scd/blob/9b243ffc37a64797d56ede4e29dc7704bb0702ed/src/task_manager.rs
src/task_manager.rs
use std::collections::HashMap; use std::env; use std::io::Write; use std::io::{self, BufRead, BufReader}; use std::process::{ChildStdin, Command, ExitStatus, Stdio}; use std::thread; use anyhow::Result; use crossbeam_channel::{self as channel, Receiver, Sender}; use nix::sys::signal::{kill, Signal}; use nix::unistd::Pid; use once_cell::sync::Lazy; use regex::Regex; use termion::event::Key; use termion::{color, cursor}; use tui::{backend::Backend, layout::Rect, Frame}; use unicode_width::UnicodeWidthStr; use crate::app::ListExt; use crate::status_bar::StatusBar; pub enum Event { Stdout { pid: Pid, line: String }, Stderr { pid: Pid, line: String }, Exit { pid: Pid, exit_status: ExitStatus }, } pub enum Status { Running(String), Stopped, Exited(ExitStatus), } pub struct Task { pub pid: Pid, pub command: String, pub rendered: String, pub status: Status, stdin: ChildStdin, } impl Task { pub fn new(command: String, rendered: String, tx: Sender<Event>) -> Result<Self> { let mut child = { let shell = env::var("SHELL").unwrap_or("sh".to_string()); let mut builder = Command::new(&shell); builder.arg("-c"); if shell.ends_with("fish") { builder.arg(format!("exec {}", command)); } else { builder.arg(&command); } builder .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()? }; let pid = Pid::from_raw(child.id() as _); let stdin = child.stdin.take().unwrap(); let stdout = BufReader::new(child.stdout.take().unwrap()); let stderr = BufReader::new(child.stderr.take().unwrap()); thread::spawn({ let tx = tx.clone(); move || { stdout .split(b'\r') .map(Result::unwrap) .map(String::from_utf8) .map(Result::unwrap) .for_each(|line| tx.send(Event::Stdout { pid, line }).unwrap()); let exit_status = child.wait().unwrap(); tx.send(Event::Exit { pid, exit_status }).unwrap(); } }); thread::spawn({ move || { stderr .split(b'\r') .map(Result::unwrap) .map(String::from_utf8) .map(Result::unwrap) .for_each(|line| tx.send(Event::Stderr { pid, line }).unwrap()); } }); Ok(Self { pid, command, rendered, status: Status::Running("\u{f110} ".to_string()), stdin, }) } } pub struct TaskManager { tx: Sender<Event>, pub tasks: Vec<Task>, list_state: TaskListState, } impl TaskManager { pub fn new() -> Result<(TaskManager, Receiver<Event>)> { let (tx, rx) = channel::bounded(0); let task_manager = TaskManager { tx, tasks: vec![], list_state: TaskListState::default(), }; Ok((task_manager, rx)) } pub fn on_event(&mut self, event: Event) { match event { Event::Stdout { pid, line } | Event::Stderr { pid, line } => { let mut task = self.tasks.iter_mut().find(|t| t.pid == pid).unwrap(); let name = task.command.split(' ').next().unwrap(); let status = PARSERS .get(name) .and_then(|parser| parser.parse(line)) .unwrap_or("\u{f110} ".to_string()); task.status = Status::Running(status); } Event::Exit { pid, exit_status } => { let mut task = self.tasks.iter_mut().find(|t| t.pid == pid).unwrap(); task.status = Status::Exited(exit_status); self.tasks.sort_by_key(|t| match t.status { Status::Running(_) => 3, Status::Stopped => 2, Status::Exited(exit_status) => { if !exit_status.success() { 1 } else { 0 } } }); } } } pub fn new_task(&mut self, command: String, rendered: String) -> Result<()> { let task = Task::new(command, rendered, self.tx.clone())?; self.tasks.push(task); self.select_first(); Ok(()) } pub fn on_key(&mut self, key: Key, status_bar: &mut StatusBar) -> Result<()> { match key { Key::Char('c') => { self.tasks .retain(|t| matches!(t.status, Status::Running(_))); self.select_first(); } Key::Char('t') => { if let Some(task) = self.selected() { let pid = task.pid; status_bar.ask( format!("Terminate '{}' with SIGTERM?", task.command), move |_, _| Ok(kill(pid, Signal::SIGTERM)?), ); } } Key::Char('9') => { if let Some(task) = self.selected() { let pid = task.pid; status_bar.ask( format!("Kill '{}' with SIGKILL?", task.command), move |_, _| Ok(kill(pid, Signal::SIGKILL)?), ); } } Key::Char('z') => { if let Some(idx) = self.list_state.selected { let task = &mut self.tasks[idx]; kill(task.pid, Signal::SIGINT)?; task.status = Status::Stopped; } } key => self.on_list_key(key)?, } Ok(()) } pub fn draw(&mut self, _frame: &mut Frame<impl Backend>, area: Rect) { let height = area.height as usize; // Make sure the list show the selected item self.list_state.offset = if let Some(selected) = self.list_state.selected { if selected >= height + self.list_state.offset - 1 { selected + 1 - height } else if selected < self.list_state.offset { selected } else { self.list_state.offset } } else { 0 }; let max_status_width = self .tasks .iter() .map(|t| match &t.status { Status::Running(s) => s.width(), Status::Stopped | Status::Exited(_) => 1, }) .max() .unwrap() .max("Status".len()) as u16; let mut stdout = io::stdout(); macro_rules! draw { ($i:expr, $left:expr, $right_color:expr, $right:expr) => {{ if matches!(self.list_state.selected, Some(s) if s + 1 == $i) { write!(stdout, "{}> {}", color::Fg(color::Blue), color::Fg(color::Reset)).unwrap(); } // `Goto` is (1,1)-based let y = area.top() + $i as u16 + 1; let left_pos = cursor::Goto(area.left() + 2 + 1, y); let right_pos = cursor::Goto(area.width - max_status_width, y); write!(stdout, "{}{}", left_pos, " ".repeat(area.width as usize)).unwrap(); write!(stdout, "{}{}", left_pos, $left).unwrap(); write!( stdout, "{} {}{:>w$}", right_pos, $right_color, $right, w = max_status_width as usize ) .unwrap(); }}; } draw!(0, "Task", color::White.fg_str(), "Status"); self.tasks .iter() .rev() .map(|task| { let (status_color, status) = match &task.status { Status::Running(s) => (color::White.fg_str(), s.as_str()), Status::Stopped => (color::LightYellow.fg_str(), "\u{f04c} "), Status::Exited(s) => { if s.success() { (color::LightCyan.fg_str(), "✓ ") } else { (color::LightRed.fg_str(), "✗ ") } } }; (task.rendered.as_str(), status_color, status) }) .skip(self.list_state.offset) .take(height - 1) .enumerate() .for_each(|(i, (command, status_color, status))| { draw!(i + 1, command, status_color, status) }); write!( stdout, "{}{}", cursor::Goto(area.left() + 1, area.bottom()), " ".repeat(area.width as usize) ) .unwrap(); stdout.flush().unwrap(); } } pub struct TaskListState { offset: usize, selected: Option<usize>, } impl Default for TaskListState { fn default() -> Self { Self { offset: 0, selected: None, } } } impl ListExt for TaskManager { type Item = Task; fn get_index(&self) -> Option<usize> { self.list_state.selected } fn get_list(&self) -> &[Self::Item] { &self.tasks } fn select(&mut self, index: Option<usize>) { self.list_state.selected = index; } } static PARSERS: Lazy<HashMap<&str, Box<dyn ParseOutput>>> = Lazy::new(|| { let mut m: HashMap<&str, Box<dyn ParseOutput>> = HashMap::new(); m.insert("curl", Box::new(Curl::new())); m }); trait ParseOutput: Send + Sync { fn parse(&self, line: String) -> Option<String>; } struct Curl { re: Regex, } impl Curl { fn new() -> Self { Self { re: Regex::new(r"(\d+).*?(\w+)$").unwrap(), } } } impl ParseOutput for Curl { fn parse(&self, line: String) -> Option<String> { self.re .captures(&line) .map(|caps| format!("{}/s {}%", &caps[2], &caps[1])) } }
rust
MIT
9b243ffc37a64797d56ede4e29dc7704bb0702ed
2026-01-04T20:24:43.087867Z
false
cshuaimin/scd
https://github.com/cshuaimin/scd/blob/9b243ffc37a64797d56ede4e29dc7704bb0702ed/src/main.rs
src/main.rs
use std::path::PathBuf; use anyhow::Result; use structopt::StructOpt; use app::App; mod app; mod file_manager; mod shell; mod status_bar; mod system_monitor; mod task_manager; /// A tiny file manager focused on shell integration #[derive(Debug, StructOpt)] struct Opt { #[structopt(subcommand)] command: Option<Command>, } #[derive(Debug, StructOpt)] enum Command { FishInit, ZshInit, GetCmd, Cd { dir: PathBuf }, SendPid { pid: i32 }, SendTask { command: String, rendered: String }, Exit, } fn main() -> Result<()> { let opt = Opt::from_args(); match opt.command { None => App::new()?.run()?, Some(command) => match command { Command::FishInit => println!("{}", shell::FISH_INIT), Command::ZshInit => println!("{}", shell::ZSH_INIT), Command::GetCmd => println!("{}", shell::receive_command()?), Command::SendPid { pid } => shell::send_event(shell::Event::Pid(pid))?, Command::SendTask { command, rendered } => { shell::send_event(shell::Event::Task { command, rendered })? } Command::Cd { dir } => shell::send_event(shell::Event::ChangeDirectory(dir))?, Command::Exit => shell::send_event(shell::Event::Exit)?, }, } Ok(()) }
rust
MIT
9b243ffc37a64797d56ede4e29dc7704bb0702ed
2026-01-04T20:24:43.087867Z
false
cshuaimin/scd
https://github.com/cshuaimin/scd/blob/9b243ffc37a64797d56ede4e29dc7704bb0702ed/src/shell/mod.rs
src/shell/mod.rs
use std::fs::{File, OpenOptions}; use std::io::prelude::*; use std::mem; use std::path::PathBuf; use anyhow::{ensure, Context, Result}; use crossbeam_channel::Sender; use nix::sys::signal::{kill, Signal}; use nix::sys::stat::Mode; use nix::unistd::{mkfifo, Pid}; use serde::{Deserialize, Serialize}; /// Send shell commands from scd to shell. pub const CMDS_TO_RUN: &str = "/tmp/scd-cmds-to-run"; /// Send shell events from the shell to scd. pub const SHELL_EVENTS: &str = "/tmp/scd-shell-events"; pub const FISH_INIT: &str = include_str!("scd.fish"); pub const ZSH_INIT: &str = include_str!("scd.zsh"); /// Events emitted from the shell. #[derive(Debug, Serialize, Deserialize)] pub enum Event { /// Shell PID. Pid(i32), /// The shell's current directory was changed. ChangeDirectory(PathBuf), /// Shell exited. Exit, /// Run and montior the task. Task { command: String, rendered: String }, } fn write(mut file: impl Write, buf: impl AsRef<[u8]>) -> Result<()> { let buf = buf.as_ref(); file.write_all(&buf.len().to_ne_bytes())?; file.write_all(buf)?; Ok(()) } fn read(mut file: impl Read) -> Result<String> { let mut len_bytes = [0; mem::size_of::<usize>()]; file.read_exact(&mut len_bytes)?; let len = usize::from_ne_bytes(len_bytes); let mut buf = vec![0; len]; file.read_exact(&mut buf)?; let s = String::from_utf8(buf)?; Ok(s) } /// Run a command in the shell. pub fn run(pid: Pid, cmd: &str, args: &[impl AsRef<str>], echo: bool) -> Result<()> { ensure!(pid.as_raw() > 0, "shell not initialized"); let _ = mkfifo(CMDS_TO_RUN, Mode::S_IRWXU); let args = args .iter() .map(|a| format!("'{}'", a.as_ref())) .collect::<Vec<_>>() .join(" "); let cmd = if cmd.contains("{}") { cmd.replace("{}", &args) } else { format!("{} {}", cmd, args) }; let cmd = if echo { format!("scd_run_with_echo \"{}\"", cmd) } else { format!("scd_run_silently \"{}\"", cmd) }; kill(pid, Signal::SIGUSR1).with_context(|| "Failed to notify the shell")?; let fifo = OpenOptions::new().write(true).open(CMDS_TO_RUN)?; write(fifo, cmd) } /// Receive a shell command to run. /// /// This function is called on the shell side. pub fn receive_command() -> Result<String> { let _ = mkfifo(CMDS_TO_RUN, Mode::S_IRWXU); let file = File::open(CMDS_TO_RUN)?; read(file) } /// Send a shell event to the file manager. /// /// This function is called on the shell side. pub fn send_event(event: Event) -> Result<()> { let _ = mkfifo(SHELL_EVENTS, Mode::S_IRWXU); let fifo = OpenOptions::new().write(true).open(SHELL_EVENTS)?; write(fifo, &serde_yaml::to_vec(&event)?) } pub fn receive_events(tx: Sender<Event>) -> Result<()> { let _ = mkfifo(SHELL_EVENTS, Mode::S_IRWXU); loop { let fifo = File::open(SHELL_EVENTS)?; let event = serde_yaml::from_str(&read(fifo)?)?; tx.send(event)?; } } pub fn deinit(pid: Pid) -> Result<()> { run(pid, "scd_deinit", &[""], false) }
rust
MIT
9b243ffc37a64797d56ede4e29dc7704bb0702ed
2026-01-04T20:24:43.087867Z
false
char-ptr/bsod-rs
https://github.com/char-ptr/bsod-rs/blob/67c534745bc918b1165d4f5fdd734703812c765f/src/lib.rs
src/lib.rs
/// # bsod /// The safest library on the block. Calling the bsod function will cause a blue screen of death. /// ## links /// - [`crates.io`](https://crates.io/crates/bsod) /// - [`docs.rs`](https://docs.rs/bsod/latest/bsod/) use std::{ ffi::{c_ulong, c_ulonglong, CString}, mem::transmute, }; #[cfg(target_os = "linux")] use std::process::Command; #[cfg(target_os = "linux")] use zbus::export::serde::Serialize; #[cfg(target_os = "linux")] use zbus::zvariant::DynamicType; #[cfg(windows)] use windows::{ core::PCSTR, Win32::{ Foundation::{NTSTATUS, STATUS_FLOAT_MULTIPLE_FAULTS}, System::LibraryLoader::{GetProcAddress, LoadLibraryA}, }, }; #[cfg(windows)] type RtlAdjustPrivilige = unsafe extern "C" fn( privilge: c_ulong, enable: bool, currentThread: bool, enabled: *mut bool, ) -> NTSTATUS; #[cfg(windows)] type NtRaiseHardError = unsafe extern "C" fn( errorStatus: NTSTATUS, numberOfParams: c_ulong, unicodeStrParamMask: c_ulong, params: *const c_ulonglong, responseOption: c_ulong, response: *mut c_ulong, ) -> i64; #[cfg(windows)] macro_rules! make_pcstr { ($str:expr) => {{ // considering the program will exit almost immediately i don't care about mem leaks. let cstr = CString::new($str).unwrap(); let pc = PCSTR::from_raw(cstr.as_ptr() as *const u8); std::mem::forget(cstr); pc }}; } /// this function will cause a blue screen of death #[cfg(windows)] pub fn bsod() { unsafe { let hndl = LoadLibraryA(make_pcstr!("ntdll.dll")).expect("ntdll to exist"); let adjust_priv: RtlAdjustPrivilige = transmute( GetProcAddress(hndl, make_pcstr!("RtlAdjustPrivilege")) .expect("RtlAdjustPrivilige to exist"), ); let raise_hard_err: NtRaiseHardError = transmute( GetProcAddress(hndl, make_pcstr!("NtRaiseHardError")) .expect("NtRaiseHardError to exist"), ); let mut lol: c_ulong = 0; let mut enabled = false; adjust_priv(19, true, false, &mut enabled); raise_hard_err( STATUS_FLOAT_MULTIPLE_FAULTS, 0, 0, std::mem::zeroed(), 6, &mut lol, ); } } #[cfg(all(not(windows), not(target_os = "linux")))] pub fn bsod() {} /// this will cause a shutdown on linux #[cfg(target_os = "linux")] pub fn bsod() { dbus( "org.kde.ksmserver", "/KSMServer", "org.kde.KSMServerInterface", "logout", &(-1, 2, 2), ); dbus( "org.gnome.SessionManager", "org/gnome/SessionManager", "org.gnome.SessionManager", "Shutdown", &(), ); dbus( "org.xfce.SessionManager", "/org/xfce/SessionManager", "org.xfce.SessionManager", "Shutdown", &(true), ); dbus( "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "PowerOff", &(true), ); dbus( "org.freedesktop.PowerManagement", "/org/freedesktop/PowerManagement", "org.freedesktop.PowerManagement", "Shutdown", &(), ); dbus( "org.freedesktop.SessionManagement", "/org/freedesktop/Sessionmanagement", "org.freedesktop.SessionManagement", "Shutdown", &(), ); dbus( "org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", "org.freedesktop.ConsoleKit.Manager", "Stop", &(), ); dbus( "org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer", "org.freedesktop.Hal.Device.SystemPowermanagement", "Shutdown", &(), ); dbus( "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "PowerOff", &(), ); // If dbus doesn't work, this is the last resort Command::new("shutdown").args(&["-h", "now"]).output(); } #[cfg(target_os = "linux")] fn dbus<T: Serialize + DynamicType>( destination: &str, path: &str, interface: &str, method: &str, body: &T, ) { let mut owner: bool = false; if let Ok(connection) = zbus::blocking::Connection::session() { let reply = connection.call_method( Some("org.freedesktop.DBus"), "/", Some("org.freedesktop.DBus"), "NameHasOwner", &(destination), ); owner = reply.and_then(|r| r.body()).unwrap_or(false); } if owner { if let Ok(connection) = zbus::blocking::Connection::session() { let reply = connection.call_method(Some(destination), path, Some(interface), method, body); } } }
rust
Unlicense
67c534745bc918b1165d4f5fdd734703812c765f
2026-01-04T20:24:44.192785Z
false
char-ptr/bsod-rs
https://github.com/char-ptr/bsod-rs/blob/67c534745bc918b1165d4f5fdd734703812c765f/examples/bsod.rs
examples/bsod.rs
use bsod::bsod; fn main() { bsod(); }
rust
Unlicense
67c534745bc918b1165d4f5fdd734703812c765f
2026-01-04T20:24:44.192785Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/lib.rs
nmrs/src/lib.rs
//! A Rust library for managing network connections via NetworkManager. //! //! This crate provides a high-level async API for NetworkManager over D-Bus, //! enabling easy management of WiFi, Ethernet, and VPN connections on Linux. //! //! # Quick Start //! //! ## WiFi Connection //! //! ```no_run //! use nmrs::{NetworkManager, WifiSecurity}; //! //! # async fn example() -> nmrs::Result<()> { //! let nm = NetworkManager::new().await?; //! //! // List visible networks //! let networks = nm.list_networks().await?; //! for net in &networks { //! println!("{} - Signal: {}%", net.ssid, net.strength.unwrap_or(0)); //! } //! //! // Connect to a network //! nm.connect("MyNetwork", WifiSecurity::WpaPsk { //! psk: "password123".into() //! }).await?; //! //! // Check current connection //! if let Some(ssid) = nm.current_ssid().await { //! println!("Connected to: {}", ssid); //! } //! # Ok(()) //! # } //! ``` //! //! ## VPN Connection (WireGuard) //! //! ```no_run //! use nmrs::{NetworkManager, VpnCredentials, VpnType, WireGuardPeer}; //! //! # async fn example() -> nmrs::Result<()> { //! let nm = NetworkManager::new().await?; //! //! // Configure WireGuard VPN //! let creds = VpnCredentials { //! vpn_type: VpnType::WireGuard, //! name: "MyVPN".into(), //! gateway: "vpn.example.com:51820".into(), //! private_key: "your_private_key".into(), //! address: "10.0.0.2/24".into(), //! peers: vec![WireGuardPeer { //! public_key: "peer_public_key".into(), //! gateway: "vpn.example.com:51820".into(), //! allowed_ips: vec!["0.0.0.0/0".into()], //! preshared_key: None, //! persistent_keepalive: Some(25), //! }], //! dns: Some(vec!["1.1.1.1".into(), "8.8.8.8".into()]), //! mtu: None, //! uuid: None, //! }; //! //! // Connect to VPN //! nm.connect_vpn(creds).await?; //! //! // List VPN connections //! let vpns = nm.list_vpn_connections().await?; //! for vpn in vpns { //! println!("{}: {:?} - {:?}", vpn.name, vpn.vpn_type, vpn.state); //! } //! //! // Disconnect //! nm.disconnect_vpn("MyVPN").await?; //! # Ok(()) //! # } //! ``` //! //! # Core Concepts //! //! ## NetworkManager //! //! The main entry point is [`NetworkManager`], which provides methods for: //! - Listing and managing network devices //! - Scanning for available WiFi networks //! - Connecting to networks (WiFi, Ethernet, VPN) //! - Managing saved connection profiles //! - Real-time monitoring of network changes //! //! ## Models //! //! The [`models`] module contains all types, enums, and errors: //! - [`Device`] - Represents a network device (WiFi, Ethernet, etc.) //! - [`Network`] - Represents a discovered WiFi network //! - [`WifiSecurity`] - Security types (Open, WPA-PSK, WPA-EAP) //! - [`VpnCredentials`] - VPN connection credentials //! - [`VpnType`] - Supported VPN types (WireGuard, etc.) //! - [`VpnConnection`] - Active VPN connection information //! - [`WireGuardPeer`] - WireGuard peer configuration //! - [`ConnectionError`] - Comprehensive error types //! //! ## Connection Builders //! //! The [`builders`] module provides functions to construct connection settings //! for different network types. These are typically used internally but exposed //! for advanced use cases. //! //! # Examples //! //! ## Connecting to Different Network Types //! //! ```no_run //! use nmrs::{NetworkManager, WifiSecurity, EapOptions, EapMethod, Phase2}; //! //! # async fn example() -> nmrs::Result<()> { //! let nm = NetworkManager::new().await?; //! //! // Open network //! nm.connect("OpenWiFi", WifiSecurity::Open).await?; //! //! // WPA-PSK (password-protected) //! nm.connect("HomeWiFi", WifiSecurity::WpaPsk { //! psk: "my_password".into() //! }).await?; //! //! // WPA-EAP (Enterprise) //! nm.connect("CorpWiFi", WifiSecurity::WpaEap { //! opts: EapOptions { //! identity: "user@company.com".into(), //! password: "password".into(), //! anonymous_identity: None, //! domain_suffix_match: Some("company.com".into()), //! ca_cert_path: None, //! system_ca_certs: true, //! method: EapMethod::Peap, //! phase2: Phase2::Mschapv2, //! } //! }).await?; //! //! // Ethernet (auto-connects when cable is plugged in) //! nm.connect_wired().await?; //! # Ok(()) //! # } //! ``` //! //! ## Error Handling //! //! All operations return [`Result<T>`], which is an alias for `Result<T, ConnectionError>`. //! The [`ConnectionError`] type provides specific variants for different failure modes: //! //! ```no_run //! use nmrs::{NetworkManager, WifiSecurity, ConnectionError}; //! //! # async fn example() -> nmrs::Result<()> { //! let nm = NetworkManager::new().await?; //! //! match nm.connect("MyNetwork", WifiSecurity::WpaPsk { //! psk: "wrong_password".into() //! }).await { //! Ok(_) => println!("Connected successfully"), //! Err(ConnectionError::AuthFailed) => { //! eprintln!("Wrong password!"); //! } //! Err(ConnectionError::NotFound) => { //! eprintln!("Network not found or out of range"); //! } //! Err(ConnectionError::Timeout) => { //! eprintln!("Connection timed out"); //! } //! Err(ConnectionError::DhcpFailed) => { //! eprintln!("Failed to obtain IP address"); //! } //! Err(e) => eprintln!("Error: {}", e), //! } //! # Ok(()) //! # } //! ``` //! //! ## Device Management //! //! ```no_run //! use nmrs::NetworkManager; //! //! # async fn example() -> nmrs::Result<()> { //! let nm = NetworkManager::new().await?; //! //! // List all devices //! let devices = nm.list_devices().await?; //! for device in devices { //! println!("{}: {} ({})", //! device.interface, //! device.device_type, //! device.state //! ); //! } //! //! // Enable/disable WiFi //! nm.set_wifi_enabled(false).await?; //! nm.set_wifi_enabled(true).await?; //! # Ok(()) //! # } //! ``` //! //! ## Real-Time Monitoring //! //! Monitor network and device changes in real-time using D-Bus signals: //! //! ```ignore //! use nmrs::NetworkManager; //! //! # async fn example() -> nmrs::Result<()> { //! let nm = NetworkManager::new().await?; //! //! // Monitor network changes (new networks, signal changes, etc.) //! nm.monitor_network_changes(|| { //! println!("Networks changed! Refresh your UI."); //! }).await?; //! //! // Monitor device state changes (cable plugged in, device activated, etc.) //! nm.monitor_device_changes(|| { //! println!("Device state changed!"); //! }).await?; //! # Ok(()) //! # } //! ``` //! //! # Architecture //! //! This crate uses D-Bus signals for efficient state monitoring instead of polling. //! When connecting to a network, it subscribes to NetworkManager's `StateChanged` //! signals to detect connection success or failure immediately. This provides: //! //! - **Faster response times** - Immediate notification vs polling delay //! - **Lower CPU usage** - No spinning loops //! - **Better error messages** - Specific failure reasons from NetworkManager //! //! # Logging //! //! This crate uses the [`log`](https://docs.rs/log) facade. To see log output, //! add a logging implementation like `env_logger`: //! //! ```no_run,ignore //! env_logger::init(); //! ``` //! //! # Feature Flags //! //! This crate currently has no optional features. All functionality is enabled by default. //! //! # Platform Support //! //! This crate is Linux-only and requires: //! - NetworkManager running and accessible via D-Bus //! - Appropriate permissions to manage network connections // Internal modules (not exposed in public API) mod api; mod core; mod dbus; mod monitoring; mod types; mod util; // ============================================================================ // Public API // ============================================================================ /// Connection builders for WiFi, Ethernet, and VPN connections. /// /// This module provides functions to construct NetworkManager connection settings /// dictionaries. These are primarily used internally but exposed for advanced use cases. /// /// # Examples /// /// ```rust /// use nmrs::builders::build_wifi_connection; /// use nmrs::{WifiSecurity, ConnectionOptions}; /// /// let opts = ConnectionOptions { /// autoconnect: true, /// autoconnect_priority: None, /// autoconnect_retries: None, /// }; /// /// let settings = build_wifi_connection( /// "MyNetwork", /// &WifiSecurity::Open, /// &opts /// ); /// ``` pub mod builders { pub use crate::api::builders::*; } /// Types, enums, and errors for NetworkManager operations. /// /// This module contains all the public types used throughout the crate: /// /// # Core Types /// - [`NetworkManager`] - Main API entry point /// - [`Device`] - Network device representation /// - [`Network`] - WiFi network representation /// - [`NetworkInfo`] - Detailed network information /// /// # Configuration /// - [`WifiSecurity`] - WiFi security types (Open, WPA-PSK, WPA-EAP) /// - [`EapOptions`] - Enterprise authentication options /// - [`ConnectionOptions`] - Connection settings (autoconnect, priority, etc.) /// /// # Enums /// - [`DeviceType`] - Device types (Ethernet, WiFi, etc.) /// - [`DeviceState`] - Device states (Disconnected, Activated, etc.) /// - [`EapMethod`] - EAP authentication methods /// - [`Phase2`] - Phase 2 authentication for EAP /// /// # Errors /// - [`ConnectionError`] - Comprehensive error type for all operations /// - [`StateReason`] - Device state change reasons /// - [`ConnectionStateReason`] - Connection state change reasons /// /// # Helper Functions /// - [`reason_to_error`] - Convert device state reason to error /// - [`connection_state_reason_to_error`] - Convert connection state reason to error pub mod models { pub use crate::api::models::*; } // Re-export commonly used types at crate root for convenience pub use api::models::{ connection_state_reason_to_error, reason_to_error, ActiveConnectionState, ConnectionError, ConnectionOptions, ConnectionStateReason, Device, DeviceState, DeviceType, EapMethod, EapOptions, Network, NetworkInfo, Phase2, StateReason, VpnConnection, VpnConnectionInfo, VpnCredentials, VpnType, WifiSecurity, WireGuardPeer, }; pub use api::network_manager::NetworkManager; /// A specialized `Result` type for network operations. /// /// This is an alias for `Result<T, ConnectionError>` and is used throughout /// the crate for all fallible operations. /// /// # Examples /// /// ```rust /// use nmrs::Result; /// /// async fn connect_to_wifi() -> Result<()> { /// // Your code here /// Ok(()) /// } /// ``` pub type Result<T> = std::result::Result<T, ConnectionError>;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/util/utils.rs
nmrs/src/util/utils.rs
//! Utility functions for Wi-Fi data conversion and display. //! //! Provides helpers for converting between Wi-Fi data representations: //! frequency to channel, signal strength to visual bars, SSID bytes to strings. use log::warn; use std::borrow::Cow; use std::str; use zbus::Connection; use crate::dbus::{NMAccessPointProxy, NMDeviceProxy, NMProxy, NMWirelessProxy}; use crate::types::constants::{device_type, frequency, signal_strength, wifi_mode}; use crate::Result; /// Converts a Wi-Fi frequency in MHz to a channel number. /// /// Supports 2.4GHz (channels 1-14), 5GHz, and 6GHz bands. /// Returns `None` for frequencies outside known Wi-Fi bands. pub(crate) fn channel_from_freq(mhz: u32) -> Option<u16> { match mhz { frequency::BAND_2_4_START..=frequency::BAND_2_4_END => { Some(((mhz - frequency::BAND_2_4_START) / frequency::CHANNEL_SPACING + 1) as u16) } frequency::BAND_2_4_CH14 => Some(14), frequency::BAND_5_START..=frequency::BAND_5_END => { Some(((mhz - 5000) / frequency::CHANNEL_SPACING) as u16) } frequency::BAND_6_START..=frequency::BAND_6_END => { Some(((mhz - frequency::BAND_6_START) / frequency::CHANNEL_SPACING + 1) as u16) } _ => None, } } /// Converts signal strength (0-100) to a visual bar representation. /// /// Returns a 4-character string using Unicode block characters: /// - 0-24%: `▂___` (1 bar) /// - 25-49%: `▂▄__` (2 bars) /// - 50-74%: `▂▄▆_` (3 bars) /// - 75-100%: `▂▄▆█` (4 bars) pub(crate) fn bars_from_strength(s: u8) -> &'static str { match s { 0..=signal_strength::BAR_1_MAX => "▂___", signal_strength::BAR_2_MIN..=signal_strength::BAR_2_MAX => "▂▄__", signal_strength::BAR_3_MIN..=signal_strength::BAR_3_MAX => "▂▄▆_", _ => "▂▄▆█", } } /// Converts a Wi-Fi mode code to a human-readable string. /// /// Mode codes: 1 = Ad-hoc, 2 = Infrastructure, 3 = Access Point. pub(crate) fn mode_to_string(m: u32) -> &'static str { match m { wifi_mode::ADHOC => "Adhoc", wifi_mode::INFRA => "Infra", wifi_mode::AP => "AP", _ => "Unknown", } } /// Decode SSID bytes, defaulting to `<Hidden Network>` if empty or invalid UTF-8. /// This is safer than unwrap_or and logs the error. pub(crate) fn decode_ssid_or_hidden(bytes: &[u8]) -> Cow<'static, str> { if bytes.is_empty() { return Cow::Borrowed("<Hidden Network>"); } match str::from_utf8(bytes) { Ok(s) => Cow::Owned(s.to_owned()), Err(e) => { warn!("Invalid UTF-8 in SSID during comparison: {e}"); Cow::Borrowed("<Hidden Network>") } } } /// Decode SSID bytes for comparison purposes, defaulting to empty string if invalid. pub(crate) fn decode_ssid_or_empty(bytes: &[u8]) -> Cow<'static, str> { if bytes.is_empty() { return Cow::Borrowed(""); } match str::from_utf8(bytes) { Ok(s) => Cow::Owned(s.to_owned()), Err(e) => { warn!("Invalid UTF-8 in SSID during comparison: {e}"); Cow::Borrowed("") } } } /// Safely get signal strength with a default value. /// This is safer than unwrap_or(0) as it makes the default explicit. pub(crate) fn strength_or_zero(strength: Option<u8>) -> u8 { strength.unwrap_or(0) } /// This helper iterates through all WiFi access points and calls the provided async function. /// /// Loops through devices, filters for WiFi, and invokes `func` with each access point proxy. /// The function is awaited immediately in the loop to avoid lifetime issues. pub(crate) async fn for_each_access_point<F, T>(conn: &Connection, mut func: F) -> Result<Vec<T>> where F: for<'a> FnMut( &'a NMAccessPointProxy<'a>, ) -> std::pin::Pin< Box<dyn std::future::Future<Output = Result<Option<T>>> + 'a>, >, { let nm = NMProxy::new(conn).await?; let devices = nm.get_devices().await?; let mut results = Vec::new(); for dp in devices { let d_proxy = NMDeviceProxy::builder(conn) .path(dp.clone())? .build() .await?; if d_proxy.device_type().await? != device_type::WIFI { continue; } let wifi = NMWirelessProxy::builder(conn) .path(dp.clone())? .build() .await?; for ap_path in wifi.access_points().await? { let ap = NMAccessPointProxy::builder(conn) .path(ap_path)? .build() .await?; if let Some(result) = func(&ap).await? { results.push(result); } } } Ok(results) } /// Macro to convert Result to Option with error logging. /// Usage: `try_log!(result, "context message")?` #[macro_export] macro_rules! try_log { ($result:expr, $context:expr) => { match $result { Ok(value) => value, Err(e) => { log::warn!("{}: {:?}", $context, e); return None; } } }; } #[cfg(test)] mod tests { use super::*; #[test] fn test_channel_from_freq_2_4ghz() { assert_eq!(channel_from_freq(2412), Some(1)); assert_eq!(channel_from_freq(2437), Some(6)); assert_eq!(channel_from_freq(2472), Some(13)); assert_eq!(channel_from_freq(2484), Some(14)); } #[test] fn test_channel_from_freq_5ghz() { assert_eq!(channel_from_freq(5180), Some(36)); assert_eq!(channel_from_freq(5220), Some(44)); assert_eq!(channel_from_freq(5500), Some(100)); } #[test] fn test_channel_from_freq_6ghz() { assert_eq!(channel_from_freq(5955), Some(1)); assert_eq!(channel_from_freq(6115), Some(33)); } #[test] fn test_channel_from_freq_invalid() { assert_eq!(channel_from_freq(1000), None); assert_eq!(channel_from_freq(9999), None); } #[test] fn test_bars_from_strength() { assert_eq!(bars_from_strength(0), "▂___"); assert_eq!(bars_from_strength(24), "▂___"); assert_eq!(bars_from_strength(25), "▂▄__"); assert_eq!(bars_from_strength(49), "▂▄__"); assert_eq!(bars_from_strength(50), "▂▄▆_"); assert_eq!(bars_from_strength(74), "▂▄▆_"); assert_eq!(bars_from_strength(75), "▂▄▆█"); assert_eq!(bars_from_strength(100), "▂▄▆█"); } #[test] fn test_mode_to_string() { assert_eq!(mode_to_string(1), "Adhoc"); assert_eq!(mode_to_string(2), "Infra"); assert_eq!(mode_to_string(3), "AP"); assert_eq!(mode_to_string(99), "Unknown"); } #[test] fn test_decode_ssid_or_hidden() { assert_eq!(decode_ssid_or_hidden(b"MyNetwork"), "MyNetwork"); assert_eq!(decode_ssid_or_hidden(b""), "<Hidden Network>"); assert_eq!(decode_ssid_or_hidden(b"Test_SSID-123"), "Test_SSID-123"); } #[test] fn test_decode_ssid_or_empty() { assert_eq!(decode_ssid_or_empty(b"MyNetwork"), "MyNetwork"); assert_eq!(decode_ssid_or_empty(b""), ""); // Test with valid UTF-8 assert_eq!(decode_ssid_or_empty("café".as_bytes()), "café"); } #[test] fn test_strength_or_zero() { assert_eq!(strength_or_zero(Some(75)), 75); assert_eq!(strength_or_zero(Some(0)), 0); assert_eq!(strength_or_zero(Some(100)), 100); assert_eq!(strength_or_zero(None), 0); } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/util/mod.rs
nmrs/src/util/mod.rs
//! Utility functions. //! //! This module contains helper functions used throughout the crate. pub(crate) mod utils;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/dbus/device.rs
nmrs/src/dbus/device.rs
//! NetworkManager Device proxy. use zbus::{proxy, Result}; /// Proxy for NetworkManager device interface. /// /// Provides access to device properties like interface name, type, state, /// and the reason for state transitions. /// /// # Signals /// /// The `StateChanged` signal is emitted whenever the device state changes. /// Use `receive_device_state_changed()` to get a stream of state change events: /// /// ```ignore /// let mut stream = device_proxy.receive_device_state_changed().await?; /// while let Some(signal) = stream.next().await { /// let args = signal.args()?; /// println!("New state: {}, Old state: {}, Reason: {}", /// args.new_state, args.old_state, args.reason); /// } /// ``` #[proxy( interface = "org.freedesktop.NetworkManager.Device", default_service = "org.freedesktop.NetworkManager" )] pub trait NMDevice { /// The network interface name (e.g., "wlan0"). #[zbus(property)] fn interface(&self) -> Result<String>; /// Device type as a numeric code (2 = Wi-Fi). #[zbus(property)] fn device_type(&self) -> Result<u32>; /// Current device state (100 = activated, 120 = failed). #[zbus(property)] fn state(&self) -> Result<u32>; /// Whether NetworkManager manages this device. #[zbus(property)] fn managed(&self) -> Result<bool>; /// The kernel driver in use. #[zbus(property)] fn driver(&self) -> Result<String>; /// Current state and reason code for the last state change. #[zbus(property)] fn state_reason(&self) -> Result<(u32, u32)>; /// Hardware (MAC) address of the device. #[zbus(property)] fn hw_address(&self) -> Result<String>; /// Permanent hardware (MAC) address of the device. /// Note: This property may not be available on all device types or systems. #[zbus(property, name = "PermHwAddress")] fn perm_hw_address(&self) -> Result<String>; /// Signal emitted when device state changes. /// /// The method is named `device_state_changed` to avoid conflicts with the /// `state` property's change stream. Use `receive_device_state_changed()` /// to subscribe to this signal. /// /// Arguments: /// - `new_state`: The new device state code /// - `old_state`: The previous device state code /// - `reason`: The reason code for the state change #[zbus(signal, name = "StateChanged")] fn device_state_changed(&self, new_state: u32, old_state: u32, reason: u32); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/dbus/wired.rs
nmrs/src/dbus/wired.rs
//! NetworkManager Wired (Ethernet) Device Proxy use zbus::Result; use zbus::proxy; /// Proxy for wired devices (Ethernet). /// /// Provides access to wired-specific properties like carrier status. #[proxy( interface = "org.freedesktop.NetworkManager.Device.Wired", default_service = "org.freedesktop.NetworkManager" )] pub trait NMWired { /// Design speed of the device, in megabits/second (Mb/s). #[zbus(property)] fn speed(&self) -> Result<u32>; }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/dbus/active_connection.rs
nmrs/src/dbus/active_connection.rs
//! NetworkManager Active Connection proxy. use zbus::{proxy, Result}; use zvariant::OwnedObjectPath; /// Proxy for active connection interface. /// /// Provides access to the state of an active (in-progress or established) /// network connection. Use this to monitor connection activation progress /// and detect failures with specific reason codes. /// /// # Signals /// /// The `StateChanged` signal is emitted when the connection activation state /// changes. Use `receive_activation_state_changed()` to get a stream of state changes: /// /// ```ignore /// let mut stream = active_conn_proxy.receive_activation_state_changed().await?; /// while let Some(signal) = stream.next().await { /// let args = signal.args()?; /// match args.state { /// 2 => println!("Connection activated!"), /// 4 => println!("Connection failed: reason {}", args.reason), /// _ => {} /// } /// } /// ``` #[proxy( interface = "org.freedesktop.NetworkManager.Connection.Active", default_service = "org.freedesktop.NetworkManager" )] pub trait NMActiveConnection { /// Current state of the active connection. /// /// Values: /// - 0: Unknown /// - 1: Activating /// - 2: Activated /// - 3: Deactivating /// - 4: Deactivated #[zbus(property)] fn state(&self) -> Result<u32>; /// Path to the connection settings used for this connection. #[zbus(property)] fn connection(&self) -> Result<OwnedObjectPath>; /// Path to the specific object (e.g., access point) used for this connection. #[zbus(property)] fn specific_object(&self) -> Result<OwnedObjectPath>; /// Connection identifier (usually the SSID for Wi-Fi). #[zbus(property)] fn id(&self) -> Result<String>; /// Connection UUID. #[zbus(property)] fn uuid(&self) -> Result<String>; /// Paths to devices using this connection. #[zbus(property)] fn devices(&self) -> Result<Vec<OwnedObjectPath>>; /// Signal emitted when the connection activation state changes. /// /// The method is named `activation_state_changed` to avoid conflicts with /// the `state` property's change stream. Use `receive_activation_state_changed()` /// to subscribe to this signal. /// /// Arguments: /// - `state`: The new connection state (see `ActiveConnectionState`) /// - `reason`: The reason for the state change (see `ConnectionStateReason`) #[zbus(signal, name = "StateChanged")] fn activation_state_changed(&self, state: u32, reason: u32); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/dbus/mod.rs
nmrs/src/dbus/mod.rs
//! D-Bus proxy interfaces for NetworkManager. //! //! This module contains low-level D-Bus proxy definitions for communicating //! with NetworkManager over the system bus. mod access_point; mod active_connection; mod device; mod main_nm; mod wireless; pub(crate) use access_point::NMAccessPointProxy; pub(crate) use active_connection::NMActiveConnectionProxy; pub(crate) use device::NMDeviceProxy; pub(crate) use main_nm::NMProxy; pub(crate) use wireless::NMWirelessProxy;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/dbus/wireless.rs
nmrs/src/dbus/wireless.rs
//! NetworkManager Wireless Device proxy. use std::collections::HashMap; use zbus::{proxy, Result}; use zvariant::OwnedObjectPath; /// Proxy for wireless device interface. /// /// Extends the base device interface with Wi-Fi specific functionality /// like scanning and access point enumeration. #[proxy( interface = "org.freedesktop.NetworkManager.Device.Wireless", default_service = "org.freedesktop.NetworkManager" )] pub trait NMWireless { /// Requests a Wi-Fi scan. Options are usually empty. fn request_scan(&self, options: HashMap<String, zvariant::Value<'_>>) -> Result<()>; /// Signal emitted when a new access point is discovered. #[zbus(signal)] fn access_point_added(&self, path: OwnedObjectPath); /// Signal emitted when an access point is no longer visible. #[zbus(signal)] fn access_point_removed(&self, path: OwnedObjectPath); /// The operating mode of the wireless device #[zbus(property)] fn mode(&self) -> Result<u32>; /// Current connection bitrate in Kbit/s. #[zbus(property)] fn bitrate(&self) -> Result<u32>; /// List of object paths of access point visible to this wireless device. #[zbus(property)] fn access_points(&self) -> Result<Vec<OwnedObjectPath>>; /// Path to the currently connected access point ("/" if none). #[zbus(property)] fn active_access_point(&self) -> Result<OwnedObjectPath>; /// The capabilities of the wireless device. #[zbus(property)] fn wireless_capabilities(&self) -> Result<u32>; /// The timestamp (in CLOCK_BOOTTIME milliseconds) for the last finished network scan. /// A value of -1 means the device never scanned for access points. #[zbus(property)] fn last_scan(&self) -> Result<i64>; }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/dbus/main_nm.rs
nmrs/src/dbus/main_nm.rs
//! Main NetworkManager proxy. use std::collections::HashMap; use zbus::proxy; use zvariant::OwnedObjectPath; /// Proxy for the main NetworkManager interface. /// /// Provides methods for listing devices, managing connections, /// and controlling Wi-Fi state. #[proxy( interface = "org.freedesktop.NetworkManager", default_service = "org.freedesktop.NetworkManager", default_path = "/org/freedesktop/NetworkManager" )] pub trait NM { /// Returns paths to all network devices. fn get_devices(&self) -> zbus::Result<Vec<OwnedObjectPath>>; /// Whether Wi-Fi is globally enabled. #[zbus(property)] fn wireless_enabled(&self) -> zbus::Result<bool>; /// Enable or disable Wi-Fi globally. #[zbus(property)] fn set_wireless_enabled(&self, value: bool) -> zbus::Result<()>; /// Paths to all active connections. #[zbus(property)] fn active_connections(&self) -> zbus::Result<Vec<OwnedObjectPath>>; /// Creates a new connection and activates it simultaneously. /// /// Returns paths to both the new connection settings and active connection. fn add_and_activate_connection( &self, connection: HashMap<&str, HashMap<&str, zvariant::Value<'_>>>, device: OwnedObjectPath, specific_object: OwnedObjectPath, ) -> zbus::Result<(OwnedObjectPath, OwnedObjectPath)>; /// Activates an existing saved connection. fn activate_connection( &self, connection: OwnedObjectPath, device: OwnedObjectPath, specific_object: OwnedObjectPath, ) -> zbus::Result<OwnedObjectPath>; /// Deactivates an active connection. fn deactivate_connection(&self, active_connection: OwnedObjectPath) -> zbus::Result<()>; /// Signal emitted when a device is added to NetworkManager. #[zbus(signal, name = "DeviceAdded")] fn device_added(&self, device: OwnedObjectPath); /// Signal emitted when a device is removed from NetworkManager. #[zbus(signal, name = "DeviceRemoved")] fn device_removed(&self, device: OwnedObjectPath); /// Signal emitted when any device changes state. #[zbus(signal, name = "StateChanged")] fn state_changed(&self, state: u32); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/dbus/access_point.rs
nmrs/src/dbus/access_point.rs
//! NetworkManager Access Point proxy. use zbus::{proxy, Result}; /// Proxy for access point interface. /// /// Provides information about a visible Wi-Fi network including /// SSID, signal strength, security capabilities, and frequency. #[proxy( interface = "org.freedesktop.NetworkManager.AccessPoint", default_service = "org.freedesktop.NetworkManager" )] pub trait NMAccessPoint { /// SSID as raw bytes (may not be valid UTF-8). #[zbus(property)] fn ssid(&self) -> Result<Vec<u8>>; /// Signal strength as percentage (0-100). #[zbus(property)] fn strength(&self) -> Result<u8>; /// BSSID (MAC address) of the access point. #[zbus(property)] fn hw_address(&self) -> Result<String>; /// General capability flags (bit 0 = privacy/WEP). #[zbus(property)] fn flags(&self) -> Result<u32>; /// WPA security flags (PSK, EAP, etc.). #[zbus(property)] fn wpa_flags(&self) -> Result<u32>; /// RSN/WPA2 security flags. #[zbus(property)] fn rsn_flags(&self) -> Result<u32>; /// Operating frequency in MHz. #[zbus(property)] fn frequency(&self) -> Result<u32>; /// Maximum supported bitrate in Kbit/s. #[zbus(property)] fn max_bitrate(&self) -> Result<u32>; /// Wi-Fi mode (1 = adhoc, 2 = infrastructure, 3 = AP). #[zbus(property)] fn mode(&self) -> Result<u32>; }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/api/network_manager.rs
nmrs/src/api/network_manager.rs
use zbus::Connection; use crate::api::models::{Device, Network, NetworkInfo, WifiSecurity}; use crate::core::connection::{connect, connect_wired, forget}; use crate::core::connection_settings::{get_saved_connection_path, has_saved_connection}; use crate::core::device::{list_devices, set_wifi_enabled, wait_for_wifi_ready, wifi_enabled}; use crate::core::scan::{list_networks, scan_networks}; use crate::core::vpn::{connect_vpn, disconnect_vpn, get_vpn_info, list_vpn_connections}; use crate::models::{VpnConnection, VpnConnectionInfo, VpnCredentials}; use crate::monitoring::device as device_monitor; use crate::monitoring::info::{current_connection_info, current_ssid, show_details}; use crate::monitoring::network as network_monitor; use crate::Result; /// High-level interface to NetworkManager over D-Bus. /// /// This is the main entry point for managing network connections on Linux systems. /// It provides a safe, async Rust API over NetworkManager's D-Bus interface. /// /// # Creating an Instance /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// # Ok(()) /// # } /// ``` /// /// # Capabilities /// /// - **Device Management**: List devices, enable/disable WiFi /// - **Network Scanning**: Discover available WiFi networks /// - **Connection Management**: Connect to WiFi, Ethernet networks /// - **Profile Management**: Save, retrieve, and delete connection profiles /// - **Real-Time Monitoring**: Subscribe to network and device state changes /// /// # Examples /// /// ## Basic WiFi Connection /// /// ```no_run /// use nmrs::{NetworkManager, WifiSecurity}; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// // Scan and list networks /// let networks = nm.list_networks().await?; /// for net in &networks { /// println!("{}: {}%", net.ssid, net.strength.unwrap_or(0)); /// } /// /// // Connect to a network /// nm.connect("MyNetwork", WifiSecurity::WpaPsk { /// psk: "password".into() /// }).await?; /// # Ok(()) /// # } /// ``` /// /// ## Device Management /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// // List all network devices /// let devices = nm.list_devices().await?; /// /// // Control WiFi /// nm.set_wifi_enabled(false).await?; // Disable WiFi /// nm.set_wifi_enabled(true).await?; // Enable WiFi /// # Ok(()) /// # } /// ``` /// /// ## Connection Profiles /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// // Check for saved connection /// if nm.has_saved_connection("MyNetwork").await? { /// println!("Connection profile exists"); /// /// // Delete it /// nm.forget("MyNetwork").await?; /// } /// # Ok(()) /// # } /// ``` /// /// # Thread Safety /// /// `NetworkManager` is `Clone` and can be safely shared across async tasks. /// Each clone shares the same underlying D-Bus connection. #[derive(Clone)] pub struct NetworkManager { conn: Connection, } impl NetworkManager { /// Creates a new `NetworkManager` connected to the system D-Bus. pub async fn new() -> Result<Self> { let conn = Connection::system().await?; Ok(Self { conn }) } /// List all network devices managed by NetworkManager. pub async fn list_devices(&self) -> Result<Vec<Device>> { list_devices(&self.conn).await } /// Lists all network devices managed by NetworkManager. pub async fn list_wireless_devices(&self) -> Result<Vec<Device>> { let devices = list_devices(&self.conn).await?; Ok(devices.into_iter().filter(|d| d.is_wireless()).collect()) } /// List all wired (Ethernet) devices. pub async fn list_wired_devices(&self) -> Result<Vec<Device>> { let devices = list_devices(&self.conn).await?; Ok(devices.into_iter().filter(|d| d.is_wired()).collect()) } /// Lists all visible Wi-Fi networks. pub async fn list_networks(&self) -> Result<Vec<Network>> { list_networks(&self.conn).await } /// Connects to a Wi-Fi network with the given credentials. /// /// # Errors /// /// Returns `ConnectionError::NotFound` if the network is not visible, /// `ConnectionError::AuthFailed` if authentication fails, or other /// variants for specific failure reasons. pub async fn connect(&self, ssid: &str, creds: WifiSecurity) -> Result<()> { connect(&self.conn, ssid, creds).await } /// Connects to a wired (Ethernet) device. /// /// Finds the first available wired device and either activates an existing /// saved connection or creates a new one. The connection will activate /// when a cable is plugged in. /// /// # Errors /// /// Returns `ConnectionError::NoWiredDevice` if no wired device is found. pub async fn connect_wired(&self) -> Result<()> { connect_wired(&self.conn).await } /// Connects to a VPN using the provided credentials. /// /// Currently supports WireGuard VPN connections. The function checks for an /// existing saved VPN connection by name. If found, it activates the saved /// connection. If not found, it creates a new VPN connection with the provided /// credentials. /// /// # Example /// /// ```no_run /// use nmrs::{NetworkManager, VpnCredentials, VpnType, WireGuardPeer}; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// let creds = VpnCredentials { /// vpn_type: VpnType::WireGuard, /// name: "MyVPN".into(), /// gateway: "vpn.example.com:51820".into(), /// private_key: "your_private_key".into(), /// address: "10.0.0.2/24".into(), /// peers: vec![WireGuardPeer { /// public_key: "peer_public_key".into(), /// gateway: "vpn.example.com:51820".into(), /// allowed_ips: vec!["0.0.0.0/0".into()], /// preshared_key: None, /// persistent_keepalive: Some(25), /// }], /// dns: Some(vec!["1.1.1.1".into()]), /// mtu: None, /// uuid: None, /// }; /// /// nm.connect_vpn(creds).await?; /// # Ok(()) /// # } /// ``` /// /// # Errors /// /// Returns an error if: /// - NetworkManager is not running or accessible /// - The credentials are invalid or incomplete /// - The VPN connection fails to activate pub async fn connect_vpn(&self, creds: VpnCredentials) -> Result<()> { connect_vpn(&self.conn, creds).await } /// Disconnects from an active VPN connection by name. /// /// Searches through active connections for a VPN matching the given name. /// If found, deactivates the connection. If not found or already disconnected, /// returns success. /// /// # Example /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// nm.disconnect_vpn("MyVPN").await?; /// # Ok(()) /// # } /// ``` pub async fn disconnect_vpn(&self, name: &str) -> Result<()> { disconnect_vpn(&self.conn, name).await } /// Lists all saved VPN connections. /// /// Returns a list of all VPN connection profiles saved in NetworkManager, /// including their name, type, and current state. Only VPN connections with /// recognized types (currently WireGuard) are returned. /// /// # Example /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// let vpns = nm.list_vpn_connections().await?; /// /// for vpn in vpns { /// println!("{}: {:?}", vpn.name, vpn.vpn_type); /// } /// # Ok(()) /// # } /// ``` pub async fn list_vpn_connections(&self) -> Result<Vec<VpnConnection>> { list_vpn_connections(&self.conn).await } /// Forgets (deletes) a saved VPN connection by name. /// /// Searches through saved connections for a VPN matching the given name. /// If found, deletes the connection profile. If currently connected, the /// VPN will be disconnected first before deletion. /// /// # Example /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// nm.forget_vpn("MyVPN").await?; /// # Ok(()) /// # } /// ``` /// /// # Errors /// /// Returns `ConnectionError::NoSavedConnection` if no VPN with the given /// name is found. pub async fn forget_vpn(&self, name: &str) -> Result<()> { crate::core::vpn::forget_vpn(&self.conn, name).await } /// Gets detailed information about an active VPN connection. /// /// Retrieves comprehensive information about a VPN connection, including /// IP configuration, DNS servers, gateway, interface, and connection state. /// The VPN must be actively connected to retrieve this information. /// /// # Example /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// let info = nm.get_vpn_info("MyVPN").await?; /// /// println!("VPN: {}", info.name); /// println!("Interface: {:?}", info.interface); /// println!("IP Address: {:?}", info.ip4_address); /// println!("DNS Servers: {:?}", info.dns_servers); /// println!("State: {:?}", info.state); /// # Ok(()) /// # } /// ``` /// /// # Errors /// /// Returns `ConnectionError::NoVpnConnection` if the VPN is not found /// or not currently active. pub async fn get_vpn_info(&self, name: &str) -> Result<VpnConnectionInfo> { get_vpn_info(&self.conn, name).await } /// Returns whether Wi-Fi is currently enabled. pub async fn wifi_enabled(&self) -> Result<bool> { wifi_enabled(&self.conn).await } /// Enables or disables Wi-Fi. pub async fn set_wifi_enabled(&self, value: bool) -> Result<()> { set_wifi_enabled(&self.conn, value).await } /// Waits for a Wi-Fi device to become ready (disconnected or activated). pub async fn wait_for_wifi_ready(&self) -> Result<()> { wait_for_wifi_ready(&self.conn).await } /// Triggers a Wi-Fi scan on all wireless devices. pub async fn scan_networks(&self) -> Result<()> { scan_networks(&self.conn).await } /// Returns the SSID of the currently connected network, if any. #[must_use] pub async fn current_ssid(&self) -> Option<String> { current_ssid(&self.conn).await } /// Returns the SSID and frequency of the current connection, if any. #[must_use] pub async fn current_connection_info(&self) -> Option<(String, Option<u32>)> { current_connection_info(&self.conn).await } /// Returns detailed information about a specific network. pub async fn show_details(&self, net: &Network) -> Result<NetworkInfo> { show_details(&self.conn, net).await } /// Returns whether a saved connection exists for the given SSID. pub async fn has_saved_connection(&self, ssid: &str) -> Result<bool> { has_saved_connection(&self.conn, ssid).await } /// Returns the D-Bus object path of a saved connection for the given SSID. pub async fn get_saved_connection_path( &self, ssid: &str, ) -> Result<Option<zvariant::OwnedObjectPath>> { get_saved_connection_path(&self.conn, ssid).await } /// Forgets (deletes) a saved connection for the given SSID. /// /// If currently connected to this network, disconnects first. pub async fn forget(&self, ssid: &str) -> Result<()> { forget(&self.conn, ssid).await } /// Monitors Wi-Fi network changes in real-time. /// /// Subscribes to D-Bus signals for access point additions and removals /// on all Wi-Fi devices. Invokes the callback whenever the network list /// changes, enabling live UI updates without polling. /// /// This function runs indefinitely until an error occurs. Run it in a /// background task. /// /// # Example /// /// ```ignore /// # use nmrs::NetworkManager; /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// // Spawn monitoring task /// glib::MainContext::default().spawn_local({ /// let nm = nm.clone(); /// async move { /// nm.monitor_network_changes(|| { /// println!("Networks changed!"); /// }).await /// } /// }); /// # Ok(()) /// # } /// ``` pub async fn monitor_network_changes<F>(&self, callback: F) -> Result<()> where F: Fn() + 'static, { network_monitor::monitor_network_changes(&self.conn, callback).await } /// Monitors device state changes in real-time. /// /// Subscribes to D-Bus signals for device state changes on all network /// devices (both wired and wireless). Invokes the callback whenever a /// device state changes (e.g., cable plugged in, device activated), /// enabling live UI updates without polling. /// /// This function runs indefinitely until an error occurs. Run it in a /// background task. /// /// # Example /// /// ```ignore /// # use nmrs::NetworkManager; /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// // Spawn monitoring task /// glib::MainContext::default().spawn_local({ /// let nm = nm.clone(); /// async move { /// nm.monitor_device_changes(|| { /// println!("Device state changed!"); /// }).await /// } /// }); /// # Ok(()) /// # } /// ``` pub async fn monitor_device_changes<F>(&self, callback: F) -> Result<()> where F: Fn() + 'static, { device_monitor::monitor_device_changes(&self.conn, callback).await } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/api/mod.rs
nmrs/src/api/mod.rs
//! Public API module. //! //! This module contains the high-level user-facing API for the `nmrs` crate. pub mod builders; pub mod models; pub mod network_manager;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/api/models.rs
nmrs/src/api/models.rs
use serde::{Deserialize, Serialize}; use std::fmt::{Display, Formatter}; use thiserror::Error; use uuid::Uuid; /// NetworkManager active connection state. /// /// These values represent the lifecycle states of an active connection /// as reported by the NM D-Bus API. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ActiveConnectionState { /// Connection state is unknown. Unknown, /// Connection is activating (connecting). Activating, /// Connection is fully activated (connected). Activated, /// Connection is deactivating (disconnecting). Deactivating, /// Connection is fully deactivated (disconnected). Deactivated, /// Unknown state code not mapped to a specific variant. Other(u32), } impl From<u32> for ActiveConnectionState { fn from(code: u32) -> Self { match code { 0 => Self::Unknown, 1 => Self::Activating, 2 => Self::Activated, 3 => Self::Deactivating, 4 => Self::Deactivated, v => Self::Other(v), } } } impl Display for ActiveConnectionState { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Unknown => write!(f, "unknown"), Self::Activating => write!(f, "activating"), Self::Activated => write!(f, "activated"), Self::Deactivating => write!(f, "deactivating"), Self::Deactivated => write!(f, "deactivated"), Self::Other(v) => write!(f, "unknown state ({v})"), } } } /// NetworkManager active connection state reason codes. /// /// These values indicate why an active connection transitioned to its /// current state. Use `ConnectionStateReason::from(code)` to convert /// from the raw u32 values returned by NetworkManager signals. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ConnectionStateReason { /// The reason is unknown. Unknown, /// No specific reason. None, /// User disconnected. UserDisconnected, /// Device disconnected. DeviceDisconnected, /// The NetworkManager service stopped. ServiceStopped, /// IP configuration was invalid. IpConfigInvalid, /// Connection timed out while activating. ConnectTimeout, /// Service start timed out. ServiceStartTimeout, /// Service failed to start. ServiceStartFailed, /// No secrets (password) were provided. NoSecrets, /// Login/authentication failed. LoginFailed, /// The connection was removed. ConnectionRemoved, /// A dependency failed. DependencyFailed, /// Device realization failed. DeviceRealizeFailed, /// Device was removed. DeviceRemoved, /// Unknown reason code not mapped to a specific variant. Other(u32), } impl From<u32> for ConnectionStateReason { fn from(code: u32) -> Self { match code { 0 => Self::Unknown, 1 => Self::None, 2 => Self::UserDisconnected, 3 => Self::DeviceDisconnected, 4 => Self::ServiceStopped, 5 => Self::IpConfigInvalid, 6 => Self::ConnectTimeout, 7 => Self::ServiceStartTimeout, 8 => Self::ServiceStartFailed, 9 => Self::NoSecrets, 10 => Self::LoginFailed, 11 => Self::ConnectionRemoved, 12 => Self::DependencyFailed, 13 => Self::DeviceRealizeFailed, 14 => Self::DeviceRemoved, v => Self::Other(v), } } } impl Display for ConnectionStateReason { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Unknown => write!(f, "unknown"), Self::None => write!(f, "none"), Self::UserDisconnected => write!(f, "user disconnected"), Self::DeviceDisconnected => write!(f, "device disconnected"), Self::ServiceStopped => write!(f, "service stopped"), Self::IpConfigInvalid => write!(f, "IP configuration invalid"), Self::ConnectTimeout => write!(f, "connection timed out"), Self::ServiceStartTimeout => write!(f, "service start timed out"), Self::ServiceStartFailed => write!(f, "service start failed"), Self::NoSecrets => write!(f, "no secrets (password) provided"), Self::LoginFailed => write!(f, "login/authentication failed"), Self::ConnectionRemoved => write!(f, "connection was removed"), Self::DependencyFailed => write!(f, "dependency failed"), Self::DeviceRealizeFailed => write!(f, "device realization failed"), Self::DeviceRemoved => write!(f, "device was removed"), Self::Other(v) => write!(f, "unknown reason ({v})"), } } } /// Converts a connection state reason code to a specific `ConnectionError`. /// /// Maps authentication-related failures to `AuthFailed`, timeout issues to `Timeout`, /// and other failures to the appropriate variant. pub fn connection_state_reason_to_error(code: u32) -> ConnectionError { let reason = ConnectionStateReason::from(code); match reason { // Authentication failures ConnectionStateReason::NoSecrets | ConnectionStateReason::LoginFailed => { ConnectionError::AuthFailed } // Timeout failures ConnectionStateReason::ConnectTimeout | ConnectionStateReason::ServiceStartTimeout => { ConnectionError::Timeout } // IP configuration failures (often DHCP) ConnectionStateReason::IpConfigInvalid => ConnectionError::DhcpFailed, // All other failures _ => ConnectionError::ActivationFailed(reason), } } /// NetworkManager device state reason codes. /// /// These values come from the NM D-Bus API and indicate why a device /// transitioned to its current state. Use `StateReason::from(code)` to /// convert from the raw u32 values returned by NetworkManager. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StateReason { /// The reason is unknown. Unknown, /// No specific reason given. None, /// The user disconnected the device. UserDisconnected, /// The device was disconnected by the system. DeviceDisconnected, /// The carrier/link status changed (e.g., cable unplugged). CarrierChanged, /// The Wi-Fi supplicant disconnected unexpectedly. SupplicantDisconnected, /// The Wi-Fi supplicant's configuration failed. SupplicantConfigFailed, /// The Wi-Fi supplicant failed (authentication issue). SupplicantFailed, /// The Wi-Fi supplicant timed out during authentication. SupplicantTimeout, /// PPP connection start failed. PppStartFailed, /// DHCP client failed to start. DhcpStartFailed, /// DHCP client encountered an error. DhcpError, /// DHCP client failed to obtain an IP address. DhcpFailed, /// Modem connection failed. ModemConnectionFailed, /// Modem initialization failed. ModemInitFailed, /// InfiniBand device mode mismatch. InfinibandMode, /// A dependency connection failed. DependencyFailed, /// BR2684 bridge setup failed. Br2684Failed, /// Failed to set the device mode (e.g., AP mode). ModeSetFailed, /// GSM modem APN selection failed. GsmApnSelectFailed, /// GSM modem is not searching for networks. GsmNotSearching, /// GSM network registration was denied. GsmRegistrationDenied, /// GSM network registration timed out. GsmRegistrationTimeout, /// GSM network registration failed. GsmRegistrationFailed, /// GSM SIM PIN check failed. GsmPinCheckFailed, /// Required firmware is missing for the device. FirmwareMissing, /// The device was removed from the system. DeviceRemoved, /// The system is entering sleep mode. Sleeping, /// The connection profile was removed. ConnectionRemoved, /// The user requested the operation. UserRequested, /// Carrier status changed. Carrier, /// NetworkManager assumed an existing connection. ConnectionAssumed, /// The Wi-Fi supplicant became available. SupplicantAvailable, /// The modem device was not found. ModemNotFound, /// Bluetooth connection failed. BluetoothFailed, /// GSM SIM card is not inserted. GsmSimNotInserted, /// GSM SIM PIN is required. GsmSimPinRequired, /// GSM SIM PUK is required. GsmSimPukRequired, /// Wrong GSM SIM card inserted. GsmSimWrong, /// The requested SSID was not found. SsidNotFound, /// A secondary connection failed. SecondaryConnectionFailed, /// DCB/FCoE setup failed. DcbFcoeFailed, /// teamd control interface failed. TeamdControlFailed, /// Modem operation failed. ModemFailed, /// Modem became available. ModemAvailable, /// SIM PIN was incorrect. SimPinIncorrect, /// A new connection activation was queued. NewActivationEnqueued, /// Parent device became unreachable. ParentUnreachable, /// Parent device changed. ParentChanged, /// Unknown reason code not mapped to a specific variant. Other(u32), } /// Represents a Wi-Fi network discovered during a scan. /// /// This struct contains information about a WiFi network that was discovered /// by NetworkManager during a scan operation. /// /// # Examples /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// // Scan for networks /// nm.scan_networks().await?; /// let networks = nm.list_networks().await?; /// /// for net in networks { /// println!("SSID: {}", net.ssid); /// println!(" Signal: {}%", net.strength.unwrap_or(0)); /// println!(" Secured: {}", net.secured); /// /// if let Some(freq) = net.frequency { /// let band = if freq > 5000 { "5GHz" } else { "2.4GHz" }; /// println!(" Band: {}", band); /// } /// } /// # Ok(()) /// # } /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Network { /// Device interface name (e.g., "wlan0") pub device: String, /// Network SSID (name) pub ssid: String, /// Access point MAC address (BSSID) pub bssid: Option<String>, /// Signal strength (0-100) pub strength: Option<u8>, /// Frequency in MHz (e.g., 2437 for channel 6) pub frequency: Option<u32>, /// Whether the network requires authentication pub secured: bool, /// Whether the network uses WPA-PSK authentication pub is_psk: bool, /// Whether the network uses WPA-EAP (Enterprise) authentication pub is_eap: bool, } /// Detailed information about a Wi-Fi network. /// /// Contains comprehensive information about a WiFi network, including /// connection status, signal quality, and technical details. /// /// # Examples /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// let networks = nm.list_networks().await?; /// /// if let Some(network) = networks.first() { /// let info = nm.show_details(network).await?; /// /// println!("Network: {}", info.ssid); /// println!("Signal: {} {}", info.strength, info.bars); /// println!("Security: {}", info.security); /// println!("Status: {}", info.status); /// /// if let Some(rate) = info.rate_mbps { /// println!("Speed: {} Mbps", rate); /// } /// } /// # Ok(()) /// # } /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] pub struct NetworkInfo { /// Network SSID (name) pub ssid: String, /// Access point MAC address (BSSID) pub bssid: String, /// Signal strength (0-100) pub strength: u8, /// Frequency in MHz pub freq: Option<u32>, /// WiFi channel number pub channel: Option<u16>, /// Operating mode (e.g., "infrastructure") pub mode: String, /// Connection speed in Mbps pub rate_mbps: Option<u32>, /// Visual signal strength representation (e.g., "▂▄▆█") pub bars: String, /// Security type description pub security: String, /// Connection status pub status: String, } /// Represents a network device managed by NetworkManager. /// /// A device can be a WiFi adapter, Ethernet interface, or other network hardware. /// /// # Examples /// /// ```no_run /// use nmrs::NetworkManager; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// let devices = nm.list_devices().await?; /// /// for device in devices { /// println!("Interface: {}", device.interface); /// println!(" Type: {}", device.device_type); /// println!(" State: {}", device.state); /// println!(" MAC: {}", device.identity.current_mac); /// /// if device.is_wireless() { /// println!(" This is a WiFi device"); /// } else if device.is_wired() { /// println!(" This is an Ethernet device"); /// } /// /// if let Some(driver) = &device.driver { /// println!(" Driver: {}", driver); /// } /// } /// # Ok(()) /// # } /// ``` #[derive(Debug, Clone)] pub struct Device { /// D-Bus object path pub path: String, /// Interface name (e.g., "wlan0", "eth0") pub interface: String, /// Device hardware identity (MAC addresses) pub identity: DeviceIdentity, /// Type of device (WiFi, Ethernet, etc.) pub device_type: DeviceType, /// Current device state pub state: DeviceState, /// Whether NetworkManager manages this device pub managed: Option<bool>, /// Kernel driver name pub driver: Option<String>, } /// Represents the hardware identity of a network device. /// /// Contains MAC addresses that uniquely identify the device. The permanent /// MAC is burned into the hardware, while the current MAC may be different /// if MAC address randomization or spoofing is enabled. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct DeviceIdentity { /// The permanent (factory-assigned) MAC address. pub permanent_mac: String, /// The current MAC address in use (may differ if randomized/spoofed). pub current_mac: String, } /// EAP (Extensible Authentication Protocol) method for WPA-Enterprise Wi-Fi. /// /// These are the outer authentication methods used in 802.1X authentication. #[derive(Debug, Clone, PartialEq, Eq)] pub enum EapMethod { /// Protected EAP (PEAPv0) - tunnels inner authentication in TLS. /// Most commonly used with MSCHAPv2 inner authentication. Peap, /// Tunneled TLS (EAP-TTLS) - similar to PEAP but more flexible. /// Can use various inner authentication methods like PAP or MSCHAPv2. Ttls, } /// Phase 2 (inner) authentication methods for EAP connections. /// /// These methods run inside the TLS tunnel established by the outer /// EAP method (PEAP or TTLS). #[derive(Debug, Clone, PartialEq, Eq)] pub enum Phase2 { /// Microsoft Challenge Handshake Authentication Protocol v2. /// More secure than PAP, commonly used with PEAP. Mschapv2, /// Password Authentication Protocol. /// Simple plaintext password (protected by TLS tunnel). /// Often used with TTLS. Pap, } /// EAP options for WPA-EAP (Enterprise) Wi-Fi connections. /// /// Configuration for 802.1X authentication, commonly used in corporate /// and educational networks. /// /// # Examples /// /// ## PEAP with MSCHAPv2 (Common Corporate Setup) /// /// ```rust /// use nmrs::{EapOptions, EapMethod, Phase2}; /// /// let opts = EapOptions { /// identity: "employee@company.com".into(), /// password: "my_password".into(), /// anonymous_identity: Some("anonymous@company.com".into()), /// domain_suffix_match: Some("company.com".into()), /// ca_cert_path: None, /// system_ca_certs: true, // Use system certificate store /// method: EapMethod::Peap, /// phase2: Phase2::Mschapv2, /// }; /// ``` /// /// ## TTLS with PAP (Alternative Setup) /// /// ```rust /// use nmrs::{EapOptions, EapMethod, Phase2}; /// /// let opts = EapOptions { /// identity: "student@university.edu".into(), /// password: "password".into(), /// anonymous_identity: None, /// domain_suffix_match: None, /// ca_cert_path: Some("file:///etc/ssl/certs/university-ca.pem".into()), /// system_ca_certs: false, /// method: EapMethod::Ttls, /// phase2: Phase2::Pap, /// }; /// ``` #[derive(Debug, Clone, PartialEq, Eq)] pub struct EapOptions { /// User identity (usually email or username) pub identity: String, /// Password for authentication pub password: String, /// Anonymous outer identity (for privacy) pub anonymous_identity: Option<String>, /// Domain to match against server certificate pub domain_suffix_match: Option<String>, /// Path to CA certificate file (file:// URL) pub ca_cert_path: Option<String>, /// Use system CA certificate store pub system_ca_certs: bool, /// EAP method (PEAP or TTLS) pub method: EapMethod, /// Phase 2 inner authentication method pub phase2: Phase2, } /// Connection options for saved NetworkManager connections. /// /// Controls how NetworkManager handles saved connection profiles, /// including automatic connection behavior. /// /// # Examples /// /// ```rust /// use nmrs::ConnectionOptions; /// /// // Basic auto-connect /// let opts = ConnectionOptions { /// autoconnect: true, /// autoconnect_priority: None, /// autoconnect_retries: None, /// }; /// /// // High-priority connection with retry limit /// let opts_priority = ConnectionOptions { /// autoconnect: true, /// autoconnect_priority: Some(10), // Higher = more preferred /// autoconnect_retries: Some(3), // Retry up to 3 times /// }; /// /// // Manual connection only /// let opts_manual = ConnectionOptions { /// autoconnect: false, /// autoconnect_priority: None, /// autoconnect_retries: None, /// }; /// ``` #[derive(Debug, Clone)] pub struct ConnectionOptions { /// Whether to automatically connect when available pub autoconnect: bool, /// Priority for auto-connection (higher = more preferred) pub autoconnect_priority: Option<i32>, /// Maximum number of auto-connect retry attempts pub autoconnect_retries: Option<i32>, } /// Wi-Fi connection security types. /// /// Represents the authentication method for connecting to a WiFi network. /// /// # Variants /// /// - [`Open`](WifiSecurity::Open) - No authentication required (open network) /// - [`WpaPsk`](WifiSecurity::WpaPsk) - WPA/WPA2/WPA3 Personal (password-based) /// - [`WpaEap`](WifiSecurity::WpaEap) - WPA/WPA2 Enterprise (802.1X authentication) /// /// # Examples /// /// ## Open Network /// /// ```rust /// use nmrs::WifiSecurity; /// /// let security = WifiSecurity::Open; /// ``` /// /// ## Password-Protected Network /// /// ```no_run /// use nmrs::{NetworkManager, WifiSecurity}; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// nm.connect("HomeWiFi", WifiSecurity::WpaPsk { /// psk: "my_secure_password".into() /// }).await?; /// # Ok(()) /// # } /// ``` /// /// ## Enterprise Network (WPA-EAP) /// /// ```no_run /// use nmrs::{NetworkManager, WifiSecurity, EapOptions, EapMethod, Phase2}; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// nm.connect("CorpWiFi", WifiSecurity::WpaEap { /// opts: EapOptions { /// identity: "user@company.com".into(), /// password: "password".into(), /// anonymous_identity: None, /// domain_suffix_match: Some("company.com".into()), /// ca_cert_path: None, /// system_ca_certs: true, /// method: EapMethod::Peap, /// phase2: Phase2::Mschapv2, /// } /// }).await?; /// # Ok(()) /// # } /// ``` #[derive(Debug, Clone, PartialEq, Eq)] pub enum WifiSecurity { /// Open network (no authentication) Open, /// WPA-PSK (password-based authentication) WpaPsk { /// Pre-shared key (password) psk: String, }, /// WPA-EAP (Enterprise authentication via 802.1X) WpaEap { /// EAP configuration options opts: EapOptions, }, } /// VPN connection type. /// /// Identifies the VPN protocol/technology used for the connection. /// Currently only WireGuard is supported. #[derive(Debug, Clone, PartialEq, Eq)] pub enum VpnType { /// WireGuard - modern, high-performance VPN protocol. WireGuard, } /// VPN Credentials for establishing a VPN connection. /// /// Stores the necessary information to configure and connect to a VPN. /// Currently supports WireGuard VPN connections. /// /// # Fields /// /// - `vpn_type`: The type of VPN (currently only WireGuard) /// - `name`: Unique identifier for the connection /// - `gateway`: VPN gateway endpoint (e.g., "vpn.example.com:51820") /// - `private_key`: Client's WireGuard private key /// - `address`: Client's IP address with CIDR notation (e.g., "10.0.0.2/24") /// - `peers`: List of WireGuard peers to connect to /// - `dns`: Optional DNS servers to use (e.g., ["1.1.1.1", "8.8.8.8"]) /// - `mtu`: Optional Maximum Transmission Unit /// - `uuid`: Optional UUID for the connection (auto-generated if not provided) /// /// # Example /// /// ```rust /// use nmrs::{VpnCredentials, VpnType, WireGuardPeer}; /// /// let creds = VpnCredentials { /// vpn_type: VpnType::WireGuard, /// name: "HomeVPN".into(), /// gateway: "vpn.home.com:51820".into(), /// private_key: "aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789=".into(), /// address: "10.0.0.2/24".into(), /// peers: vec![WireGuardPeer { /// public_key: "server_public_key".into(), /// gateway: "vpn.home.com:51820".into(), /// allowed_ips: vec!["0.0.0.0/0".into()], /// preshared_key: None, /// persistent_keepalive: Some(25), /// }], /// dns: Some(vec!["1.1.1.1".into()]), /// mtu: None, /// uuid: None, /// }; /// ``` #[derive(Debug, Clone)] pub struct VpnCredentials { /// The type of VPN (currently only WireGuard). pub vpn_type: VpnType, /// Unique name for the connection profile. pub name: String, /// VPN gateway endpoint (e.g., "vpn.example.com:51820"). pub gateway: String, /// Client's WireGuard private key (base64 encoded). pub private_key: String, /// Client's IP address with CIDR notation (e.g., "10.0.0.2/24"). pub address: String, /// List of WireGuard peers to connect to. pub peers: Vec<WireGuardPeer>, /// Optional DNS servers to use when connected. pub dns: Option<Vec<String>>, /// Optional Maximum Transmission Unit size. pub mtu: Option<u32>, /// Optional UUID for the connection (auto-generated if not provided). pub uuid: Option<Uuid>, } /// WireGuard peer configuration. /// /// Represents a single WireGuard peer (server) to connect to. /// /// # Fields /// /// - `public_key`: The peer's WireGuard public key /// - `gateway`: Peer endpoint in "host:port" format (e.g., "vpn.example.com:51820") /// - `allowed_ips`: List of IP ranges allowed through this peer (e.g., ["0.0.0.0/0"]) /// - `preshared_key`: Optional pre-shared key for additional security /// - `persistent_keepalive`: Optional keepalive interval in seconds (e.g., 25) /// /// # Example /// /// ```rust /// use nmrs::WireGuardPeer; /// /// let peer = WireGuardPeer { /// public_key: "aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789=".into(), /// gateway: "vpn.example.com:51820".into(), /// allowed_ips: vec!["0.0.0.0/0".into(), "::/0".into()], /// preshared_key: None, /// persistent_keepalive: Some(25), /// }; /// ``` #[derive(Debug, Clone)] pub struct WireGuardPeer { /// The peer's WireGuard public key (base64 encoded). pub public_key: String, /// Peer endpoint in "host:port" format. pub gateway: String, /// IP ranges to route through this peer (e.g., ["0.0.0.0/0"]). pub allowed_ips: Vec<String>, /// Optional pre-shared key for additional security. pub preshared_key: Option<String>, /// Optional keepalive interval in seconds (e.g., 25). pub persistent_keepalive: Option<u32>, } /// VPN Connection information. /// /// Represents a VPN connection managed by NetworkManager, including both /// saved and active connections. /// /// # Fields /// /// - `name`: The connection name/identifier /// - `vpn_type`: The type of VPN (WireGuard, etc.) /// - `state`: Current connection state (for active connections) /// - `interface`: Network interface name (e.g., "wg0") when active /// /// # Example /// /// ```rust /// use nmrs::{VpnConnection, VpnType, DeviceState}; /// /// let vpn = VpnConnection { /// name: "WorkVPN".into(), /// vpn_type: VpnType::WireGuard, /// state: DeviceState::Activated, /// interface: Some("wg0".into()), /// }; /// ``` #[derive(Debug, Clone)] pub struct VpnConnection { /// The connection name/identifier. pub name: String, /// The type of VPN (WireGuard, etc.). pub vpn_type: VpnType, /// Current connection state. pub state: DeviceState, /// Network interface name when active (e.g., "wg0"). pub interface: Option<String>, } /// Detailed VPN connection information and statistics. /// /// Provides comprehensive information about an active VPN connection, /// including IP configuration and connection details. /// /// # Limitations /// /// - `ip6_address`: IPv6 address parsing is not currently implemented and will /// always return `None`. IPv4 addresses are fully supported. /// /// # Example /// /// ```rust /// use nmrs::{VpnConnectionInfo, VpnType, DeviceState}; /// /// let info = VpnConnectionInfo { /// name: "WorkVPN".into(), /// vpn_type: VpnType::WireGuard, /// state: DeviceState::Activated, /// interface: Some("wg0".into()), /// gateway: Some("vpn.example.com:51820".into()), /// ip4_address: Some("10.0.0.2/24".into()), /// ip6_address: None, // IPv6 not yet implemented /// dns_servers: vec!["1.1.1.1".into()], /// }; /// ``` #[derive(Debug, Clone)] pub struct VpnConnectionInfo { /// The connection name/identifier. pub name: String, /// The type of VPN (WireGuard, etc.). pub vpn_type: VpnType, /// Current connection state. pub state: DeviceState, /// Network interface name when active (e.g., "wg0"). pub interface: Option<String>, /// VPN gateway endpoint address. pub gateway: Option<String>, /// Assigned IPv4 address with CIDR notation. pub ip4_address: Option<String>, /// IPv6 address (currently always `None` - IPv6 parsing not yet implemented). pub ip6_address: Option<String>, /// DNS servers configured for this VPN. pub dns_servers: Vec<String>, } /// NetworkManager device types. /// /// Represents the type of network hardware managed by NetworkManager. #[derive(Debug, Clone, PartialEq)] pub enum DeviceType { /// Wired Ethernet device. Ethernet, /// Wi-Fi (802.11) wireless device. Wifi, /// Wi-Fi P2P (peer-to-peer) device. WifiP2P, /// Loopback device (localhost). Loopback, /// Unknown or unsupported device type with raw code. Other(u32), } /// NetworkManager device states. /// /// Represents the current operational state of a network device. #[derive(Debug, Clone, PartialEq)] pub enum DeviceState { /// Device is not managed by NetworkManager. Unmanaged, /// Device is managed but not yet available (e.g., Wi-Fi disabled). Unavailable, /// Device is available but not connected. Disconnected, /// Device is preparing to connect. Prepare, /// Device is being configured (IP, etc.). Config, /// Device is fully connected and operational. Activated, /// Device is disconnecting. Deactivating, /// Device connection failed. Failed, /// Unknown or unsupported state with raw code. Other(u32), } impl Device { /// Returns `true` if this is a wired (Ethernet) device. pub fn is_wired(&self) -> bool { matches!(self.device_type, DeviceType::Ethernet) } /// Returns `true` if this is a wireless (Wi-Fi) device. pub fn is_wireless(&self) -> bool { matches!(self.device_type, DeviceType::Wifi) } } /// Errors that can occur during network operations. /// /// This enum provides specific error types for different failure modes, /// making it easy to handle errors appropriately in your application. /// /// # Examples /// /// ## Basic Error Handling /// /// ```no_run /// use nmrs::{NetworkManager, WifiSecurity, ConnectionError}; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// match nm.connect("MyNetwork", WifiSecurity::WpaPsk { /// psk: "password".into() /// }).await { /// Ok(_) => println!("Connected!"), /// Err(ConnectionError::AuthFailed) => { /// eprintln!("Wrong password"); /// } /// Err(ConnectionError::NotFound) => { /// eprintln!("Network not in range"); /// } /// Err(ConnectionError::Timeout) => { /// eprintln!("Connection timed out"); /// } /// Err(e) => eprintln!("Error: {}", e), /// } /// # Ok(()) /// # } /// ``` /// /// ## Retry Logic /// /// ```no_run /// use nmrs::{NetworkManager, WifiSecurity, ConnectionError}; /// /// # async fn example() -> nmrs::Result<()> { /// let nm = NetworkManager::new().await?; /// /// for attempt in 1..=3 { /// match nm.connect("MyNetwork", WifiSecurity::Open).await { /// Ok(_) => { /// println!("Connected on attempt {}", attempt); /// break; /// } /// Err(ConnectionError::Timeout) if attempt < 3 => { /// println!("Timeout, retrying..."); /// continue; /// } /// Err(e) => return Err(e), /// } /// } /// # Ok(()) /// # } /// ``` #[derive(Debug, Error)] pub enum ConnectionError { /// A D-Bus communication error occurred. #[error("D-Bus error: {0}")] Dbus(#[from] zbus::Error), /// The requested network was not found during scan. #[error("network not found")] NotFound, /// Authentication with the access point failed (wrong password, rejected credentials). #[error("authentication failed")] AuthFailed, /// The supplicant (wpa_supplicant) encountered a configuration error. #[error("supplicant configuration failed")] SupplicantConfigFailed, /// The supplicant timed out during authentication. #[error("supplicant timeout")] SupplicantTimeout, /// DHCP failed to obtain an IP address. #[error("DHCP failed")] DhcpFailed, /// The connection timed out waiting for activation. #[error("connection timeout")] Timeout, /// The connection is stuck in an unexpected state. #[error("connection stuck in state: {0}")] Stuck(String), /// No Wi-Fi device was found on the system. #[error("no Wi-Fi device found")] NoWifiDevice, /// No wired (ethernet) device was found on the system. #[error("no wired device was found")] NoWiredDevice, /// Wi-Fi device did not become ready in time. #[error("Wi-Fi device not ready")] WifiNotReady, /// No saved connection exists for the requested network. #[error("no saved connection for network")] NoSavedConnection, /// A general connection failure with a device state reason code. #[error("connection failed: {0}")] DeviceFailed(StateReason), /// A connection activation failure with a connection state reason. #[error("connection activation failed: {0}")] ActivationFailed(ConnectionStateReason), /// Invalid UTF-8 encountered in SSID. #[error("invalid UTF-8 in SSID: {0}")] InvalidUtf8(#[from] std::str::Utf8Error), /// No VPN connection found #[error("no VPN connection found")] NoVpnConnection, /// Invalid IP address or CIDR notation #[error("invalid address: {0}")] InvalidAddress(String), /// Invalid VPN peer configuration #[error("invalid peer configuration: {0}")] InvalidPeers(String), /// Invalid WireGuard private key format #[error("invalid WireGuard private key: {0}")] InvalidPrivateKey(String), /// Invalid WireGuard public key format #[error("invalid WireGuard public key: {0}")] InvalidPublicKey(String), /// Invalid VPN gateway format (should be host:port) #[error("invalid VPN gateway: {0}")] InvalidGateway(String), /// VPN connection failed #[error("VPN connection failed: {0}")] VpnFailed(String), } /// NetworkManager device state reason codes. impl From<u32> for StateReason {
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
true
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/api/builders/wifi.rs
nmrs/src/api/builders/wifi.rs
//! NetworkManager connection settings builder. //! //! Constructs the D-Bus settings dictionaries required by NetworkManager's //! `AddAndActivateConnection` method. These settings define the connection //! type, security parameters, and IP configuration. //! //! # NetworkManager Settings Structure //! //! A connection is represented as a nested dictionary: //! - `connection`: General settings (type, id, uuid, autoconnect) //! - `802-11-wireless`: Wi-Fi specific settings (ssid, mode, security reference) //! - `802-11-wireless-security`: Security settings (key-mgmt, psk, auth-alg) //! - `802-1x`: Enterprise authentication settings (for WPA-EAP) //! - `ipv4` / `ipv6`: IP configuration (usually "auto" for DHCP) use std::collections::HashMap; use zvariant::Value; use crate::api::models::{self, ConnectionOptions, EapMethod}; /// Converts a string to bytes for SSID encoding. fn bytes(val: &str) -> Vec<u8> { val.as_bytes().to_vec() } /// Creates a D-Bus string array value. fn string_array(xs: &[&str]) -> Value<'static> { let vals: Vec<String> = xs.iter().map(|s| s.to_string()).collect(); Value::from(vals) } /// Builds the `802-11-wireless` section with SSID and mode. fn base_wifi_section(ssid: &str) -> HashMap<&'static str, Value<'static>> { let mut s = HashMap::new(); s.insert("ssid", Value::from(bytes(ssid))); s.insert("mode", Value::from("infrastructure")); s } /// Builds the `connection` section with type, id, uuid, and autoconnect settings. fn base_connection_section( ssid: &str, opts: &ConnectionOptions, ) -> HashMap<&'static str, Value<'static>> { let mut s = HashMap::new(); s.insert("type", Value::from("802-11-wireless")); s.insert("id", Value::from(ssid.to_string())); s.insert("uuid", Value::from(uuid::Uuid::new_v4().to_string())); s.insert("autoconnect", Value::from(opts.autoconnect)); if let Some(p) = opts.autoconnect_priority { s.insert("autoconnect-priority", Value::from(p)); } if let Some(r) = opts.autoconnect_retries { s.insert("autoconnect-retries", Value::from(r)); } s } /// Builds the `connection` section for Ethernet connections. fn base_ethernet_connection_section( connection_id: &str, opts: &ConnectionOptions, ) -> HashMap<&'static str, Value<'static>> { let mut s = HashMap::new(); s.insert("type", Value::from("802-3-ethernet")); s.insert("id", Value::from(connection_id.to_string())); s.insert("uuid", Value::from(uuid::Uuid::new_v4().to_string())); s.insert("autoconnect", Value::from(opts.autoconnect)); if let Some(p) = opts.autoconnect_priority { s.insert("autoconnect-priority", Value::from(p)); } if let Some(r) = opts.autoconnect_retries { s.insert("autoconnect-retries", Value::from(r)); } s } /// Builds the `802-11-wireless-security` section for WPA-PSK networks. /// /// Uses WPA2 (RSN) with CCMP encryption. The `psk-flags` of 0 means the /// password is stored in the connection (agent-owned). fn build_psk_security(psk: &str) -> HashMap<&'static str, Value<'static>> { let mut sec = HashMap::new(); sec.insert("key-mgmt", Value::from("wpa-psk")); sec.insert("psk", Value::from(psk.to_string())); sec.insert("psk-flags", Value::from(0u32)); sec.insert("auth-alg", Value::from("open")); // Enforce WPA2 with AES sec.insert("proto", string_array(&["rsn"])); sec.insert("pairwise", string_array(&["ccmp"])); sec.insert("group", string_array(&["ccmp"])); sec } /// Builds security sections for WPA-EAP (802.1X) networks. /// /// Returns both the `802-11-wireless-security` section and the `802-1x` section. /// Supports PEAP and TTLS methods with MSCHAPv2 or PAP inner authentication. fn build_eap_security( opts: &models::EapOptions, ) -> ( HashMap<&'static str, Value<'static>>, HashMap<&'static str, Value<'static>>, ) { let mut sec = HashMap::new(); sec.insert("key-mgmt", Value::from("wpa-eap")); sec.insert("auth-alg", Value::from("open")); let mut e1x = HashMap::new(); // EAP method (outer authentication) let eap_str = match opts.method { EapMethod::Peap => "peap", EapMethod::Ttls => "ttls", }; e1x.insert("eap", string_array(&[eap_str])); e1x.insert("identity", Value::from(opts.identity.clone())); e1x.insert("password", Value::from(opts.password.clone())); if let Some(ai) = &opts.anonymous_identity { e1x.insert("anonymous-identity", Value::from(ai.clone())); } // Phase 2 (inner authentication) let p2 = match opts.phase2 { models::Phase2::Mschapv2 => "mschapv2", models::Phase2::Pap => "pap", }; e1x.insert("phase2-auth", Value::from(p2)); // CA certificate handling for server verification if opts.system_ca_certs { e1x.insert("system-ca-certs", Value::from(true)); } if let Some(cert) = &opts.ca_cert_path { e1x.insert("ca-cert", Value::from(cert.clone())); } if let Some(dom) = &opts.domain_suffix_match { e1x.insert("domain-suffix-match", Value::from(dom.clone())); } (sec, e1x) } /// Builds a complete Wi-Fi connection settings dictionary. /// /// Constructs all required sections for NetworkManager based on the /// security type. The returned dictionary can be passed directly to /// `AddAndActivateConnection`. /// /// # Sections Created /// /// - `connection`: Always present /// - `802-11-wireless`: Always present /// - `ipv4` / `ipv6`: Always present (set to "auto" for DHCP) /// - `802-11-wireless-security`: Present for PSK and EAP networks /// - `802-1x`: Present only for EAP networks pub fn build_wifi_connection( ssid: &str, security: &models::WifiSecurity, opts: &ConnectionOptions, ) -> HashMap<&'static str, HashMap<&'static str, Value<'static>>> { let mut conn: HashMap<&'static str, HashMap<&'static str, Value<'static>>> = HashMap::new(); // base connections conn.insert("connection", base_connection_section(ssid, opts)); conn.insert("802-11-wireless", base_wifi_section(ssid)); // Add IPv4 and IPv6 configuration to prevent state 60 stall // TODO: Expand upon auto/manual configuration options let mut ipv4 = HashMap::new(); ipv4.insert("method", Value::from("auto")); conn.insert("ipv4", ipv4); let mut ipv6 = HashMap::new(); ipv6.insert("method", Value::from("auto")); conn.insert("ipv6", ipv6); match security { models::WifiSecurity::Open => {} models::WifiSecurity::WpaPsk { psk } => { // point wireless at security section if let Some(w) = conn.get_mut("802-11-wireless") { w.insert("security", Value::from("802-11-wireless-security")); } let sec = build_psk_security(psk); conn.insert("802-11-wireless-security", sec); } models::WifiSecurity::WpaEap { opts } => { if let Some(w) = conn.get_mut("802-11-wireless") { w.insert("security", Value::from("802-11-wireless-security")); } let (mut sec, e1x) = build_eap_security(opts); sec.insert("auth-alg", Value::from("open")); conn.insert("802-11-wireless-security", sec); conn.insert("802-1x", e1x); } } conn } /// Builds a complete Ethernet connection settings dictionary. /// /// Constructs all required sections for NetworkManager. The returned dictionary /// can be passed directly to `AddAndActivateConnection`. /// /// # Sections Created /// /// - `connection`: Always present (type: "802-3-ethernet") /// - `802-3-ethernet`: Ethernet-specific settings (currently empty, can be extended) /// - `ipv4` / `ipv6`: Always present (set to "auto" for DHCP) pub fn build_ethernet_connection( connection_id: &str, opts: &ConnectionOptions, ) -> HashMap<&'static str, HashMap<&'static str, Value<'static>>> { let mut conn: HashMap<&'static str, HashMap<&'static str, Value<'static>>> = HashMap::new(); // Base connection section conn.insert( "connection", base_ethernet_connection_section(connection_id, opts), ); // Ethernet section (minimal - can be extended for MAC address, MTU, etc.) let ethernet = HashMap::new(); conn.insert("802-3-ethernet", ethernet); // Add IPv4 and IPv6 configuration let mut ipv4 = HashMap::new(); ipv4.insert("method", Value::from("auto")); conn.insert("ipv4", ipv4); let mut ipv6 = HashMap::new(); ipv6.insert("method", Value::from("auto")); conn.insert("ipv6", ipv6); conn } #[cfg(test)] mod tests { use super::*; use crate::models::{ConnectionOptions, EapOptions, Phase2, WifiSecurity}; use zvariant::Value; fn default_opts() -> ConnectionOptions { ConnectionOptions { autoconnect: true, autoconnect_priority: None, autoconnect_retries: None, } } fn opts_with_priority() -> ConnectionOptions { ConnectionOptions { autoconnect: false, autoconnect_priority: Some(10), autoconnect_retries: Some(3), } } #[test] fn builds_open_wifi_connection() { let conn = build_wifi_connection("testnet", &WifiSecurity::Open, &default_opts()); assert!(conn.contains_key("connection")); assert!(conn.contains_key("802-11-wireless")); assert!(conn.contains_key("ipv4")); assert!(conn.contains_key("ipv6")); // Open networks should NOT have security section assert!(!conn.contains_key("802-11-wireless-security")); } #[test] fn open_connection_has_correct_type() { let conn = build_wifi_connection("open_net", &WifiSecurity::Open, &default_opts()); let connection_section = conn.get("connection").unwrap(); assert_eq!( connection_section.get("type"), Some(&Value::from("802-11-wireless")) ); } #[test] fn builds_psk_wifi_connection_with_security_section() { let conn = build_wifi_connection( "secure", &WifiSecurity::WpaPsk { psk: "pw123".into(), }, &default_opts(), ); assert!( conn.contains_key("802-11-wireless-security"), "security section missing" ); let sec = conn.get("802-11-wireless-security").unwrap(); assert_eq!(sec.get("psk"), Some(&Value::from("pw123".to_string()))); assert_eq!(sec.get("key-mgmt"), Some(&Value::from("wpa-psk"))); } #[test] fn psk_connection_links_wireless_to_security() { let conn = build_wifi_connection( "secure", &WifiSecurity::WpaPsk { psk: "test".into() }, &default_opts(), ); let wireless = conn.get("802-11-wireless").unwrap(); assert_eq!( wireless.get("security"), Some(&Value::from("802-11-wireless-security")) ); } #[test] fn builds_eap_peap_connection() { let eap_opts = EapOptions { identity: "user@example.com".into(), password: "secret123".into(), anonymous_identity: Some("anonymous@example.com".into()), domain_suffix_match: Some("example.com".into()), ca_cert_path: None, system_ca_certs: true, method: EapMethod::Peap, phase2: Phase2::Mschapv2, }; let conn = build_wifi_connection( "enterprise", &WifiSecurity::WpaEap { opts: eap_opts }, &default_opts(), ); assert!(conn.contains_key("802-11-wireless-security")); assert!(conn.contains_key("802-1x")); let sec = conn.get("802-11-wireless-security").unwrap(); assert_eq!(sec.get("key-mgmt"), Some(&Value::from("wpa-eap"))); let e1x = conn.get("802-1x").unwrap(); assert_eq!( e1x.get("identity"), Some(&Value::from("user@example.com".to_string())) ); assert_eq!( e1x.get("password"), Some(&Value::from("secret123".to_string())) ); assert_eq!(e1x.get("phase2-auth"), Some(&Value::from("mschapv2"))); assert_eq!(e1x.get("system-ca-certs"), Some(&Value::from(true))); } #[test] fn builds_eap_ttls_connection() { let eap_opts = EapOptions { identity: "student@uni.edu".into(), password: "campus123".into(), anonymous_identity: None, domain_suffix_match: None, ca_cert_path: Some("file:///etc/ssl/certs/ca.pem".into()), system_ca_certs: false, method: EapMethod::Ttls, phase2: Phase2::Pap, }; let conn = build_wifi_connection( "eduroam", &WifiSecurity::WpaEap { opts: eap_opts }, &default_opts(), ); let e1x = conn.get("802-1x").unwrap(); assert_eq!(e1x.get("phase2-auth"), Some(&Value::from("pap"))); assert_eq!( e1x.get("ca-cert"), Some(&Value::from("file:///etc/ssl/certs/ca.pem".to_string())) ); // system-ca-certs should NOT be present when false assert!(e1x.get("system-ca-certs").is_none()); } #[test] fn connection_with_priority_and_retries() { let conn = build_wifi_connection("priority_net", &WifiSecurity::Open, &opts_with_priority()); let connection_section = conn.get("connection").unwrap(); assert_eq!( connection_section.get("autoconnect"), Some(&Value::from(false)) ); assert_eq!( connection_section.get("autoconnect-priority"), Some(&Value::from(10i32)) ); assert_eq!( connection_section.get("autoconnect-retries"), Some(&Value::from(3i32)) ); } #[test] fn connection_without_optional_fields() { let conn = build_wifi_connection("simple", &WifiSecurity::Open, &default_opts()); let connection_section = conn.get("connection").unwrap(); assert_eq!( connection_section.get("autoconnect"), Some(&Value::from(true)) ); // Optional fields should not be present assert!(connection_section.get("autoconnect-priority").is_none()); assert!(connection_section.get("autoconnect-retries").is_none()); } #[test] fn ssid_is_stored_as_bytes() { let conn = build_wifi_connection("MyNetwork", &WifiSecurity::Open, &default_opts()); let wireless = conn.get("802-11-wireless").unwrap(); let ssid = wireless.get("ssid").unwrap(); assert_eq!(ssid, &Value::from(b"MyNetwork".to_vec())); } #[test] fn ssid_with_special_characters() { let conn = build_wifi_connection("Café-Wïfì_123", &WifiSecurity::Open, &default_opts()); let wireless = conn.get("802-11-wireless").unwrap(); let ssid = wireless.get("ssid").unwrap(); assert_eq!(ssid, &Value::from("Café-Wïfì_123".as_bytes().to_vec())); } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/api/builders/mod.rs
nmrs/src/api/builders/mod.rs
//! Connection builders for different network types. //! //! This module provides functions to construct NetworkManager connection settings //! dictionaries for various connection types. These settings are used with //! NetworkManager's D-Bus API to create and activate connections. //! //! # Available Builders //! //! - [`wifi`] - WiFi connection builders (WPA-PSK, WPA-EAP, Open) //! - [`vpn`] - VPN connection builders (WireGuard) //! - Ethernet builders (via [`build_ethernet_connection`]) //! //! # When to Use These //! //! Most users should use the high-level [`NetworkManager`](crate::NetworkManager) API //! instead of calling these builders directly. These are exposed for advanced use cases //! where you need fine-grained control over connection settings. //! //! # Examples //! //! ```rust //! use nmrs::builders::{build_wifi_connection, build_ethernet_connection}; //! use nmrs::{WifiSecurity, ConnectionOptions}; //! //! let opts = ConnectionOptions { //! autoconnect: true, //! autoconnect_priority: Some(10), //! autoconnect_retries: Some(3), //! }; //! //! // Build WiFi connection settings //! let wifi_settings = build_wifi_connection( //! "MyNetwork", //! &WifiSecurity::WpaPsk { psk: "password".into() }, //! &opts //! ); //! //! // Build Ethernet connection settings //! let eth_settings = build_ethernet_connection("eth0", &opts); //! ``` //! // Build WireGuard VPN connection settings //! let creds = VpnCredentials { //! vpn_type: VpnType::WireGuard, //! name: "MyVPN".into(), //! gateway: "vpn.example.com:51820".into(), //! private_key: "PRIVATE-KEY".into(), //! address: "10.0.0.2/24".into(), //! peers: vec![WireGuardPeer { //! public_key: "PUBLIC-KEY".into(), //! gateway: "vpn.example.com:51820".into(), //! allowed_ips: vec!["0.0.0.0/0".into()], //! preshared_key: None, //! persistent_keepalive: Some(25), //! }], //! dns: None, //! mtu: None, //! uuid: None, //! }; //! //! let vpn_settings = build_wireguard_connection(&creds, &opts).unwrap(); //! ``` //! //! These settings can then be passed to NetworkManager’s //! `AddConnection` or `AddAndActivateConnection` D-Bus methods. pub mod vpn; pub mod wifi; // Re-export builder functions for convenience pub use vpn::build_wireguard_connection; pub use wifi::{build_ethernet_connection, build_wifi_connection};
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/api/builders/vpn.rs
nmrs/src/api/builders/vpn.rs
//! VPN connection settings builders. //! //! This module provides functions to build NetworkManager settings dictionaries //! for VPN connections. Currently supports: //! //! - **WireGuard** - Modern, high-performance VPN protocol //! //! # Usage //! //! Most users should call [`NetworkManager::connect_vpn`][crate::NetworkManager::connect_vpn] //! instead of using these builders directly. This module is intended for //! advanced use cases where you need low-level control over the connection settings. //! //! # Example //! //! ```rust //! use nmrs::builders::build_wireguard_connection; //! use nmrs::{VpnCredentials, VpnType, WireGuardPeer, ConnectionOptions}; //! //! let creds = VpnCredentials { //! vpn_type: VpnType::WireGuard, //! name: "MyVPN".into(), //! gateway: "vpn.example.com:51820".into(), //! // Valid WireGuard private key (44 chars base64) //! private_key: "YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=".into(), //! address: "10.0.0.2/24".into(), //! peers: vec![WireGuardPeer { //! // Valid WireGuard public key (44 chars base64) //! public_key: "HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=".into(), //! gateway: "vpn.example.com:51820".into(), //! allowed_ips: vec!["0.0.0.0/0".into()], //! preshared_key: None, //! persistent_keepalive: Some(25), //! }], //! dns: Some(vec!["1.1.1.1".into()]), //! mtu: None, //! uuid: None, //! }; //! //! let opts = ConnectionOptions { //! autoconnect: false, //! autoconnect_priority: None, //! autoconnect_retries: None, //! }; //! //! let settings = build_wireguard_connection(&creds, &opts).unwrap(); //! // Pass settings to NetworkManager's AddAndActivateConnection //! ``` use std::collections::HashMap; use std::net::Ipv4Addr; use uuid::Uuid; use zvariant::Value; use crate::api::models::{ConnectionError, ConnectionOptions, VpnCredentials}; /// Validates a WireGuard key (private or public). /// /// WireGuard keys are 32-byte values encoded in base64, resulting in 44 characters /// (including padding). fn validate_wireguard_key(key: &str, key_type: &str) -> Result<(), ConnectionError> { // Basic validation: should be non-empty and reasonable length if key.trim().is_empty() { return Err(ConnectionError::InvalidPrivateKey(format!( "{} cannot be empty", key_type ))); } // WireGuard keys are 32 bytes, base64 encoded = 44 chars with padding // We'll be lenient and allow 43-45 characters let len = key.trim().len(); if !(40..=50).contains(&len) { return Err(ConnectionError::InvalidPrivateKey(format!( "{} has invalid length: {} (expected ~44 characters)", key_type, len ))); } // Check if it's valid base64 (contains only base64 characters) let is_valid_base64 = key .trim() .chars() .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='); if !is_valid_base64 { return Err(ConnectionError::InvalidPrivateKey(format!( "{} contains invalid base64 characters", key_type ))); } Ok(()) } /// Validates an IP address with CIDR notation (e.g., "10.0.0.2/24"). fn validate_address(address: &str) -> Result<(String, u32), ConnectionError> { let (ip, prefix) = address.split_once('/').ok_or_else(|| { ConnectionError::InvalidAddress(format!( "missing CIDR prefix (e.g., '10.0.0.2/24'): {}", address )) })?; // Validate IP address format (basic check) if ip.trim().is_empty() { return Err(ConnectionError::InvalidAddress( "IP address cannot be empty".into(), )); } // Parse CIDR prefix let prefix: u32 = prefix .parse() .map_err(|_| ConnectionError::InvalidAddress(format!("invalid CIDR prefix: {}", prefix)))?; // Validate prefix range (IPv4: 0-32, IPv6: 0-128) // We'll accept up to 128 to support IPv6 if prefix > 128 { return Err(ConnectionError::InvalidAddress(format!( "CIDR prefix too large: {} (max 128)", prefix ))); } // Basic IPv4 validation (if it contains dots) if ip.contains('.') { let octets: Vec<&str> = ip.split('.').collect(); if octets.len() != 4 { return Err(ConnectionError::InvalidAddress(format!( "invalid IPv4 address: {}", ip ))); } for octet in octets { let num: u32 = octet.parse().map_err(|_| { ConnectionError::InvalidAddress(format!("invalid IPv4 octet: {}", octet)) })?; if num > 255 { return Err(ConnectionError::InvalidAddress(format!( "IPv4 octet out of range: {}", num ))); } } if prefix > 32 { return Err(ConnectionError::InvalidAddress(format!( "IPv4 CIDR prefix too large: {} (max 32)", prefix ))); } } Ok((ip.to_string(), prefix)) } /// Validates a VPN gateway endpoint (should be in "host:port" format). fn validate_gateway(gateway: &str) -> Result<(), ConnectionError> { if gateway.trim().is_empty() { return Err(ConnectionError::InvalidGateway( "gateway cannot be empty".into(), )); } // Should contain a colon for port if !gateway.contains(':') { return Err(ConnectionError::InvalidGateway(format!( "gateway must be in 'host:port' format: {}", gateway ))); } let parts: Vec<&str> = gateway.rsplitn(2, ':').collect(); if parts.len() != 2 { return Err(ConnectionError::InvalidGateway(format!( "invalid gateway format: {}", gateway ))); } // Validate port let port_str = parts[0]; let port: u16 = port_str.parse().map_err(|_| { ConnectionError::InvalidGateway(format!("invalid port number: {}", port_str)) })?; if port == 0 { return Err(ConnectionError::InvalidGateway("port cannot be 0".into())); } Ok(()) } /// Builds WireGuard VPN connection settings. /// /// Returns a complete NetworkManager settings dictionary suitable for /// `AddAndActivateConnection`. /// /// # Errors /// /// - `ConnectionError::InvalidPeers` if no peers are provided /// - `ConnectionError::InvalidAddress` if the address is missing or malformed pub fn build_wireguard_connection( creds: &VpnCredentials, opts: &ConnectionOptions, ) -> Result<HashMap<&'static str, HashMap<&'static str, Value<'static>>>, ConnectionError> { // Validate peers if creds.peers.is_empty() { return Err(ConnectionError::InvalidPeers("No peers provided".into())); } // Validate private key validate_wireguard_key(&creds.private_key, "Private key")?; // Validate gateway validate_gateway(&creds.gateway)?; // Validate address let (ip, prefix) = validate_address(&creds.address)?; // Validate each peer for (i, peer) in creds.peers.iter().enumerate() { validate_wireguard_key(&peer.public_key, &format!("Peer {} public key", i))?; validate_gateway(&peer.gateway)?; if peer.allowed_ips.is_empty() { return Err(ConnectionError::InvalidPeers(format!( "Peer {} has no allowed IPs", i ))); } } let mut conn = HashMap::new(); // [connection] section let mut connection = HashMap::new(); connection.insert("type", Value::from("wireguard")); connection.insert("id", Value::from(creds.name.clone())); let interface_name = format!( "wg-{}", creds .name .to_lowercase() .chars() .filter(|c| c.is_alphanumeric() || *c == '-') .take(10) .collect::<String>() ); connection.insert("interface-name", Value::from(interface_name)); let uuid = creds.uuid.unwrap_or_else(|| { Uuid::new_v5( &Uuid::NAMESPACE_DNS, format!("wg:{}@{}", creds.name, creds.gateway).as_bytes(), ) }); connection.insert("uuid", Value::from(uuid.to_string())); connection.insert("autoconnect", Value::from(opts.autoconnect)); if let Some(p) = opts.autoconnect_priority { connection.insert("autoconnect-priority", Value::from(p)); } if let Some(r) = opts.autoconnect_retries { connection.insert("autoconnect-retries", Value::from(r)); } conn.insert("connection", connection); // [wireguard] section let mut wireguard = HashMap::new(); wireguard.insert( "service-type", Value::from("org.freedesktop.NetworkManager.wireguard"), ); wireguard.insert("private-key", Value::from(creds.private_key.clone())); let mut peers_array: Vec<HashMap<String, zvariant::Value<'static>>> = Vec::new(); for peer in creds.peers.iter() { let mut peer_dict: HashMap<String, zvariant::Value<'static>> = HashMap::new(); peer_dict.insert("public-key".into(), Value::from(peer.public_key.clone())); peer_dict.insert("endpoint".into(), Value::from(peer.gateway.clone())); peer_dict.insert("allowed-ips".into(), Value::from(peer.allowed_ips.clone())); if let Some(psk) = &peer.preshared_key { peer_dict.insert("preshared-key".into(), Value::from(psk.clone())); } if let Some(ka) = peer.persistent_keepalive { peer_dict.insert("persistent-keepalive".into(), Value::from(ka)); } peers_array.push(peer_dict); } wireguard.insert("peers", Value::from(peers_array)); if let Some(mtu) = creds.mtu { wireguard.insert("mtu", Value::from(mtu)); } conn.insert("wireguard", wireguard); // [ipv4] section let mut ipv4 = HashMap::new(); ipv4.insert("method", Value::from("manual")); // address-data must be an array of dictionaries with "address" and "prefix" keys let mut addr_dict: HashMap<String, Value<'static>> = HashMap::new(); addr_dict.insert("address".into(), Value::from(ip)); addr_dict.insert("prefix".into(), Value::from(prefix)); let addresses = vec![addr_dict]; ipv4.insert("address-data", Value::from(addresses)); if let Some(dns) = &creds.dns { // NetworkManager expects DNS as array of u32 (IP addresses as integers) let dns_u32: Result<Vec<u32>, _> = dns .iter() .map(|ip_str| { ip_str .parse::<Ipv4Addr>() .map(u32::from) .map_err(|_| format!("Invalid IP: {ip_str}")) }) .collect(); match dns_u32 { Ok(ips) => { ipv4.insert("dns", Value::from(ips)); } Err(e) => { return Err(crate::api::models::ConnectionError::VpnFailed(format!( "Invalid DNS server address: {}", e ))); } } } if let Some(mtu) = creds.mtu { ipv4.insert("mtu", Value::from(mtu)); } conn.insert("ipv4", ipv4); // [ipv6] section (required but typically ignored for WireGuard) let mut ipv6 = HashMap::new(); ipv6.insert("method", Value::from("ignore")); conn.insert("ipv6", ipv6); Ok(conn) } #[cfg(test)] mod tests { use super::*; use crate::api::models::{VpnType, WireGuardPeer}; fn create_test_credentials() -> VpnCredentials { VpnCredentials { vpn_type: VpnType::WireGuard, name: "TestVPN".into(), gateway: "vpn.example.com:51820".into(), private_key: "YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=".into(), address: "10.0.0.2/24".into(), peers: vec![WireGuardPeer { public_key: "HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=".into(), gateway: "vpn.example.com:51820".into(), allowed_ips: vec!["0.0.0.0/0".into()], preshared_key: None, persistent_keepalive: Some(25), }], dns: Some(vec!["1.1.1.1".into(), "8.8.8.8".into()]), mtu: Some(1420), uuid: None, } } fn create_test_options() -> ConnectionOptions { ConnectionOptions { autoconnect: false, autoconnect_priority: None, autoconnect_retries: None, } } #[test] fn builds_wireguard_connection() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts); assert!(settings.is_ok()); let settings = settings.unwrap(); assert!(settings.contains_key("connection")); assert!(settings.contains_key("wireguard")); assert!(settings.contains_key("ipv4")); assert!(settings.contains_key("ipv6")); } #[test] fn connection_section_has_correct_type() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let connection = settings.get("connection").unwrap(); let conn_type = connection.get("type").unwrap(); assert_eq!(conn_type, &Value::from("wireguard")); let id = connection.get("id").unwrap(); assert_eq!(id, &Value::from("TestVPN")); } #[test] fn vpn_section_has_wireguard_service_type() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let vpn = settings.get("wireguard").unwrap(); let service_type = vpn.get("service-type").unwrap(); assert_eq!( service_type, &Value::from("org.freedesktop.NetworkManager.wireguard") ); } #[test] fn ipv4_section_is_manual() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let ipv4 = settings.get("ipv4").unwrap(); let method = ipv4.get("method").unwrap(); assert_eq!(method, &Value::from("manual")); } #[test] fn ipv6_section_is_ignored() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let ipv6 = settings.get("ipv6").unwrap(); let method = ipv6.get("method").unwrap(); assert_eq!(method, &Value::from("ignore")); } #[test] fn rejects_empty_peers() { let mut creds = create_test_credentials(); creds.peers = vec![]; let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidPeers(_) )); } #[test] fn rejects_invalid_address_format() { let mut creds = create_test_credentials(); creds.address = "invalid".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidAddress(_) )); } #[test] fn rejects_address_without_cidr() { let mut creds = create_test_credentials(); creds.address = "10.0.0.2".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidAddress(_) )); } #[test] fn accepts_ipv6_address() { let mut creds = create_test_credentials(); creds.address = "fd00::2/64".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok()); } #[test] fn handles_multiple_peers() { let mut creds = create_test_credentials(); creds.peers.push(WireGuardPeer { public_key: "xScVkH3fUGUVRvGLFcjkx+GGD7cf5eBVyN3Gh4FLjmI=".into(), gateway: "peer2.example.com:51821".into(), allowed_ips: vec!["192.168.0.0/16".into()], preshared_key: Some("PSKABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm=".into()), persistent_keepalive: None, }); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok()); } #[test] fn handles_optional_dns() { let mut creds = create_test_credentials(); creds.dns = None; let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok()); } #[test] fn handles_optional_mtu() { let mut creds = create_test_credentials(); creds.mtu = None; let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok()); } #[test] fn includes_dns_when_provided() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let ipv4 = settings.get("ipv4").unwrap(); assert!(ipv4.contains_key("dns")); } #[test] fn includes_mtu_when_provided() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let ipv4 = settings.get("ipv4").unwrap(); assert!(ipv4.contains_key("mtu")); } #[test] fn respects_autoconnect_option() { let creds = create_test_credentials(); let mut opts = create_test_options(); opts.autoconnect = true; let settings = build_wireguard_connection(&creds, &opts).unwrap(); let connection = settings.get("connection").unwrap(); let autoconnect = connection.get("autoconnect").unwrap(); assert_eq!(autoconnect, &Value::from(true)); } #[test] fn includes_autoconnect_priority_when_provided() { let creds = create_test_credentials(); let mut opts = create_test_options(); opts.autoconnect_priority = Some(10); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let connection = settings.get("connection").unwrap(); assert!(connection.contains_key("autoconnect-priority")); } #[test] fn generates_uuid_when_not_provided() { let creds = create_test_credentials(); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let connection = settings.get("connection").unwrap(); assert!(connection.contains_key("uuid")); } #[test] fn uses_provided_uuid() { let mut creds = create_test_credentials(); let test_uuid = uuid::Uuid::new_v4(); creds.uuid = Some(test_uuid); let opts = create_test_options(); let settings = build_wireguard_connection(&creds, &opts).unwrap(); let connection = settings.get("connection").unwrap(); let uuid = connection.get("uuid").unwrap(); assert_eq!(uuid, &Value::from(test_uuid.to_string())); } #[test] fn peer_with_preshared_key() { let mut creds = create_test_credentials(); creds.peers[0].preshared_key = Some("PSKABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm=".into()); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok()); } #[test] fn peer_without_keepalive() { let mut creds = create_test_credentials(); creds.peers[0].persistent_keepalive = None; let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok()); } #[test] fn multiple_allowed_ips_for_peer() { let mut creds = create_test_credentials(); creds.peers[0].allowed_ips = vec!["0.0.0.0/0".into(), "::/0".into(), "192.168.1.0/24".into()]; let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok()); } // Validation tests #[test] fn rejects_empty_private_key() { let mut creds = create_test_credentials(); creds.private_key = "".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidPrivateKey(_) )); } #[test] fn rejects_short_private_key() { let mut creds = create_test_credentials(); creds.private_key = "tooshort".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidPrivateKey(_) )); } #[test] fn rejects_invalid_private_key_characters() { let mut creds = create_test_credentials(); creds.private_key = "this is not base64 encoded!!!!!!!!!!!!!!!!!!".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidPrivateKey(_) )); } #[test] fn rejects_empty_gateway() { let mut creds = create_test_credentials(); creds.gateway = "".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidGateway(_) )); } #[test] fn rejects_gateway_without_port() { let mut creds = create_test_credentials(); creds.gateway = "vpn.example.com".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidGateway(_) )); } #[test] fn rejects_gateway_with_invalid_port() { let mut creds = create_test_credentials(); creds.gateway = "vpn.example.com:99999".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidGateway(_) )); } #[test] fn rejects_gateway_with_zero_port() { let mut creds = create_test_credentials(); creds.gateway = "vpn.example.com:0".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidGateway(_) )); } #[test] fn rejects_invalid_ipv4_address() { let mut creds = create_test_credentials(); creds.address = "999.999.999.999/24".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidAddress(_) )); } #[test] fn rejects_ipv4_with_invalid_prefix() { let mut creds = create_test_credentials(); creds.address = "10.0.0.2/999".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidAddress(_) )); } #[test] fn rejects_peer_with_empty_allowed_ips() { let mut creds = create_test_credentials(); creds.peers[0].allowed_ips = vec![]; let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); assert!(matches!( result.unwrap_err(), ConnectionError::InvalidPeers(_) )); } #[test] fn rejects_peer_with_invalid_public_key() { let mut creds = create_test_credentials(); creds.peers[0].public_key = "invalid!@#$key".into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_err()); // Should get InvalidPrivateKey error (we use same validation for both) assert!(matches!( result.unwrap_err(), ConnectionError::InvalidPrivateKey(_) )); } #[test] fn accepts_valid_ipv4_addresses() { let test_cases = vec![ "10.0.0.2/24", "192.168.1.100/32", "172.16.0.1/16", "1.1.1.1/8", ]; for address in test_cases { let mut creds = create_test_credentials(); creds.address = address.into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!( result.is_ok(), "Should accept valid IPv4 address: {}", address ); } } #[test] fn accepts_standard_wireguard_ports() { let test_cases = vec![ "vpn.example.com:51820", "192.168.1.1:51821", "test.local:12345", ]; for gateway in test_cases { let mut creds = create_test_credentials(); creds.gateway = gateway.into(); let opts = create_test_options(); let result = build_wireguard_connection(&creds, &opts); assert!(result.is_ok(), "Should accept valid gateway: {}", gateway); } } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/types/mod.rs
nmrs/src/types/mod.rs
//! Type definitions and constants. //! //! This module contains NetworkManager constants and type definitions. pub(crate) mod constants;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/types/constants.rs
nmrs/src/types/constants.rs
//! Constants for NetworkManager D-Bus interface values. //! //! These constants correspond to the numeric codes used by NetworkManager's //! D-Bus API for device types, states, security flags, and other values. /// NetworkManager device type constants. pub mod device_type { pub const ETHERNET: u32 = 1; pub const WIFI: u32 = 2; // pub const WIFI_P2P: u32 = 30; // pub const LOOPBACK: u32 = 32; } /// NetworkManager device state constants pub mod device_state { pub const UNAVAILABLE: u32 = 20; pub const DISCONNECTED: u32 = 30; pub const ACTIVATED: u32 = 100; } /// WiFi security flag constants pub mod security_flags { pub const WEP: u32 = 0x1; pub const PSK: u32 = 0x0100; pub const EAP: u32 = 0x0200; } /// WiFi mode constants pub mod wifi_mode { pub const ADHOC: u32 = 1; pub const INFRA: u32 = 2; pub const AP: u32 = 3; } /// Timeout constants for signal-based waiting. /// /// These timeouts are used with D-Bus signal monitoring instead of polling. /// They define how long to wait for state transitions before giving up. pub mod timeouts { use std::time::Duration; /// Maximum time to wait for Wi-Fi device to become ready (60 seconds). /// /// Used after enabling Wi-Fi to wait for the hardware to initialize. const WIFI_READY_TIMEOUT_SECS: u64 = 60; /// Time to wait after requesting a scan before checking results (2 seconds). /// /// While we could use signals for scan completion, a short delay is /// sufficient for now, and simpler for most use cases. const SCAN_WAIT_SECS: u64 = 2; /// Brief delay after state transitions to allow NetworkManager to stabilize. const STABILIZATION_DELAY_MS: u64 = 100; /// Returns the Wi-Fi ready timeout duration. pub fn wifi_ready_timeout() -> Duration { Duration::from_secs(WIFI_READY_TIMEOUT_SECS) } /// Returns the scan wait duration. pub fn scan_wait() -> Duration { Duration::from_secs(SCAN_WAIT_SECS) } /// Returns a brief stabilization delay. pub fn stabilization_delay() -> Duration { Duration::from_millis(STABILIZATION_DELAY_MS) } } /// Signal strength thresholds for bar display pub mod signal_strength { pub const BAR_1_MAX: u8 = 24; pub const BAR_2_MIN: u8 = BAR_1_MAX + 1; pub const BAR_2_MAX: u8 = 49; pub const BAR_3_MIN: u8 = BAR_2_MAX + 1; pub const BAR_3_MAX: u8 = 74; } /// WiFi frequency constants (MHz) pub mod frequency { pub const BAND_2_4_START: u32 = 2412; pub const BAND_2_4_END: u32 = 2472; pub const BAND_2_4_CH14: u32 = 2484; pub const BAND_5_START: u32 = 5150; pub const BAND_5_END: u32 = 5925; pub const BAND_6_START: u32 = 5955; pub const BAND_6_END: u32 = 7115; pub const CHANNEL_SPACING: u32 = 5; } /// Rate conversion constants pub mod rate { pub const KBIT_TO_MBPS: u32 = 1000; }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/monitoring/device.rs
nmrs/src/monitoring/device.rs
//! Real-time device state monitoring using D-Bus signals. //! //! Provides functionality to monitor device state changes (e.g., ethernet cable //! plugged in/out, device activation/deactivation) in real-time without needing //! to poll. This enables live UI updates for both wired and wireless devices. use futures::stream::{Stream, StreamExt}; use log::{debug, warn}; use std::pin::Pin; use zbus::Connection; use crate::api::models::ConnectionError; use crate::dbus::{NMDeviceProxy, NMProxy}; use crate::Result; /// Monitors device state changes on all network devices. /// /// Subscribes to `StateChanged` signals on all network devices. When any signal /// is received (device activated, disconnected, cable plugged in, etc.), invokes /// the callback to notify the caller that device states have changed. /// /// This function runs indefinitely until an error occurs or the connection /// is lost. Run it in a background task. /// /// # Example /// /// ```ignore /// let nm = NetworkManager::new().await?; /// nm.monitor_device_changes(|| { /// println!("Device state changed, refresh UI!"); /// }).await?; /// ``` pub async fn monitor_device_changes<F>(conn: &Connection, callback: F) -> Result<()> where F: Fn() + 'static, { let nm = NMProxy::new(conn).await?; // Use dynamic dispatch to handle different signal stream types let mut streams: Vec<Pin<Box<dyn Stream<Item = _>>>> = Vec::new(); // Subscribe to DeviceAdded and DeviceRemoved signals from main NetworkManager // This is more reliable than subscribing to individual devices let device_added_stream = nm.receive_device_added().await?; let device_removed_stream = nm.receive_device_removed().await?; let state_changed_stream = nm.receive_state_changed().await?; streams.push(Box::pin(device_added_stream.map(|_| ()))); streams.push(Box::pin(device_removed_stream.map(|_| ()))); streams.push(Box::pin(state_changed_stream.map(|_| ()))); debug!("Subscribed to NetworkManager device signals"); // Also subscribe to individual device state changes for existing devices let devices = nm.get_devices().await?; for dev_path in devices { if let Ok(dev) = NMDeviceProxy::builder(conn) .path(dev_path.clone())? .build() .await { if let Ok(state_stream) = dev.receive_device_state_changed().await { streams.push(Box::pin(state_stream.map(|_| ()))); debug!("Subscribed to state change signals on device: {dev_path}"); } } } debug!( "Monitoring {} signal streams for device changes", streams.len() ); // Merge all streams and listen for any signal let mut merged = futures::stream::select_all(streams); while let Some(_signal) = merged.next().await { debug!("Device change detected"); callback(); } warn!("Device monitoring stream ended unexpectedly"); Err(ConnectionError::Stuck("monitoring stream ended".into())) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/monitoring/network.rs
nmrs/src/monitoring/network.rs
//! Real-time network monitoring using D-Bus signals. //! //! Provides functionality to monitor access point changes (additions/removals) //! in real-time without needing to poll. This enables live UI updates. use futures::stream::{Stream, StreamExt}; use log::{debug, warn}; use std::pin::Pin; use zbus::Connection; use crate::api::models::ConnectionError; use crate::dbus::{NMDeviceProxy, NMProxy, NMWirelessProxy}; use crate::types::constants::device_type; use crate::Result; /// Monitors access point changes on all Wi-Fi devices. /// /// Subscribes to `AccessPointAdded` and `AccessPointRemoved` signals on all /// wireless devices. When any signal is received, invokes the callback to /// notify the caller that the network list has changed. /// /// This function runs indefinitely until an error occurs or the connection /// is lost. Run it in a background task. /// /// # Example /// /// ```ignore /// let nm = NetworkManager::new().await?; /// nm.monitor_network_changes(|| { /// println!("Network list changed, refresh UI!"); /// }).await?; /// ``` pub async fn monitor_network_changes<F>(conn: &Connection, callback: F) -> Result<()> where F: Fn() + 'static, { let nm = NMProxy::new(conn).await?; let devices = nm.get_devices().await?; // Use dynamic dispatch to handle different signal stream types let mut streams: Vec<Pin<Box<dyn Stream<Item = _>>>> = Vec::new(); // Subscribe to signals on all Wi-Fi devices for dev_path in devices { let dev = NMDeviceProxy::builder(conn) .path(dev_path.clone())? .build() .await?; if dev.device_type().await? != device_type::WIFI { continue; } let wifi = NMWirelessProxy::builder(conn) .path(dev_path.clone())? .build() .await?; let added_stream = wifi.receive_access_point_added().await?; let removed_stream = wifi.receive_access_point_removed().await?; // Box both streams as trait objects streams.push(Box::pin(added_stream.map(|_| ()))); streams.push(Box::pin(removed_stream.map(|_| ()))); debug!("Subscribed to AP signals on device: {dev_path}"); } if streams.is_empty() { warn!("No Wi-Fi devices found to monitor"); return Err(ConnectionError::NoWifiDevice); } debug!( "Monitoring {} signal streams for network changes", streams.len() ); // Merge all streams and listen for any signal let mut merged = futures::stream::select_all(streams); while let Some(_signal) = merged.next().await { debug!("Network change detected"); callback(); } warn!("Network monitoring stream ended unexpectedly"); Err(ConnectionError::Stuck("monitoring stream ended".into())) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/monitoring/info.rs
nmrs/src/monitoring/info.rs
//! Network information and current connection status. //! //! Provides functions to retrieve detailed information about networks //! and query the current connection state. use zbus::Connection; use crate::api::models::{ConnectionError, Network, NetworkInfo}; #[allow(unused_imports)] // Used within try_log! macro use crate::dbus::{NMAccessPointProxy, NMDeviceProxy, NMProxy, NMWirelessProxy}; use crate::try_log; use crate::types::constants::{device_type, rate, security_flags}; use crate::util::utils::{ bars_from_strength, channel_from_freq, decode_ssid_or_empty, for_each_access_point, mode_to_string, strength_or_zero, }; use crate::Result; /// Returns detailed information about a network. /// /// Queries the access point for comprehensive details including: /// - BSSID (MAC address) /// - Signal strength and visual bars /// - Frequency and channel /// - Wi-Fi mode (infrastructure, adhoc, etc.) /// - Connection speed (actual if connected, max otherwise) /// - Security capabilities (WEP, WPA, WPA2, PSK, 802.1X) /// - Current connection status pub(crate) async fn show_details(conn: &Connection, net: &Network) -> Result<NetworkInfo> { let active_ssid = current_ssid(conn).await; let is_connected_outer = active_ssid.as_deref() == Some(&net.ssid); let target_ssid_outer = net.ssid.clone(); let target_strength = net.strength; let results = for_each_access_point(conn, |ap| { let target_ssid = target_ssid_outer.clone(); let is_connected = is_connected_outer; Box::pin(async move { let ssid_bytes = ap.ssid().await?; if decode_ssid_or_empty(&ssid_bytes) != target_ssid { return Ok(None); } let strength = strength_or_zero(target_strength); let bssid = ap.hw_address().await?; let flags = ap.flags().await?; let wpa_flags = ap.wpa_flags().await?; let rsn_flags = ap.rsn_flags().await?; let freq = ap.frequency().await.ok(); let max_br = ap.max_bitrate().await.ok(); let mode_raw = ap.mode().await.ok(); let wep = (flags & security_flags::WEP) != 0 && wpa_flags == 0 && rsn_flags == 0; let wpa1 = wpa_flags != 0; let wpa2_or_3 = rsn_flags != 0; let psk = ((wpa_flags | rsn_flags) & security_flags::PSK) != 0; let eap = ((wpa_flags | rsn_flags) & security_flags::EAP) != 0; let mut parts = Vec::new(); if wep { parts.push("WEP"); } if wpa1 { parts.push("WPA"); } if wpa2_or_3 { parts.push("WPA2/WPA3"); } if psk { parts.push("PSK"); } if eap { parts.push("802.1X"); } let security = if parts.is_empty() { "Open".to_string() } else { parts.join(" + ") }; let status = if is_connected { "Connected".to_string() } else { "Disconnected".to_string() }; let channel = freq.and_then(channel_from_freq); let rate_mbps = max_br.map(|kbit| kbit / rate::KBIT_TO_MBPS); let bars = bars_from_strength(strength).to_string(); let mode = mode_raw .map(mode_to_string) .unwrap_or("Unknown") .to_string(); Ok(Some(NetworkInfo { ssid: target_ssid, bssid, strength, freq, channel, mode, rate_mbps, bars, security, status, })) }) }) .await?; results.into_iter().next().ok_or(ConnectionError::NotFound) } /// Returns the SSID of the currently connected Wi-Fi network. /// /// Checks all Wi-Fi devices for an active access point and returns /// its SSID. Returns `None` if not connected to any Wi-Fi network. /// /// Uses the `try_log!` macro to gracefully handle errors without /// propagating them, since this is often used in non-critical contexts. pub(crate) async fn current_ssid(conn: &Connection) -> Option<String> { let nm = try_log!(NMProxy::new(conn).await, "Failed to create NM proxy"); let devices = try_log!(nm.get_devices().await, "Failed to get devices"); for dp in devices { let dev_builder = try_log!( NMDeviceProxy::builder(conn).path(dp.clone()), "Failed to create device proxy builder" ); let dev = try_log!(dev_builder.build().await, "Failed to build device proxy"); let dev_type = try_log!(dev.device_type().await, "Failed to get device type"); if dev_type != device_type::WIFI { continue; } let wifi_builder = try_log!( NMWirelessProxy::builder(conn).path(dp.clone()), "Failed to create wireless proxy builder" ); let wifi = try_log!(wifi_builder.build().await, "Failed to build wireless proxy"); if let Ok(active_ap) = wifi.active_access_point().await { if active_ap.as_str() != "/" { let ap_builder = try_log!( NMAccessPointProxy::builder(conn).path(active_ap), "Failed to create access point proxy builder" ); let ap = try_log!( ap_builder.build().await, "Failed to build access point proxy" ); let ssid_bytes = try_log!(ap.ssid().await, "Failed to get SSID bytes"); let ssid = decode_ssid_or_empty(&ssid_bytes); return Some(ssid.to_string()); } } } None } /// Returns the SSID and frequency of the current Wi-Fi connection. /// /// Similar to `current_ssid` but also returns the operating frequency /// in MHz, useful for determining if connected to 2.4GHz or 5GHz band. pub(crate) async fn current_connection_info(conn: &Connection) -> Option<(String, Option<u32>)> { let nm = try_log!(NMProxy::new(conn).await, "Failed to create NM proxy"); let devices = try_log!(nm.get_devices().await, "Failed to get devices"); for dp in devices { let dev_builder = try_log!( NMDeviceProxy::builder(conn).path(dp.clone()), "Failed to create device proxy builder" ); let dev = try_log!(dev_builder.build().await, "Failed to build device proxy"); let dev_type = try_log!(dev.device_type().await, "Failed to get device type"); if dev_type != device_type::WIFI { continue; } let wifi_builder = try_log!( NMWirelessProxy::builder(conn).path(dp.clone()), "Failed to create wireless proxy builder" ); let wifi = try_log!(wifi_builder.build().await, "Failed to build wireless proxy"); if let Ok(active_ap) = wifi.active_access_point().await { if active_ap.as_str() != "/" { let ap_builder = try_log!( NMAccessPointProxy::builder(conn).path(active_ap), "Failed to create access point proxy builder" ); let ap = try_log!( ap_builder.build().await, "Failed to build access point proxy" ); let ssid_bytes = try_log!(ap.ssid().await, "Failed to get SSID bytes"); let ssid = decode_ssid_or_empty(&ssid_bytes); let frequency = ap.frequency().await.ok(); return Some((ssid.to_string(), frequency)); } } } None }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/monitoring/mod.rs
nmrs/src/monitoring/mod.rs
//! Real-time monitoring of network and device changes. //! //! This module provides functions for monitoring network state changes, //! device state changes, and retrieving current connection information. pub(crate) mod device; pub(crate) mod info; pub(crate) mod network;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/core/device.rs
nmrs/src/core/device.rs
//! Network device enumeration and control. //! //! Provides functions for listing network devices, checking Wi-Fi state, //! and enabling/disabling Wi-Fi. Uses D-Bus signals for efficient state //! monitoring instead of polling. use log::debug; use zbus::Connection; use crate::api::models::{ConnectionError, Device, DeviceIdentity, DeviceState}; use crate::core::state_wait::wait_for_wifi_device_ready; use crate::dbus::{NMDeviceProxy, NMProxy}; use crate::types::constants::device_type; use crate::Result; /// Lists all network devices managed by NetworkManager. /// /// Returns information about each device including its interface name, /// type (Ethernet, Wi-Fi, etc.), current state, and driver. pub(crate) async fn list_devices(conn: &Connection) -> Result<Vec<Device>> { let proxy = NMProxy::new(conn).await?; let paths = proxy.get_devices().await?; let mut devices = Vec::new(); for p in paths { let d_proxy = NMDeviceProxy::builder(conn) .path(p.clone())? .build() .await?; let interface = d_proxy.interface().await?; let raw_type = d_proxy.device_type().await?; let current_mac = d_proxy .hw_address() .await .unwrap_or_else(|_| String::from("00:00:00:00:00:00")); // PermHwAddress may not be available on all systems/devices // If not available, fall back to HwAddress let perm_mac = d_proxy .perm_hw_address() .await .unwrap_or_else(|_| current_mac.clone()); let device_type = raw_type.into(); let raw_state = d_proxy.state().await?; let state = raw_state.into(); let managed = d_proxy.managed().await.ok(); let driver = d_proxy.driver().await.ok(); devices.push(Device { path: p.to_string(), interface, identity: DeviceIdentity { permanent_mac: perm_mac, current_mac, }, device_type, state, managed, driver, }); } Ok(devices) } /// Waits for a Wi-Fi device to become ready for operations. /// /// Uses D-Bus signals to efficiently wait until a Wi-Fi device reaches /// either Disconnected or Activated state, indicating it's ready for /// scanning or connection operations. This is useful after enabling Wi-Fi, /// as the device may take time to initialize. /// /// Returns `WifiNotReady` if no Wi-Fi device becomes ready within the timeout. pub(crate) async fn wait_for_wifi_ready(conn: &Connection) -> Result<()> { let nm = NMProxy::new(conn).await?; let devices = nm.get_devices().await?; // Find the Wi-Fi device for dev_path in devices { let dev = NMDeviceProxy::builder(conn) .path(dev_path.clone())? .build() .await?; if dev.device_type().await? != device_type::WIFI { continue; } debug!("Found Wi-Fi device, waiting for it to become ready"); // Check current state first let current_state = dev.state().await?; let state = DeviceState::from(current_state); if state == DeviceState::Disconnected || state == DeviceState::Activated { debug!("Wi-Fi device already ready"); return Ok(()); } // Wait for device to become ready using signal-based monitoring return wait_for_wifi_device_ready(&dev).await; } Err(ConnectionError::NoWifiDevice) } /// Enables or disables Wi-Fi globally. /// /// This is equivalent to the Wi-Fi toggle in system settings. /// When disabled, all Wi-Fi connections are terminated and /// no scanning occurs. pub(crate) async fn set_wifi_enabled(conn: &Connection, value: bool) -> Result<()> { let nm = NMProxy::new(conn).await?; Ok(nm.set_wireless_enabled(value).await?) } /// Returns whether Wi-Fi is currently enabled. pub(crate) async fn wifi_enabled(conn: &Connection) -> Result<bool> { let nm = NMProxy::new(conn).await?; Ok(nm.wireless_enabled().await?) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/core/state_wait.rs
nmrs/src/core/state_wait.rs
//! Connection state monitoring using D-Bus signals. //! //! Provides functions to wait for device and connection state transitions //! using NetworkManager's signal-based API instead of polling. This approach //! is more efficient and provides faster response times. //! //! # Signal-Based Monitoring //! //! Instead of polling device state in a loop, these functions subscribe to //! D-Bus signals that NetworkManager emits when state changes occur: //! //! - `NMDevice.StateChanged` - Emitted when device state changes //! - `NMActiveConnection.StateChanged` - Emitted when connection activation state changes //! //! This provides a few benefits: //! - Immediate response to state changes (no polling delay) //! - Lower CPU usage (no spinning loops) //! - More reliable; at least in the sense that we won't miss rapid state transitions. //! - Better error messages with specific failure reasons use futures::{select, FutureExt, StreamExt}; use futures_timer::Delay; use log::{debug, warn}; use std::pin::pin; use std::time::Duration; use zbus::Connection; use crate::api::models::{ connection_state_reason_to_error, ActiveConnectionState, ConnectionError, ConnectionStateReason, }; use crate::dbus::{NMActiveConnectionProxy, NMDeviceProxy}; use crate::types::constants::{device_state, timeouts}; use crate::Result; /// Default timeout for connection activation (30 seconds). const CONNECTION_TIMEOUT: Duration = Duration::from_secs(30); /// Default timeout for device disconnection (10 seconds). const DISCONNECT_TIMEOUT: Duration = Duration::from_secs(10); /// Waits for an active connection to reach the activated state. /// /// Monitors the connection activation process by subscribing to the /// `StateChanged` signal on the active connection object. This provides /// more detailed error information than device-level monitoring. pub(crate) async fn wait_for_connection_activation( conn: &Connection, active_conn_path: &zvariant::OwnedObjectPath, ) -> Result<()> { let active_conn = NMActiveConnectionProxy::builder(conn) .path(active_conn_path.clone())? .build() .await?; // Subscribe to signals FIRST to avoid race condition let mut stream = active_conn.receive_activation_state_changed().await?; debug!("Subscribed to ActiveConnection StateChanged signal"); // Check current state - if already terminal, return immediately let current_state = active_conn.state().await?; let state = ActiveConnectionState::from(current_state); debug!("Current active connection state: {state}"); match state { ActiveConnectionState::Activated => { debug!("Connection already activated"); return Ok(()); } ActiveConnectionState::Deactivated => { warn!("Connection already deactivated"); return Err(ConnectionError::ActivationFailed( ConnectionStateReason::Unknown, )); } _ => {} } // Wait for state change with timeout (runtime-agnostic) let mut timeout_delay = pin!(Delay::new(CONNECTION_TIMEOUT).fuse()); loop { select! { _ = timeout_delay => { warn!("Connection activation timed out after {:?}", CONNECTION_TIMEOUT); return Err(ConnectionError::Timeout); } signal_opt = stream.next() => { match signal_opt { Some(signal) => { match signal.args() { Ok(args) => { let new_state = ActiveConnectionState::from(args.state); let reason = ConnectionStateReason::from(args.reason); debug!("Active connection state changed to: {new_state} (reason: {reason})"); match new_state { ActiveConnectionState::Activated => { debug!("Connection activation successful"); return Ok(()); } ActiveConnectionState::Deactivated => { debug!("Connection activation failed: {reason}"); return Err(connection_state_reason_to_error(args.reason)); } _ => {} } } Err(e) => { warn!("Failed to parse StateChanged signal args: {e}"); } } } None => { return Err(ConnectionError::Stuck("signal stream ended".into())); } } } } } } /// Waits for a device to reach the disconnected state using D-Bus signals. pub(crate) async fn wait_for_device_disconnect(dev: &NMDeviceProxy<'_>) -> Result<()> { // Subscribe to signals FIRST to avoid race condition let mut stream = dev.receive_device_state_changed().await?; debug!("Subscribed to device StateChanged signal for disconnect"); let current_state = dev.state().await?; debug!("Current device state for disconnect: {current_state}"); if current_state == device_state::DISCONNECTED || current_state == device_state::UNAVAILABLE { debug!("Device already disconnected"); return Ok(()); } // Wait for disconnect with timeout (runtime-agnostic) let mut timeout_delay = pin!(Delay::new(DISCONNECT_TIMEOUT).fuse()); loop { select! { _ = timeout_delay => { // Check final state - might have reached target during the last moments let final_state = dev.state().await?; if final_state == device_state::DISCONNECTED || final_state == device_state::UNAVAILABLE { return Ok(()); } else { warn!("Disconnect timed out, device still in state: {final_state}"); return Err(ConnectionError::Stuck(format!("state {final_state}"))); } } signal_opt = stream.next() => { match signal_opt { Some(signal) => { match signal.args() { Ok(args) => { let new_state = args.new_state; debug!("Device state during disconnect: {new_state}"); if new_state == device_state::DISCONNECTED || new_state == device_state::UNAVAILABLE { debug!("Device reached disconnected state"); return Ok(()); } } Err(e) => { warn!("Failed to parse StateChanged signal args: {e}"); } } } None => { return Err(ConnectionError::Stuck("signal stream ended".into())); } } } } } } /// Waits for a Wi-Fi device to be ready (Disconnected or Activated state). pub(crate) async fn wait_for_wifi_device_ready(dev: &NMDeviceProxy<'_>) -> Result<()> { // Subscribe to signals FIRST to avoid race condition let mut stream = dev.receive_device_state_changed().await?; debug!("Subscribed to device StateChanged signal for ready check"); let current_state = dev.state().await?; debug!("Current device state for ready check: {current_state}"); if current_state == device_state::DISCONNECTED || current_state == device_state::ACTIVATED { debug!("Device already ready"); return Ok(()); } let ready_timeout = timeouts::wifi_ready_timeout(); let mut timeout_delay = pin!(Delay::new(ready_timeout).fuse()); loop { select! { _ = timeout_delay => { // Check final state let final_state = dev.state().await?; if final_state == device_state::DISCONNECTED || final_state == device_state::ACTIVATED { return Ok(()); } else { warn!("Wi-Fi device not ready after timeout, state: {final_state}"); return Err(ConnectionError::WifiNotReady); } } signal_opt = stream.next() => { match signal_opt { Some(signal) => { match signal.args() { Ok(args) => { let new_state = args.new_state; debug!("Device state during ready wait: {new_state}"); if new_state == device_state::DISCONNECTED || new_state == device_state::ACTIVATED { debug!("Device is now ready"); return Ok(()); } } Err(e) => { warn!("Failed to parse StateChanged signal args: {e}"); } } } None => { return Err(ConnectionError::WifiNotReady); } } } } } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/core/connection_settings.rs
nmrs/src/core/connection_settings.rs
//! Saved connection profile management. //! //! Provides functions for querying and deleting saved NetworkManager //! connection profiles. Saved connections persist across reboots and //! store credentials for automatic reconnection. use log::debug; use std::collections::HashMap; use zbus::Connection; use zvariant::{OwnedObjectPath, Value}; use crate::Result; /// Finds the D-Bus path of a saved connection by SSID. /// /// Iterates through all saved connections in NetworkManager's settings /// and returns the path of the first one whose connection ID matches /// the given SSID. /// /// Returns `None` if no saved connection exists for this SSID. pub(crate) async fn get_saved_connection_path( conn: &Connection, ssid: &str, ) -> Result<Option<OwnedObjectPath>> { let settings = zbus::proxy::Proxy::new( conn, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings", "org.freedesktop.NetworkManager.Settings", ) .await?; let reply = settings.call_method("ListConnections", &()).await?; let conns: Vec<OwnedObjectPath> = reply.body().deserialize()?; for cpath in conns { let cproxy = zbus::proxy::Proxy::new( conn, "org.freedesktop.NetworkManager", cpath.as_str(), "org.freedesktop.NetworkManager.Settings.Connection", ) .await?; let msg = cproxy.call_method("GetSettings", &()).await?; let body = msg.body(); let all: HashMap<String, HashMap<String, Value>> = body.deserialize()?; if let Some(conn_section) = all.get("connection") { if let Some(Value::Str(id)) = conn_section.get("id") { if id == ssid { return Ok(Some(cpath)); } } } } Ok(None) } /// Checks whether a saved connection exists for the given SSID. pub(crate) async fn has_saved_connection(conn: &Connection, ssid: &str) -> Result<bool> { get_saved_connection_path(conn, ssid) .await .map(|p| p.is_some()) } /// Deletes a saved connection by its D-Bus path. /// /// Calls the Delete method on the connection settings object. /// This permanently removes the saved connection from NetworkManager. pub(crate) async fn delete_connection(conn: &Connection, conn_path: OwnedObjectPath) -> Result<()> { let cproxy: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(conn_path.clone())? .interface("org.freedesktop.NetworkManager.Settings.Connection")? .build() .await?; cproxy.call_method("Delete", &()).await?; debug!("Deleted connection: {}", conn_path.as_str()); Ok(()) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/core/connection.rs
nmrs/src/core/connection.rs
use futures_timer::Delay; use log::{debug, error, info, warn}; use std::collections::HashMap; use zbus::Connection; use zvariant::OwnedObjectPath; use crate::api::builders::wifi::{build_ethernet_connection, build_wifi_connection}; use crate::api::models::{ConnectionError, ConnectionOptions, WifiSecurity}; use crate::core::connection_settings::{delete_connection, get_saved_connection_path}; use crate::core::state_wait::{wait_for_connection_activation, wait_for_device_disconnect}; use crate::dbus::{NMAccessPointProxy, NMDeviceProxy, NMProxy, NMWirelessProxy}; use crate::monitoring::info::current_ssid; use crate::types::constants::{device_state, device_type, timeouts}; use crate::util::utils::decode_ssid_or_empty; use crate::Result; /// Decision on whether to reuse a saved connection or create a fresh one. enum SavedDecision { /// Reuse the saved connection at this path. UseSaved(OwnedObjectPath), /// Delete any saved connection and create a new one with fresh credentials. RebuildFresh, } /// Connects to a Wi-Fi network. /// /// This is the main entry point for establishing a Wi-Fi connection. The flow: /// 1. Check for an existing saved connection for this SSID /// 2. Decide whether to reuse it or create fresh (based on credentials) /// 3. Find the Wi-Fi device and target access point /// 4. Either activate the saved connection or create and activate a new one /// 5. Wait for the connection to reach the activated state /// /// If a saved connection exists but fails, it will be deleted and a fresh /// connection will be attempted with the provided credentials. pub(crate) async fn connect(conn: &Connection, ssid: &str, creds: WifiSecurity) -> Result<()> { debug!( "Connecting to '{}' | secured={} is_psk={} is_eap={}", ssid, creds.secured(), creds.is_psk(), creds.is_eap() ); let nm = NMProxy::new(conn).await?; let saved_raw = get_saved_connection_path(conn, ssid).await?; let decision = decide_saved_connection(saved_raw, &creds)?; let wifi_device = find_wifi_device(conn, &nm).await?; debug!("Found WiFi device: {}", wifi_device.as_str()); let wifi = NMWirelessProxy::builder(conn) .path(wifi_device.clone())? .build() .await?; if let Some(active) = current_ssid(conn).await { debug!("Currently connected to: {active}"); if active == ssid { debug!("Already connected to {active}, skipping connect()"); return Ok(()); } } else { debug!("Not currently connected to any network"); } let specific_object = scan_and_resolve_ap(conn, &wifi, ssid).await?; match decision { SavedDecision::UseSaved(saved) => { ensure_disconnected(conn, &nm, &wifi_device).await?; connect_via_saved(conn, &nm, &wifi_device, &specific_object, &creds, saved).await?; } SavedDecision::RebuildFresh => { build_and_activate_new(conn, &nm, &wifi_device, &specific_object, ssid, creds).await?; } } // Connection activation is now handled within connect_via_saved() and // build_and_activate_new() using signal-based monitoring info!("Successfully connected to '{ssid}'"); Ok(()) } /// Connects to a wired (Ethernet) device. /// /// This is the main entry point for establishing a wired connection. The flow: /// 1. Find a wired device /// 2. Check for an existing saved connection /// 3. Either activate the saved connection or create and activate a new one /// 4. Wait for the connection to reach the activated state /// /// Ethernet connections are typically simpler than Wi-Fi - no scanning or /// access points needed. The connection will activate when a cable is plugged in. pub(crate) async fn connect_wired(conn: &Connection) -> Result<()> { debug!("Connecting to wired device"); let nm = NMProxy::new(conn).await?; let wired_device = find_wired_device(conn, &nm).await?; debug!("Found wired device: {}", wired_device.as_str()); // Check if already connected let dev = NMDeviceProxy::builder(conn) .path(wired_device.clone())? .build() .await?; let current_state = dev.state().await?; if current_state == device_state::ACTIVATED { debug!("Wired device already activated, skipping connect()"); return Ok(()); } // Check for saved connection (by interface name) let interface = dev.interface().await?; let saved = get_saved_connection_path(conn, &interface).await?; // For Ethernet, we use "/" as the specific_object (no access point needed) let specific_object = OwnedObjectPath::try_from("/").unwrap(); match saved { Some(saved_path) => { debug!("Activating saved wired connection: {}", saved_path.as_str()); let active_conn = nm .activate_connection(saved_path, wired_device.clone(), specific_object) .await?; wait_for_connection_activation(conn, &active_conn).await?; } None => { debug!("No saved connection found, creating new wired connection"); let opts = ConnectionOptions { autoconnect: true, autoconnect_priority: None, autoconnect_retries: None, }; let settings = build_ethernet_connection(&interface, &opts); let (_, active_conn) = nm .add_and_activate_connection(settings, wired_device.clone(), specific_object) .await?; wait_for_connection_activation(conn, &active_conn).await?; } } info!("Successfully connected to wired device"); Ok(()) } /// Forgets (deletes) all saved connections for a network. /// /// If currently connected to this network, disconnects first, then deletes /// all saved connection profiles matching the SSID. Matches are found by /// both the connection ID and the wireless SSID bytes. /// /// Returns `NoSavedConnection` if no matching connections were found. pub(crate) async fn forget(conn: &Connection, ssid: &str) -> Result<()> { use std::collections::HashMap; use zvariant::{OwnedObjectPath, Value}; debug!("Starting forget operation for: {ssid}"); let nm = NMProxy::new(conn).await?; let devices = nm.get_devices().await?; for dev_path in &devices { let dev = NMDeviceProxy::builder(conn) .path(dev_path.clone())? .build() .await?; if dev.device_type().await? != device_type::WIFI { continue; } let wifi = NMWirelessProxy::builder(conn) .path(dev_path.clone())? .build() .await?; if let Ok(ap_path) = wifi.active_access_point().await { if ap_path.as_str() != "/" { let ap = NMAccessPointProxy::builder(conn) .path(ap_path.clone())? .build() .await?; if let Ok(bytes) = ap.ssid().await { if decode_ssid_or_empty(&bytes) == ssid { debug!("Disconnecting from active network: {ssid}"); if let Err(e) = disconnect_wifi_and_wait(conn, dev_path).await { warn!("Disconnect wait failed: {e}"); let final_state = dev.state().await?; if final_state != device_state::DISCONNECTED && final_state != device_state::UNAVAILABLE { error!( "Device still connected (state: {final_state}), cannot safely delete" ); return Err(ConnectionError::Stuck(format!( "disconnect failed, device in state {final_state}" ))); } debug!("Device confirmed disconnected, proceeding with deletion"); } debug!("Disconnect phase completed"); } } } } } debug!("Starting connection deletion phase..."); let settings: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path("/org/freedesktop/NetworkManager/Settings")? .interface("org.freedesktop.NetworkManager.Settings")? .build() .await?; let list_reply = settings.call_method("ListConnections", &()).await?; let conns: Vec<OwnedObjectPath> = list_reply.body().deserialize()?; let mut deleted_count = 0; for cpath in conns { let cproxy: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(cpath.clone())? .interface("org.freedesktop.NetworkManager.Settings.Connection")? .build() .await?; if let Ok(msg) = cproxy.call_method("GetSettings", &()).await { let body = msg.body(); let settings_map: HashMap<String, HashMap<String, Value>> = body.deserialize()?; let mut should_delete = false; if let Some(conn_sec) = settings_map.get("connection") { if let Some(Value::Str(id)) = conn_sec.get("id") { if id.as_str() == ssid { should_delete = true; debug!("Found connection by ID: {id}"); } } } if let Some(wifi_sec) = settings_map.get("802-11-wireless") { if let Some(Value::Array(arr)) = wifi_sec.get("ssid") { let mut raw = Vec::new(); for v in arr.iter() { if let Ok(b) = u8::try_from(v.clone()) { raw.push(b); } } if decode_ssid_or_empty(&raw) == ssid { should_delete = true; debug!("Found connection by SSID match"); } } } if let Some(wsec) = settings_map.get("802-11-wireless-security") { let missing_psk = !wsec.contains_key("psk"); let empty_psk = matches!(wsec.get("psk"), Some(Value::Str(s)) if s.is_empty()); if (missing_psk || empty_psk) && should_delete { debug!("Connection has missing/empty PSK, will delete"); } } if should_delete { match cproxy.call_method("Delete", &()).await { Ok(_) => { deleted_count += 1; debug!("Deleted connection: {}", cpath.as_str()); } Err(e) => { warn!("Failed to delete connection {}: {}", cpath.as_str(), e); } } } } } if deleted_count > 0 { info!("Successfully deleted {deleted_count} connection(s) for '{ssid}'"); Ok(()) } else { debug!("No saved connections found for '{ssid}'"); Err(ConnectionError::NoSavedConnection) } } /// Disconnects a Wi-Fi device and waits for it to reach disconnected state. /// /// Calls the Disconnect method on the device and waits for the `StateChanged` /// signal to indicate the device has reached Disconnected or Unavailable state. /// This is more efficient than polling and responds immediately when the /// device disconnects. pub(crate) async fn disconnect_wifi_and_wait( conn: &Connection, dev_path: &OwnedObjectPath, ) -> Result<()> { let dev = NMDeviceProxy::builder(conn) .path(dev_path.clone())? .build() .await?; // Check if already disconnected let current_state = dev.state().await?; if current_state == device_state::DISCONNECTED || current_state == device_state::UNAVAILABLE { debug!("Device already disconnected"); return Ok(()); } let raw: zbus::proxy::Proxy = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(dev_path.clone())? .interface("org.freedesktop.NetworkManager.Device")? .build() .await?; debug!("Sending disconnect request"); let _ = raw.call_method("Disconnect", &()).await; // Wait for disconnect using signal-based monitoring wait_for_device_disconnect(&dev).await?; // Brief stabilization delay Delay::new(timeouts::stabilization_delay()).await; Ok(()) } /// Find the first wired (Ethernet) device on the system. /// /// Iterates through all NetworkManager devices and returns the first one /// with device type `ETHERNET`. Returns `NoWiredDevice` if none found. pub(crate) async fn find_wired_device( conn: &Connection, nm: &NMProxy<'_>, ) -> Result<OwnedObjectPath> { let devices = nm.get_devices().await?; for dp in devices { let dev = NMDeviceProxy::builder(conn) .path(dp.clone())? .build() .await?; if dev.device_type().await? == device_type::ETHERNET { return Ok(dp); } } Err(ConnectionError::NoWiredDevice) } /// Finds the first Wi-Fi device on the system. /// /// Iterates through all NetworkManager devices and returns the first one /// with device type `WIFI`. Returns `NoWifiDevice` if none found. async fn find_wifi_device(conn: &Connection, nm: &NMProxy<'_>) -> Result<OwnedObjectPath> { let devices = nm.get_devices().await?; for dp in devices { let dev = NMDeviceProxy::builder(conn) .path(dp.clone())? .build() .await?; if dev.device_type().await? == device_type::WIFI { return Ok(dp); } } Err(ConnectionError::NoWifiDevice) } /// Finds an access point by SSID. /// /// Searches through all visible access points on the wireless device /// and returns the path of the first one matching the target SSID. /// Returns `NotFound` if no matching access point is visible. async fn find_ap( conn: &Connection, wifi: &NMWirelessProxy<'_>, target_ssid: &str, ) -> Result<OwnedObjectPath> { let access_points = wifi.access_points().await?; for ap_path in access_points { let ap = NMAccessPointProxy::builder(conn) .path(ap_path.clone())? .build() .await?; let ssid_bytes = ap.ssid().await?; let ssid = decode_ssid_or_empty(&ssid_bytes); if ssid == target_ssid { return Ok(ap_path); } } Err(ConnectionError::NotFound) } /// Ensures the Wi-Fi device is disconnected before attempting a new connection. /// /// If currently connected to any network, deactivates all active connections /// and waits for the device to reach disconnected state. async fn ensure_disconnected( conn: &Connection, nm: &NMProxy<'_>, wifi_device: &OwnedObjectPath, ) -> Result<()> { if let Some(active) = current_ssid(conn).await { debug!("Disconnecting from {active}"); if let Ok(conns) = nm.active_connections().await { for conn_path in conns { let _ = nm.deactivate_connection(conn_path).await; } } disconnect_wifi_and_wait(conn, wifi_device).await?; } Ok(()) } /// Attempts to connect using a saved connection profile. /// /// Activates the saved connection and monitors the activation state using /// D-Bus signals. If activation fails (device disconnects or enters failed /// state), deletes the saved connection and creates a fresh one with the /// provided credentials. /// /// This handles cases where saved passwords are outdated or corrupted. async fn connect_via_saved( conn: &Connection, nm: &NMProxy<'_>, wifi_device: &OwnedObjectPath, ap: &OwnedObjectPath, creds: &WifiSecurity, saved: OwnedObjectPath, ) -> Result<()> { debug!("Activating saved connection: {}", saved.as_str()); match nm .activate_connection(saved.clone(), wifi_device.clone(), ap.clone()) .await { Ok(active_conn) => { debug!( "activate_connection() succeeded, active connection: {}", active_conn.as_str() ); // Wait for connection activation using signal-based monitoring match wait_for_connection_activation(conn, &active_conn).await { Ok(()) => { debug!("Saved connection activated successfully"); } Err(e) => { warn!("Saved connection activation failed: {e}"); warn!("Deleting saved connection and retrying with fresh credentials"); let _ = nm.deactivate_connection(active_conn).await; let _ = delete_connection(conn, saved.clone()).await; let opts = ConnectionOptions { autoconnect: true, autoconnect_priority: None, autoconnect_retries: None, }; let settings = build_wifi_connection(ap.as_str(), creds, &opts); debug!("Creating fresh connection with corrected settings"); let (_, new_active_conn) = nm .add_and_activate_connection(settings, wifi_device.clone(), ap.clone()) .await .map_err(|e| { error!("Fresh connection also failed: {e}"); e })?; // Wait for the fresh connection to activate wait_for_connection_activation(conn, &new_active_conn).await?; } } } Err(e) => { warn!("activate_connection() failed: {e}"); warn!("Saved connection may be corrupted, deleting and retrying with fresh connection"); let _ = delete_connection(conn, saved.clone()).await; let opts = ConnectionOptions { autoconnect: true, autoconnect_priority: None, autoconnect_retries: None, }; let settings = build_wifi_connection(ap.as_str(), creds, &opts); let (_, active_conn) = nm .add_and_activate_connection(settings, wifi_device.clone(), ap.clone()) .await .map_err(|e| { error!("Fresh connection also failed: {e}"); e })?; // Wait for the fresh connection to activate wait_for_connection_activation(conn, &active_conn).await?; } } Ok(()) } /// Creates a new connection profile and activates it. /// /// Builds connection settings from the provided credentials, ensures the /// device is disconnected, then calls AddAndActivateConnection to create /// and activate the connection in one step. Monitors activation using /// D-Bus signals for immediate feedback on success or failure. async fn build_and_activate_new( conn: &Connection, nm: &NMProxy<'_>, wifi_device: &OwnedObjectPath, ap: &OwnedObjectPath, ssid: &str, creds: WifiSecurity, ) -> Result<()> { let opts = ConnectionOptions { autoconnect: true, autoconnect_retries: None, autoconnect_priority: None, }; let settings = build_wifi_connection(ssid, &creds, &opts); debug!("Creating new connection, settings: \n{settings:#?}"); ensure_disconnected(conn, nm, wifi_device).await?; let (_, active_conn) = match nm .add_and_activate_connection(settings, wifi_device.clone(), ap.clone()) .await { Ok(paths) => { debug!( "add_and_activate_connection() succeeded, active connection: {}", paths.1.as_str() ); paths } Err(e) => { error!("add_and_activate_connection() failed: {e}"); return Err(e.into()); } }; debug!("Waiting for connection activation using signal monitoring..."); // Wait for connection activation using the ActiveConnection signals wait_for_connection_activation(conn, &active_conn).await?; info!("Connection to '{ssid}' activated successfully"); Ok(()) } /// Triggers a Wi-Fi scan and finds the target access point. /// /// Requests a scan, waits briefly for results, then searches for an /// access point matching the target SSID. The wait time is shorter than /// polling-based approaches since we just need the scan to populate /// initial results. async fn scan_and_resolve_ap( conn: &Connection, wifi: &NMWirelessProxy<'_>, ssid: &str, ) -> Result<OwnedObjectPath> { match wifi.request_scan(HashMap::new()).await { Ok(_) => debug!("Scan requested successfully"), Err(e) => warn!("Scan request failed: {e}"), } // Brief wait for scan results to populate Delay::new(timeouts::scan_wait()).await; debug!("Scan wait complete"); let ap = find_ap(conn, wifi, ssid).await?; debug!("Matched target SSID '{ssid}'"); Ok(ap) } /// Decides whether to use a saved connection or create a fresh one. /// /// Decision logic: /// - If a saved connection exists and credentials are empty PSK, use saved /// (user wants to connect with stored password) /// - If a saved connection exists but new PSK credentials provided, rebuild /// (user is updating the password) /// - If no saved connection and PSK is empty, error (can't connect without password) /// - Otherwise, create a fresh connection fn decide_saved_connection( saved: Option<OwnedObjectPath>, creds: &WifiSecurity, ) -> Result<SavedDecision> { match saved { Some(_) if matches!(creds, WifiSecurity::WpaPsk { psk } if !psk.trim().is_empty()) => { Ok(SavedDecision::RebuildFresh) } Some(path) => Ok(SavedDecision::UseSaved(path)), None if matches!(creds, WifiSecurity::WpaPsk { psk } if psk.trim().is_empty()) => { Err(ConnectionError::NoSavedConnection) } None => Ok(SavedDecision::RebuildFresh), } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/core/mod.rs
nmrs/src/core/mod.rs
//! Core internal logic for connection management. //! //! This module contains the internal implementation details for managing //! network connections, devices, scanning, and state monitoring. pub(crate) mod connection; pub(crate) mod connection_settings; pub(crate) mod device; pub(crate) mod scan; pub(crate) mod state_wait; pub(crate) mod vpn;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/core/vpn.rs
nmrs/src/core/vpn.rs
//! Core VPN connection management logic. //! //! This module contains internal implementation for managing VPN connections //! through NetworkManager, including connecting, disconnecting, listing, and //! deleting VPN profiles. //! //! Currently supports: //! - WireGuard connections (NetworkManager connection.type == "wireguard") //! //! These functions are not part of the public API and should be accessed //! through the [`NetworkManager`][crate::NetworkManager] interface. use log::{debug, info, warn}; use std::collections::HashMap; use zbus::Connection; use zvariant::OwnedObjectPath; use crate::api::models::{ ConnectionOptions, DeviceState, VpnConnection, VpnConnectionInfo, VpnCredentials, VpnType, }; use crate::builders::build_wireguard_connection; use crate::core::state_wait::wait_for_connection_activation; use crate::dbus::{NMActiveConnectionProxy, NMProxy}; use crate::Result; /// Connects to a WireGuard connection. /// /// This function checks for an existing saved connection by name. /// If found, it activates the saved connection. If not found, it creates /// a new WireGuard connection using the provided credentials. /// The function waits for the connection to reach the activated state /// before returning. /// /// WireGuard activations do not require binding to an underlying device. /// Use "/" so NetworkManager auto-selects. pub(crate) async fn connect_vpn(conn: &Connection, creds: VpnCredentials) -> Result<()> { debug!("Connecting to VPN: {}", creds.name); let nm = NMProxy::new(conn).await?; // Check saved connections let saved = crate::core::connection_settings::get_saved_connection_path(conn, &creds.name).await?; // For WireGuard activation, always use "/" as device path - NetworkManager will auto-select let vpn_device_path = OwnedObjectPath::try_from("/").unwrap(); let specific_object = OwnedObjectPath::try_from("/").unwrap(); let active_conn = if let Some(saved_path) = saved { debug!("Activating existent VPN connection"); nm.activate_connection(saved_path, vpn_device_path.clone(), specific_object.clone()) .await? } else { debug!("Creating new VPN connection"); let opts = ConnectionOptions { autoconnect: false, autoconnect_priority: None, autoconnect_retries: None, }; let settings = build_wireguard_connection(&creds, &opts)?; // Use Settings API to add connection first, then activate separately // This avoids NetworkManager's device validation when using add_and_activate_connection let settings_proxy: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path("/org/freedesktop/NetworkManager/Settings")? .interface("org.freedesktop.NetworkManager.Settings")? .build() .await?; debug!("Adding connection via Settings API"); let add_reply = settings_proxy .call_method("AddConnection", &(settings,)) .await?; let conn_path: OwnedObjectPath = add_reply.body().deserialize()?; debug!("Connection added, activating VPN connection"); nm.activate_connection(conn_path, vpn_device_path, specific_object) .await? }; wait_for_connection_activation(conn, &active_conn).await?; debug!("Connection reached Activated state, waiting briefly..."); match NMActiveConnectionProxy::builder(conn).path(active_conn.clone()) { Ok(builder) => match builder.build().await { Ok(active_conn_check) => { let final_state = active_conn_check.state().await?; let state = crate::api::models::ActiveConnectionState::from(final_state); debug!("Connection state after delay: {:?}", state); match state { crate::api::models::ActiveConnectionState::Activated => { info!("Successfully connected to VPN: {}", creds.name); Ok(()) } crate::api::models::ActiveConnectionState::Deactivated => { warn!("Connection deactivated immediately after activation"); Err(crate::api::models::ConnectionError::ActivationFailed( crate::api::models::ConnectionStateReason::Unknown, )) } _ => { warn!("Connection in unexpected state: {:?}", state); Err(crate::api::models::ConnectionError::Stuck(format!( "connection in state {:?}", state ))) } } } Err(e) => { warn!("Failed to build active connection proxy after delay: {}", e); Err(crate::api::models::ConnectionError::ActivationFailed( crate::api::models::ConnectionStateReason::Unknown, )) } }, Err(e) => { warn!( "Failed to create active connection proxy builder after delay: {}", e ); Err(crate::api::models::ConnectionError::ActivationFailed( crate::api::models::ConnectionStateReason::Unknown, )) } } } /// Disconnects from a connection by name. /// /// Searches through active connections for a WireGuard connection matching the given name. /// If found, deactivates the connection. If not found, assumes already /// disconnected and returns success. pub(crate) async fn disconnect_vpn(conn: &Connection, name: &str) -> Result<()> { debug!("Disconnecting VPN: {name}"); let nm = NMProxy::new(conn).await?; let active_conns = match nm.active_connections().await { Ok(conns) => conns, Err(e) => { debug!("Failed to get active connections: {}", e); info!("Disconnected VPN: {name} (could not verify active state)"); return Ok(()); } }; for ac_path in active_conns { let ac_proxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(ac_path.clone())? .interface("org.freedesktop.NetworkManager.Connection.Active")? .build() .await { Ok(p) => p, Err(_) => continue, }; let conn_path: OwnedObjectPath = match ac_proxy.call_method("Connection", &()).await { Ok(msg) => match msg.body().deserialize::<OwnedObjectPath>() { Ok(path) => path, Err(_) => continue, }, Err(_) => continue, }; let cproxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(conn_path.clone())? .interface("org.freedesktop.NetworkManager.Settings.Connection")? .build() .await { Ok(p) => p, Err(_) => continue, }; let msg = match cproxy.call_method("GetSettings", &()).await { Ok(msg) => msg, Err(_) => continue, }; let body = msg.body(); let settings_map: HashMap<String, HashMap<String, zvariant::Value>> = match body.deserialize() { Ok(map) => map, Err(_) => continue, }; if let Some(conn_sec) = settings_map.get("connection") { let id_match = conn_sec .get("id") .and_then(|v| match v { zvariant::Value::Str(s) => Some(s.as_str() == name), _ => None, }) .unwrap_or(false); let is_wireguard = conn_sec .get("type") .and_then(|v| match v { zvariant::Value::Str(s) => Some(s.as_str() == "wireguard"), _ => None, }) .unwrap_or(false); if id_match && is_wireguard { debug!("Found active WireGuard connection, deactivating: {name}"); let _ = nm.deactivate_connection(ac_path).await; info!("Successfully disconnected VPN: {name}"); return Ok(()); } } } info!("Disconnected VPN: {name} (not active)"); Ok(()) } /// Lists all saved WireGuard connections with their current state. /// /// Returns connections where `connection.type == "wireguard"`. /// For active connections, populates `state` and `interface` from the active connection. pub(crate) async fn list_vpn_connections(conn: &Connection) -> Result<Vec<VpnConnection>> { let nm = NMProxy::new(conn).await?; let settings: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path("/org/freedesktop/NetworkManager/Settings")? .interface("org.freedesktop.NetworkManager.Settings")? .build() .await?; let list_reply = settings.call_method("ListConnections", &()).await?; let saved_conns: Vec<OwnedObjectPath> = list_reply.body().deserialize()?; // Map active WireGuard connection id -> (state, interface) let active_conns = nm.active_connections().await?; let mut active_wg_map: HashMap<String, (DeviceState, Option<String>)> = HashMap::new(); for ac_path in active_conns { let ac_proxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(ac_path.clone())? .interface("org.freedesktop.NetworkManager.Connection.Active")? .build() .await { Ok(p) => p, Err(_) => continue, }; let conn_path: OwnedObjectPath = match ac_proxy.call_method("Connection", &()).await { Ok(msg) => match msg.body().deserialize::<OwnedObjectPath>() { Ok(p) => p, Err(_) => continue, }, Err(_) => continue, }; let cproxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(conn_path)? .interface("org.freedesktop.NetworkManager.Settings.Connection")? .build() .await { Ok(p) => p, Err(_) => continue, }; let msg = match cproxy.call_method("GetSettings", &()).await { Ok(m) => m, Err(_) => continue, }; let body = msg.body(); let settings_map: HashMap<String, HashMap<String, zvariant::Value>> = match body.deserialize() { Ok(m) => m, Err(_) => continue, }; let conn_sec = match settings_map.get("connection") { Some(s) => s, None => continue, }; let id = match conn_sec.get("id") { Some(zvariant::Value::Str(s)) => s.as_str().to_string(), _ => continue, }; let conn_type = match conn_sec.get("type") { Some(zvariant::Value::Str(s)) => s.as_str(), _ => continue, }; if conn_type != "wireguard" { continue; } let state = if let Ok(state_val) = ac_proxy.get_property::<u32>("State").await { DeviceState::from(state_val) } else { DeviceState::Other(0) }; let interface = if let Ok(dev_paths) = ac_proxy .get_property::<Vec<OwnedObjectPath>>("Devices") .await { if let Some(dev_path) = dev_paths.first() { match zbus::proxy::Builder::<zbus::Proxy>::new(conn) .destination("org.freedesktop.NetworkManager")? .path(dev_path.clone())? .interface("org.freedesktop.NetworkManager.Device")? .build() .await { Ok(dev_proxy) => dev_proxy.get_property::<String>("Interface").await.ok(), Err(_) => None, } } else { None } } else { None }; active_wg_map.insert(id, (state, interface)); } let mut wg_conns = Vec::new(); for cpath in saved_conns { let cproxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(cpath.clone())? .interface("org.freedesktop.NetworkManager.Settings.Connection")? .build() .await { Ok(p) => p, Err(_) => continue, }; let msg = match cproxy.call_method("GetSettings", &()).await { Ok(m) => m, Err(_) => continue, }; let body = msg.body(); let settings_map: HashMap<String, HashMap<String, zvariant::Value>> = match body.deserialize() { Ok(m) => m, Err(_) => continue, }; let conn_sec = match settings_map.get("connection") { Some(s) => s, None => continue, }; let id = match conn_sec.get("id") { Some(zvariant::Value::Str(s)) => s.as_str().to_string(), _ => continue, }; let conn_type = match conn_sec.get("type") { Some(zvariant::Value::Str(s)) => s.as_str(), _ => continue, }; if conn_type != "wireguard" { continue; } let (state, interface) = active_wg_map .get(&id) .cloned() .unwrap_or((DeviceState::Other(0), None)); wg_conns.push(VpnConnection { name: id, vpn_type: VpnType::WireGuard, interface, state, }); } Ok(wg_conns) } /// Forgets (deletes) a saved WireGuard connection by name. /// /// If currently connected, the connection will be disconnected first before deletion. pub(crate) async fn forget_vpn(conn: &Connection, name: &str) -> Result<()> { debug!("Starting forget operation for VPN: {name}"); let _ = disconnect_vpn(conn, name).await; let settings: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path("/org/freedesktop/NetworkManager/Settings")? .interface("org.freedesktop.NetworkManager.Settings")? .build() .await?; let list_reply = settings.call_method("ListConnections", &()).await?; let conns: Vec<OwnedObjectPath> = list_reply.body().deserialize()?; for cpath in conns { let cproxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(cpath.clone())? .interface("org.freedesktop.NetworkManager.Settings.Connection")? .build() .await { Ok(p) => p, Err(_) => continue, }; if let Ok(msg) = cproxy.call_method("GetSettings", &()).await { let body = msg.body(); let settings_map: HashMap<String, HashMap<String, zvariant::Value>> = body.deserialize()?; if let Some(conn_sec) = settings_map.get("connection") { let id_ok = conn_sec .get("id") .and_then(|v| match v { zvariant::Value::Str(s) => Some(s.as_str() == name), _ => None, }) .unwrap_or(false); let type_ok = conn_sec .get("type") .and_then(|v| match v { zvariant::Value::Str(s) => Some(s.as_str() == "wireguard"), _ => None, }) .unwrap_or(false); if id_ok && type_ok { debug!("Found WireGuard connection, deleting: {name}"); cproxy.call_method("Delete", &()).await?; info!("Successfully deleted VPN connection: {name}"); return Ok(()); } } } } debug!("No saved VPN connection found for '{name}'"); Err(crate::api::models::ConnectionError::NoSavedConnection) } /// Gets detailed information about a WireGuard connection. /// /// The connection must be in the active connections list to retrieve full details. pub(crate) async fn get_vpn_info(conn: &Connection, name: &str) -> Result<VpnConnectionInfo> { let nm = NMProxy::new(conn).await?; let active_conns = nm.active_connections().await?; for ac_path in active_conns { let ac_proxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(ac_path.clone())? .interface("org.freedesktop.NetworkManager.Connection.Active")? .build() .await { Ok(p) => p, Err(_) => continue, }; let conn_path: OwnedObjectPath = match ac_proxy.call_method("Connection", &()).await { Ok(msg) => match msg.body().deserialize::<OwnedObjectPath>() { Ok(p) => p, Err(_) => continue, }, Err(_) => continue, }; let cproxy: zbus::Proxy<'_> = match zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(conn_path)? .interface("org.freedesktop.NetworkManager.Settings.Connection")? .build() .await { Ok(p) => p, Err(_) => continue, }; let msg = match cproxy.call_method("GetSettings", &()).await { Ok(m) => m, Err(_) => continue, }; let body = msg.body(); let settings_map: HashMap<String, HashMap<String, zvariant::Value>> = match body.deserialize() { Ok(m) => m, Err(_) => continue, }; let conn_sec = match settings_map.get("connection") { Some(s) => s, None => continue, }; let id = match conn_sec.get("id") { Some(zvariant::Value::Str(s)) => s.as_str(), _ => continue, }; let conn_type = match conn_sec.get("type") { Some(zvariant::Value::Str(s)) => s.as_str(), _ => continue, }; if conn_type != "wireguard" || id != name { continue; } // WireGuard type is known by connection.type let vpn_type = VpnType::WireGuard; // ActiveConnection state let state_val: u32 = ac_proxy.get_property("State").await?; let state = DeviceState::from(state_val); // Device/interface let dev_paths: Vec<OwnedObjectPath> = ac_proxy.get_property("Devices").await?; let interface = if let Some(dev_path) = dev_paths.first() { let dev_proxy: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(dev_path.clone())? .interface("org.freedesktop.NetworkManager.Device")? .build() .await?; Some(dev_proxy.get_property::<String>("Interface").await?) } else { None }; // Best-effort endpoint extraction from wireguard.peers (nmcli-style string) // This is not guaranteed to exist or be populated. let gateway = settings_map .get("wireguard") .and_then(|wg_sec| wg_sec.get("peers")) .and_then(|v| match v { zvariant::Value::Str(s) => Some(s.as_str().to_string()), _ => None, }) .and_then(|peers| { // peers: "pubkey endpoint=host:port allowed-ips=... , pubkey2 ..." let first = peers.split(',').next()?.trim().to_string(); for tok in first.split_whitespace() { if let Some(rest) = tok.strip_prefix("endpoint=") { return Some(rest.to_string()); } } None }); // IPv4 config let ip4_path: OwnedObjectPath = ac_proxy.get_property("Ip4Config").await?; let (ip4_address, dns_servers) = if ip4_path.as_str() != "/" { let ip4_proxy: zbus::Proxy<'_> = zbus::proxy::Builder::new(conn) .destination("org.freedesktop.NetworkManager")? .path(ip4_path)? .interface("org.freedesktop.NetworkManager.IP4Config")? .build() .await?; let ip4_address = if let Ok(addr_array) = ip4_proxy .get_property::<Vec<HashMap<String, zvariant::Value>>>("AddressData") .await { addr_array.first().and_then(|addr_map| { let address = addr_map.get("address").and_then(|v| match v { zvariant::Value::Str(s) => Some(s.as_str().to_string()), _ => None, })?; let prefix = addr_map.get("prefix").and_then(|v| match v { zvariant::Value::U32(p) => Some(*p), _ => None, })?; Some(format!("{}/{}", address, prefix)) }) } else { None }; let dns_servers = if let Ok(dns_array) = ip4_proxy.get_property::<Vec<u32>>("Nameservers").await { dns_array .iter() .map(|ip| { format!( "{}.{}.{}.{}", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF ) }) .collect() } else { vec![] }; (ip4_address, dns_servers) } else { (None, vec![]) }; // IPv6 config parsing not implemented let ip6_address = None; return Ok(VpnConnectionInfo { name: id.to_string(), vpn_type, state, interface, gateway, ip4_address, ip6_address, dns_servers, }); } Err(crate::api::models::ConnectionError::NoVpnConnection) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/src/core/scan.rs
nmrs/src/core/scan.rs
//! Wi-Fi network scanning and enumeration. //! //! Provides functions to trigger Wi-Fi scans and list visible networks //! with their properties (SSID, signal strength, security type). use std::collections::HashMap; use zbus::Connection; use crate::api::models::Network; use crate::dbus::{NMDeviceProxy, NMProxy, NMWirelessProxy}; use crate::types::constants::{device_type, security_flags}; use crate::util::utils::{decode_ssid_or_hidden, for_each_access_point}; use crate::Result; /// Triggers a Wi-Fi scan on all wireless devices. /// /// Requests NetworkManager to scan for available networks. The scan /// runs asynchronously; call `list_networks` after a delay to see results. pub(crate) async fn scan_networks(conn: &Connection) -> Result<()> { let nm = NMProxy::new(conn).await?; let devices = nm.get_devices().await?; for dp in devices { let d_proxy = NMDeviceProxy::builder(conn) .path(dp.clone())? .build() .await?; if d_proxy.device_type().await? != device_type::WIFI { continue; } let wifi = NMWirelessProxy::builder(conn) .path(dp.clone())? .build() .await?; let opts = std::collections::HashMap::new(); wifi.request_scan(opts).await?; } Ok(()) } /// Lists all visible Wi-Fi networks. /// /// Enumerates access points from all Wi-Fi devices and returns a deduplicated /// list of networks. Networks are keyed by (SSID, frequency) to distinguish /// 2.4GHz and 5GHz bands of the same network. /// /// When multiple access points share the same SSID and frequency (e.g., mesh /// networks), the one with the strongest signal is returned. pub(crate) async fn list_networks(conn: &Connection) -> Result<Vec<Network>> { let mut networks: HashMap<(String, u32), Network> = HashMap::new(); let all_networks = for_each_access_point(conn, |ap| { Box::pin(async move { let ssid_bytes = ap.ssid().await?; let ssid = decode_ssid_or_hidden(&ssid_bytes); let strength = ap.strength().await?; let bssid = ap.hw_address().await?; let flags = ap.flags().await?; let wpa = ap.wpa_flags().await?; let rsn = ap.rsn_flags().await?; let frequency = ap.frequency().await?; let secured = (flags & security_flags::WEP) != 0 || wpa != 0 || rsn != 0; let is_psk = (wpa & security_flags::PSK) != 0 || (rsn & security_flags::PSK) != 0; let is_eap = (wpa & security_flags::EAP) != 0 || (rsn & security_flags::EAP) != 0; let network = Network { device: String::new(), ssid: ssid.to_string(), bssid: Some(bssid), strength: Some(strength), frequency: Some(frequency), secured, is_psk, is_eap, }; Ok(Some((ssid, frequency, network))) }) }) .await?; // Deduplicate: use (SSID, frequency) as key, keep strongest signal for (ssid, frequency, new_net) in all_networks { networks .entry((ssid.to_string(), frequency)) .and_modify(|n| n.merge_ap(&new_net)) .or_insert(new_net); } Ok(networks.into_values().collect()) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/tests/integration_test.rs
nmrs/tests/integration_test.rs
use nmrs::{ reason_to_error, ConnectionError, DeviceState, DeviceType, NetworkManager, StateReason, VpnCredentials, VpnType, WifiSecurity, WireGuardPeer, }; use std::time::Duration; use tokio::time::sleep; /// Helper function to check if NetworkManager is available /// Returns true if we can connect to NetworkManager, false otherwise async fn is_networkmanager_available() -> bool { NetworkManager::new().await.is_ok() } /// Check if WiFi is available async fn has_wifi_device(nm: &NetworkManager) -> bool { nm.list_wireless_devices() .await .map(|d| !d.is_empty()) .unwrap_or(false) } /// Check if Ethernet is available async fn has_ethernet_device(nm: &NetworkManager) -> bool { nm.list_wired_devices() .await .map(|d| !d.is_empty()) .unwrap_or(false) } /// Skip tests if NetworkManager is not available macro_rules! require_networkmanager { () => { if !is_networkmanager_available().await { eprintln!("Skipping test: NetworkManager not available"); return; } }; } /// Skip tests if WiFi device is not available macro_rules! require_wifi { ($nm:expr) => { if !has_wifi_device($nm).await { eprintln!("Skipping test: No WiFi device available"); return; } }; } /// Skip tests if Ethernet device is not available macro_rules! require_ethernet { ($nm:expr) => { if !has_ethernet_device($nm).await { eprintln!("Skipping test: No Ethernet device available"); return; } }; } #[tokio::test] async fn test_networkmanager_initialization() { require_networkmanager!(); let _nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); } /// Test listing devices #[tokio::test] async fn test_list_devices() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); let devices = nm.list_devices().await.expect("Failed to list devices"); assert!(!devices.is_empty(), "Expected at least one device"); for device in &devices { assert!(!device.path.is_empty(), "Device path should not be empty"); assert!( !device.interface.is_empty(), "Device interface should not be empty" ); } } /// Test WiFi enabled state #[tokio::test] async fn test_wifi_enabled_get_set() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); let initial_state = nm .wifi_enabled() .await .expect("Failed to get WiFi enabled state"); match nm.set_wifi_enabled(!initial_state).await { Ok(_) => { sleep(Duration::from_millis(500)).await; let new_state = nm .wifi_enabled() .await .expect("Failed to get WiFi enabled state after toggle"); if new_state == initial_state { eprintln!( "Warning: WiFi state didn't change (may lack permissions). Initial: {}, New: {}", initial_state, new_state ); return; } } Err(e) => { eprintln!("Failed to toggle WiFi (may lack permissions): {}", e); return; } } nm.set_wifi_enabled(initial_state) .await .expect("Failed to restore WiFi enabled state"); sleep(Duration::from_millis(500)).await; let restored_state = nm .wifi_enabled() .await .expect("Failed to get WiFi enabled state after restore"); assert_eq!( restored_state, initial_state, "WiFi state should be restored to original" ); } /// Test waiting for WiFi to be ready #[tokio::test] async fn test_wait_for_wifi_ready() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let result = nm.wait_for_wifi_ready().await; // This should either succeed or fail gracefully // We don't assert success because WiFi might not be ready in all test environments match result { Ok(_) => {} Err(e) => { eprintln!( "WiFi not ready (this may be expected in some environments): {}", e ); } } } /// Test scanning networks #[tokio::test] async fn test_scan_networks() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let _ = nm.wait_for_wifi_ready().await; // Request a scan let result = nm.scan_networks().await; // Scan should either succeed or fail gracefully match result { Ok(_) => { // Success - wait a bit for scan to complete sleep(Duration::from_secs(2)).await; } Err(e) => { eprintln!("Scan failed (may be expected in some environments): {}", e); } } } /// Test listing networks #[tokio::test] async fn test_list_networks() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let _ = nm.wait_for_wifi_ready().await; // Request a scan first let _ = nm.scan_networks().await; sleep(Duration::from_secs(2)).await; // List networks let networks = nm.list_networks().await.expect("Failed to list networks"); // Verify network structure for network in &networks { assert!( !network.ssid.is_empty() || network.ssid == "<hidden>", "SSID should not be empty (unless hidden)" ); assert!( !network.device.is_empty(), "Device path should not be empty" ); } } /// Test getting current SSID #[tokio::test] async fn test_current_ssid() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Get current SSID (may be None if not connected) let current_ssid = nm.current_ssid().await; // If connected, SSID should not be empty if let Some(ssid) = current_ssid { assert!( !ssid.is_empty(), "Current SSID should not be empty if connected" ); } } /// Test getting current connection info #[tokio::test] async fn test_current_connection_info() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Get current connection info (may be None if not connected) let info = nm.current_connection_info().await; // If connected, SSID should not be empty if let Some((ssid, _frequency)) = info { assert!( !ssid.is_empty(), "Current SSID should not be empty if connected" ); } } /// Test showing details #[tokio::test] async fn test_show_details() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let _ = nm.wait_for_wifi_ready().await; // Request a scan first let _ = nm.scan_networks().await; sleep(Duration::from_secs(2)).await; // List networks let networks = nm.list_networks().await.expect("Failed to list networks"); // Try to show details for the first network (if any) if let Some(network) = networks.first() { let result = nm.show_details(network).await; match result { Ok(details) => { // Verify details structure assert_eq!(details.ssid, network.ssid, "SSID should match"); assert!(!details.bssid.is_empty(), "BSSID should not be empty"); assert!(details.strength <= 100, "Strength should be <= 100"); assert!(!details.mode.is_empty(), "Mode should not be empty"); assert!(!details.security.is_empty(), "Security should not be empty"); assert!(!details.status.is_empty(), "Status should not be empty"); } Err(e) => { // Network might have disappeared between scan and details request eprintln!("Failed to show details (may be expected): {}", e); } } } } /// Test checking if a connection is saved #[tokio::test] async fn test_has_saved_connection() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Test with a non-existent SSID let result = nm .has_saved_connection("__NONEXISTENT_TEST_SSID__") .await .expect("Failed to check saved connection"); assert!( !result, "Non-existent SSID should not have saved connection" ); // Test with empty SSID let _result = nm .has_saved_connection("") .await .expect("Failed to check saved connection for empty SSID"); } /// Test getting the path of a saved connection #[tokio::test] async fn test_get_saved_connection_path() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Test with a non-existent SSID let result = nm .get_saved_connection_path("__NONEXISTENT_TEST_SSID__") .await .expect("Failed to get saved connection path"); assert!( result.is_none(), "Non-existent SSID should not have saved connection path" ); // Test with empty SSID let result = nm .get_saved_connection_path("") .await .expect("Failed to get saved connection path for empty SSID"); // Result can be Some or None depending on system state assert!(result.is_some() || result.is_none()); } /// Test connecting to an open network #[tokio::test] async fn test_connect_open_network() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let _ = nm.wait_for_wifi_ready().await; // Request a scan first let _ = nm.scan_networks().await; sleep(Duration::from_secs(2)).await; // List networks to find an open network let networks = nm.list_networks().await.expect("Failed to list networks"); // Find an open network (if any) let open_network = networks.iter().find(|n| !n.secured); if let Some(network) = open_network { let test_ssid = &network.ssid; // Skip if SSID is hidden or empty if test_ssid.is_empty() || test_ssid == "<hidden>" { eprintln!("Skipping: Found open network but SSID is hidden/empty"); return; } // Try to connect to the open network let result = nm.connect(test_ssid, WifiSecurity::Open).await; match result { Ok(_) => { // Connection succeeded - wait a bit and verify sleep(Duration::from_secs(3)).await; let current = nm.current_ssid().await; if let Some(connected_ssid) = current { // May or may not match depending on connection success eprintln!("Connected SSID: {}", connected_ssid); } } Err(e) => { // Connection failed - this is acceptable in test environments eprintln!("Connection failed (may be expected): {}", e); } } } else { eprintln!("No open networks found for testing"); } } /// Test connecting to a PSK network with an empty password #[tokio::test] async fn test_connect_psk_network_with_empty_password() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let _ = nm.wait_for_wifi_ready().await; // Request a scan first let _ = nm.scan_networks().await; sleep(Duration::from_secs(2)).await; // List networks to find a PSK network let networks = nm.list_networks().await.expect("Failed to list networks"); // Find a PSK network (if any) let psk_network = networks.iter().find(|n| n.is_psk); if let Some(network) = psk_network { let test_ssid = &network.ssid; // Skip if SSID is hidden or empty if test_ssid.is_empty() || test_ssid == "<hidden>" { eprintln!("Skipping: Found PSK network but SSID is hidden/empty"); return; } // Check if we have a saved connection for this network let has_saved = nm .has_saved_connection(test_ssid) .await .expect("Failed to check saved connection"); if has_saved { // Try to connect with empty password (should use saved credentials) let result = nm .connect(test_ssid, WifiSecurity::WpaPsk { psk: String::new() }) .await; match result { Ok(_) => { // Connection succeeded - wait a bit sleep(Duration::from_secs(3)).await; } Err(e) => { // Connection failed - this is acceptable eprintln!("Connection with saved credentials failed: {}", e); } } } else { eprintln!("No saved connection for PSK network, skipping test"); } } else { eprintln!("No PSK networks found for testing"); } } /// Test forgetting a nonexistent network #[tokio::test] async fn test_forget_nonexistent_network() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Try to forget a non-existent network let result = nm.forget("__NONEXISTENT_TEST_SSID_TO_FORGET__").await; // This should fail since the network doesn't exist assert!( result.is_err(), "Forgetting non-existent network should fail" ); } /// Test device states #[tokio::test] async fn test_device_states() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); let devices = nm.list_devices().await.expect("Failed to list devices"); // Verify that all devices have valid states for device in &devices { // DeviceState should be one of the known states match device.state { DeviceState::Unmanaged | DeviceState::Unavailable | DeviceState::Disconnected | DeviceState::Prepare | DeviceState::Config | DeviceState::Activated | DeviceState::Deactivating | DeviceState::Failed | DeviceState::Other(_) => { // Valid state } } } } /// Test device types #[tokio::test] async fn test_device_types() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); let devices = nm.list_devices().await.expect("Failed to list devices"); // Verify that all devices have valid types for device in &devices { // DeviceType should be one of the known types match device.device_type { DeviceType::Ethernet | DeviceType::Wifi | DeviceType::WifiP2P | DeviceType::Loopback | DeviceType::Other(_) => { // Valid type } } } } /// Test network properties #[tokio::test] async fn test_network_properties() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let _ = nm.wait_for_wifi_ready().await; // Request a scan first let _ = nm.scan_networks().await; sleep(Duration::from_secs(2)).await; // List networks let networks = nm.list_networks().await.expect("Failed to list networks"); // Verify network properties for network in &networks { // SSID should not be empty (unless hidden) assert!( !network.ssid.is_empty() || network.ssid == "<hidden>", "SSID should not be empty" ); // Device path should not be empty assert!( !network.device.is_empty(), "Device path should not be empty" ); // If strength is Some, it should be <= 100 if let Some(strength) = network.strength { assert!(strength <= 100, "Strength should be <= 100"); } // Security flags should be consistent if !network.secured { assert!(!network.is_psk, "Unsecured network should not be PSK"); assert!(!network.is_eap, "Unsecured network should not be EAP"); } } } /// Test multiple scan requests #[tokio::test] async fn test_multiple_scan_requests() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Wait for WiFi to be ready let _ = nm.wait_for_wifi_ready().await; // Request multiple scans for i in 0..3 { nm.wait_for_wifi_ready().await.expect("WiFi not ready"); let result = nm.scan_networks().await; match result { Ok(_) => eprintln!("Scan {} succeeded", i + 1), Err(e) => eprintln!("Scan {} failed: {}", i + 1, e), } nm.wait_for_wifi_ready() .await .expect("WiFi did not recover"); sleep(Duration::from_secs(3)).await; } // List networks after multiple scans let networks = nm.list_networks().await.expect("Failed to list networks"); eprintln!("Found {} networks after multiple scans", networks.len()); } /// Test concurrent operations #[tokio::test] async fn test_concurrent_operations() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); // Ensure WiFi is enabled nm.set_wifi_enabled(true) .await .expect("Failed to enable WiFi"); // Run multiple operations concurrently let (devices_result, wifi_enabled_result, networks_result) = tokio::join!(nm.list_devices(), nm.wifi_enabled(), nm.list_networks()); // All should succeed assert!(devices_result.is_ok(), "list_devices should succeed"); assert!(wifi_enabled_result.is_ok(), "wifi_enabled should succeed"); // networks_result may fail if WiFi is not ready, which is acceptable let _ = networks_result; } /// Test that reason_to_error maps auth failures correctly #[test] fn reason_to_error_auth_mapping() { // Supplicant failed (code 9) should map to AuthFailed assert!(matches!(reason_to_error(9), ConnectionError::AuthFailed)); // Supplicant disconnected (code 7) should map to AuthFailed assert!(matches!(reason_to_error(7), ConnectionError::AuthFailed)); // DHCP failed (code 17) should map to DhcpFailed assert!(matches!(reason_to_error(17), ConnectionError::DhcpFailed)); // SSID not found (code 70) should map to NotFound assert!(matches!(reason_to_error(70), ConnectionError::NotFound)); } /// Test StateReason conversions #[test] fn state_reason_conversion() { assert_eq!(StateReason::from(9), StateReason::SupplicantFailed); assert_eq!(StateReason::from(70), StateReason::SsidNotFound); assert_eq!(StateReason::from(999), StateReason::Other(999)); } /// Test ConnectionError display formatting #[test] fn connection_error_display() { let auth_err = ConnectionError::AuthFailed; assert_eq!(format!("{}", auth_err), "authentication failed"); let not_found_err = ConnectionError::NotFound; assert_eq!(format!("{}", not_found_err), "network not found"); let timeout_err = ConnectionError::Timeout; assert_eq!(format!("{}", timeout_err), "connection timeout"); let stuck_err = ConnectionError::Stuck("config".into()); assert_eq!( format!("{}", stuck_err), "connection stuck in state: config" ); } /// Test forgetting a network returns NoSavedConnection error #[tokio::test] async fn forget_returns_no_saved_connection_error() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_wifi!(&nm); let result = nm.forget("__NONEXISTENT_TEST_SSID__").await; match result { Err(ConnectionError::NoSavedConnection) => { // Expected error type } Err(e) => { panic!("Expected NoSavedConnection error, got: {}", e); } Ok(_) => { panic!("Expected error, got success"); } } } /// Test listing wired devices #[tokio::test] async fn test_list_wired_devices() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); let devices = nm .list_wired_devices() .await .expect("Failed to list wired devices"); // Verify device structure for wired devices for device in &devices { assert!(!device.path.is_empty(), "Device path should not be empty"); assert!( !device.interface.is_empty(), "Device interface should not be empty" ); assert_eq!( device.device_type, DeviceType::Ethernet, "Device type should be Ethernet" ); } } /// Test connecting to wired device #[tokio::test] async fn test_connect_wired() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); require_ethernet!(&nm); // Try to connect to wired device let result = nm.connect_wired().await; match result { Ok(_) => { // Connection succeeded or is waiting for cable eprintln!("Wired connection initiated successfully"); } Err(e) => { // Connection failed - this is acceptable in test environments eprintln!("Wired connection failed (may be expected): {}", e); } } } /// Helper to create test VPN credentials fn create_test_vpn_creds(name: &str) -> VpnCredentials { VpnCredentials { vpn_type: VpnType::WireGuard, name: name.into(), gateway: "test.example.com:51820".into(), private_key: "YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=".into(), address: "10.100.0.2/24".into(), peers: vec![WireGuardPeer { public_key: "HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=".into(), gateway: "test.example.com:51820".into(), allowed_ips: vec!["0.0.0.0/0".into(), "::/0".into()], preshared_key: None, persistent_keepalive: Some(25), }], dns: Some(vec!["1.1.1.1".into(), "8.8.8.8".into()]), mtu: Some(1420), uuid: None, } } /// Test listing VPN connections #[tokio::test] async fn test_list_vpn_connections() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); // List VPN connections (should not fail even if empty) let result = nm.list_vpn_connections().await; assert!(result.is_ok(), "Should be able to list VPN connections"); let vpns = result.unwrap(); eprintln!("Found {} VPN connection(s)", vpns.len()); // Verify structure of any VPN connections found for vpn in &vpns { assert!(!vpn.name.is_empty(), "VPN name should not be empty"); eprintln!("VPN: {} ({:?})", vpn.name, vpn.vpn_type); } } /// Test VPN connection lifecycle (does not actually connect) #[tokio::test] async fn test_vpn_lifecycle_dry_run() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); // Note: This test does NOT actually connect to a VPN // It only tests the API structure and error handling // Create test credentials let creds = create_test_vpn_creds("test_vpn_lifecycle"); // Attempt to connect (will likely fail as test server doesn't exist) let result = nm.connect_vpn(creds).await; match result { Ok(_) => { eprintln!("VPN connection succeeded (unexpected in test)"); // Clean up let _ = nm.disconnect_vpn("test_vpn_lifecycle").await; let _ = nm.forget_vpn("test_vpn_lifecycle").await; } Err(e) => { eprintln!("VPN connection failed as expected: {}", e); // This is expected since we're using fake credentials } } } /// Test VPN disconnection with non-existent VPN #[tokio::test] async fn test_disconnect_nonexistent_vpn() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); // Disconnecting a non-existent VPN should succeed (idempotent) let result = nm.disconnect_vpn("nonexistent_vpn_connection_12345").await; assert!( result.is_ok(), "Disconnecting non-existent VPN should succeed" ); } /// Test forgetting non-existent VPN #[tokio::test] async fn test_forget_nonexistent_vpn() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); // Forgetting a non-existent VPN should fail let result = nm.forget_vpn("nonexistent_vpn_connection_12345").await; assert!( result.is_err(), "Forgetting non-existent VPN should return error" ); match result { Err(ConnectionError::NoSavedConnection) => { eprintln!("Correct error: NoSavedConnection"); } Err(e) => { panic!("Unexpected error type: {}", e); } Ok(_) => { panic!("Should have failed"); } } } /// Test getting info for non-existent VPN #[tokio::test] async fn test_get_nonexistent_vpn_info() { require_networkmanager!(); let nm = NetworkManager::new() .await .expect("Failed to create NetworkManager"); // Getting info for non-existent/inactive VPN should fail let result = nm.get_vpn_info("nonexistent_vpn_connection_12345").await; assert!( result.is_err(), "Getting info for non-existent VPN should return error" ); match result { Err(ConnectionError::NoVpnConnection) => { eprintln!("Correct error: NoVpnConnection"); } Err(e) => { eprintln!("Error (acceptable): {}", e); } Ok(_) => { panic!("Should have failed"); } } } /// Test VPN type enum #[tokio::test] async fn test_vpn_type() { // Verify VPN types are properly defined let wg = VpnType::WireGuard; assert_eq!(format!("{:?}", wg), "WireGuard"); } /// Test WireGuard peer structure #[tokio::test] async fn test_wireguard_peer_structure() { let peer = WireGuardPeer { public_key: "test_key".into(), gateway: "test.example.com:51820".into(), allowed_ips: vec!["0.0.0.0/0".into()], preshared_key: Some("psk".into()), persistent_keepalive: Some(25), }; assert_eq!(peer.public_key, "test_key"); assert_eq!(peer.gateway, "test.example.com:51820"); assert_eq!(peer.allowed_ips.len(), 1); assert_eq!(peer.preshared_key, Some("psk".into())); assert_eq!(peer.persistent_keepalive, Some(25)); } /// Test VPN credentials structure #[tokio::test] async fn test_vpn_credentials_structure() { let creds = create_test_vpn_creds("test_credentials"); assert_eq!(creds.name, "test_credentials"); assert_eq!(creds.vpn_type, VpnType::WireGuard); assert_eq!(creds.peers.len(), 1); assert_eq!(creds.address, "10.100.0.2/24"); assert!(creds.dns.is_some()); assert_eq!(creds.dns.as_ref().unwrap().len(), 2); assert_eq!(creds.mtu, Some(1420)); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/examples/wifi_scan.rs
nmrs/examples/wifi_scan.rs
use nmrs::NetworkManager; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; println!("Scanning for WiFi networks..."); nm.scan_networks().await?; let networks = nm.list_networks().await?; for net in networks { println!("{:30} {}%", net.ssid, net.strength.unwrap_or(0)); } Ok(()) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs/examples/vpn_connect.rs
nmrs/examples/vpn_connect.rs
use nmrs::{NetworkManager, VpnCredentials, VpnType, WireGuardPeer}; #[tokio::main] async fn main() -> nmrs::Result<()> { let nm = NetworkManager::new().await?; let creds = VpnCredentials { vpn_type: VpnType::WireGuard, name: "ExampleVPN".into(), gateway: "vpn.example.com:51820".into(), private_key: std::env::var("WG_PRIVATE_KEY").expect("Set WG_PRIVATE_KEY env var"), address: "10.0.0.2/24".into(), peers: vec![WireGuardPeer { public_key: std::env::var("WG_PUBLIC_KEY").expect("Set WG_PUBLIC_KEY env var"), gateway: "vpn.example.com:51820".into(), allowed_ips: vec!["0.0.0.0/0".into()], preshared_key: None, persistent_keepalive: Some(25), }], dns: Some(vec!["1.1.1.1".into()]), mtu: None, uuid: None, }; println!("Connecting to VPN..."); nm.connect_vpn(creds).await?; let info = nm.get_vpn_info("ExampleVPN").await?; println!("Connected! IP: {:?}", info.ip4_address); Ok(()) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/build.rs
nmrs-gui/build.rs
use std::process::Command; fn main() { let output = Command::new("git") .args(["rev-parse", "--short", "HEAD"]) .output(); let hash = match output { Ok(output) if output.status.success() => { String::from_utf8_lossy(&output.stdout).trim().to_string() } _ => { println!("cargo:warning=Unable to determine git hash, using 'unknown'"); String::from("unknown") } }; println!("cargo:rustc-env=GIT_HASH={}", hash); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/lib.rs
nmrs-gui/src/lib.rs
pub mod file_lock; pub mod objects; pub mod style; pub mod theme_config; pub mod ui; use clap::{ArgAction, Parser}; use gtk::prelude::*; use gtk::Application; use crate::file_lock::acquire_app_lock; use crate::style::load_css; use crate::ui::build_ui; #[derive(Parser, Debug)] #[command(name = "nmrs")] #[command(disable_version_flag = true)] #[command(version)] struct Args { #[arg(short = 'V', long = "version", action = ArgAction::SetTrue)] version: bool, } pub fn run() -> anyhow::Result<()> { let args = Args::parse(); if let Args { version: true } = args { println!( "nmrs {}-beta ({})", env!("CARGO_PKG_VERSION"), env!("GIT_HASH") ); return Ok(()); } let app = Application::builder() .application_id("org.netrs.ui") .build(); let _lock = match acquire_app_lock() { Ok(lock) => lock, Err(e) => { eprintln!("Failed to start: {e}"); std::process::exit(1); } }; app.connect_activate(|app| { load_css(); build_ui(app); }); app.run(); Ok(()) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/theme_config.rs
nmrs-gui/src/theme_config.rs
use std::fs; use std::path::PathBuf; fn get_config_path() -> Option<PathBuf> { dirs::config_dir().map(|mut path| { path.push("nmrs"); fs::create_dir_all(&path).ok()?; path.push("theme"); Some(path) })? } /// Save the selected theme *name* (e.g. "nord", "gruvbox", "dracula") pub fn save_theme(name: &str) { if let Some(path) = get_config_path() { let _ = fs::write(path, name); } } /// Load the previously selected theme. /// Returns Some("nord") or None if missing. pub fn load_theme() -> Option<String> { get_config_path() .and_then(|path| fs::read_to_string(path).ok()) .map(|s| s.trim().to_string()) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/style.rs
nmrs-gui/src/style.rs
use gtk::gdk::Display; use gtk::gio::File; use gtk::{CssProvider, STYLE_PROVIDER_PRIORITY_APPLICATION, STYLE_PROVIDER_PRIORITY_USER}; use std::fs; use std::io::Write; fn load_user_css_if_exists(display: &Display, default: &str) { let path = dirs::config_dir() .unwrap_or_default() .join("nmrs/style.css"); if path.exists() { let provider = CssProvider::new(); let file = File::for_path(&path); provider.load_from_file(&file); gtk::style_context_add_provider_for_display( display, &provider, STYLE_PROVIDER_PRIORITY_USER, ); } else { if let Some(parent) = path.parent() { fs::create_dir_all(parent).ok(); } let mut f = fs::File::create(&path).expect("Failed to create CSS file"); f.write_all(default.as_bytes()) .expect("Failed to write default CSS"); } } pub fn load_css() { let provider = CssProvider::new(); let css = include_str!("style.css"); provider.load_from_data(css); let display = Display::default().expect("No display found"); gtk::style_context_add_provider_for_display( &display, &provider, STYLE_PROVIDER_PRIORITY_APPLICATION, ); load_user_css_if_exists(&display, css); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/file_lock.rs
nmrs-gui/src/file_lock.rs
use fs2::FileExt; use std::fs::File; pub fn acquire_app_lock() -> Result<File, String> { let mut lock_path = dirs::data_local_dir().unwrap_or(std::env::temp_dir()); lock_path.push("my_app.lock"); let file = File::create(&lock_path).map_err(|e| format!("Failed to create lock file: {e}"))?; // Exclusive lock; fails if another instance holds it file.try_lock_exclusive() .map_err(|_| "Another instance is already running".to_string())?; Ok(file) }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/main.rs
nmrs-gui/src/main.rs
#[tokio::main(flavor = "current_thread")] async fn main() { nmrs_gui::run().ok(); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/ui/networks.rs
nmrs-gui/src/ui/networks.rs
use anyhow::Result; use gtk::prelude::*; use gtk::Align; use gtk::GestureClick; use gtk::{Box, Image, Label, ListBox, ListBoxRow, Orientation}; use nmrs::models::WifiSecurity; use nmrs::{models, NetworkManager}; use std::rc::Rc; use crate::ui::connect; use crate::ui::network_page::NetworkPage; pub struct NetworkRowController { pub row: gtk::ListBoxRow, pub arrow: gtk::Image, pub ctx: Rc<NetworksContext>, pub net: models::Network, pub details_page: Rc<NetworkPage>, } pub struct NetworksContext { pub nm: Rc<NetworkManager>, pub on_success: Rc<dyn Fn()>, pub status: Label, pub stack: gtk::Stack, pub parent_window: gtk::ApplicationWindow, pub details_page: Rc<NetworkPage>, pub wired_details_page: Rc<crate::ui::wired_page::WiredPage>, } impl NetworksContext { pub async fn new( on_success: Rc<dyn Fn()>, status: &Label, stack: &gtk::Stack, parent_window: &gtk::ApplicationWindow, details_page: Rc<NetworkPage>, wired_details_page: Rc<crate::ui::wired_page::WiredPage>, ) -> Result<Self> { let nm = Rc::new(NetworkManager::new().await?); Ok(Self { nm, on_success, status: status.clone(), stack: stack.clone(), parent_window: parent_window.clone(), details_page, wired_details_page, }) } } impl NetworkRowController { pub fn new( row: gtk::ListBoxRow, arrow: gtk::Image, ctx: Rc<NetworksContext>, net: models::Network, details_page: Rc<NetworkPage>, ) -> Self { Self { row, arrow, ctx, net, details_page, } } pub fn attach(&self) { self.attach_arrow(); self.attach_row_double(); } fn attach_arrow(&self) { let click = GestureClick::new(); let ctx = self.ctx.clone(); let net = self.net.clone(); let stack = self.ctx.stack.clone(); let page = self.details_page.clone(); click.connect_pressed(move |_, _, _, _| { let ctx_c = ctx.clone(); let net_c = net.clone(); let stack_c = stack.clone(); let page_c = page.clone(); glib::MainContext::default().spawn_local(async move { if let Ok(info) = ctx_c.nm.show_details(&net_c).await { page_c.update(&info); stack_c.set_visible_child_name("details"); } }); }); self.arrow.add_controller(click); } fn attach_row_double(&self) { let click = GestureClick::new(); let ctx = self.ctx.clone(); let net = self.net.clone(); let ssid = net.ssid.clone(); let secured = net.secured; let is_eap = net.is_eap; let status = ctx.status.clone(); let window = ctx.parent_window.clone(); let on_success = ctx.on_success.clone(); click.connect_pressed(move |_, n, _, _| { if n != 2 { return; } status.set_text(&format!("Connecting to {ssid}...")); let ssid_c = ssid.clone(); let nm_c = ctx.nm.clone(); let status_c = status.clone(); let window_c = window.clone(); let on_success_c = on_success.clone(); glib::MainContext::default().spawn_local(async move { if secured { let have = nm_c.has_saved_connection(&ssid_c).await.unwrap_or(false); if have { status_c.set_text(&format!("Connecting to {}...", ssid_c)); window_c.set_sensitive(false); let creds = WifiSecurity::WpaPsk { psk: "".into() }; match nm_c.connect(&ssid_c, creds).await { Ok(_) => { status_c.set_text(""); on_success_c(); } Err(e) => status_c.set_text(&format!("Failed to connect: {e}")), } window_c.set_sensitive(true); } else { connect::connect_modal( nm_c.clone(), &window_c, &ssid_c, is_eap, on_success_c.clone(), ); } } else { status_c.set_text(&format!("Connecting to {}...", ssid_c)); window_c.set_sensitive(false); let creds = WifiSecurity::Open; match nm_c.connect(&ssid_c, creds).await { Ok(_) => { status_c.set_text(""); on_success_c(); } Err(e) => status_c.set_text(&format!("Failed to connect: {e}")), } window_c.set_sensitive(true); } status_c.set_text(""); }); }); self.row.add_controller(click); } } pub fn networks_view( ctx: Rc<NetworksContext>, networks: &[models::Network], current_ssid: Option<&str>, current_band: Option<&str>, ) -> ListBox { let conn_threshold = 75; let list = ListBox::new(); let mut sorted_networks: Vec<_> = networks .iter() .filter(|net| !net.ssid.trim().is_empty()) .cloned() .collect(); sorted_networks.sort_by(|a, b| { let a_connected = is_current_network(a, current_ssid, current_band); let b_connected = is_current_network(b, current_ssid, current_band); match (a_connected, b_connected) { (true, false) => std::cmp::Ordering::Less, (false, true) => std::cmp::Ordering::Greater, _ => b.strength.unwrap_or(0).cmp(&a.strength.unwrap_or(0)), } }); for net in sorted_networks { let row = ListBoxRow::new(); let hbox = Box::new(Orientation::Horizontal, 6); row.add_css_class("network-selection"); if is_current_network(&net, current_ssid, current_band) { row.add_css_class("connected"); } let display_name = match net.frequency.and_then(crate::ui::freq_to_band) { Some(band) => format!("{} ({band})", net.ssid), None => net.ssid.clone(), }; hbox.append(&Label::new(Some(&display_name))); if is_current_network(&net, current_ssid, current_band) { let connected_label = Label::new(Some("Connected")); connected_label.add_css_class("connected-label"); hbox.append(&connected_label); } let spacer = Box::new(Orientation::Horizontal, 0); spacer.set_hexpand(true); hbox.append(&spacer); if let Some(s) = net.strength { let icon_name = if net.secured { "network-wireless-encrypted-symbolic" } else { "network-wireless-signal-excellent-symbolic" }; let image = Image::from_icon_name(icon_name); if net.secured { image.add_css_class("wifi-secure"); } else { image.add_css_class("wifi-open"); } let strength_label = Label::new(Some(&format!("{s}%"))); hbox.append(&image); hbox.append(&strength_label); if s >= conn_threshold { strength_label.add_css_class("network-good"); } else if s > 65 { strength_label.add_css_class("network-okay"); } else { strength_label.add_css_class("network-poor"); } } let arrow = Image::from_icon_name("go-next-symbolic"); arrow.set_halign(Align::End); arrow.add_css_class("network-arrow"); arrow.set_cursor_from_name(Some("pointer")); hbox.append(&arrow); row.set_child(Some(&hbox)); let controller = NetworkRowController::new( row.clone(), arrow.clone(), ctx.clone(), net.clone(), ctx.details_page.clone(), ); controller.attach(); list.append(&row); } list } fn is_current_network( net: &models::Network, current_ssid: Option<&str>, current_band: Option<&str>, ) -> bool { let ssid = match current_ssid { Some(s) => s, None => return false, }; if net.ssid != ssid { return false; } if let Some(band) = current_band { let net_band = net.frequency.and_then(crate::ui::freq_to_band); return net_band == Some(band); } true }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/ui/wired_page.rs
nmrs-gui/src/ui/wired_page.rs
use glib::clone; use gtk::prelude::*; use gtk::{Align, Box, Button, Image, Label, Orientation}; use nmrs::models::Device; pub struct WiredPage { root: gtk::Box, title: gtk::Label, state_label: gtk::Label, interface: gtk::Label, device_type: gtk::Label, mac_address: gtk::Label, driver: gtk::Label, managed: gtk::Label, } impl WiredPage { pub fn new(stack: &gtk::Stack) -> Self { let root = Box::new(Orientation::Vertical, 12); root.add_css_class("network-page"); let back = Button::with_label("← Back"); back.add_css_class("back-button"); back.set_halign(Align::Start); back.set_cursor_from_name(Some("pointer")); back.connect_clicked(clone![ #[weak] stack, move |_| { stack.set_visible_child_name("networks"); } ]); root.append(&back); let header = Box::new(Orientation::Horizontal, 6); let icon = Image::from_icon_name("network-wired-symbolic"); icon.set_pixel_size(24); let title = Label::new(None); title.add_css_class("network-title"); let spacer = Box::new(Orientation::Horizontal, 0); spacer.set_hexpand(true); header.append(&icon); header.append(&title); header.append(&spacer); root.append(&header); let basic_box = Box::new(Orientation::Vertical, 6); basic_box.add_css_class("basic-section"); let basic_header = Label::new(Some("Basic")); basic_header.add_css_class("section-header"); basic_box.append(&basic_header); let state_label = Label::new(None); let interface = Label::new(None); Self::add_row(&basic_box, "Connection State", &state_label); Self::add_row(&basic_box, "Interface", &interface); root.append(&basic_box); let advanced_box = Box::new(Orientation::Vertical, 8); advanced_box.add_css_class("advanced-section"); let advanced_header = Label::new(Some("Advanced")); advanced_header.add_css_class("section-header"); advanced_box.append(&advanced_header); let device_type = Label::new(None); let mac_address = Label::new(None); let driver = Label::new(None); let managed = Label::new(None); Self::add_row(&advanced_box, "Device Type", &device_type); Self::add_row(&advanced_box, "MAC Address", &mac_address); Self::add_row(&advanced_box, "Driver", &driver); Self::add_row(&advanced_box, "Managed", &managed); root.append(&advanced_box); Self { root, title, state_label, interface, device_type, mac_address, driver, managed, } } fn add_row(parent: &gtk::Box, key_text: &str, val_widget: &gtk::Label) { let row = Box::new(Orientation::Vertical, 3); row.set_halign(Align::Start); let key = Label::new(Some(key_text)); key.add_css_class("info-label"); key.set_halign(Align::Start); val_widget.add_css_class("info-value"); val_widget.set_halign(Align::Start); row.append(&key); row.append(val_widget); parent.append(&row); } pub fn update(&self, device: &Device) { self.title .set_text(&format!("Wired Device: {}", device.interface)); self.state_label.set_text(&format!("{}", device.state)); self.interface.set_text(&device.interface); self.device_type .set_text(&format!("{}", device.device_type)); self.mac_address.set_text(&device.identity.current_mac); self.driver .set_text(&device.driver.clone().unwrap_or_else(|| "-".into())); self.managed.set_text( device .managed .map(|m| if m { "Yes" } else { "No" }) .unwrap_or("-"), ); } pub fn widget(&self) -> &gtk::Box { &self.root } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/ui/connect.rs
nmrs-gui/src/ui/connect.rs
use glib::Propagation; use gtk::{ prelude::*, ApplicationWindow, Box as GtkBox, Button, CheckButton, Dialog, Entry, EventControllerKey, FileChooserAction, FileChooserDialog, Label, Orientation, ResponseType, }; use log::{debug, error}; use nmrs::{ models::{EapMethod, EapOptions, Phase2, WifiSecurity}, NetworkManager, }; use std::rc::Rc; pub fn connect_modal( nm: Rc<NetworkManager>, parent: &ApplicationWindow, ssid: &str, is_eap: bool, on_connection_success: Rc<dyn Fn()>, ) { let ssid_owned = ssid.to_string(); let parent_weak = parent.downgrade(); glib::MainContext::default().spawn_local(async move { if let Some(current) = nm.current_ssid().await { if current == ssid_owned { debug!("Already connected to {current}, skipping modal"); return; } } if let Some(parent) = parent_weak.upgrade() { draw_connect_modal(nm, &parent, &ssid_owned, is_eap, on_connection_success); } }); } fn draw_connect_modal( nm: Rc<NetworkManager>, parent: &ApplicationWindow, ssid: &str, is_eap: bool, on_connection_success: Rc<dyn Fn()>, ) { let dialog = Dialog::new(); dialog.set_title(Some("Connect to Network")); dialog.set_transient_for(Some(parent)); dialog.set_modal(true); dialog.add_css_class("diag-buttons"); let content_area = dialog.content_area(); let vbox = GtkBox::new(Orientation::Vertical, 8); vbox.set_margin_top(32); vbox.set_margin_bottom(32); vbox.set_margin_start(48); vbox.set_margin_end(48); let user_entry = if is_eap { let user_label = Label::new(Some("Username:")); let user_entry = Entry::new(); user_entry.add_css_class("pw-entry"); user_entry.set_placeholder_text(Some("email, username, id...")); vbox.append(&user_label); vbox.append(&user_entry); Some(user_entry) } else { None }; let label = Label::new(Some("Password:")); let entry = Entry::new(); entry.add_css_class("pw-entry"); entry.set_placeholder_text(Some("Password")); entry.set_visibility(false); vbox.append(&label); vbox.append(&entry); let (cert_entry, use_system_certs, browse_btn) = if is_eap { let cert_label = Label::new(Some("CA Certificate (optional):")); cert_label.set_margin_top(8); let cert_entry = Entry::new(); cert_entry.add_css_class("pw-entry"); cert_entry.set_placeholder_text(Some("/path/to/ca-cert.pem")); let cert_hbox = GtkBox::new(Orientation::Horizontal, 8); let browse_btn = Button::with_label("Browse..."); browse_btn.add_css_class("cert-browse-btn"); cert_hbox.append(&cert_entry); cert_hbox.append(&browse_btn); vbox.append(&cert_label); vbox.append(&cert_hbox); let system_certs_check = CheckButton::with_label("Use system CA certificates"); system_certs_check.set_active(true); system_certs_check.set_margin_top(4); vbox.append(&system_certs_check); (Some(cert_entry), Some(system_certs_check), Some(browse_btn)) } else { (None, None, None) }; content_area.append(&vbox); let dialog_rc = Rc::new(dialog); let ssid_owned = ssid.to_string(); let user_entry_clone = user_entry.clone(); let status_label = Label::new(Some("")); status_label.add_css_class("status-label"); vbox.append(&status_label); if let Some(browse_btn) = browse_btn { let cert_entry_for_browse = cert_entry.clone(); let dialog_weak = dialog_rc.downgrade(); browse_btn.connect_clicked(move |_| { if let Some(parent_dialog) = dialog_weak.upgrade() { let file_dialog = FileChooserDialog::new( Some("Select CA Certificate"), Some(&parent_dialog), FileChooserAction::Open, &[ ("Cancel", ResponseType::Cancel), ("Open", ResponseType::Accept), ], ); let cert_entry = cert_entry_for_browse.clone(); file_dialog.connect_response(move |dialog, response| { if response == ResponseType::Accept { if let Some(file) = dialog.file() { if let Some(path) = file.path() { cert_entry .as_ref() .unwrap() .set_text(&path.to_string_lossy()); } } } dialog.close(); }); file_dialog.show(); } }); } { let dialog_rc = dialog_rc.clone(); let status_label = status_label.clone(); let refresh_callback = on_connection_success.clone(); let nm = nm.clone(); let cert_entry_clone = cert_entry.clone(); let use_system_certs_clone = use_system_certs.clone(); entry.connect_activate(move |entry| { let pwd = entry.text().to_string(); let username = user_entry_clone .as_ref() .map(|e| e.text().to_string()) .unwrap_or_default(); let cert_path = cert_entry_clone.as_ref().and_then(|e| { let text = e.text().to_string(); if text.trim().is_empty() { None } else { Some(text) } }); let use_system_ca = use_system_certs_clone .as_ref() .map(|cb| cb.is_active()) .unwrap_or(true); let ssid = ssid_owned.clone(); let dialog = dialog_rc.clone(); let status = status_label.clone(); let entry = entry.clone(); let user_entry = user_entry_clone.clone(); let on_success = refresh_callback.clone(); let nm = nm.clone(); entry.set_sensitive(false); if let Some(ref user_entry) = user_entry { user_entry.set_sensitive(false); } status.set_text("Connecting..."); glib::MainContext::default().spawn_local(async move { let creds = if is_eap { WifiSecurity::WpaEap { opts: EapOptions { identity: username, password: pwd, anonymous_identity: None, domain_suffix_match: None, ca_cert_path: cert_path, system_ca_certs: use_system_ca, method: EapMethod::Peap, phase2: Phase2::Mschapv2, }, } } else { WifiSecurity::WpaPsk { psk: pwd } }; debug!("Calling nm.connect() for '{ssid}'"); match nm.connect(&ssid, creds).await { Ok(_) => { debug!("nm.connect() succeeded!"); status.set_text("✓ Connected!"); on_success(); glib::timeout_future_seconds(1).await; dialog.close(); } Err(err) => { error!("nm.connect() failed: {err}"); let err_str = err.to_string().to_lowercase(); if err_str.contains("authentication") || err_str.contains("supplicant") || err_str.contains("password") || err_str.contains("psk") || err_str.contains("wrong") { status.set_text("Wrong password, try again"); entry.set_text(""); entry.grab_focus(); } else { status.set_text(&format!("✗ Failed: {err}")); } entry.set_sensitive(true); if let Some(ref user_entry) = user_entry { user_entry.set_sensitive(true); } } } }); }); } { let dialog_rc = dialog_rc.clone(); let key_controller = EventControllerKey::new(); key_controller.connect_key_pressed(move |_, key, _, _| { if key == gtk::gdk::Key::Escape { dialog_rc.close(); Propagation::Stop } else { Propagation::Proceed } }); entry.add_controller(key_controller); } dialog_rc.show(); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/ui/header.rs
nmrs-gui/src/ui/header.rs
use glib::clone; use gtk::prelude::*; use gtk::STYLE_PROVIDER_PRIORITY_USER; use gtk::{glib, Align, Box as GtkBox, HeaderBar, Label, ListBox, Orientation, Switch}; use std::cell::Cell; use std::collections::HashSet; use std::rc::Rc; use nmrs::models; use crate::ui::networks; use crate::ui::networks::NetworksContext; use crate::ui::wired_devices; pub struct ThemeDef { pub key: &'static str, pub name: &'static str, pub css: &'static str, } pub static THEMES: &[ThemeDef] = &[ ThemeDef { key: "gruvbox", name: "Gruvbox", css: include_str!("../themes/gruvbox.css"), }, ThemeDef { key: "nord", name: "Nord", css: include_str!("../themes/nord.css"), }, ThemeDef { key: "dracula", name: "Dracula", css: include_str!("../themes/dracula.css"), }, ThemeDef { key: "catppuccin", name: "Catppuccin", css: include_str!("../themes/catppuccin.css"), }, ThemeDef { key: "tokyo", name: "Tokyo Night", css: include_str!("../themes/tokyo.css"), }, ]; pub fn build_header( ctx: Rc<NetworksContext>, list_container: &GtkBox, is_scanning: Rc<Cell<bool>>, window: &gtk::ApplicationWindow, ) -> HeaderBar { let header = HeaderBar::new(); header.set_show_title_buttons(false); let list_container = list_container.clone(); let wifi_box = GtkBox::new(Orientation::Horizontal, 6); let wifi_label = Label::new(Some("Wi-Fi")); wifi_label.set_halign(gtk::Align::Start); wifi_label.add_css_class("wifi-label"); let names: Vec<&str> = THEMES.iter().map(|t| t.name).collect(); let dropdown = gtk::DropDown::from_strings(&names); if let Some(saved) = crate::theme_config::load_theme() { if let Some(idx) = THEMES.iter().position(|t| t.key == saved.as_str()) { dropdown.set_selected(idx as u32); } } dropdown.set_valign(gtk::Align::Center); dropdown.add_css_class("dropdown"); let window_weak = window.downgrade(); dropdown.connect_selected_notify(move |dd| { let idx = dd.selected() as usize; if idx >= THEMES.len() { return; } let theme = &THEMES[idx]; if let Some(window) = window_weak.upgrade() { let provider = gtk::CssProvider::new(); provider.load_from_data(theme.css); let display = gtk::prelude::RootExt::display(&window); gtk::style_context_add_provider_for_display( &display, &provider, STYLE_PROVIDER_PRIORITY_USER, ); crate::theme_config::save_theme(theme.key); } }); wifi_box.append(&wifi_label); wifi_box.append(&dropdown); header.pack_start(&wifi_box); let refresh_btn = gtk::Button::from_icon_name("view-refresh-symbolic"); refresh_btn.add_css_class("refresh-btn"); refresh_btn.set_tooltip_text(Some("Refresh networks and devices")); header.pack_end(&refresh_btn); refresh_btn.connect_clicked(clone!( #[weak] list_container, #[strong] ctx, #[strong] is_scanning, move |_| { let ctx = ctx.clone(); let list_container = list_container.clone(); let is_scanning = is_scanning.clone(); glib::MainContext::default().spawn_local(async move { refresh_networks(ctx, &list_container, &is_scanning).await; }); } )); let theme_btn = gtk::Button::new(); theme_btn.add_css_class("theme-toggle-btn"); theme_btn.set_valign(gtk::Align::Center); theme_btn.set_has_frame(false); let is_light = window.has_css_class("light-theme"); let initial_icon = if is_light { "weather-clear-night-symbolic" } else { "weather-clear-symbolic" }; theme_btn.set_icon_name(initial_icon); let window_weak = window.downgrade(); theme_btn.connect_clicked(move |btn| { if let Some(window) = window_weak.upgrade() { let is_light = window.has_css_class("light-theme"); if is_light { window.remove_css_class("light-theme"); window.add_css_class("dark-theme"); btn.set_icon_name("weather-clear-symbolic"); crate::theme_config::save_theme("light"); } else { window.remove_css_class("dark-theme"); window.add_css_class("light-theme"); btn.set_icon_name("weather-clear-night-symbolic"); crate::theme_config::save_theme("dark"); } } }); header.pack_end(&theme_btn); let wifi_switch = Switch::new(); wifi_switch.set_valign(gtk::Align::Center); header.pack_end(&wifi_switch); wifi_switch.set_size_request(24, 24); header.pack_end(&ctx.status); { let list_container = list_container.clone(); let wifi_switch = wifi_switch.clone(); let ctx = ctx.clone(); let is_scanning = is_scanning.clone(); glib::MainContext::default().spawn_local(async move { ctx.stack.set_visible_child_name("loading"); clear_children(&list_container); match ctx.nm.wifi_enabled().await { Ok(enabled) => { wifi_switch.set_active(enabled); if enabled { refresh_networks(ctx, &list_container, &is_scanning).await; } } Err(err) => { ctx.status .set_text(&format!("Error fetching networks: {err}")); } } }) }; { let ctx = ctx.clone(); wifi_switch.connect_active_notify(move |sw| { let ctx = ctx.clone(); let list_container = list_container.clone(); let sw = sw.clone(); let is_scanning = is_scanning.clone(); glib::MainContext::default().spawn_local(async move { clear_children(&list_container); if let Err(err) = ctx.nm.set_wifi_enabled(sw.is_active()).await { ctx.status.set_text(&format!("Error setting Wi-Fi: {err}")); return; } if sw.is_active() { if ctx.nm.wait_for_wifi_ready().await.is_ok() { refresh_networks(ctx, &list_container, &is_scanning).await; } else { ctx.status.set_text("Wi-Fi failed to initialize"); } } }); }); } header } pub async fn refresh_networks( ctx: Rc<NetworksContext>, list_container: &GtkBox, is_scanning: &Rc<Cell<bool>>, ) { if is_scanning.get() { ctx.status.set_text("Scan already in progress"); return; } is_scanning.set(true); clear_children(list_container); ctx.status.set_text("Scanning..."); // Fetch wired devices first match ctx.nm.list_wired_devices().await { Ok(wired_devices) => { // eprintln!("Found {} wired devices total", wired_devices.len()); let available_devices: Vec<_> = wired_devices .into_iter() .filter(|dev| { let show = matches!( dev.state, models::DeviceState::Activated | models::DeviceState::Disconnected | models::DeviceState::Prepare | models::DeviceState::Config ); /* eprintln!( " - {} ({}): {} -> {}", dev.interface, dev.device_type, dev.state, if show { "SHOW" } else { "HIDE" } ); */ show }) .collect(); /* eprintln!( "Showing {} available wired devices", available_devices.len() ); */ if !available_devices.is_empty() { let wired_header = Label::new(Some("Wired")); wired_header.add_css_class("section-header"); wired_header.add_css_class("wired-section-header"); wired_header.set_halign(Align::Start); wired_header.set_margin_top(8); wired_header.set_margin_bottom(4); wired_header.set_margin_start(12); list_container.append(&wired_header); // Create a wired devices context let wired_ctx = wired_devices::WiredDevicesContext { nm: ctx.nm.clone(), on_success: ctx.on_success.clone(), status: ctx.status.clone(), stack: ctx.stack.clone(), parent_window: ctx.parent_window.clone(), }; let wired_ctx = Rc::new(wired_ctx); let wired_list = wired_devices::wired_devices_view( wired_ctx, &available_devices, ctx.wired_details_page.clone(), ); wired_list.add_css_class("wired-devices-list"); list_container.append(&wired_list); let separator = gtk::Separator::new(Orientation::Horizontal); separator.add_css_class("device-separator"); separator.set_margin_top(12); separator.set_margin_bottom(12); list_container.append(&separator); } } Err(e) => { eprintln!("Failed to list wired devices: {}", e); } } let wireless_header = Label::new(Some("Wireless")); wireless_header.add_css_class("section-header"); wireless_header.add_css_class("wireless-section-header"); wireless_header.set_halign(Align::Start); wireless_header.set_margin_top(8); wireless_header.set_margin_bottom(4); wireless_header.set_margin_start(12); list_container.append(&wireless_header); if let Err(err) = ctx.nm.scan_networks().await { ctx.status.set_text(&format!("Scan failed: {err}")); is_scanning.set(false); return; } let mut last_len = 0; for _ in 0..5 { let nets = ctx.nm.list_networks().await.unwrap_or_default(); if nets.len() == last_len && last_len > 0 { break; } last_len = nets.len(); glib::timeout_future_seconds(1).await; } match ctx.nm.list_networks().await { Ok(mut nets) => { let current_conn = ctx.nm.current_connection_info().await; let (current_ssid, current_band) = if let Some((ssid, freq)) = current_conn { let ssid_str = ssid.clone(); let band: Option<String> = freq .and_then(crate::ui::freq_to_band) .map(|s| s.to_string()); (Some(ssid_str), band) } else { (None, None) }; nets.sort_by(|a, b| b.strength.unwrap_or(0).cmp(&a.strength.unwrap_or(0))); let mut seen_combinations = HashSet::new(); nets.retain(|net| { let band = net.frequency.and_then(crate::ui::freq_to_band); let key = (net.ssid.clone(), band); seen_combinations.insert(key) }); ctx.status.set_text(""); let list: ListBox = networks::networks_view( ctx.clone(), &nets, current_ssid.as_deref(), current_band.as_deref(), ); list_container.append(&list); ctx.stack.set_visible_child_name("networks"); } Err(err) => ctx .status .set_text(&format!("Error fetching networks: {err}")), } is_scanning.set(false); } pub fn clear_children(container: &gtk::Box) { let mut child = container.first_child(); while let Some(widget) = child { child = widget.next_sibling(); container.remove(&widget); } } /// Refresh the network list WITHOUT triggering a new scan. /// This is useful for live updates when the network list changes /// (e.g., wired device state changes, AP added/removed). pub async fn refresh_networks_no_scan( ctx: Rc<NetworksContext>, list_container: &GtkBox, is_scanning: &Rc<Cell<bool>>, ) { if is_scanning.get() { // Don't interfere with an ongoing scan or refresh return; } // Set flag to prevent concurrent refreshes is_scanning.set(true); clear_children(list_container); // Fetch wired devices first if let Ok(wired_devices) = ctx.nm.list_wired_devices().await { // eprintln!("Found {} wired devices total", wired_devices.len()); // Filter out unavailable devices to reduce clutter let available_devices: Vec<_> = wired_devices .into_iter() .filter(|dev| { let show = matches!( dev.state, models::DeviceState::Activated | models::DeviceState::Disconnected | models::DeviceState::Prepare | models::DeviceState::Config | models::DeviceState::Unmanaged ); /* eprintln!( " - {} ({}): {} -> {}", dev.interface, dev.device_type, dev.state, if show { "SHOW" } else { "HIDE" } ); */ show }) .collect(); /* eprintln!( "Showing {} available wired devices", available_devices.len() );*/ if !available_devices.is_empty() { let wired_header = Label::new(Some("Wired")); wired_header.add_css_class("section-header"); wired_header.add_css_class("wired-section-header"); wired_header.set_halign(Align::Start); wired_header.set_margin_top(8); wired_header.set_margin_bottom(4); wired_header.set_margin_start(12); list_container.append(&wired_header); let wired_ctx = wired_devices::WiredDevicesContext { nm: ctx.nm.clone(), on_success: ctx.on_success.clone(), status: ctx.status.clone(), stack: ctx.stack.clone(), parent_window: ctx.parent_window.clone(), }; let wired_ctx = Rc::new(wired_ctx); let wired_list = wired_devices::wired_devices_view( wired_ctx, &available_devices, ctx.wired_details_page.clone(), ); wired_list.add_css_class("wired-devices-list"); list_container.append(&wired_list); let separator = gtk::Separator::new(Orientation::Horizontal); separator.add_css_class("device-separator"); separator.set_margin_top(12); separator.set_margin_bottom(12); list_container.append(&separator); } } let wireless_header = Label::new(Some("Wireless")); wireless_header.add_css_class("section-header"); wireless_header.add_css_class("wireless-section-header"); wireless_header.set_halign(Align::Start); wireless_header.set_margin_top(8); wireless_header.set_margin_bottom(4); wireless_header.set_margin_start(12); list_container.append(&wireless_header); match ctx.nm.list_networks().await { Ok(mut nets) => { let current_conn = ctx.nm.current_connection_info().await; let (current_ssid, current_band) = if let Some((ssid, freq)) = current_conn { let ssid_str = ssid.clone(); let band: Option<String> = freq .and_then(crate::ui::freq_to_band) .map(|s| s.to_string()); (Some(ssid_str), band) } else { (None, None) }; nets.sort_by(|a, b| b.strength.unwrap_or(0).cmp(&a.strength.unwrap_or(0))); let mut seen_combinations = HashSet::new(); nets.retain(|net| { let band = net.frequency.and_then(crate::ui::freq_to_band); let key = (net.ssid.clone(), band); seen_combinations.insert(key) }); let list: ListBox = networks::networks_view( ctx.clone(), &nets, current_ssid.as_deref(), current_band.as_deref(), ); list_container.append(&list); ctx.stack.set_visible_child_name("networks"); } Err(err) => { ctx.status .set_text(&format!("Error fetching networks: {err}")); } } // Release the lock is_scanning.set(false); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/ui/wired_devices.rs
nmrs-gui/src/ui/wired_devices.rs
use gtk::prelude::*; use gtk::Align; use gtk::GestureClick; use gtk::{Box, Image, Label, ListBox, ListBoxRow, Orientation}; use nmrs::{models, NetworkManager}; use std::rc::Rc; use crate::ui::wired_page::WiredPage; pub struct WiredDeviceRowController { pub row: gtk::ListBoxRow, pub arrow: gtk::Image, pub ctx: Rc<WiredDevicesContext>, pub device: models::Device, pub details_page: Rc<WiredPage>, } pub struct WiredDevicesContext { pub nm: Rc<NetworkManager>, pub on_success: Rc<dyn Fn()>, pub status: Label, pub stack: gtk::Stack, pub parent_window: gtk::ApplicationWindow, } impl WiredDeviceRowController { pub fn new( row: gtk::ListBoxRow, arrow: gtk::Image, ctx: Rc<WiredDevicesContext>, device: models::Device, details_page: Rc<WiredPage>, ) -> Self { Self { row, arrow, ctx, device, details_page, } } pub fn attach(&self) { self.attach_arrow(); self.attach_row_double(); } fn attach_arrow(&self) { let click = GestureClick::new(); let device = self.device.clone(); let stack = self.ctx.stack.clone(); let page = self.details_page.clone(); click.connect_pressed(move |_, _, _, _| { let device_c = device.clone(); let stack_c = stack.clone(); let page_c = page.clone(); glib::MainContext::default().spawn_local(async move { page_c.update(&device_c); stack_c.set_visible_child_name("wired-details"); }); }); self.arrow.add_controller(click); } fn attach_row_double(&self) { let click = GestureClick::new(); let ctx = self.ctx.clone(); let device = self.device.clone(); let interface = device.interface.clone(); let status = ctx.status.clone(); let window = ctx.parent_window.clone(); let on_success = ctx.on_success.clone(); click.connect_pressed(move |_, n, _, _| { if n != 2 { return; } status.set_text(&format!("Connecting to {interface}...")); let nm_c = ctx.nm.clone(); let status_c = status.clone(); let window_c = window.clone(); let on_success_c = on_success.clone(); glib::MainContext::default().spawn_local(async move { window_c.set_sensitive(false); match nm_c.connect_wired().await { Ok(_) => { status_c.set_text(""); on_success_c(); } Err(e) => status_c.set_text(&format!("Failed to connect: {e}")), } window_c.set_sensitive(true); status_c.set_text(""); }); }); self.row.add_controller(click); } } pub fn wired_devices_view( ctx: Rc<WiredDevicesContext>, devices: &[models::Device], details_page: Rc<WiredPage>, ) -> ListBox { let list = ListBox::new(); for device in devices { let row = ListBoxRow::new(); let hbox = Box::new(Orientation::Horizontal, 6); row.add_css_class("network-selection"); if device.state == models::DeviceState::Activated { row.add_css_class("connected"); } let display_name = format!("{} ({})", device.interface, device.device_type); hbox.append(&Label::new(Some(&display_name))); if device.state == models::DeviceState::Activated { let connected_label = Label::new(Some("Connected")); connected_label.add_css_class("connected-label"); hbox.append(&connected_label); } let spacer = Box::new(Orientation::Horizontal, 0); spacer.set_hexpand(true); hbox.append(&spacer); // Only show state for meaningful states (not transitional ones) let state_text = match device.state { models::DeviceState::Activated => Some("Connected"), models::DeviceState::Disconnected => Some("Disconnected"), models::DeviceState::Unavailable => Some("Unavailable"), models::DeviceState::Failed => Some("Failed"), // Hide transitional states (Unmanaged, Prepare, Config, etc) _ => None, }; if let Some(text) = state_text { let state_label = Label::new(Some(text)); state_label.add_css_class(match device.state { models::DeviceState::Activated => "network-good", models::DeviceState::Unavailable | models::DeviceState::Disconnected | models::DeviceState::Failed => "network-poor", _ => "network-okay", }); hbox.append(&state_label); } let icon = Image::from_icon_name("network-wired-symbolic"); icon.add_css_class("wired-icon"); hbox.append(&icon); let arrow = Image::from_icon_name("go-next-symbolic"); arrow.set_halign(Align::End); arrow.add_css_class("network-arrow"); arrow.set_cursor_from_name(Some("pointer")); hbox.append(&arrow); row.set_child(Some(&hbox)); let controller = WiredDeviceRowController::new( row.clone(), arrow.clone(), ctx.clone(), device.clone(), details_page.clone(), ); controller.attach(); list.append(&row); } list }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/ui/mod.rs
nmrs-gui/src/ui/mod.rs
pub mod connect; pub mod header; pub mod network_page; pub mod networks; pub mod wired_devices; pub mod wired_page; use gtk::prelude::*; use gtk::{ Application, ApplicationWindow, Box as GtkBox, Label, Orientation, ScrolledWindow, Spinner, Stack, STYLE_PROVIDER_PRIORITY_USER, }; use std::cell::Cell; use std::rc::Rc; use crate::ui::header::THEMES; type Callback = Rc<dyn Fn()>; type CallbackCell = Rc<std::cell::RefCell<Option<Callback>>>; pub fn freq_to_band(freq: u32) -> Option<&'static str> { match freq { 2400..=2500 => Some("2.4GHz"), 5150..=5925 => Some("5GHz"), 5926..=7125 => Some("6GHz"), _ => None, } } pub fn build_ui(app: &Application) { let win = ApplicationWindow::new(app); win.set_title(Some("")); win.set_default_size(100, 600); if let Some(key) = crate::theme_config::load_theme() { if let Some(theme) = THEMES.iter().find(|t| t.key == key.as_str()) { let provider = gtk::CssProvider::new(); provider.load_from_data(theme.css); let display = gtk::prelude::RootExt::display(&win); gtk::style_context_add_provider_for_display( &display, &provider, STYLE_PROVIDER_PRIORITY_USER, ); win.add_css_class("dark-theme"); } } let vbox = GtkBox::new(Orientation::Vertical, 0); let status = Label::new(None); let list_container = GtkBox::new(Orientation::Vertical, 0); let stack = Stack::new(); let is_scanning = Rc::new(Cell::new(false)); let spinner = Spinner::new(); spinner.set_halign(gtk::Align::Center); spinner.set_valign(gtk::Align::Center); spinner.set_property("width-request", 24i32); spinner.set_property("height-request", 24i32); spinner.add_css_class("loading-spinner"); spinner.start(); stack.add_named(&spinner, Some("loading")); stack.set_visible_child_name("loading"); let status_clone = status.clone(); let list_container_clone = list_container.clone(); let stack_clone = stack.clone(); let win_clone = win.clone(); let is_scanning_clone = is_scanning.clone(); let vbox_clone = vbox.clone(); glib::MainContext::default().spawn_local(async move { match nmrs::NetworkManager::new().await { Ok(nm) => { let nm = Rc::new(nm); let details_page = Rc::new(network_page::NetworkPage::new(&stack_clone)); let details_scroller = ScrolledWindow::new(); details_scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic); details_scroller.set_child(Some(details_page.widget())); stack_clone.add_named(&details_scroller, Some("details")); let wired_details_page = Rc::new(wired_page::WiredPage::new(&stack_clone)); let wired_details_scroller = ScrolledWindow::new(); wired_details_scroller .set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic); wired_details_scroller.set_child(Some(wired_details_page.widget())); stack_clone.add_named(&wired_details_scroller, Some("wired-details")); let on_success: Rc<dyn Fn()> = { let list_container = list_container_clone.clone(); let is_scanning = is_scanning_clone.clone(); let nm = nm.clone(); let status = status_clone.clone(); let stack = stack_clone.clone(); let parent_window = win_clone.clone(); let details_page = details_page.clone(); let wired_details_page = wired_details_page.clone(); let on_success_cell: CallbackCell = Rc::new(std::cell::RefCell::new(None)); let on_success_cell_clone = on_success_cell.clone(); let callback = Rc::new(move || { let list_container = list_container.clone(); let is_scanning = is_scanning.clone(); let nm = nm.clone(); let status = status.clone(); let stack = stack.clone(); let parent_window = parent_window.clone(); let on_success_cell = on_success_cell.clone(); let details_page = details_page.clone(); let wired_details_page = wired_details_page.clone(); glib::MainContext::default().spawn_local(async move { let callback = on_success_cell.borrow().as_ref().map(|cb| cb.clone()); let refresh_ctx = Rc::new(networks::NetworksContext { nm, on_success: callback.unwrap_or_else(|| Rc::new(|| {})), status, stack, parent_window, details_page: details_page.clone(), wired_details_page: wired_details_page.clone(), }); header::refresh_networks(refresh_ctx, &list_container, &is_scanning) .await; }); }) as Rc<dyn Fn()>; *on_success_cell_clone.borrow_mut() = Some(callback.clone()); callback }; let ctx = Rc::new(networks::NetworksContext { nm: nm.clone(), on_success: on_success.clone(), status: status_clone.clone(), stack: stack_clone.clone(), parent_window: win_clone.clone(), details_page: details_page.clone(), wired_details_page, }); details_page.set_on_success(on_success); let header = header::build_header( ctx.clone(), &list_container_clone, is_scanning_clone.clone(), &win_clone, ); vbox_clone.prepend(&header); { let nm_device_monitor = nm.clone(); let list_container_device = list_container_clone.clone(); let is_scanning_device = is_scanning_clone.clone(); let ctx_device = ctx.clone(); let pending_device_refresh = Rc::new(std::cell::RefCell::new(false)); glib::MainContext::default().spawn_local(async move { loop { let ctx_device_clone = ctx_device.clone(); let list_container_clone = list_container_device.clone(); let is_scanning_clone = is_scanning_device.clone(); let pending_device_refresh_clone = pending_device_refresh.clone(); let result = nm_device_monitor .monitor_device_changes(move || { let ctx = ctx_device_clone.clone(); let list_container = list_container_clone.clone(); let is_scanning = is_scanning_clone.clone(); let pending_refresh = pending_device_refresh_clone.clone(); if pending_refresh.replace(true) { return; } glib::MainContext::default().spawn_local(async move { glib::timeout_future_seconds(3).await; *pending_refresh.borrow_mut() = false; let current_page = ctx.stack.visible_child_name(); let on_networks_page = current_page.as_deref() == Some("networks"); if !is_scanning.get() && on_networks_page { header::refresh_networks_no_scan( ctx, &list_container, &is_scanning, ) .await; } }); }) .await; if let Err(e) = result { eprintln!("Device monitoring error: {}, restarting in 5s...", e) } glib::timeout_future_seconds(5).await; } }); } { let nm_network_monitor = nm.clone(); let list_container_network = list_container_clone.clone(); let is_scanning_network = is_scanning_clone.clone(); let ctx_network = ctx.clone(); let pending_network_refresh = Rc::new(std::cell::RefCell::new(false)); glib::MainContext::default().spawn_local(async move { loop { let ctx_network_clone = ctx_network.clone(); let list_container_clone = list_container_network.clone(); let is_scanning_clone = is_scanning_network.clone(); let pending_network_refresh_clone = pending_network_refresh.clone(); let result = nm_network_monitor .monitor_network_changes(move || { let ctx = ctx_network_clone.clone(); let list_container = list_container_clone.clone(); let is_scanning = is_scanning_clone.clone(); let pending_refresh = pending_network_refresh_clone.clone(); if pending_refresh.replace(true) { return; } glib::MainContext::default().spawn_local(async move { glib::timeout_future_seconds(8).await; *pending_refresh.borrow_mut() = false; let current_page = ctx.stack.visible_child_name(); let on_networks_page = current_page.as_deref() == Some("networks"); if !is_scanning.get() && on_networks_page { header::refresh_networks_no_scan( ctx, &list_container, &is_scanning, ) .await; } }); }) .await; if let Err(e) = result { eprintln!("Network monitoring error: {}, restarting in 5s...", e) } glib::timeout_future_seconds(5).await; } }); } } Err(err) => { status_clone.set_text(&format!("Failed to initialize: {err}")); } } }); let networks_scroller = ScrolledWindow::new(); networks_scroller.set_vexpand(true); networks_scroller.set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic); networks_scroller.set_child(Some(&list_container)); stack.add_named(&networks_scroller, Some("networks")); stack.set_vexpand(true); vbox.append(&stack); win.set_child(Some(&vbox)); win.show(); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false