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 |
|---|---|---|---|---|---|---|---|---|
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/rgsw/mod.rs | src/rgsw/mod.rs | mod keygen;
mod runtime;
pub(crate) use keygen::*;
pub(crate) use runtime::*;
#[cfg(test)]
pub(crate) mod tests {
use std::{fmt::Debug, marker::PhantomData, vec};
use itertools::{izip, Itertools};
use rand::{thread_rng, Rng};
use crate::{
backend::{GetModulus, ModInit, ModularOpsU64, Modulus, VectorOps},
decomposer::{Decomposer, DefaultDecomposer, RlweDecomposer},
ntt::{Ntt, NttBackendU64, NttInit},
random::{DefaultSecureRng, NewWithSeed, RandomFillUniformInModulus},
rgsw::{
rlwe_auto_scratch_rows, rlwe_auto_shoup, rlwe_by_rgsw_shoup, rlwe_x_rgsw_scratch_rows,
RgswCiphertextRef, RlweCiphertextMutRef, RlweKskRef, RuntimeScratchMutRef,
},
utils::{
fill_random_ternary_secret_with_hamming_weight, generate_prime, negacyclic_mul,
tests::Stats, ToShoup, TryConvertFrom1, WithLocal,
},
Matrix, MatrixEntity, MatrixMut, Row, RowEntity, RowMut,
};
use super::{
keygen::{
decrypt_rlwe, generate_auto_map, rlwe_public_key, secret_key_encrypt_rgsw,
seeded_auto_key_gen, seeded_secret_key_encrypt_rlwe,
},
rgsw_x_rgsw_scratch_rows,
runtime::{rgsw_by_rgsw_inplace, rlwe_auto, rlwe_by_rgsw},
RgswCiphertextMutRef,
};
struct SeededAutoKey<M, S, Mod>
where
M: Matrix,
{
data: M,
seed: S,
modulus: Mod,
}
impl<M: Matrix + MatrixEntity, S, Mod: Modulus<Element = M::MatElement>> SeededAutoKey<M, S, Mod> {
fn empty<D: Decomposer>(
ring_size: usize,
auto_decomposer: &D,
seed: S,
modulus: Mod,
) -> Self {
SeededAutoKey {
data: M::zeros(auto_decomposer.decomposition_count().0, ring_size),
seed,
modulus,
}
}
}
struct AutoKeyEvaluationDomain<M: Matrix, R, N> {
data: M,
_phantom: PhantomData<(R, N)>,
}
impl<
M: MatrixMut + MatrixEntity,
Mod: Modulus<Element = M::MatElement> + Clone,
R: RandomFillUniformInModulus<[M::MatElement], Mod> + NewWithSeed,
N: NttInit<Mod> + Ntt<Element = M::MatElement>,
> From<&SeededAutoKey<M, R::Seed, Mod>> for AutoKeyEvaluationDomain<M, R, N>
where
<M as Matrix>::R: RowMut,
M::MatElement: Copy,
R::Seed: Clone,
{
fn from(value: &SeededAutoKey<M, R::Seed, Mod>) -> Self {
let (d, ring_size) = value.data.dimension();
let mut data = M::zeros(2 * d, ring_size);
// sample RLWE'_A(-s(X^k))
let mut p_rng = R::new_with_seed(value.seed.clone());
data.iter_rows_mut().take(d).for_each(|r| {
RandomFillUniformInModulus::random_fill(&mut p_rng, &value.modulus, r.as_mut());
});
// copy over RLWE'_B(-s(X^k))
izip!(data.iter_rows_mut().skip(d), value.data.iter_rows()).for_each(
|(to_r, from_r)| {
to_r.as_mut().copy_from_slice(from_r.as_ref());
},
);
// send RLWE'(-s(X^k)) polynomials to evaluation domain
let ntt_op = N::new(&value.modulus, ring_size);
data.iter_rows_mut()
.for_each(|r| ntt_op.forward(r.as_mut()));
AutoKeyEvaluationDomain {
data,
_phantom: PhantomData,
}
}
}
struct RgswCiphertext<M: Matrix, Mod> {
/// Rgsw ciphertext polynomials
data: M,
modulus: Mod,
/// Decomposition for RLWE part A
d_a: usize,
/// Decomposition for RLWE part B
d_b: usize,
}
impl<M: MatrixEntity, Mod: Modulus<Element = M::MatElement>> RgswCiphertext<M, Mod> {
pub(crate) fn empty<D: RlweDecomposer>(
ring_size: usize,
decomposer: &D,
modulus: Mod,
) -> RgswCiphertext<M, Mod> {
RgswCiphertext {
data: M::zeros(
decomposer.a().decomposition_count().0 * 2
+ decomposer.b().decomposition_count().0 * 2,
ring_size,
),
d_a: decomposer.a().decomposition_count().0,
d_b: decomposer.b().decomposition_count().0,
modulus,
}
}
}
pub struct SeededRgswCiphertext<M, S, Mod>
where
M: Matrix,
{
pub(crate) data: M,
seed: S,
modulus: Mod,
/// Decomposition for RLWE part A
d_a: usize,
/// Decomposition for RLWE part B
d_b: usize,
}
impl<M: Matrix + MatrixEntity, S, Mod> SeededRgswCiphertext<M, S, Mod> {
pub(crate) fn empty<D: RlweDecomposer>(
ring_size: usize,
decomposer: &D,
seed: S,
modulus: Mod,
) -> SeededRgswCiphertext<M, S, Mod> {
SeededRgswCiphertext {
data: M::zeros(
decomposer.a().decomposition_count().0 * 2
+ decomposer.b().decomposition_count().0,
ring_size,
),
seed,
modulus,
d_a: decomposer.a().decomposition_count().0,
d_b: decomposer.b().decomposition_count().0,
}
}
}
impl<M: Debug + Matrix, S: Debug, Mod: Debug> Debug for SeededRgswCiphertext<M, S, Mod>
where
M::MatElement: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SeededRgswCiphertext")
.field("data", &self.data)
.field("seed", &self.seed)
.field("modulus", &self.modulus)
.finish()
}
}
pub struct RgswCiphertextEvaluationDomain<M, Mod, R, N> {
pub(crate) data: M,
modulus: Mod,
_phantom: PhantomData<(R, N)>,
}
impl<
M: MatrixMut + MatrixEntity,
Mod: Modulus<Element = M::MatElement> + Clone,
R: NewWithSeed + RandomFillUniformInModulus<[M::MatElement], Mod>,
N: NttInit<Mod> + Ntt<Element = M::MatElement> + Debug,
> From<&SeededRgswCiphertext<M, R::Seed, Mod>>
for RgswCiphertextEvaluationDomain<M, Mod, R, N>
where
<M as Matrix>::R: RowMut,
M::MatElement: Copy,
R::Seed: Clone,
M: Debug,
{
fn from(value: &SeededRgswCiphertext<M, R::Seed, Mod>) -> Self {
let mut data = M::zeros(value.d_a * 2 + value.d_b * 2, value.data.dimension().1);
// copy RLWE'(-sm)
izip!(
data.iter_rows_mut().take(value.d_a * 2),
value.data.iter_rows().take(value.d_a * 2)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// sample A polynomials of RLWE'(m) - RLWE'A(m)
let mut p_rng = R::new_with_seed(value.seed.clone());
izip!(data.iter_rows_mut().skip(value.d_a * 2).take(value.d_b * 1))
.for_each(|ri| p_rng.random_fill(&value.modulus, ri.as_mut()));
// RLWE'_B(m)
izip!(
data.iter_rows_mut().skip(value.d_a * 2 + value.d_b),
value.data.iter_rows().skip(value.d_a * 2)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// Send polynomials to evaluation domain
let ring_size = data.dimension().1;
let nttop = N::new(&value.modulus, ring_size);
data.iter_rows_mut()
.for_each(|ri| nttop.forward(ri.as_mut()));
Self {
data: data,
modulus: value.modulus.clone(),
_phantom: PhantomData,
}
}
}
impl<
M: MatrixMut + MatrixEntity,
Mod: Modulus<Element = M::MatElement> + Clone,
R,
N: NttInit<Mod> + Ntt<Element = M::MatElement>,
> From<&RgswCiphertext<M, Mod>> for RgswCiphertextEvaluationDomain<M, Mod, R, N>
where
<M as Matrix>::R: RowMut,
M::MatElement: Copy,
M: Debug,
{
fn from(value: &RgswCiphertext<M, Mod>) -> Self {
let mut data = M::zeros(value.d_a * 2 + value.d_b * 2, value.data.dimension().1);
// copy RLWE'(-sm)
izip!(
data.iter_rows_mut().take(value.d_a * 2),
value.data.iter_rows().take(value.d_a * 2)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// copy RLWE'(m)
izip!(
data.iter_rows_mut().skip(value.d_a * 2),
value.data.iter_rows().skip(value.d_a * 2)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// Send polynomials to evaluation domain
let ring_size = data.dimension().1;
let nttop = N::new(&value.modulus, ring_size);
data.iter_rows_mut()
.for_each(|ri| nttop.forward(ri.as_mut()));
Self {
data: data,
modulus: value.modulus.clone(),
_phantom: PhantomData,
}
}
}
impl<M: Debug, Mod: Debug, R, N> Debug for RgswCiphertextEvaluationDomain<M, Mod, R, N> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RgswCiphertextEvaluationDomain")
.field("data", &self.data)
.field("modulus", &self.modulus)
.field("_phantom", &self._phantom)
.finish()
}
}
struct SeededRlweCiphertext<R, S, Mod> {
data: R,
seed: S,
modulus: Mod,
}
impl<R: RowEntity, S, Mod> SeededRlweCiphertext<R, S, Mod> {
fn empty(ring_size: usize, seed: S, modulus: Mod) -> Self {
SeededRlweCiphertext {
data: R::zeros(ring_size),
seed,
modulus,
}
}
}
pub struct RlweCiphertext<M, Rng> {
data: M,
_phatom: PhantomData<Rng>,
}
impl<
R: Row,
M: MatrixEntity<R = R, MatElement = R::Element> + MatrixMut,
Rng: NewWithSeed + RandomFillUniformInModulus<[M::MatElement], Mod>,
Mod: Modulus<Element = R::Element>,
> From<&SeededRlweCiphertext<R, Rng::Seed, Mod>> for RlweCiphertext<M, Rng>
where
Rng::Seed: Clone,
<M as Matrix>::R: RowMut,
R::Element: Copy,
{
fn from(value: &SeededRlweCiphertext<R, Rng::Seed, Mod>) -> Self {
let mut data = M::zeros(2, value.data.as_ref().len());
// sample a
let mut p_rng = Rng::new_with_seed(value.seed.clone());
RandomFillUniformInModulus::random_fill(
&mut p_rng,
&value.modulus,
data.get_row_mut(0),
);
data.get_row_mut(1).copy_from_slice(value.data.as_ref());
RlweCiphertext {
data,
_phatom: PhantomData,
}
}
}
struct SeededRlwePublicKey<Ro: Row, S> {
data: Ro,
seed: S,
modulus: Ro::Element,
}
impl<Ro: RowEntity, S> SeededRlwePublicKey<Ro, S> {
pub(crate) fn empty(ring_size: usize, seed: S, modulus: Ro::Element) -> Self {
Self {
data: Ro::zeros(ring_size),
seed,
modulus,
}
}
}
struct RlwePublicKey<M, R> {
data: M,
_phantom: PhantomData<R>,
}
impl<
M: MatrixMut + MatrixEntity,
Rng: NewWithSeed + RandomFillUniformInModulus<[M::MatElement], M::MatElement>,
> From<&SeededRlwePublicKey<M::R, Rng::Seed>> for RlwePublicKey<M, Rng>
where
<M as Matrix>::R: RowMut,
M::MatElement: Copy,
Rng::Seed: Copy,
{
fn from(value: &SeededRlwePublicKey<M::R, Rng::Seed>) -> Self {
let mut data = M::zeros(2, value.data.as_ref().len());
// sample a
let mut p_rng = Rng::new_with_seed(value.seed);
RandomFillUniformInModulus::random_fill(
&mut p_rng,
&value.modulus,
data.get_row_mut(0),
);
// copy over b
data.get_row_mut(1).copy_from_slice(value.data.as_ref());
Self {
data,
_phantom: PhantomData,
}
}
}
#[derive(Clone)]
struct RlweSecret {
pub(crate) values: Vec<i32>,
}
impl RlweSecret {
pub fn random(hw: usize, n: usize) -> RlweSecret {
DefaultSecureRng::with_local_mut(|rng| {
let mut out = vec![0i32; n];
fill_random_ternary_secret_with_hamming_weight(&mut out, hw, rng);
RlweSecret { values: out }
})
}
fn values(&self) -> &[i32] {
&self.values
}
}
fn random_seed() -> [u8; 32] {
let mut rng = DefaultSecureRng::new();
let mut seed = [0u8; 32];
rng.fill_bytes(&mut seed);
seed
}
/// Encrypts m as RGSW ciphertext RGSW(m) using supplied secret key. Returns
/// seeded RGSW ciphertext in coefficient domain
fn sk_encrypt_rgsw<T: Modulus<Element = u64> + Clone>(
m: &[u64],
s: &[i32],
decomposer: &(DefaultDecomposer<u64>, DefaultDecomposer<u64>),
mod_op: &ModularOpsU64<T>,
ntt_op: &NttBackendU64,
) -> SeededRgswCiphertext<Vec<Vec<u64>>, [u8; 32], T> {
let ring_size = s.len();
assert!(m.len() == s.len());
let mut rng = DefaultSecureRng::new();
let q = mod_op.modulus();
let rgsw_seed = random_seed();
let mut seeded_rgsw_ct = SeededRgswCiphertext::<Vec<Vec<u64>>, [u8; 32], T>::empty(
ring_size as usize,
decomposer,
rgsw_seed,
q.clone(),
);
let mut p_rng = DefaultSecureRng::new_seeded(rgsw_seed);
secret_key_encrypt_rgsw(
&mut seeded_rgsw_ct.data,
m,
&decomposer.a().gadget_vector(),
&decomposer.b().gadget_vector(),
s,
mod_op,
ntt_op,
&mut p_rng,
&mut rng,
);
seeded_rgsw_ct
}
#[test]
fn rlwe_encrypt_decryption() {
let logq = 50;
let logp = 2;
let ring_size = 1 << 4;
let q = generate_prime(logq, ring_size, 1u64 << logq).unwrap();
let p = 1u64 << logp;
let mut rng = DefaultSecureRng::new();
let s = RlweSecret::random((ring_size >> 1) as usize, ring_size as usize);
// sample m0
let mut m0 = vec![0u64; ring_size as usize];
RandomFillUniformInModulus::<[u64], u64>::random_fill(
&mut rng,
&(1u64 << logp),
m0.as_mut_slice(),
);
let ntt_op = NttBackendU64::new(&q, ring_size as usize);
let mod_op = ModularOpsU64::new(q);
// encrypt m0
let encoded_m = m0
.iter()
.map(|v| (((*v as f64) * q as f64) / (p as f64)).round() as u64)
.collect_vec();
let seed = random_seed();
let mut rlwe_in_ct =
SeededRlweCiphertext::<Vec<u64>, _, _>::empty(ring_size as usize, seed, q);
let mut p_rng = DefaultSecureRng::new_seeded(seed);
seeded_secret_key_encrypt_rlwe(
&encoded_m,
&mut rlwe_in_ct.data,
s.values(),
&mod_op,
&ntt_op,
&mut p_rng,
&mut rng,
);
let rlwe_in_ct = RlweCiphertext::<Vec<Vec<u64>>, DefaultSecureRng>::from(&rlwe_in_ct);
let mut encoded_m_back = vec![0u64; ring_size as usize];
decrypt_rlwe(
&rlwe_in_ct.data,
s.values(),
&mut encoded_m_back,
&ntt_op,
&mod_op,
);
let m_back = encoded_m_back
.iter()
.map(|v| (((*v as f64 * p as f64) / q as f64).round() as u64) % p)
.collect_vec();
assert_eq!(m0, m_back);
}
#[test]
fn rlwe_by_rgsw_works() {
let logq = 50;
let logp = 2;
let ring_size = 1 << 4;
let q = generate_prime(logq, ring_size, 1u64 << logq).unwrap();
let p: u64 = 1u64 << logp;
let mut rng = DefaultSecureRng::new_seeded([0u8; 32]);
let s = RlweSecret::random((ring_size >> 1) as usize, ring_size as usize);
let mut m0 = vec![0u64; ring_size as usize];
RandomFillUniformInModulus::<[u64], _>::random_fill(
&mut rng,
&(1u64 << logp),
m0.as_mut_slice(),
);
let mut m1 = vec![0u64; ring_size as usize];
m1[thread_rng().gen_range(0..ring_size) as usize] = 1;
let ntt_op = NttBackendU64::new(&q, ring_size as usize);
let mod_op = ModularOpsU64::new(q);
let d_rgsw = 10;
let logb = 5;
let decomposer = (
DefaultDecomposer::new(q, logb, d_rgsw),
DefaultDecomposer::new(q, logb, d_rgsw),
);
// create public key
let pk_seed = random_seed();
let mut pk_prng = DefaultSecureRng::new_seeded(pk_seed);
let mut seeded_pk =
SeededRlwePublicKey::<Vec<u64>, _>::empty(ring_size as usize, pk_seed, q);
rlwe_public_key(
&mut seeded_pk.data,
s.values(),
&ntt_op,
&mod_op,
&mut pk_prng,
&mut rng,
);
// let pk = RlwePublicKey::<Vec<Vec<u64>>, DefaultSecureRng>::from(&seeded_pk);
// Encrypt m1 as RGSW(m1)
let rgsw_ct = {
// Encryption m1 as RGSW(m1) using secret key
let seeded_rgsw_ct = sk_encrypt_rgsw(&m1, s.values(), &decomposer, &mod_op, &ntt_op);
RgswCiphertextEvaluationDomain::<Vec<Vec<u64>>, _,DefaultSecureRng, NttBackendU64>::from(&seeded_rgsw_ct)
};
// Encrypt m0 as RLWE(m0)
let mut rlwe_in_ct = {
let encoded_m = m0
.iter()
.map(|v| (((*v as f64) * q as f64) / (p as f64)).round() as u64)
.collect_vec();
let seed = random_seed();
let mut p_rng = DefaultSecureRng::new_seeded(seed);
let mut seeded_rlwe = SeededRlweCiphertext::empty(ring_size as usize, seed, q);
seeded_secret_key_encrypt_rlwe(
&encoded_m,
&mut seeded_rlwe.data,
s.values(),
&mod_op,
&ntt_op,
&mut p_rng,
&mut rng,
);
RlweCiphertext::<Vec<Vec<u64>>, DefaultSecureRng>::from(&seeded_rlwe)
};
// RLWE(m0m1) = RLWE(m0) x RGSW(m1)
let mut scratch_space =
vec![vec![0u64; ring_size as usize]; rlwe_x_rgsw_scratch_rows(&decomposer)];
// rlwe x rgsw with with soup repr
let rlwe_in_ct_shoup = {
let mut rlwe_in_ct_shoup = rlwe_in_ct.data.clone();
let rgsw_ct_shoup = ToShoup::to_shoup(&rgsw_ct.data, q);
rlwe_by_rgsw_shoup(
&mut RlweCiphertextMutRef::new(rlwe_in_ct_shoup.as_mut()),
&RgswCiphertextRef::new(
rgsw_ct.data.as_ref(),
decomposer.a().decomposition_count().0,
decomposer.b().decomposition_count().0,
),
&RgswCiphertextRef::new(
rgsw_ct_shoup.as_ref(),
decomposer.a().decomposition_count().0,
decomposer.b().decomposition_count().0,
),
&mut RuntimeScratchMutRef::new(scratch_space.as_mut()),
&decomposer,
&ntt_op,
&mod_op,
false,
);
rlwe_in_ct_shoup
};
// rlwe x rgsw normal
{
rlwe_by_rgsw(
&mut RlweCiphertextMutRef::new(rlwe_in_ct.data.as_mut()),
&RgswCiphertextRef::new(
rgsw_ct.data.as_ref(),
decomposer.a().decomposition_count().0,
decomposer.b().decomposition_count().0,
),
&mut RuntimeScratchMutRef::new(scratch_space.as_mut()),
&decomposer,
&ntt_op,
&mod_op,
false,
);
}
// output from both functions must be equal
assert_eq!(rlwe_in_ct.data, rlwe_in_ct_shoup);
// Decrypt RLWE(m0m1)
let mut encoded_m0m1_back = vec![0u64; ring_size as usize];
decrypt_rlwe(
&rlwe_in_ct_shoup,
s.values(),
&mut encoded_m0m1_back,
&ntt_op,
&mod_op,
);
let m0m1_back = encoded_m0m1_back
.iter()
.map(|v| (((*v as f64 * p as f64) / (q as f64)).round() as u64) % p)
.collect_vec();
let mul_mod = |v0: &u64, v1: &u64| (v0 * v1) % p;
let m0m1 = negacyclic_mul(&m0, &m1, mul_mod, p);
// {
// // measure noise
// let encoded_m_ideal = m0m1
// .iter()
// .map(|v| (((*v as f64) * q as f64) / (p as f64)).round() as u64)
// .collect_vec();
// let noise = measure_noise(&rlwe_in_ct, &encoded_m_ideal, &ntt_op,
// &mod_op, s.values()); println!("Noise RLWE(m0m1)(=
// RLWE(m0)xRGSW(m1)) : {noise}"); }
assert!(
m0m1 == m0m1_back,
"Expected {:?} \n Got {:?}",
m0m1,
m0m1_back
);
}
#[test]
fn rlwe_auto_works() {
let logq = 55;
let ring_size = 1 << 11;
let q = generate_prime(logq, 2 * ring_size, 1u64 << logq).unwrap();
let logp = 3;
let p = 1u64 << logp;
let d_rgsw = 5;
let logb = 11;
let mut rng = DefaultSecureRng::new();
let s = RlweSecret::random((ring_size >> 1) as usize, ring_size as usize);
let mut m = vec![0u64; ring_size as usize];
RandomFillUniformInModulus::random_fill(&mut rng, &p, m.as_mut_slice());
let encoded_m = m
.iter()
.map(|v| (((*v as f64 * q as f64) / (p as f64)).round() as u64))
.collect_vec();
let ntt_op = NttBackendU64::new(&q, ring_size as usize);
let mod_op = ModularOpsU64::new(q);
// RLWE_{s}(m)
let seed_rlwe = random_seed();
let mut seeded_rlwe_m = SeededRlweCiphertext::empty(ring_size as usize, seed_rlwe, q);
let mut p_rng = DefaultSecureRng::new_seeded(seed_rlwe);
seeded_secret_key_encrypt_rlwe(
&encoded_m,
&mut seeded_rlwe_m.data,
s.values(),
&mod_op,
&ntt_op,
&mut p_rng,
&mut rng,
);
let mut rlwe_m = RlweCiphertext::<Vec<Vec<u64>>, DefaultSecureRng>::from(&seeded_rlwe_m);
let auto_k = -125;
// Generate auto key to key switch from s^k to s
let decomposer = DefaultDecomposer::new(q, logb, d_rgsw);
let seed_auto = random_seed();
let mut seeded_auto_key =
SeededAutoKey::empty(ring_size as usize, &decomposer, seed_auto, q);
let mut p_rng = DefaultSecureRng::new_seeded(seed_auto);
let gadget_vector = decomposer.gadget_vector();
seeded_auto_key_gen(
&mut seeded_auto_key.data,
s.values(),
auto_k,
&gadget_vector,
&mod_op,
&ntt_op,
&mut p_rng,
&mut rng,
);
let auto_key =
AutoKeyEvaluationDomain::<Vec<Vec<u64>>, DefaultSecureRng, NttBackendU64>::from(
&seeded_auto_key,
);
// Send RLWE_{s}(m) -> RLWE_{s}(m^k)
let mut scratch_space =
vec![vec![0; ring_size as usize]; rlwe_auto_scratch_rows(&decomposer)];
let (auto_map_index, auto_map_sign) = generate_auto_map(ring_size as usize, auto_k);
// galois auto with auto key in shoup repr
let rlwe_m_shoup = {
let auto_key_shoup = ToShoup::to_shoup(&auto_key.data, q);
let mut rlwe_m_shoup = rlwe_m.data.clone();
rlwe_auto_shoup(
&mut RlweCiphertextMutRef::new(&mut rlwe_m_shoup),
&RlweKskRef::new(&auto_key.data, decomposer.decomposition_count().0),
&RlweKskRef::new(&auto_key_shoup, decomposer.decomposition_count().0),
&mut RuntimeScratchMutRef::new(&mut scratch_space),
&auto_map_index,
&auto_map_sign,
&mod_op,
&ntt_op,
&decomposer,
false,
);
rlwe_m_shoup
};
// normal galois auto
{
rlwe_auto(
&mut RlweCiphertextMutRef::new(rlwe_m.data.as_mut()),
&RlweKskRef::new(auto_key.data.as_ref(), decomposer.decomposition_count().0),
&mut RuntimeScratchMutRef::new(scratch_space.as_mut()),
&auto_map_index,
&auto_map_sign,
&mod_op,
&ntt_op,
&decomposer,
false,
);
}
// rlwe out from both functions must be same
assert_eq!(rlwe_m.data, rlwe_m_shoup);
let rlwe_m_k = rlwe_m;
// Decrypt RLWE_{s}(m^k) and check
let mut encoded_m_k_back = vec![0u64; ring_size as usize];
decrypt_rlwe(
&rlwe_m_k.data,
s.values(),
&mut encoded_m_k_back,
&ntt_op,
&mod_op,
);
let m_k_back = encoded_m_k_back
.iter()
.map(|v| (((*v as f64 * p as f64) / q as f64).round() as u64) % p)
.collect_vec();
let mut m_k = vec![0u64; ring_size as usize];
// Send \delta m -> \delta m^k
izip!(m.iter(), auto_map_index.iter(), auto_map_sign.iter()).for_each(
|(v, to_index, sign)| {
if !*sign {
m_k[*to_index] = (p - *v) % p;
} else {
m_k[*to_index] = *v;
}
},
);
// {
// let encoded_m_k = m_k
// .iter()
// .map(|v| ((*v as f64 * q as f64) / p as f64).round() as u64)
// .collect_vec();
// let noise = measure_noise(&rlwe_m_k, &encoded_m_k, &ntt_op, &mod_op,
// s.values()); println!("Ksk noise: {noise}");
// }
assert_eq!(m_k_back, m_k);
}
/// Collect noise stats of RGSW ciphertext
///
/// - rgsw_ct: RGSW ciphertext must be in coefficient domain
fn rgsw_noise_stats<T: Modulus<Element = u64> + Clone>(
rgsw_ct: &[Vec<u64>],
m: &[u64],
s: &[i32],
decomposer: &(DefaultDecomposer<u64>, DefaultDecomposer<u64>),
q: &T,
) -> Stats<i64> {
let gadget_vector_a = decomposer.a().gadget_vector();
let gadget_vector_b = decomposer.b().gadget_vector();
let d_a = gadget_vector_a.len();
let d_b = gadget_vector_b.len();
let ring_size = s.len();
assert!(Matrix::dimension(&rgsw_ct) == (d_a * 2 + d_b * 2, ring_size));
assert!(m.len() == ring_size);
let mod_op = ModularOpsU64::new(q.clone());
let ntt_op = NttBackendU64::new(q, ring_size);
let mul_mod =
|a: &u64, b: &u64| ((*a as u128 * *b as u128) % q.q().unwrap() as u128) as u64;
let s_poly = Vec::<u64>::try_convert_from(s, q);
let mut neg_s = s_poly.clone();
mod_op.elwise_neg_mut(neg_s.as_mut());
let neg_sm0m1 = negacyclic_mul(&neg_s, &m, mul_mod, q.q().unwrap());
let mut stats = Stats::new();
// RLWE(\beta^j -s * m)
for j in 0..d_a {
let want_m = {
// RLWE(\beta^j -s * m)
let mut beta_neg_sm0m1 = vec![0u64; ring_size as usize];
mod_op.elwise_scalar_mul(beta_neg_sm0m1.as_mut(), &neg_sm0m1, &gadget_vector_a[j]);
beta_neg_sm0m1
};
let mut rlwe = vec![vec![0u64; ring_size as usize]; 2];
rlwe[0].copy_from_slice(rgsw_ct.get_row_slice(j));
rlwe[1].copy_from_slice(rgsw_ct.get_row_slice(d_a + j));
let mut got_m = vec![0; ring_size];
decrypt_rlwe(&rlwe, s, &mut got_m, &ntt_op, &mod_op);
let mut diff = want_m;
mod_op.elwise_sub_mut(diff.as_mut(), got_m.as_ref());
stats.add_many_samples(&Vec::<i64>::try_convert_from(&diff, q));
}
// RLWE(\beta^j m)
for j in 0..d_b {
let want_m = {
// RLWE(\beta^j m)
let mut beta_m0m1 = vec![0u64; ring_size as usize];
mod_op.elwise_scalar_mul(beta_m0m1.as_mut(), &m, &gadget_vector_b[j]);
beta_m0m1
};
let mut rlwe = vec![vec![0u64; ring_size as usize]; 2];
rlwe[0].copy_from_slice(rgsw_ct.get_row_slice(d_a * 2 + j));
rlwe[1].copy_from_slice(rgsw_ct.get_row_slice(d_a * 2 + d_b + j));
let mut got_m = vec![0; ring_size];
decrypt_rlwe(&rlwe, s, &mut got_m, &ntt_op, &mod_op);
let mut diff = want_m;
mod_op.elwise_sub_mut(diff.as_mut(), got_m.as_ref());
stats.add_many_samples(&Vec::<i64>::try_convert_from(&diff, q));
}
stats
}
#[test]
fn print_noise_stats_rgsw_x_rgsw() {
let logq = 60;
let logp = 2;
let ring_size = 1 << 11;
let q = generate_prime(logq, ring_size, 1u64 << logq).unwrap();
let d_rgsw = 12;
let logb = 5;
let s = RlweSecret::random((ring_size >> 1) as usize, ring_size as usize);
let ntt_op = NttBackendU64::new(&q, ring_size as usize);
let mod_op = ModularOpsU64::new(q);
let decomposer = (
DefaultDecomposer::new(q, logb, d_rgsw),
DefaultDecomposer::new(q, logb, d_rgsw),
);
let d_a = decomposer.a().decomposition_count().0;
let d_b = decomposer.b().decomposition_count().0;
let mul_mod = |a: &u64, b: &u64| ((*a as u128 * *b as u128) % q as u128) as u64;
let mut carry_m = vec![0u64; ring_size as usize];
carry_m[thread_rng().gen_range(0..ring_size) as usize] = 1 << logp;
// RGSW(carry_m)
let mut rgsw_carrym = {
let seeded_rgsw = sk_encrypt_rgsw(&carry_m, s.values(), &decomposer, &mod_op, &ntt_op);
let mut rgsw_eval =
RgswCiphertextEvaluationDomain::<_, _, DefaultSecureRng, NttBackendU64>::from(
&seeded_rgsw,
);
rgsw_eval
.data
.iter_mut()
.for_each(|ri| ntt_op.backward(ri.as_mut()));
rgsw_eval.data
};
let mut scratch_matrix = vec![
vec![0u64; ring_size as usize];
rgsw_x_rgsw_scratch_rows(&decomposer, &decomposer)
];
rgsw_noise_stats(&rgsw_carrym, &carry_m, s.values(), &decomposer, &q);
for i in 0..8 {
let mut m = vec![0u64; ring_size as usize];
m[thread_rng().gen_range(0..ring_size) as usize] = if (i & 1) == 1 { q - 1 } else { 1 };
let rgsw_m =
RgswCiphertextEvaluationDomain::<_, _, DefaultSecureRng, NttBackendU64>::from(
&sk_encrypt_rgsw(&m, s.values(), &decomposer, &mod_op, &ntt_op),
);
rgsw_by_rgsw_inplace(
&mut RgswCiphertextMutRef::new(rgsw_carrym.as_mut(), d_a, d_b),
&RgswCiphertextRef::new(rgsw_m.data.as_ref(), d_a, d_b),
&decomposer,
&decomposer,
&mut RuntimeScratchMutRef::new(scratch_matrix.as_mut()),
&ntt_op,
&mod_op,
);
// measure noise
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | true |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/shortint/enc_dec.rs | src/shortint/enc_dec.rs | use itertools::Itertools;
use crate::{
bool::BoolEvaluator,
random::{DefaultSecureRng, RandomFillUniformInModulus},
utils::WithLocal,
Decryptor, Encryptor, KeySwitchWithId, Matrix, MatrixEntity, MatrixMut, MultiPartyDecryptor,
RowMut, SampleExtractor,
};
/// Fhe UInt8
///
/// Note that `Self.data` stores encryptions of bits in little endian (i.e least
/// signficant bit stored at 0th index and most signficant bit stores at 7th
/// index)
#[derive(Clone)]
pub struct FheUint8<C> {
pub(super) data: Vec<C>,
}
impl<C> FheUint8<C> {
pub(super) fn data(&self) -> &[C] {
&self.data
}
pub(super) fn data_mut(&mut self) -> &mut [C] {
&mut self.data
}
}
/// Stores a batch of Fhe Uint8 ciphertext as collection of unseeded RLWE
/// ciphertexts always encrypted under the ideal RLWE secret `s` of the MPC
/// protocol
///
/// To extract Fhe Uint8 ciphertext at `index` call `self.extract(index)`
pub struct BatchedFheUint8<C> {
/// Vector of RLWE ciphertexts `C`
data: Vec<C>,
/// Count of FheUint8s packed in vector of RLWE ciphertexts
count: usize,
}
impl<K, C> Encryptor<[u8], BatchedFheUint8<C>> for K
where
K: Encryptor<[bool], Vec<C>>,
{
/// Encrypt a batch of uint8s packed in vector of RLWE ciphertexts
///
/// Uint8s can be extracted from `BatchedFheUint8` with `SampleExtractor`
fn encrypt(&self, m: &[u8]) -> BatchedFheUint8<C> {
let bool_m = m
.iter()
.flat_map(|v| {
(0..8)
.into_iter()
.map(|i| ((*v >> i) & 1) == 1)
.collect_vec()
})
.collect_vec();
let cts = K::encrypt(&self, &bool_m);
BatchedFheUint8 {
data: cts,
count: m.len(),
}
}
}
impl<M: MatrixEntity + MatrixMut<MatElement = u64>> From<&SeededBatchedFheUint8<M::R, [u8; 32]>>
for BatchedFheUint8<M>
where
<M as Matrix>::R: RowMut,
{
/// Unseeds collection of seeded RLWE ciphertext in SeededBatchedFheUint8
/// and returns as `Self`
fn from(value: &SeededBatchedFheUint8<M::R, [u8; 32]>) -> Self {
BoolEvaluator::with_local(|e| {
let parameters = e.parameters();
let ring_size = parameters.rlwe_n().0;
let rlwe_q = parameters.rlwe_q();
let mut prng = DefaultSecureRng::new_seeded(value.seed);
let rlwes = value
.data
.iter()
.map(|partb| {
let mut rlwe = M::zeros(2, ring_size);
// sample A
RandomFillUniformInModulus::random_fill(&mut prng, rlwe_q, rlwe.get_row_mut(0));
// Copy over B
rlwe.get_row_mut(1).copy_from_slice(partb.as_ref());
rlwe
})
.collect_vec();
Self {
data: rlwes,
count: value.count,
}
})
}
}
impl<C, R> SampleExtractor<FheUint8<R>> for BatchedFheUint8<C>
where
C: SampleExtractor<R>,
{
/// Extract Fhe Uint8 ciphertext at `index`
///
/// `Self` stores batch of Fhe uint8 ciphertext as vector of RLWE
/// ciphertexts. Since Fhe uint8 ciphertext is collection of 8 bool
/// ciphertexts, Fhe uint8 ciphertext at index `i` is stored in coefficients
/// `i*8...(i+1)*8`. To extract Fhe uint8 at index `i`, sample extract bool
/// ciphertext at indices `[i*8, ..., (i+1)*8)`
fn extract_at(&self, index: usize) -> FheUint8<R> {
assert!(index < self.count);
BoolEvaluator::with_local(|e| {
let ring_size = e.parameters().rlwe_n().0;
let start_index = index * 8;
let end_index = (index + 1) * 8;
let data = (start_index..end_index)
.map(|i| {
let rlwe_index = i / ring_size;
let coeff_index = i % ring_size;
self.data[rlwe_index].extract_at(coeff_index)
})
.collect_vec();
FheUint8 { data }
})
}
/// Extracts all FheUint8s packed in vector of RLWE ciphertexts of `Self`
fn extract_all(&self) -> Vec<FheUint8<R>> {
(0..self.count)
.map(|index| self.extract_at(index))
.collect_vec()
}
/// Extracts first `how_many` FheUint8s packed in vector of RLWE
/// ciphertexts of `Self`
fn extract_many(&self, how_many: usize) -> Vec<FheUint8<R>> {
(0..how_many)
.map(|index| self.extract_at(index))
.collect_vec()
}
}
/// Stores a batch of FheUint8s packed in a collection unseeded RLWE ciphertexts
///
/// `Self` stores unseeded RLWE ciphertexts encrypted under user's RLWE secret
/// `u_j` and is different from `BatchFheUint8` which stores collection of RLWE
/// ciphertexts under ideal RLWE secret `s` of the (non-interactive/interactive)
/// MPC protocol.
///
/// To extract FheUint8s from `Self`'s collection of RLWE ciphertexts, first
/// switch `Self` to `BatchFheUint8` with `key_switch(user_id)` where `user_id`
/// is user's id. This key switches collection of RLWE ciphertexts from
/// user's RLWE secret `u_j` to ideal RLWE secret `s` of the MPC protocol. Then
/// proceed to use `SampleExtract` on `BatchFheUint8` (for ex, call
/// `extract_at(0)` to extract FheUint8 stored at index 0)
pub struct NonInteractiveBatchedFheUint8<C> {
/// Vector of RLWE ciphertexts `C`
data: Vec<C>,
/// Count of FheUint8s packed in vector of RLWE ciphertexts
count: usize,
}
impl<M: MatrixEntity + MatrixMut<MatElement = u64>> From<&SeededBatchedFheUint8<M::R, [u8; 32]>>
for NonInteractiveBatchedFheUint8<M>
where
<M as Matrix>::R: RowMut,
{
/// Unseeds collection of seeded RLWE ciphertext in SeededBatchedFheUint8
/// and returns as `Self`
fn from(value: &SeededBatchedFheUint8<M::R, [u8; 32]>) -> Self {
BoolEvaluator::with_local(|e| {
let parameters = e.parameters();
let ring_size = parameters.rlwe_n().0;
let rlwe_q = parameters.rlwe_q();
let mut prng = DefaultSecureRng::new_seeded(value.seed);
let rlwes = value
.data
.iter()
.map(|partb| {
let mut rlwe = M::zeros(2, ring_size);
// sample A
RandomFillUniformInModulus::random_fill(&mut prng, rlwe_q, rlwe.get_row_mut(0));
// Copy over B
rlwe.get_row_mut(1).copy_from_slice(partb.as_ref());
rlwe
})
.collect_vec();
Self {
data: rlwes,
count: value.count,
}
})
}
}
impl<C> KeySwitchWithId<BatchedFheUint8<C>> for NonInteractiveBatchedFheUint8<C>
where
C: KeySwitchWithId<C>,
{
/// Key switch `Self`'s collection of RLWE cihertexts encrypted under user's
/// RLWE secret `u_j` to ideal RLWE secret `s` of the MPC protocol.
///
/// - user_id: user id of user `j`
fn key_switch(&self, user_id: usize) -> BatchedFheUint8<C> {
let data = self
.data
.iter()
.map(|c| c.key_switch(user_id))
.collect_vec();
BatchedFheUint8 {
data,
count: self.count,
}
}
}
pub struct SeededBatchedFheUint8<C, S> {
/// Vector of Seeded RLWE ciphertexts `C`.
///
/// If RLWE(m) = [a, b] s.t. m + e = b - as, `a` can be seeded and seeded
/// RLWE ciphertext only contains `b` polynomial
data: Vec<C>,
/// Seed for the ciphertexts
seed: S,
/// Count of FheUint8s packed in vector of RLWE ciphertexts
count: usize,
}
impl<K, C, S> Encryptor<[u8], SeededBatchedFheUint8<C, S>> for K
where
K: Encryptor<[bool], (Vec<C>, S)>,
{
/// Encrypt a slice of u8s of arbitray length packed into collection of
/// seeded RLWE ciphertexts and return `SeededBatchedFheUint8`
fn encrypt(&self, m: &[u8]) -> SeededBatchedFheUint8<C, S> {
// convert vector of u8s to vector bools
let bool_m = m
.iter()
.flat_map(|v| (0..8).into_iter().map(|i| (((*v) >> i) & 1) == 1))
.collect_vec();
let (cts, seed) = K::encrypt(&self, &bool_m);
SeededBatchedFheUint8 {
data: cts,
seed,
count: m.len(),
}
}
}
impl<C, S> SeededBatchedFheUint8<C, S> {
/// Unseed collection of seeded RLWE ciphertexts of `Self` and returns
/// `NonInteractiveBatchedFheUint8` with collection of unseeded RLWE
/// ciphertexts.
///
/// In non-interactive MPC setting, RLWE ciphertexts are encrypted under
/// user's RLWE secret `u_j`. The RLWE ciphertexts must be key switched to
/// ideal RLWE secret `s` of the MPC protocol before use.
///
/// Note that we don't provide `unseed` API from `Self` to
/// `BatchedFheUint8`. This is because:
///
/// - In non-interactive setting (1) client encrypts private inputs using
/// their secret `u_j` as `SeededBatchedFheUint8` and sends it to the
/// server. (2) Server unseeds `SeededBatchedFheUint8` into
/// `NonInteractiveBatchedFheUint8` indicating that private inputs are
/// still encrypted under user's RLWE secret `u_j`. (3) Server key
/// switches `NonInteractiveBatchedFheUint8` from user's RLWE secret `u_j`
/// to ideal RLWE secret `s` and outputs `BatchedFheUint8`. (4)
/// `BatchedFheUint8` always stores RLWE secret under ideal RLWE secret of
/// the protocol. Hence, it is safe to extract FheUint8s. Server proceeds
/// to extract necessary FheUint8s.
///
/// - In interactive setting (1) client always encrypts private inputs using
/// public key corresponding to ideal RLWE secret `s` of the protocol and
/// produces `BatchedFheUint8`. (2) Given `BatchedFheUint8` stores
/// collection of RLWE ciphertext under ideal RLWE secret `s`, server can
/// directly extract necessary FheUint8s to use.
///
/// Thus, there's no need to go directly from `Self` to `BatchedFheUint8`.
pub fn unseed<M>(&self) -> NonInteractiveBatchedFheUint8<M>
where
NonInteractiveBatchedFheUint8<M>: for<'a> From<&'a SeededBatchedFheUint8<C, S>>,
M: Matrix<R = C>,
{
NonInteractiveBatchedFheUint8::from(self)
}
}
impl<C, K> MultiPartyDecryptor<u8, FheUint8<C>> for K
where
K: MultiPartyDecryptor<bool, C>,
<Self as MultiPartyDecryptor<bool, C>>::DecryptionShare: Clone,
{
type DecryptionShare = Vec<<Self as MultiPartyDecryptor<bool, C>>::DecryptionShare>;
fn gen_decryption_share(&self, c: &FheUint8<C>) -> Self::DecryptionShare {
assert!(c.data().len() == 8);
c.data()
.iter()
.map(|bit_c| {
let decryption_share =
MultiPartyDecryptor::<bool, C>::gen_decryption_share(self, bit_c);
decryption_share
})
.collect_vec()
}
fn aggregate_decryption_shares(&self, c: &FheUint8<C>, shares: &[Self::DecryptionShare]) -> u8 {
let mut out = 0u8;
(0..8).into_iter().for_each(|i| {
// Collect bit i^th decryption share of each party
let bit_i_decryption_shares = shares.iter().map(|s| s[i].clone()).collect_vec();
let bit_i = MultiPartyDecryptor::<bool, C>::aggregate_decryption_shares(
self,
&c.data()[i],
&bit_i_decryption_shares,
);
if bit_i {
out += 1 << i;
}
});
out
}
}
impl<C, K> Encryptor<u8, FheUint8<C>> for K
where
K: Encryptor<bool, C>,
{
fn encrypt(&self, m: &u8) -> FheUint8<C> {
let cts = (0..8)
.into_iter()
.map(|i| {
let bit = ((m >> i) & 1) == 1;
K::encrypt(self, &bit)
})
.collect_vec();
FheUint8 { data: cts }
}
}
impl<K, C> Decryptor<u8, FheUint8<C>> for K
where
K: Decryptor<bool, C>,
{
fn decrypt(&self, c: &FheUint8<C>) -> u8 {
assert!(c.data.len() == 8);
let mut out = 0u8;
c.data().iter().enumerate().for_each(|(index, bit_c)| {
let bool = K::decrypt(self, bit_c);
if bool {
out += 1 << index;
}
});
out
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/shortint/mod.rs | src/shortint/mod.rs | mod enc_dec;
mod ops;
pub type FheUint8 = enc_dec::FheUint8<Vec<u64>>;
use std::cell::RefCell;
use crate::bool::{BoolEvaluator, BooleanGates, FheBool, RuntimeServerKey};
thread_local! {
static DIV_ZERO_ERROR: RefCell<Option<FheBool>> = RefCell::new(None);
}
/// Returns Boolean ciphertext indicating whether last division was attempeted
/// with decnomiantor set to 0.
pub fn div_zero_error_flag() -> Option<FheBool> {
DIV_ZERO_ERROR.with_borrow(|c| c.clone())
}
/// Reset all error flags
///
/// Error flags are thread local. When running multiple circuits in sequence
/// within a single program you must prevent error flags set during the
/// execution of previous circuit to affect error flags set during execution of
/// the next circuit. To do so call `reset_error_flags()`.
pub fn reset_error_flags() {
DIV_ZERO_ERROR.with_borrow_mut(|c| *c = None);
}
mod frontend {
use super::ops::{
arbitrary_bit_adder, arbitrary_bit_division_for_quotient_and_rem, arbitrary_bit_subtractor,
eight_bit_mul, is_zero,
};
use crate::utils::{Global, WithLocal};
use super::*;
/// Set Div by Zero flag after each divison. Div by zero flag is set to true
/// if either 1 of the division executed in circuit evaluation has
/// denominator set to 0.
fn set_div_by_zero_flag(denominator: &FheUint8) {
{
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let is_zero = is_zero(e, denominator.data(), key);
DIV_ZERO_ERROR.with_borrow_mut(|before_is_zero| {
if before_is_zero.is_none() {
*before_is_zero = Some(FheBool { data: is_zero });
} else {
e.or_inplace(before_is_zero.as_mut().unwrap().data_mut(), &is_zero, key);
}
});
})
}
}
mod arithetic {
use super::*;
use std::ops::{Add, AddAssign, Div, Mul, Rem, Sub};
impl AddAssign<&FheUint8> for FheUint8 {
fn add_assign(&mut self, rhs: &FheUint8) {
BoolEvaluator::with_local_mut_mut(&mut |e| {
let key = RuntimeServerKey::global();
arbitrary_bit_adder(e, self.data_mut(), rhs.data(), false, key);
});
}
}
impl Add<&FheUint8> for &FheUint8 {
type Output = FheUint8;
fn add(self, rhs: &FheUint8) -> Self::Output {
let mut a = self.clone();
a += rhs;
a
}
}
impl Sub<&FheUint8> for &FheUint8 {
type Output = FheUint8;
fn sub(self, rhs: &FheUint8) -> Self::Output {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let (out, _, _) = arbitrary_bit_subtractor(e, self.data(), rhs.data(), key);
FheUint8 { data: out }
})
}
}
impl Mul<&FheUint8> for &FheUint8 {
type Output = FheUint8;
fn mul(self, rhs: &FheUint8) -> Self::Output {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let out = eight_bit_mul(e, self.data(), rhs.data(), key);
FheUint8 { data: out }
})
}
}
impl Div<&FheUint8> for &FheUint8 {
type Output = FheUint8;
fn div(self, rhs: &FheUint8) -> Self::Output {
// set div by 0 error flag
set_div_by_zero_flag(rhs);
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let (quotient, _) = arbitrary_bit_division_for_quotient_and_rem(
e,
self.data(),
rhs.data(),
key,
);
FheUint8 { data: quotient }
})
}
}
impl Rem<&FheUint8> for &FheUint8 {
type Output = FheUint8;
fn rem(self, rhs: &FheUint8) -> Self::Output {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let (_, remainder) = arbitrary_bit_division_for_quotient_and_rem(
e,
self.data(),
rhs.data(),
key,
);
FheUint8 { data: remainder }
})
}
}
impl FheUint8 {
/// Calculates `Self += rhs` and returns `overflow`
///
/// `overflow` is set to `True` if `Self += rhs` overflowed,
/// otherwise it is set to `False`
pub fn overflowing_add_assign(&mut self, rhs: &FheUint8) -> FheBool {
BoolEvaluator::with_local_mut_mut(&mut |e| {
let key = RuntimeServerKey::global();
let (overflow, _) =
arbitrary_bit_adder(e, self.data_mut(), rhs.data(), false, key);
FheBool { data: overflow }
})
}
/// Returns (Self + rhs, overflow).
///
/// `overflow` is set to `True` if `Self + rhs` overflowed,
/// otherwise it is set to `False`
pub fn overflowing_add(self, rhs: &FheUint8) -> (FheUint8, FheBool) {
BoolEvaluator::with_local_mut(|e| {
let mut lhs = self.clone();
let key = RuntimeServerKey::global();
let (overflow, _) =
arbitrary_bit_adder(e, lhs.data_mut(), rhs.data(), false, key);
(lhs, FheBool { data: overflow })
})
}
/// Returns (Self - rhs, overflow).
///
/// `overflow` is set to `True` if `Self - rhs` overflowed,
/// otherwise it is set to `False`
pub fn overflowing_sub(&self, rhs: &FheUint8) -> (FheUint8, FheBool) {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let (out, mut overflow, _) =
arbitrary_bit_subtractor(e, self.data(), rhs.data(), key);
e.not_inplace(&mut overflow);
(FheUint8 { data: out }, FheBool { data: overflow })
})
}
/// Returns (quotient, remainder) s.t. self = rhs x quotient +
/// remainder.
///
/// If rhs is 0, then quotient = 255, remainder = self, and Div by
/// Zero error flag (accessible via `div_zero_error_flag`) is set to
/// `True`
pub fn div_rem(&self, rhs: &FheUint8) -> (FheUint8, FheUint8) {
// set div by 0 error flag
set_div_by_zero_flag(rhs);
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let (quotient, remainder) = arbitrary_bit_division_for_quotient_and_rem(
e,
self.data(),
rhs.data(),
key,
);
(FheUint8 { data: quotient }, FheUint8 { data: remainder })
})
}
}
}
mod booleans {
use crate::shortint::ops::{
arbitrary_bit_comparator, arbitrary_bit_equality, arbitrary_bit_mux,
};
use super::*;
impl FheUint8 {
/// Returns `FheBool` indicating `Self == other`
pub fn eq(&self, other: &FheUint8) -> FheBool {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let out = arbitrary_bit_equality(e, self.data(), other.data(), key);
FheBool { data: out }
})
}
/// Returns `FheBool` indicating `Self != other`
pub fn neq(&self, other: &FheUint8) -> FheBool {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let mut is_equal = arbitrary_bit_equality(e, self.data(), other.data(), key);
e.not_inplace(&mut is_equal);
FheBool { data: is_equal }
})
}
/// Returns `FheBool` indicating `Self < other`
pub fn lt(&self, other: &FheUint8) -> FheBool {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let out = arbitrary_bit_comparator(e, other.data(), self.data(), key);
FheBool { data: out }
})
}
/// Returns `FheBool` indicating `Self > other`
pub fn gt(&self, other: &FheUint8) -> FheBool {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let out = arbitrary_bit_comparator(e, self.data(), other.data(), key);
FheBool { data: out }
})
}
/// Returns `FheBool` indicating `Self <= other`
pub fn le(&self, other: &FheUint8) -> FheBool {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let mut a_greater_b =
arbitrary_bit_comparator(e, self.data(), other.data(), key);
e.not_inplace(&mut a_greater_b);
FheBool { data: a_greater_b }
})
}
/// Returns `FheBool` indicating `Self >= other`
pub fn ge(&self, other: &FheUint8) -> FheBool {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let mut a_less_b = arbitrary_bit_comparator(e, other.data(), self.data(), key);
e.not_inplace(&mut a_less_b);
FheBool { data: a_less_b }
})
}
/// Returns `Self` if `selector = True` else returns `other`
pub fn mux(&self, other: &FheUint8, selector: &FheBool) -> FheUint8 {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
let out = arbitrary_bit_mux(e, selector.data(), self.data(), other.data(), key);
FheUint8 { data: out }
})
}
/// Returns max(`Self`, `other`)
pub fn max(&self, other: &FheUint8) -> FheUint8 {
let self_gt = self.gt(other);
self.mux(other, &self_gt)
}
/// Returns min(`Self`, `other`)
pub fn min(&self, other: &FheUint8) -> FheUint8 {
let self_lt = self.lt(other);
self.mux(other, &self_lt)
}
}
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/shortint/ops.rs | src/shortint/ops.rs | use itertools::{izip, Itertools};
use crate::bool::BooleanGates;
pub(super) fn half_adder<E: BooleanGates>(
evaluator: &mut E,
a: &mut E::Ciphertext,
b: &E::Ciphertext,
key: &E::Key,
) -> E::Ciphertext {
let carry = evaluator.and(a, b, key);
evaluator.xor_inplace(a, b, key);
carry
}
pub(super) fn full_adder_plain_carry_in<E: BooleanGates>(
evaluator: &mut E,
a: &mut E::Ciphertext,
b: &E::Ciphertext,
carry_in: bool,
key: &E::Key,
) -> E::Ciphertext {
let mut a_and_b = evaluator.and(a, b, key);
evaluator.xor_inplace(a, b, key); //a = a ^ b
if carry_in {
// a_and_b = A & B | ((A^B) & C_in={True})
evaluator.or_inplace(&mut a_and_b, &a, key);
} else {
// a_and_b = A & B | ((A^B) & C_in={False})
// a_and_b = A & B
// noop
}
// In xor if a input is 0, output equals the firt variable. If input is 1 then
// output equals !(first variable)
if carry_in {
// (A^B)^1 = !(A^B)
evaluator.not_inplace(a);
} else {
// (A^B)^0
// no-op
}
a_and_b
}
pub(super) fn full_adder<E: BooleanGates>(
evaluator: &mut E,
a: &mut E::Ciphertext,
b: &E::Ciphertext,
carry_in: &E::Ciphertext,
key: &E::Key,
) -> E::Ciphertext {
let mut a_and_b = evaluator.and(a, b, key);
evaluator.xor_inplace(a, b, key); //a = a ^ b
let a_xor_b_and_c = evaluator.and(&a, carry_in, key);
evaluator.or_inplace(&mut a_and_b, &a_xor_b_and_c, key); // a_and_b = A & B | ((A^B) & C_in)
evaluator.xor_inplace(a, &carry_in, key);
a_and_b
}
pub(super) fn arbitrary_bit_adder<E: BooleanGates>(
evaluator: &mut E,
a: &mut [E::Ciphertext],
b: &[E::Ciphertext],
carry_in: bool,
key: &E::Key,
) -> (E::Ciphertext, E::Ciphertext)
where
E::Ciphertext: Clone,
{
assert!(a.len() == b.len());
let n = a.len();
let mut carry = if !carry_in {
half_adder(evaluator, &mut a[0], &b[0], key)
} else {
full_adder_plain_carry_in(evaluator, &mut a[0], &b[0], true, key)
};
izip!(a.iter_mut(), b.iter())
.skip(1)
.take(n - 3)
.for_each(|(a_bit, b_bit)| {
carry = full_adder(evaluator, a_bit, b_bit, &carry, key);
});
let carry_last_last = full_adder(evaluator, &mut a[n - 2], &b[n - 2], &carry, key);
let carry_last = full_adder(evaluator, &mut a[n - 1], &b[n - 1], &carry_last_last, key);
(carry_last, carry_last_last)
}
pub(super) fn arbitrary_bit_subtractor<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
b: &[E::Ciphertext],
key: &E::Key,
) -> (Vec<E::Ciphertext>, E::Ciphertext, E::Ciphertext)
where
E::Ciphertext: Clone,
{
let mut neg_b: Vec<E::Ciphertext> = b.iter().map(|v| evaluator.not(v)).collect();
let (carry_last, carry_last_last) = arbitrary_bit_adder(evaluator, &mut neg_b, &a, true, key);
return (neg_b, carry_last, carry_last_last);
}
pub(super) fn bit_mux<E: BooleanGates>(
evaluator: &mut E,
selector: E::Ciphertext,
if_true: &E::Ciphertext,
if_false: &E::Ciphertext,
key: &E::Key,
) -> E::Ciphertext {
// (s&a) | ((1-s)^b)
let not_selector = evaluator.not(&selector);
let mut s_and_a = evaluator.and(&selector, if_true, key);
let s_and_b = evaluator.and(¬_selector, if_false, key);
evaluator.or(&mut s_and_a, &s_and_b, key);
s_and_a
}
pub(super) fn arbitrary_bit_mux<E: BooleanGates>(
evaluator: &mut E,
selector: &E::Ciphertext,
if_true: &[E::Ciphertext],
if_false: &[E::Ciphertext],
key: &E::Key,
) -> Vec<E::Ciphertext> {
// (s&a) | ((1-s)^b)
let not_selector = evaluator.not(&selector);
izip!(if_true.iter(), if_false.iter())
.map(|(a, b)| {
let mut s_and_a = evaluator.and(&selector, a, key);
let s_and_b = evaluator.and(¬_selector, b, key);
evaluator.or_inplace(&mut s_and_a, &s_and_b, key);
s_and_a
})
.collect()
}
pub(super) fn eight_bit_mul<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
b: &[E::Ciphertext],
key: &E::Key,
) -> Vec<E::Ciphertext> {
assert!(a.len() == 8);
assert!(b.len() == 8);
let mut carries = Vec::with_capacity(7);
let mut out = Vec::with_capacity(8);
for i in (0..8) {
if i == 0 {
let s = evaluator.and(&a[0], &b[0], key);
out.push(s);
} else if i == 1 {
let mut tmp0 = evaluator.and(&a[1], &b[0], key);
let tmp1 = evaluator.and(&a[0], &b[1], key);
let carry = half_adder(evaluator, &mut tmp0, &tmp1, key);
carries.push(carry);
out.push(tmp0);
} else {
let mut sum = {
let mut sum = evaluator.and(&a[i], &b[0], key);
let tmp = evaluator.and(&a[i - 1], &b[1], key);
carries[0] = full_adder(evaluator, &mut sum, &tmp, &carries[0], key);
sum
};
for j in 2..i {
let tmp = evaluator.and(&a[i - j], &b[j], key);
carries[j - 1] = full_adder(evaluator, &mut sum, &tmp, &carries[j - 1], key);
}
let tmp = evaluator.and(&a[0], &b[i], key);
let carry = half_adder(evaluator, &mut sum, &tmp, key);
carries.push(carry);
out.push(sum)
}
debug_assert!(carries.len() <= 7);
}
out
}
pub(super) fn arbitrary_bit_division_for_quotient_and_rem<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
b: &[E::Ciphertext],
key: &E::Key,
) -> (Vec<E::Ciphertext>, Vec<E::Ciphertext>)
where
E::Ciphertext: Clone,
{
let n = a.len();
let neg_b = b.iter().map(|v| evaluator.not(v)).collect_vec();
// Both remainder and quotient are initially stored in Big-endian in contrast to
// the usual little endian we use. This is more friendly to vec pushes in
// division. After computing remainder and quotient, we simply reverse the
// vectors.
let mut remainder = vec![];
let mut quotient = vec![];
for i in 0..n {
// left shift
remainder.push(a[n - 1 - i].clone());
let mut subtract = remainder.clone();
// subtraction
// At i^th iteration remainder is only filled with i bits and the rest of the
// bits are zero. For example, at i = 1
// 0 0 0 0 0 0 X X => remainder
// - Y Y Y Y Y Y Y Y => divisor .
// --------------- .
// Z Z Z Z Z Z Z Z => result
// For the next iteration we only care about result if divisor is <= remainder
// (which implies result <= remainder). Otherwise we care about remainder
// (recall re-storing division). Hence we optimise subtraction and
// ignore full adders for places where remainder bits are known to be false
// bits. We instead use `ANDs` to compute the carry overs, since the
// last carry over indicates whether the value has overflown (i.e. divisor <=
// remainder). Last carry out is `true` if value has not overflown, otherwise
// false.
let mut carry =
full_adder_plain_carry_in(evaluator, &mut subtract[i], &neg_b[0], true, key);
for j in 1..i + 1 {
carry = full_adder(evaluator, &mut subtract[i - j], &neg_b[j], &carry, key);
}
for j in i + 1..n {
// All I care about are the carries
evaluator.and_inplace(&mut carry, &neg_b[j], key);
}
let not_carry = evaluator.not(&carry);
// Choose `remainder` if subtraction has overflown (i.e. carry = false).
// Otherwise choose `subtractor`.
//
// mux k^a | !(k)^b, where k is the selector.
izip!(remainder.iter_mut(), subtract.iter_mut()).for_each(|(r, s)| {
// choose `s` when carry is true, otherwise choose r
evaluator.and_inplace(s, &carry, key);
evaluator.and_inplace(r, ¬_carry, key);
evaluator.or_inplace(r, s, key);
});
// Set i^th MSB of quotient to 1 if carry = true, otherwise set it to 0.
// X&1 | X&0 => X&1 => X
quotient.push(carry);
}
remainder.reverse();
quotient.reverse();
(quotient, remainder)
}
pub(super) fn is_zero<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
key: &E::Key,
) -> E::Ciphertext {
let mut a = a.iter().map(|v| evaluator.not(v)).collect_vec();
let (out, rest_a) = a.split_at_mut(1);
rest_a.iter().for_each(|c| {
evaluator.and_inplace(&mut out[0], c, key);
});
return a.remove(0);
}
pub(super) fn arbitrary_bit_equality<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
b: &[E::Ciphertext],
key: &E::Key,
) -> E::Ciphertext {
assert!(a.len() == b.len());
let mut out = evaluator.xnor(&a[0], &b[0], key);
izip!(a.iter(), b.iter()).skip(1).for_each(|(abit, bbit)| {
let e = evaluator.xnor(abit, bbit, key);
evaluator.and_inplace(&mut out, &e, key);
});
return out;
}
/// Comparator handle computes comparator result 2ns MSB onwards. It is
/// separated because comparator subroutine for signed and unsgind integers
/// differs only for 1st MSB and is common second MSB onwards
fn _comparator_handler_from_second_msb<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
b: &[E::Ciphertext],
mut comp: E::Ciphertext,
mut casc: E::Ciphertext,
key: &E::Key,
) -> E::Ciphertext {
let n = a.len();
// handle MSB - 1
let mut tmp = evaluator.not(&b[n - 2]);
evaluator.and_inplace(&mut tmp, &a[n - 2], key);
evaluator.and_inplace(&mut tmp, &casc, key);
evaluator.or_inplace(&mut comp, &tmp, key);
for i in 2..n {
// calculate cascading bit
let tmp_casc = evaluator.xnor(&a[n - i], &b[n - i], key);
evaluator.and_inplace(&mut casc, &tmp_casc, key);
// calculate computate bit
let mut tmp = evaluator.not(&b[n - 1 - i]);
evaluator.and_inplace(&mut tmp, &a[n - 1 - i], key);
evaluator.and_inplace(&mut tmp, &casc, key);
evaluator.or_inplace(&mut comp, &tmp, key);
}
return comp;
}
/// Signed integer comparison is same as unsigned integer with MSB flipped.
pub(super) fn arbitrary_signed_bit_comparator<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
b: &[E::Ciphertext],
key: &E::Key,
) -> E::Ciphertext {
assert!(a.len() == b.len());
let n = a.len();
// handle MSB
let mut comp = evaluator.not(&a[n - 1]);
evaluator.and_inplace(&mut comp, &b[n - 1], key); // comp
let casc = evaluator.xnor(&a[n - 1], &b[n - 1], key); // casc
return _comparator_handler_from_second_msb(evaluator, a, b, comp, casc, key);
}
pub(super) fn arbitrary_bit_comparator<E: BooleanGates>(
evaluator: &mut E,
a: &[E::Ciphertext],
b: &[E::Ciphertext],
key: &E::Key,
) -> E::Ciphertext {
assert!(a.len() == b.len());
let n = a.len();
// handle MSB
let mut comp = evaluator.not(&b[n - 1]);
evaluator.and_inplace(&mut comp, &a[n - 1], key);
let casc = evaluator.xnor(&a[n - 1], &b[n - 1], key);
return _comparator_handler_from_second_msb(evaluator, a, b, comp, casc, key);
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/backend/word_size.rs | src/backend/word_size.rs | use itertools::izip;
use num_traits::{WrappingAdd, WrappingMul, WrappingSub, Zero};
use super::{ArithmeticOps, GetModulus, ModInit, Modulus, VectorOps};
pub struct WordSizeModulus<T> {
modulus: T,
}
impl<T> ModInit for WordSizeModulus<T>
where
T: Modulus,
{
type M = T;
fn new(modulus: T) -> Self {
assert!(modulus.is_native());
// For now assume ModulusOpsU64 is only used for u64
Self { modulus: modulus }
}
}
impl<T> ArithmeticOps for WordSizeModulus<T>
where
T: Modulus,
T::Element: WrappingAdd + WrappingSub + WrappingMul + Zero,
{
type Element = T::Element;
fn add(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
T::Element::wrapping_add(a, b)
}
fn mul(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
T::Element::wrapping_mul(a, b)
}
fn neg(&self, a: &Self::Element) -> Self::Element {
T::Element::wrapping_sub(&T::Element::zero(), a)
}
fn sub(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
T::Element::wrapping_sub(a, b)
}
}
impl<T> VectorOps for WordSizeModulus<T>
where
T: Modulus,
T::Element: WrappingAdd + WrappingSub + WrappingMul + Zero,
{
type Element = T::Element;
fn elwise_add_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = T::Element::wrapping_add(ai, bi);
});
}
fn elwise_sub_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = T::Element::wrapping_sub(ai, bi);
});
}
fn elwise_mul_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = T::Element::wrapping_mul(ai, bi);
});
}
fn elwise_neg_mut(&self, a: &mut [Self::Element]) {
a.iter_mut()
.for_each(|ai| *ai = T::Element::wrapping_sub(&T::Element::zero(), ai));
}
fn elwise_scalar_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &Self::Element) {
izip!(out.iter_mut(), a.iter()).for_each(|(oi, ai)| {
*oi = T::Element::wrapping_mul(ai, b);
});
}
fn elwise_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &[Self::Element]) {
izip!(out.iter_mut(), a.iter(), b.iter()).for_each(|(oi, ai, bi)| {
*oi = T::Element::wrapping_mul(ai, bi);
});
}
fn elwise_scalar_mul_mut(&self, a: &mut [Self::Element], b: &Self::Element) {
a.iter_mut().for_each(|ai| {
*ai = T::Element::wrapping_mul(ai, b);
});
}
fn elwise_fma_mut(&self, a: &mut [Self::Element], b: &[Self::Element], c: &[Self::Element]) {
izip!(a.iter_mut(), b.iter(), c.iter()).for_each(|(ai, bi, ci)| {
*ai = T::Element::wrapping_add(ai, &T::Element::wrapping_mul(bi, ci));
});
}
fn elwise_fma_scalar_mut(
&self,
a: &mut [Self::Element],
b: &[Self::Element],
c: &Self::Element,
) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = T::Element::wrapping_add(ai, &T::Element::wrapping_mul(bi, c));
});
}
// fn modulus(&self) -> &T {
// &self.modulus
// }
}
impl<T> GetModulus for WordSizeModulus<T>
where
T: Modulus,
{
type Element = T::Element;
type M = T;
fn modulus(&self) -> &Self::M {
&self.modulus
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/backend/power_of_2.rs | src/backend/power_of_2.rs | use itertools::izip;
use crate::{ArithmeticOps, ModInit, VectorOps};
use super::{GetModulus, Modulus};
pub(crate) struct ModulusPowerOf2<T> {
modulus: T,
/// Modulus mask: (1 << q) - 1
mask: u64,
}
impl<T> ArithmeticOps for ModulusPowerOf2<T> {
type Element = u64;
#[inline]
fn add(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
(a.wrapping_add(*b)) & self.mask
}
#[inline]
fn sub(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
(a.wrapping_sub(*b)) & self.mask
}
#[inline]
fn mul(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
(a.wrapping_mul(*b)) & self.mask
}
#[inline]
fn neg(&self, a: &Self::Element) -> Self::Element {
(0u64.wrapping_sub(*a)) & self.mask
}
}
impl<T> VectorOps for ModulusPowerOf2<T> {
type Element = u64;
#[inline]
fn elwise_add_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(a0, b0)| *a0 = (a0.wrapping_add(*b0)) & self.mask);
}
#[inline]
fn elwise_mul_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(a0, b0)| *a0 = (a0.wrapping_mul(*b0)) & self.mask);
}
#[inline]
fn elwise_neg_mut(&self, a: &mut [Self::Element]) {
a.iter_mut()
.for_each(|a0| *a0 = 0u64.wrapping_sub(*a0) & self.mask);
}
#[inline]
fn elwise_sub_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(a0, b0)| *a0 = (a0.wrapping_sub(*b0)) & self.mask);
}
#[inline]
fn elwise_fma_mut(&self, a: &mut [Self::Element], b: &[Self::Element], c: &[Self::Element]) {
izip!(a.iter_mut(), b.iter(), c.iter()).for_each(|(a0, b0, c0)| {
*a0 = a0.wrapping_add(b0.wrapping_mul(*c0)) & self.mask;
});
}
#[inline]
fn elwise_fma_scalar_mut(
&self,
a: &mut [Self::Element],
b: &[Self::Element],
c: &Self::Element,
) {
izip!(a.iter_mut(), b.iter()).for_each(|(a0, b0)| {
*a0 = a0.wrapping_add(b0.wrapping_mul(*c)) & self.mask;
});
}
#[inline]
fn elwise_scalar_mul_mut(&self, a: &mut [Self::Element], b: &Self::Element) {
a.iter_mut()
.for_each(|a0| *a0 = a0.wrapping_mul(*b) & self.mask)
}
#[inline]
fn elwise_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &[Self::Element]) {
izip!(out.iter_mut(), a.iter(), b.iter()).for_each(|(o0, a0, b0)| {
*o0 = a0.wrapping_mul(*b0) & self.mask;
});
}
#[inline]
fn elwise_scalar_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &Self::Element) {
izip!(out.iter_mut(), a.iter()).for_each(|(o0, a0)| {
*o0 = a0.wrapping_mul(*b) & self.mask;
});
}
}
impl<T: Modulus<Element = u64>> ModInit for ModulusPowerOf2<T> {
type M = T;
fn new(modulus: Self::M) -> Self {
assert!(!modulus.is_native());
assert!(modulus.q().unwrap().is_power_of_two());
let q = modulus.q().unwrap();
let mask = q - 1;
Self { modulus, mask }
}
}
impl<T: Modulus<Element = u64>> GetModulus for ModulusPowerOf2<T> {
type Element = u64;
type M = T;
fn modulus(&self) -> &Self::M {
&self.modulus
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/backend/mod.rs | src/backend/mod.rs | use num_traits::ToPrimitive;
use crate::{utils::log2, Row};
mod modulus_u64;
mod power_of_2;
mod word_size;
pub use modulus_u64::ModularOpsU64;
pub(crate) use power_of_2::ModulusPowerOf2;
pub trait Modulus {
type Element;
/// Modulus value if it fits in Element
fn q(&self) -> Option<Self::Element>;
/// Log2 of `q`
fn log_q(&self) -> usize;
/// Modulus value as f64 if it fits in f64
fn q_as_f64(&self) -> Option<f64>;
/// Is modulus native?
fn is_native(&self) -> bool;
/// -1 in signed representaiton
fn neg_one(&self) -> Self::Element;
/// Largest unsigned value that fits in the modulus. That is, q - 1.
fn largest_unsigned_value(&self) -> Self::Element;
/// Smallest unsigned value that fits in the modulus
/// Always assmed to be 0.
fn smallest_unsigned_value(&self) -> Self::Element;
/// Convert unsigned value in signed represetation to i64
fn map_element_to_i64(&self, v: &Self::Element) -> i64;
/// Convert f64 to signed represented in modulus
fn map_element_from_f64(&self, v: f64) -> Self::Element;
/// Convert i64 to signed represented in modulus
fn map_element_from_i64(&self, v: i64) -> Self::Element;
}
impl Modulus for u64 {
type Element = u64;
fn is_native(&self) -> bool {
// q that fits in u64 can never be a native modulus
false
}
fn largest_unsigned_value(&self) -> Self::Element {
self - 1
}
fn neg_one(&self) -> Self::Element {
self - 1
}
fn smallest_unsigned_value(&self) -> Self::Element {
0
}
fn map_element_to_i64(&self, v: &Self::Element) -> i64 {
assert!(v <= self, "{v} must be <= {self}");
if *v >= (self >> 1) {
-ToPrimitive::to_i64(&(self - v)).unwrap()
} else {
ToPrimitive::to_i64(v).unwrap()
}
}
fn map_element_from_f64(&self, v: f64) -> Self::Element {
let v = v.round();
let v_u64 = v.abs().to_u64().unwrap();
assert!(v_u64 <= self.largest_unsigned_value());
if v < 0.0 {
self - v_u64
} else {
v_u64
}
}
fn map_element_from_i64(&self, v: i64) -> Self::Element {
let v_u64 = v.abs().to_u64().unwrap();
assert!(v_u64 <= self.largest_unsigned_value());
if v < 0 {
self - v_u64
} else {
v_u64
}
}
fn q(&self) -> Option<Self::Element> {
Some(*self)
}
fn q_as_f64(&self) -> Option<f64> {
self.to_f64()
}
fn log_q(&self) -> usize {
log2(&self.q().unwrap())
}
}
pub trait ModInit {
type M;
fn new(modulus: Self::M) -> Self;
}
pub trait GetModulus {
type Element;
type M: Modulus<Element = Self::Element>;
fn modulus(&self) -> &Self::M;
}
pub trait VectorOps {
type Element;
/// Sets out as `out[i] = a[i] * b`
fn elwise_scalar_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &Self::Element);
fn elwise_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &[Self::Element]);
fn elwise_add_mut(&self, a: &mut [Self::Element], b: &[Self::Element]);
fn elwise_sub_mut(&self, a: &mut [Self::Element], b: &[Self::Element]);
fn elwise_mul_mut(&self, a: &mut [Self::Element], b: &[Self::Element]);
fn elwise_scalar_mul_mut(&self, a: &mut [Self::Element], b: &Self::Element);
fn elwise_neg_mut(&self, a: &mut [Self::Element]);
/// inplace mutates `a`: a = a + b*c
fn elwise_fma_mut(&self, a: &mut [Self::Element], b: &[Self::Element], c: &[Self::Element]);
fn elwise_fma_scalar_mut(
&self,
a: &mut [Self::Element],
b: &[Self::Element],
c: &Self::Element,
);
}
pub trait ArithmeticOps {
type Element;
fn mul(&self, a: &Self::Element, b: &Self::Element) -> Self::Element;
fn add(&self, a: &Self::Element, b: &Self::Element) -> Self::Element;
fn sub(&self, a: &Self::Element, b: &Self::Element) -> Self::Element;
fn neg(&self, a: &Self::Element) -> Self::Element;
}
pub trait ArithmeticLazyOps {
type Element;
fn mul_lazy(&self, a: &Self::Element, b: &Self::Element) -> Self::Element;
fn add_lazy(&self, a: &Self::Element, b: &Self::Element) -> Self::Element;
}
pub trait ShoupMatrixFMA<R: Row> {
/// Returns summation of `row-wise product of matrix a and b` + out where
/// each element is in range [0, 2q)
fn shoup_matrix_fma(&self, out: &mut [R::Element], a: &[R], a_shoup: &[R], b: &[R]);
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/backend/modulus_u64.rs | src/backend/modulus_u64.rs | use itertools::izip;
use num_traits::WrappingMul;
use super::{
ArithmeticLazyOps, ArithmeticOps, GetModulus, ModInit, Modulus, ShoupMatrixFMA, VectorOps,
};
use crate::RowMut;
pub struct ModularOpsU64<T> {
q: u64,
q_twice: u64,
logq: usize,
barrett_mu: u128,
barrett_alpha: usize,
modulus: T,
}
impl<T> ModInit for ModularOpsU64<T>
where
T: Modulus<Element = u64>,
{
type M = T;
fn new(modulus: Self::M) -> ModularOpsU64<T> {
assert!(!modulus.is_native());
// largest unsigned value modulus fits is modulus-1
let q = modulus.largest_unsigned_value() + 1;
let logq = 64 - (q + 1u64).leading_zeros();
// barrett calculation
let mu = (1u128 << (logq * 2 + 3)) / (q as u128);
let alpha = logq + 3;
ModularOpsU64 {
q,
q_twice: q << 1,
logq: logq as usize,
barrett_alpha: alpha as usize,
barrett_mu: mu,
modulus,
}
}
}
impl<T> ModularOpsU64<T> {
fn add_mod_fast(&self, a: u64, b: u64) -> u64 {
debug_assert!(a < self.q);
debug_assert!(b < self.q);
let mut o = a + b;
if o >= self.q {
o -= self.q;
}
o
}
fn add_mod_fast_lazy(&self, a: u64, b: u64) -> u64 {
debug_assert!(a < self.q_twice);
debug_assert!(b < self.q_twice);
let mut o = a + b;
if o >= self.q_twice {
o -= self.q_twice;
}
o
}
fn sub_mod_fast(&self, a: u64, b: u64) -> u64 {
debug_assert!(a < self.q);
debug_assert!(b < self.q);
if a >= b {
a - b
} else {
(self.q + a) - b
}
}
// returns (a * b) % q
///
/// - both a and b must be in range [0, 2q)
/// - output is in range [0 , 2q)
fn mul_mod_fast_lazy(&self, a: u64, b: u64) -> u64 {
debug_assert!(a < 2 * self.q);
debug_assert!(b < 2 * self.q);
let ab = a as u128 * b as u128;
// ab / (2^{n + \beta})
// note: \beta is assumed to -2
let tmp = ab >> (self.logq - 2);
// k = ((ab / (2^{n + \beta})) * \mu) / 2^{\alpha - (-2)}
let k = (tmp * self.barrett_mu) >> (self.barrett_alpha + 2);
// ab - k*p
let tmp = k * (self.q as u128);
(ab - tmp) as u64
}
/// returns (a * b) % q
///
/// - both a and b must be in range [0, 2q)
/// - output is in range [0 , q)
fn mul_mod_fast(&self, a: u64, b: u64) -> u64 {
debug_assert!(a < 2 * self.q);
debug_assert!(b < 2 * self.q);
let ab = a as u128 * b as u128;
// ab / (2^{n + \beta})
// note: \beta is assumed to -2
let tmp = ab >> (self.logq - 2);
// k = ((ab / (2^{n + \beta})) * \mu) / 2^{\alpha - (-2)}
let k = (tmp * self.barrett_mu) >> (self.barrett_alpha + 2);
// ab - k*p
let tmp = k * (self.q as u128);
let mut out = (ab - tmp) as u64;
if out >= self.q {
out -= self.q;
}
return out;
}
}
impl<T> ArithmeticOps for ModularOpsU64<T> {
type Element = u64;
fn add(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
self.add_mod_fast(*a, *b)
}
fn mul(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
self.mul_mod_fast(*a, *b)
}
fn sub(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
self.sub_mod_fast(*a, *b)
}
fn neg(&self, a: &Self::Element) -> Self::Element {
self.q - *a
}
// fn modulus(&self) -> Self::Element {
// self.q
// }
}
impl<T> ArithmeticLazyOps for ModularOpsU64<T> {
type Element = u64;
fn add_lazy(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
self.add_mod_fast_lazy(*a, *b)
}
fn mul_lazy(&self, a: &Self::Element, b: &Self::Element) -> Self::Element {
self.mul_mod_fast_lazy(*a, *b)
}
}
impl<T> VectorOps for ModularOpsU64<T> {
type Element = u64;
fn elwise_add_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = self.add_mod_fast(*ai, *bi);
});
}
fn elwise_sub_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = self.sub_mod_fast(*ai, *bi);
});
}
fn elwise_mul_mut(&self, a: &mut [Self::Element], b: &[Self::Element]) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = self.mul_mod_fast(*ai, *bi);
});
}
fn elwise_neg_mut(&self, a: &mut [Self::Element]) {
a.iter_mut().for_each(|ai| *ai = self.q - *ai);
}
fn elwise_scalar_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &Self::Element) {
izip!(out.iter_mut(), a.iter()).for_each(|(oi, ai)| {
*oi = self.mul_mod_fast(*ai, *b);
});
}
fn elwise_mul(&self, out: &mut [Self::Element], a: &[Self::Element], b: &[Self::Element]) {
izip!(out.iter_mut(), a.iter(), b.iter()).for_each(|(oi, ai, bi)| {
*oi = self.mul_mod_fast(*ai, *bi);
});
}
fn elwise_scalar_mul_mut(&self, a: &mut [Self::Element], b: &Self::Element) {
a.iter_mut().for_each(|ai| {
*ai = self.mul_mod_fast(*ai, *b);
});
}
fn elwise_fma_mut(&self, a: &mut [Self::Element], b: &[Self::Element], c: &[Self::Element]) {
izip!(a.iter_mut(), b.iter(), c.iter()).for_each(|(ai, bi, ci)| {
*ai = self.add_mod_fast(*ai, self.mul_mod_fast(*bi, *ci));
});
}
fn elwise_fma_scalar_mut(
&self,
a: &mut [Self::Element],
b: &[Self::Element],
c: &Self::Element,
) {
izip!(a.iter_mut(), b.iter()).for_each(|(ai, bi)| {
*ai = self.add_mod_fast(*ai, self.mul_mod_fast(*bi, *c));
});
}
// fn modulus(&self) -> Self::Element {
// self.q
// }
}
impl<R: RowMut<Element = u64>, T> ShoupMatrixFMA<R> for ModularOpsU64<T> {
fn shoup_matrix_fma(&self, out: &mut [R::Element], a: &[R], a_shoup: &[R], b: &[R]) {
assert!(a.len() == a_shoup.len());
assert!(
a.len() == b.len(),
"Unequal length {}!={}",
a.len(),
b.len()
);
let q = self.q;
let q_twice = self.q << 1;
izip!(a.iter(), a_shoup.iter(), b.iter()).for_each(|(a_row, a_shoup_row, b_row)| {
izip!(
out.as_mut().iter_mut(),
a_row.as_ref().iter(),
a_shoup_row.as_ref().iter(),
b_row.as_ref().iter()
)
.for_each(|(o, a0, a0_shoup, b0)| {
let quotient = ((*a0_shoup as u128 * *b0 as u128) >> 64) as u64;
let mut v = (a0.wrapping_mul(b0)).wrapping_add(*o);
v = v.wrapping_sub(q.wrapping_mul(quotient));
if v >= q_twice {
v -= q_twice;
}
*o = v;
});
});
}
}
impl<T> GetModulus for ModularOpsU64<T>
where
T: Modulus,
{
type Element = T::Element;
type M = T;
fn modulus(&self) -> &Self::M {
&self.modulus
}
}
#[cfg(test)]
mod tests {
use super::*;
use itertools::Itertools;
use rand::{thread_rng, Rng};
use rand_distr::Uniform;
#[test]
fn fma() {
let mut rng = thread_rng();
let prime = 36028797017456641;
let ring_size = 1 << 3;
let dist = Uniform::new(0, prime);
let d = 2;
let a0_matrix = (0..d)
.into_iter()
.map(|_| (&mut rng).sample_iter(dist).take(ring_size).collect_vec())
.collect_vec();
// a0 in shoup representation
let a0_shoup_matrix = a0_matrix
.iter()
.map(|r| {
r.iter()
.map(|v| {
// $(v * 2^{\beta}) / p$
((*v as u128 * (1u128 << 64)) / prime as u128) as u64
})
.collect_vec()
})
.collect_vec();
let a1_matrix = (0..d)
.into_iter()
.map(|_| (&mut rng).sample_iter(dist).take(ring_size).collect_vec())
.collect_vec();
let modop = ModularOpsU64::new(prime);
let mut out_shoup_fma_lazy = vec![0u64; ring_size];
modop.shoup_matrix_fma(
&mut out_shoup_fma_lazy,
&a0_matrix,
&a0_shoup_matrix,
&a1_matrix,
);
let out_shoup_fma = out_shoup_fma_lazy
.iter()
.map(|v| if *v >= prime { v - prime } else { *v })
.collect_vec();
// expected
let mut out_expected = vec![0u64; ring_size];
izip!(a0_matrix.iter(), a1_matrix.iter()).for_each(|(a_r, b_r)| {
izip!(out_expected.iter_mut(), a_r.iter(), b_r.iter()).for_each(|(o, a0, a1)| {
*o = (*o + ((*a0 as u128 * *a1 as u128) % prime as u128) as u64) % prime;
});
});
assert_eq!(out_expected, out_shoup_fma);
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/bool/mp_api.rs | src/bool/mp_api.rs | use std::{cell::RefCell, sync::OnceLock};
use crate::{
backend::{ModularOpsU64, ModulusPowerOf2},
ntt::NttBackendU64,
random::{DefaultSecureRng, NewWithSeed},
utils::{Global, WithLocal},
};
use super::{evaluator::InteractiveMultiPartyCrs, keys::*, parameters::*, ClientKey};
pub(crate) type BoolEvaluator = super::evaluator::BoolEvaluator<
Vec<Vec<u64>>,
NttBackendU64,
ModularOpsU64<CiphertextModulus<u64>>,
ModulusPowerOf2<CiphertextModulus<u64>>,
ShoupServerKeyEvaluationDomain<Vec<Vec<u64>>>,
>;
thread_local! {
static BOOL_EVALUATOR: RefCell<Option<BoolEvaluator>> = RefCell::new(None);
}
static BOOL_SERVER_KEY: OnceLock<ShoupServerKeyEvaluationDomain<Vec<Vec<u64>>>> = OnceLock::new();
static MULTI_PARTY_CRS: OnceLock<InteractiveMultiPartyCrs<[u8; 32]>> = OnceLock::new();
pub enum ParameterSelector {
InteractiveLTE2Party,
InteractiveLTE4Party,
InteractiveLTE8Party,
}
/// Select Interactive multi-party parameter variant
pub fn set_parameter_set(select: ParameterSelector) {
match select {
ParameterSelector::InteractiveLTE2Party => {
BOOL_EVALUATOR.with_borrow_mut(|v| *v = Some(BoolEvaluator::new(I_2P_LB_SR)));
}
ParameterSelector::InteractiveLTE4Party => {
BOOL_EVALUATOR.with_borrow_mut(|v| *v = Some(BoolEvaluator::new(I_4P)));
}
ParameterSelector::InteractiveLTE8Party => {
BOOL_EVALUATOR.with_borrow_mut(|v| *v = Some(BoolEvaluator::new(I_8P)));
}
}
}
/// Set application specific interactive multi-party common reference string
pub fn set_common_reference_seed(seed: [u8; 32]) {
assert!(
MULTI_PARTY_CRS
.set(InteractiveMultiPartyCrs { seed: seed })
.is_ok(),
"Attempted to set MP SEED twice."
)
}
/// Generate client key for interactive multi-party protocol
pub fn gen_client_key() -> ClientKey {
BoolEvaluator::with_local(|e| e.client_key())
}
/// Generate client's share for collective public key, i.e round 1 share, of the
/// 2 round protocol
pub fn collective_pk_share(
ck: &ClientKey,
) -> CommonReferenceSeededCollectivePublicKeyShare<Vec<u64>, [u8; 32], BoolParameters<u64>> {
BoolEvaluator::with_local(|e| {
let pk_share = e.multi_party_public_key_share(InteractiveMultiPartyCrs::global(), ck);
pk_share
})
}
/// Generate clients share for collective server key, i.e. round 2, of the
/// 2 round protocol
pub fn collective_server_key_share<R, ModOp>(
ck: &ClientKey,
user_id: usize,
total_users: usize,
pk: &PublicKey<Vec<Vec<u64>>, R, ModOp>,
) -> CommonReferenceSeededInteractiveMultiPartyServerKeyShare<
Vec<Vec<u64>>,
BoolParameters<u64>,
InteractiveMultiPartyCrs<[u8; 32]>,
> {
BoolEvaluator::with_local_mut(|e| {
let server_key_share = e.gen_interactive_multi_party_server_key_share(
user_id,
total_users,
InteractiveMultiPartyCrs::global(),
pk.key(),
ck,
);
server_key_share
})
}
/// Aggregate public key shares from all parties.
///
/// Public key shares are generated per client in round 1. Aggregation of public
/// key shares marks the end of round 1.
pub fn aggregate_public_key_shares(
shares: &[CommonReferenceSeededCollectivePublicKeyShare<
Vec<u64>,
[u8; 32],
BoolParameters<u64>,
>],
) -> PublicKey<Vec<Vec<u64>>, DefaultSecureRng, ModularOpsU64<CiphertextModulus<u64>>> {
PublicKey::from(shares)
}
/// Aggregate server key shares
pub fn aggregate_server_key_shares(
shares: &[CommonReferenceSeededInteractiveMultiPartyServerKeyShare<
Vec<Vec<u64>>,
BoolParameters<u64>,
InteractiveMultiPartyCrs<[u8; 32]>,
>],
) -> SeededInteractiveMultiPartyServerKey<
Vec<Vec<u64>>,
InteractiveMultiPartyCrs<[u8; 32]>,
BoolParameters<u64>,
> {
BoolEvaluator::with_local(|e| e.aggregate_interactive_multi_party_server_key_shares(shares))
}
impl
SeededInteractiveMultiPartyServerKey<
Vec<Vec<u64>>,
InteractiveMultiPartyCrs<<DefaultSecureRng as NewWithSeed>::Seed>,
BoolParameters<u64>,
>
{
/// Sets the server key as a global reference for circuit evaluation
pub fn set_server_key(&self) {
assert!(
BOOL_SERVER_KEY
.set(ShoupServerKeyEvaluationDomain::from(
ServerKeyEvaluationDomain::<_, _, DefaultSecureRng, NttBackendU64>::from(self),
))
.is_ok(),
"Attempted to set server key twice."
);
}
}
// MULTIPARTY CRS //
impl Global for InteractiveMultiPartyCrs<[u8; 32]> {
fn global() -> &'static Self {
MULTI_PARTY_CRS
.get()
.expect("Multi Party Common Reference String not set")
}
}
// BOOL EVALUATOR //
impl WithLocal for BoolEvaluator {
fn with_local<F, R>(func: F) -> R
where
F: Fn(&Self) -> R,
{
BOOL_EVALUATOR.with_borrow(|s| func(s.as_ref().expect("Parameters not set")))
}
fn with_local_mut<F, R>(func: F) -> R
where
F: Fn(&mut Self) -> R,
{
BOOL_EVALUATOR.with_borrow_mut(|s| func(s.as_mut().expect("Parameters not set")))
}
fn with_local_mut_mut<F, R>(func: &mut F) -> R
where
F: FnMut(&mut Self) -> R,
{
BOOL_EVALUATOR.with_borrow_mut(|s| func(s.as_mut().expect("Parameters not set")))
}
}
pub(crate) type RuntimeServerKey = ShoupServerKeyEvaluationDomain<Vec<Vec<u64>>>;
impl Global for RuntimeServerKey {
fn global() -> &'static Self {
BOOL_SERVER_KEY.get().expect("Server key not set!")
}
}
mod impl_enc_dec {
use crate::{
bool::evaluator::BoolEncoding,
multi_party::{
multi_party_aggregate_decryption_shares_and_decrypt, multi_party_decryption_share,
},
pbs::{sample_extract, PbsInfo},
rgsw::public_key_encrypt_rlwe,
utils::TryConvertFrom1,
Encryptor, Matrix, MatrixEntity, MultiPartyDecryptor, RowEntity,
};
use itertools::Itertools;
use num_traits::{ToPrimitive, Zero};
use super::*;
type Mat = Vec<Vec<u64>>;
impl<Rng, ModOp> Encryptor<[bool], Vec<Mat>> for PublicKey<Mat, Rng, ModOp> {
fn encrypt(&self, m: &[bool]) -> Vec<Mat> {
BoolEvaluator::with_local(|e| {
DefaultSecureRng::with_local_mut(|rng| {
let parameters = e.parameters();
let ring_size = parameters.rlwe_n().0;
let rlwe_count = ((m.len() as f64 / ring_size as f64).ceil())
.to_usize()
.unwrap();
// encrypt `m` into ceil(len(m)/N) RLWE ciphertexts
let rlwes = (0..rlwe_count)
.map(|index| {
let mut message = vec![<Mat as Matrix>::MatElement::zero(); ring_size];
m[(index * ring_size)..std::cmp::min(m.len(), (index + 1) * ring_size)]
.iter()
.enumerate()
.for_each(|(i, v)| {
if *v {
message[i] = parameters.rlwe_q().true_el()
} else {
message[i] = parameters.rlwe_q().false_el()
}
});
// encrypt message
let mut rlwe_out =
<Mat as MatrixEntity>::zeros(2, parameters.rlwe_n().0);
public_key_encrypt_rlwe::<_, _, _, _, i32, _>(
&mut rlwe_out,
self.key(),
&message,
e.pbs_info().modop_rlweq(),
e.pbs_info().nttop_rlweq(),
rng,
);
rlwe_out
})
.collect_vec();
rlwes
})
})
}
}
impl<Rng, ModOp> Encryptor<bool, <Mat as Matrix>::R> for PublicKey<Mat, Rng, ModOp> {
fn encrypt(&self, m: &bool) -> <Mat as Matrix>::R {
let m = vec![*m];
let rlwe = &self.encrypt(m.as_slice())[0];
BoolEvaluator::with_local(|e| {
let mut lwe = <Mat as Matrix>::R::zeros(e.parameters().rlwe_n().0 + 1);
sample_extract(&mut lwe, rlwe, e.pbs_info().modop_rlweq(), 0);
lwe
})
}
}
impl<K> MultiPartyDecryptor<bool, <Mat as Matrix>::R> for K
where
K: InteractiveMultiPartyClientKey,
<Mat as Matrix>::R:
TryConvertFrom1<[K::Element], CiphertextModulus<<Mat as Matrix>::MatElement>>,
{
type DecryptionShare = <Mat as Matrix>::MatElement;
fn gen_decryption_share(&self, c: &<Mat as Matrix>::R) -> Self::DecryptionShare {
BoolEvaluator::with_local(|e| {
DefaultSecureRng::with_local_mut(|rng| {
multi_party_decryption_share(
c,
self.sk_rlwe().as_slice(),
e.pbs_info().modop_rlweq(),
rng,
)
})
})
}
fn aggregate_decryption_shares(
&self,
c: &<Mat as Matrix>::R,
shares: &[Self::DecryptionShare],
) -> bool {
BoolEvaluator::with_local(|e| {
let noisy_m = multi_party_aggregate_decryption_shares_and_decrypt(
c,
shares,
e.pbs_info().modop_rlweq(),
);
e.pbs_info().rlwe_q().decode(noisy_m)
})
}
}
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
use rand::{thread_rng, Rng, RngCore};
use crate::{bool::evaluator::BoolEncoding, Encryptor, MultiPartyDecryptor, SampleExtractor};
use super::*;
#[test]
fn batched_fhe_u8s_extract_works() {
set_parameter_set(ParameterSelector::InteractiveLTE2Party);
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let parties = 2;
let cks = (0..parties).map(|_| gen_client_key()).collect_vec();
// round 1
let pk_shares = cks.iter().map(|k| collective_pk_share(k)).collect_vec();
// collective pk
let pk = aggregate_public_key_shares(&pk_shares);
let parameters = BoolEvaluator::with_local(|e| e.parameters().clone());
let batch_size = parameters.rlwe_n().0 * 3 + 123;
let m = (0..batch_size)
.map(|_| thread_rng().gen::<u8>())
.collect_vec();
let seeded_ct = pk.encrypt(m.as_slice());
let m_back = (0..batch_size)
.map(|i| {
let ct = seeded_ct.extract_at(i);
cks[0].aggregate_decryption_shares(
&ct,
&cks.iter()
.map(|k| k.gen_decryption_share(&ct))
.collect_vec(),
)
})
.collect_vec();
assert_eq!(m, m_back);
}
mod sp_api {
use num_traits::ToPrimitive;
use crate::{
bool::impl_bool_frontend::FheBool, pbs::PbsInfo, rgsw::seeded_secret_key_encrypt_rlwe,
Decryptor,
};
use super::*;
pub(crate) fn set_single_party_parameter_sets(parameter: BoolParameters<u64>) {
BOOL_EVALUATOR.with_borrow_mut(|e| *e = Some(BoolEvaluator::new(parameter)));
}
// SERVER KEY EVAL (/SHOUP) DOMAIN //
impl SeededSinglePartyServerKey<Vec<Vec<u64>>, BoolParameters<u64>, [u8; 32]> {
pub fn set_server_key(&self) {
assert!(
BOOL_SERVER_KEY
.set(
ShoupServerKeyEvaluationDomain::from(ServerKeyEvaluationDomain::<
_,
_,
DefaultSecureRng,
NttBackendU64,
>::from(
self
),)
)
.is_ok(),
"Attempted to set server key twice."
);
}
}
pub(crate) fn gen_keys() -> (
ClientKey,
SeededSinglePartyServerKey<Vec<Vec<u64>>, BoolParameters<u64>, [u8; 32]>,
) {
super::BoolEvaluator::with_local_mut(|e| {
let ck = e.client_key();
let sk = e.single_party_server_key(&ck);
(ck, sk)
})
}
impl<K: SinglePartyClientKey<Element = i32>> Encryptor<bool, Vec<u64>> for K {
fn encrypt(&self, m: &bool) -> Vec<u64> {
BoolEvaluator::with_local(|e| e.sk_encrypt(*m, self))
}
}
impl<K: SinglePartyClientKey<Element = i32>> Decryptor<bool, Vec<u64>> for K {
fn decrypt(&self, c: &Vec<u64>) -> bool {
BoolEvaluator::with_local(|e| e.sk_decrypt(c, self))
}
}
impl<K: SinglePartyClientKey<Element = i32>, C> Encryptor<bool, FheBool<C>> for K
where
K: Encryptor<bool, C>,
{
fn encrypt(&self, m: &bool) -> FheBool<C> {
FheBool {
data: self.encrypt(m),
}
}
}
impl<K: SinglePartyClientKey<Element = i32>, C> Decryptor<bool, FheBool<C>> for K
where
K: Decryptor<bool, C>,
{
fn decrypt(&self, c: &FheBool<C>) -> bool {
self.decrypt(c.data())
}
}
impl<K> Encryptor<[bool], (Vec<Vec<u64>>, [u8; 32])> for K
where
K: SinglePartyClientKey<Element = i32>,
{
fn encrypt(&self, m: &[bool]) -> (Vec<Vec<u64>>, [u8; 32]) {
BoolEvaluator::with_local(|e| {
DefaultSecureRng::with_local_mut(|rng| {
let parameters = e.parameters();
let ring_size = parameters.rlwe_n().0;
let rlwe_count = ((m.len() as f64 / ring_size as f64).ceil())
.to_usize()
.unwrap();
let mut seed = <DefaultSecureRng as NewWithSeed>::Seed::default();
rng.fill_bytes(&mut seed);
let mut prng = DefaultSecureRng::new_seeded(seed);
let sk_u = self.sk_rlwe();
// encrypt `m` into ceil(len(m)/N) RLWE ciphertexts
let rlwes = (0..rlwe_count)
.map(|index| {
let mut message = vec![0; ring_size];
m[(index * ring_size)
..std::cmp::min(m.len(), (index + 1) * ring_size)]
.iter()
.enumerate()
.for_each(|(i, v)| {
if *v {
message[i] = parameters.rlwe_q().true_el()
} else {
message[i] = parameters.rlwe_q().false_el()
}
});
// encrypt message
let mut rlwe_out = vec![0u64; parameters.rlwe_n().0];
seeded_secret_key_encrypt_rlwe(
&message,
&mut rlwe_out,
&sk_u,
e.pbs_info().modop_rlweq(),
e.pbs_info().nttop_rlweq(),
&mut prng,
rng,
);
rlwe_out
})
.collect_vec();
(rlwes, seed)
})
})
}
}
#[test]
#[cfg(feature = "interactive_mp")]
fn all_uint8_apis() {
use num_traits::Euclid;
use crate::{div_zero_error_flag, FheBool};
set_single_party_parameter_sets(SP_TEST_BOOL_PARAMS);
let (ck, sk) = gen_keys();
sk.set_server_key();
for i in 0..=255 {
for j in 0..=255 {
let m0 = i;
let m1 = j;
let c0 = ck.encrypt(&m0);
let c1 = ck.encrypt(&m1);
assert!(ck.decrypt(&c0) == m0);
assert!(ck.decrypt(&c1) == m1);
// Arithmetic
{
{
// Add
let c_add = &c0 + &c1;
let m0_plus_m1 = ck.decrypt(&c_add);
assert_eq!(
m0_plus_m1,
m0.wrapping_add(m1),
"Expected {} but got {m0_plus_m1} for
{i}+{j}",
m0.wrapping_add(m1)
);
}
{
// Sub
let c_sub = &c0 - &c1;
let m0_sub_m1 = ck.decrypt(&c_sub);
assert_eq!(
m0_sub_m1,
m0.wrapping_sub(m1),
"Expected {} but got {m0_sub_m1} for
{i}-{j}",
m0.wrapping_sub(m1)
);
}
{
// Mul
let c_m0m1 = &c0 * &c1;
let m0m1 = ck.decrypt(&c_m0m1);
assert_eq!(
m0m1,
m0.wrapping_mul(m1),
"Expected {} but got {m0m1} for {i}x{j}",
m0.wrapping_mul(m1)
);
}
// Div & Rem
{
let (c_quotient, c_rem) = c0.div_rem(&c1);
let m_quotient = ck.decrypt(&c_quotient);
let m_remainder = ck.decrypt(&c_rem);
if j != 0 {
let (q, r) = i.div_rem_euclid(&j);
assert_eq!(
m_quotient, q,
"Expected {} but got {m_quotient} for
{i}/{j}",
q
);
assert_eq!(
m_remainder, r,
"Expected {} but got {m_remainder} for
{i}%{j}",
r
);
} else {
assert_eq!(
m_quotient, 255,
"Expected 255 but got {m_quotient}. Case
div by zero"
);
assert_eq!(
m_remainder, i,
"Expected {i} but got {m_remainder}. Case
div by zero"
);
let div_by_zero = ck.decrypt(&div_zero_error_flag().unwrap());
assert_eq!(
div_by_zero, true,
"Expected true but got {div_by_zero}"
);
}
}
}
// // Comparisons
{
{
let c_eq = c0.eq(&c1);
let is_eq = ck.decrypt(&c_eq);
assert_eq!(
is_eq,
i == j,
"Expected {} but got {is_eq} for {i}=={j}",
i == j
);
}
{
let c_gt = c0.gt(&c1);
let is_gt = ck.decrypt(&c_gt);
assert_eq!(
is_gt,
i > j,
"Expected {} but got {is_gt} for {i}>{j}",
i > j
);
}
{
let c_lt = c0.lt(&c1);
let is_lt = ck.decrypt(&c_lt);
assert_eq!(
is_lt,
i < j,
"Expected {} but got {is_lt} for {i}<{j}",
i < j
);
}
{
let c_ge = c0.ge(&c1);
let is_ge = ck.decrypt(&c_ge);
assert_eq!(
is_ge,
i >= j,
"Expected {} but got {is_ge} for {i}>={j}",
i >= j
);
}
{
let c_le = c0.le(&c1);
let is_le = ck.decrypt(&c_le);
assert_eq!(
is_le,
i <= j,
"Expected {} but got {is_le} for {i}<={j}",
i <= j
);
}
}
// mux
{
let selector = thread_rng().gen_bool(0.5);
let selector_enc: FheBool = ck.encrypt(&selector);
let mux_out = ck.decrypt(&c0.mux(&c1, &selector_enc));
let want_mux_out = if selector { m0 } else { m1 };
assert_eq!(mux_out, want_mux_out);
}
}
}
}
#[test]
#[cfg(feature = "interactive_mp")]
fn all_bool_apis() {
use crate::FheBool;
set_single_party_parameter_sets(SP_TEST_BOOL_PARAMS);
let (ck, sk) = gen_keys();
sk.set_server_key();
for _ in 0..100 {
let a = thread_rng().gen_bool(0.5);
let b = thread_rng().gen_bool(0.5);
let c_a: FheBool = ck.encrypt(&a);
let c_b: FheBool = ck.encrypt(&b);
let c_out = &c_a & &c_b;
let out = ck.decrypt(&c_out);
assert_eq!(out, a & b, "Expected {} but got {out}", a & b);
let c_out = &c_a | &c_b;
let out = ck.decrypt(&c_out);
assert_eq!(out, a | b, "Expected {} but got {out}", a | b);
let c_out = &c_a ^ &c_b;
let out = ck.decrypt(&c_out);
assert_eq!(out, a ^ b, "Expected {} but got {out}", a ^ b);
let c_out = !(&c_a);
let out = ck.decrypt(&c_out);
assert_eq!(out, !a, "Expected {} but got {out}", !a);
}
}
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/bool/parameters.rs | src/bool/parameters.rs | use num_traits::{ConstZero, FromPrimitive, PrimInt};
use crate::{
backend::Modulus,
decomposer::{Decomposer, NumInfo},
utils::log2,
};
pub(crate) trait DoubleDecomposerCount {
type Count;
fn a(&self) -> Self::Count;
fn b(&self) -> Self::Count;
}
pub(crate) trait DoubleDecomposerParams {
type Base;
type Count;
fn decomposition_base(&self) -> Self::Base;
fn decomposition_count_a(&self) -> Self::Count;
fn decomposition_count_b(&self) -> Self::Count;
}
pub(crate) trait SingleDecomposerParams {
type Base;
type Count;
// fn new(base: Self::Base, count: Self::Count) -> Self;
fn decomposition_base(&self) -> Self::Base;
fn decomposition_count(&self) -> Self::Count;
}
impl DoubleDecomposerParams
for (
DecompostionLogBase,
// Assume (Decomposition count for A, Decomposition count for B)
(DecompositionCount, DecompositionCount),
)
{
type Base = DecompostionLogBase;
type Count = DecompositionCount;
// fn new(
// base: DecompostionLogBase,
// count_a: DecompositionCount,
// count_b: DecompositionCount,
// ) -> Self {
// (base, (count_a, count_b))
// }
fn decomposition_base(&self) -> Self::Base {
self.0
}
fn decomposition_count_a(&self) -> Self::Count {
self.1 .0
}
fn decomposition_count_b(&self) -> Self::Count {
self.1 .1
}
}
impl SingleDecomposerParams for (DecompostionLogBase, DecompositionCount) {
type Base = DecompostionLogBase;
type Count = DecompositionCount;
// fn new(base: DecompostionLogBase, count: DecompositionCount) -> Self {
// (base, count)
// }
fn decomposition_base(&self) -> Self::Base {
self.0
}
fn decomposition_count(&self) -> Self::Count {
self.1
}
}
#[derive(Clone, PartialEq, Debug)]
pub(crate) enum SecretKeyDistribution {
/// Elements of secret key are sample from Gaussian distribitution with
/// \sigma = 3.19 and \mu = 0.0
ErrorDistribution,
/// Elements of secret key are chosen from the set {1,0,-1} with hamming
/// weight `floor(N/2)` where `N` is the secret dimension.
TernaryDistribution,
}
#[derive(Clone, PartialEq, Debug)]
pub(crate) enum ParameterVariant {
SingleParty,
InteractiveMultiParty,
NonInteractiveMultiParty,
}
#[derive(Clone, PartialEq)]
pub struct BoolParameters<El> {
/// RLWE secret key distribution
rlwe_secret_key_dist: SecretKeyDistribution,
/// LWE secret key distribtuion
lwe_secret_key_dist: SecretKeyDistribution,
/// RLWE ciphertext modulus Q
rlwe_q: CiphertextModulus<El>,
/// LWE ciphertext modulus q (usually referred to as Q_{ks})
lwe_q: CiphertextModulus<El>,
/// Blind rotation modulus. It is the modulus to which we switch before
/// blind rotation.
///
/// Since blind rotation decrypts LWE ciphertext in the exponent of a ring
/// polynomial, which is a ring mod 2N, blind rotation modulus is
/// always <= 2N.
br_q: usize,
/// Ring dimension `N` for 2N^{th} cyclotomic polynomial ring
rlwe_n: PolynomialSize,
/// LWE dimension `n`
lwe_n: LweDimension,
/// LWE key switch decompositon params
lwe_decomposer_params: (DecompostionLogBase, DecompositionCount),
/// Decompostion parameters for RLWE x RGSW.
///
/// We restrict decomposition for RLWE'(-sm) and RLWE'(m) to have same base
/// but can have different decomposition count. We refer to this
/// DoubleDecomposer / RlweDecomposer
///
/// Decomposition count `d_a` (i.e. for SignedDecompose(RLWE_A(m)) x
/// RLWE'(-sm)) and `d_b` (i.e. for SignedDecompose(RLWE_B(m)) x RLWE'(m))
/// are always stored as `(d_a, d_b)`
rlrg_decomposer_params: (
DecompostionLogBase,
(DecompositionCount, DecompositionCount),
),
/// Decomposition parameters for RLWE automorphism
auto_decomposer_params: (DecompostionLogBase, DecompositionCount),
/// Decomposition parameters for RGSW0 x RGSW1
///
/// `0` and `1` indicate that RGSW0 and RGSW1 may not use same decomposition
/// parameters.
///
/// In RGSW0 x RGSW1, decomposition parameters for RGSW1 are required.
/// Hence, the parameters we store are decomposition parameters of RGSW1.
///
/// Like RLWE x RGSW decomposition parameters (1) we restrict to same base
/// but can have different decomposition counts `d_a` and `d_b` and (2)
/// decomposition count `d_a` and `d_b` are always stored as `(d_a, d_b)`
///
/// RGSW0 x RGSW1 are optional because they only necessary to be supplied in
/// multi-party setting.
rgrg_decomposer_params: Option<(
DecompostionLogBase,
(DecompositionCount, DecompositionCount),
)>,
/// Decomposition parameters for non-interactive key switching from u_j to
/// s, hwere u_j is RLWE secret `u` of party `j` and `s` is the ideal RLWE
/// secret key.
///
/// Decomposition parameters for non-interactive key switching are optional
/// and must be supplied only for non-interactive multi-party
non_interactive_ui_to_s_key_switch_decomposer:
Option<(DecompostionLogBase, DecompositionCount)>,
/// Group generator for Z^*_{br_q}
g: usize,
/// Window size parameter for LMKC++ blind rotation
w: usize,
/// Parameter variant
variant: ParameterVariant,
}
impl<El> BoolParameters<El> {
pub(crate) fn rlwe_secret_key_dist(&self) -> &SecretKeyDistribution {
&self.rlwe_secret_key_dist
}
pub(crate) fn lwe_secret_key_dist(&self) -> &SecretKeyDistribution {
&self.lwe_secret_key_dist
}
pub(crate) fn rlwe_q(&self) -> &CiphertextModulus<El> {
&self.rlwe_q
}
pub(crate) fn lwe_q(&self) -> &CiphertextModulus<El> {
&self.lwe_q
}
pub(crate) fn br_q(&self) -> &usize {
&self.br_q
}
pub(crate) fn rlwe_n(&self) -> &PolynomialSize {
&self.rlwe_n
}
pub(crate) fn lwe_n(&self) -> &LweDimension {
&self.lwe_n
}
pub(crate) fn g(&self) -> usize {
self.g
}
pub(crate) fn w(&self) -> usize {
self.w
}
pub(crate) fn rlwe_by_rgsw_decomposition_params(
&self,
) -> &(
DecompostionLogBase,
(DecompositionCount, DecompositionCount),
) {
&self.rlrg_decomposer_params
}
pub(crate) fn rgsw_by_rgsw_decomposition_params(
&self,
) -> (
DecompostionLogBase,
(DecompositionCount, DecompositionCount),
) {
self.rgrg_decomposer_params.expect(&format!(
"Parameter variant {:?} does not support RGSWxRGSW",
self.variant
))
}
pub(crate) fn rlwe_rgsw_decomposition_base(&self) -> DecompostionLogBase {
self.rlrg_decomposer_params.0
}
pub(crate) fn rlwe_rgsw_decomposition_count(&self) -> (DecompositionCount, DecompositionCount) {
self.rlrg_decomposer_params.1
}
pub(crate) fn rgsw_rgsw_decomposition_count(&self) -> (DecompositionCount, DecompositionCount) {
let params = self.rgrg_decomposer_params.expect(&format!(
"Parameter variant {:?} does not support RGSW x RGSW",
self.variant
));
params.1
}
pub(crate) fn auto_decomposition_param(&self) -> &(DecompostionLogBase, DecompositionCount) {
&self.auto_decomposer_params
}
pub(crate) fn auto_decomposition_base(&self) -> DecompostionLogBase {
self.auto_decomposer_params.decomposition_base()
}
pub(crate) fn auto_decomposition_count(&self) -> DecompositionCount {
self.auto_decomposer_params.decomposition_count()
}
pub(crate) fn lwe_decomposition_base(&self) -> DecompostionLogBase {
self.lwe_decomposer_params.decomposition_base()
}
pub(crate) fn lwe_decomposition_count(&self) -> DecompositionCount {
self.lwe_decomposer_params.decomposition_count()
}
pub(crate) fn non_interactive_ui_to_s_key_switch_decomposition_count(
&self,
) -> DecompositionCount {
let params = self
.non_interactive_ui_to_s_key_switch_decomposer
.expect(&format!(
"Parameter variant {:?} does not support non-interactive",
self.variant
));
params.decomposition_count()
}
pub(crate) fn rgsw_rgsw_decomposer<D: Decomposer<Element = El>>(&self) -> (D, D)
where
El: Copy,
{
let params = self.rgrg_decomposer_params.expect(&format!(
"Parameter variant {:?} does not support RGSW x RGSW",
self.variant
));
(
// A
D::new(
self.rlwe_q.0,
params.decomposition_base().0,
params.decomposition_count_a().0,
),
// B
D::new(
self.rlwe_q.0,
params.decomposition_base().0,
params.decomposition_count_b().0,
),
)
}
pub(crate) fn auto_decomposer<D: Decomposer<Element = El>>(&self) -> D
where
El: Copy,
{
D::new(
self.rlwe_q.0,
self.auto_decomposer_params.decomposition_base().0,
self.auto_decomposer_params.decomposition_count().0,
)
}
pub(crate) fn lwe_decomposer<D: Decomposer<Element = El>>(&self) -> D
where
El: Copy,
{
D::new(
self.lwe_q.0,
self.lwe_decomposer_params.decomposition_base().0,
self.lwe_decomposer_params.decomposition_count().0,
)
}
pub(crate) fn rlwe_rgsw_decomposer<D: Decomposer<Element = El>>(&self) -> (D, D)
where
El: Copy,
{
(
// A
D::new(
self.rlwe_q.0,
self.rlrg_decomposer_params.decomposition_base().0,
self.rlrg_decomposer_params.decomposition_count_a().0,
),
// B
D::new(
self.rlwe_q.0,
self.rlrg_decomposer_params.decomposition_base().0,
self.rlrg_decomposer_params.decomposition_count_b().0,
),
)
}
pub(crate) fn non_interactive_ui_to_s_key_switch_decomposer<D: Decomposer<Element = El>>(
&self,
) -> D
where
El: Copy,
{
let params = self
.non_interactive_ui_to_s_key_switch_decomposer
.expect(&format!(
"Parameter variant {:?} does not support non-interactive",
self.variant
));
D::new(
self.rlwe_q.0,
params.decomposition_base().0,
params.decomposition_count().0,
)
}
/// Returns dlogs of `g` for which auto keys are required as
/// per the parameter. Given that autos are required for [-g, g, g^2, ...,
/// g^w] function returns the following [0, 1, 2, ..., w] where `w` is
/// the window size. Note that although g^0 = 1, we use 0 for -g.
pub(crate) fn auto_element_dlogs(&self) -> Vec<usize> {
let mut els = vec![0];
(1..self.w + 1).into_iter().for_each(|e| {
els.push(e);
});
els
}
pub(crate) fn variant(&self) -> &ParameterVariant {
&self.variant
}
}
#[derive(Clone, Copy, PartialEq)]
pub struct DecompostionLogBase(pub(crate) usize);
impl AsRef<usize> for DecompostionLogBase {
fn as_ref(&self) -> &usize {
&self.0
}
}
#[derive(Clone, Copy, PartialEq)]
pub struct DecompositionCount(pub(crate) usize);
impl AsRef<usize> for DecompositionCount {
fn as_ref(&self) -> &usize {
&self.0
}
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct LweDimension(pub(crate) usize);
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct PolynomialSize(pub(crate) usize);
#[derive(Clone, Copy, PartialEq, Debug)]
/// T equals modulus when modulus is non-native. Otherwise T equals 0. bool is
/// true when modulus is native, false otherwise.
pub struct CiphertextModulus<T>(T, bool);
impl<T: ConstZero> CiphertextModulus<T> {
const fn new_native() -> Self {
// T::zero is stored only for convenience. It has no use when modulus
// is native. That is, either u128,u64,u32,u16
Self(T::ZERO, true)
}
const fn new_non_native(q: T) -> Self {
Self(q, false)
}
}
impl<T> CiphertextModulus<T>
where
T: PrimInt + NumInfo,
{
fn _bits() -> usize {
T::BITS as usize
}
fn _native(&self) -> bool {
self.1
}
fn _half_q(&self) -> T {
if self._native() {
T::one() << (Self::_bits() - 1)
} else {
self.0 >> 1
}
}
fn _q(&self) -> Option<T> {
if self._native() {
None
} else {
Some(self.0)
}
}
}
impl<T> Modulus for CiphertextModulus<T>
where
T: PrimInt + FromPrimitive + NumInfo,
{
type Element = T;
fn is_native(&self) -> bool {
self._native()
}
fn largest_unsigned_value(&self) -> Self::Element {
if self._native() {
T::max_value()
} else {
self.0 - T::one()
}
}
fn neg_one(&self) -> Self::Element {
if self._native() {
T::max_value()
} else {
self.0 - T::one()
}
}
// fn signed_max(&self) -> Self::Element {}
// fn signed_min(&self) -> Self::Element {}
fn smallest_unsigned_value(&self) -> Self::Element {
T::zero()
}
fn map_element_to_i64(&self, v: &Self::Element) -> i64 {
assert!(*v <= self.largest_unsigned_value());
if *v > self._half_q() {
-((self.largest_unsigned_value() - *v) + T::one())
.to_i64()
.unwrap()
} else {
v.to_i64().unwrap()
}
}
fn map_element_from_f64(&self, v: f64) -> Self::Element {
let v = v.round();
let v_el = T::from_f64(v.abs()).unwrap();
assert!(v_el <= self.largest_unsigned_value());
if v < 0.0 {
self.largest_unsigned_value() - v_el + T::one()
} else {
v_el
}
}
fn map_element_from_i64(&self, v: i64) -> Self::Element {
let v_el = T::from_i64(v.abs()).unwrap();
assert!(v_el <= self.largest_unsigned_value());
if v < 0 {
self.largest_unsigned_value() - v_el + T::one()
} else {
v_el
}
}
fn q(&self) -> Option<Self::Element> {
self._q()
}
fn q_as_f64(&self) -> Option<f64> {
if self._native() {
Some(T::max_value().to_f64().unwrap() + 1.0)
} else {
self.0.to_f64()
}
}
fn log_q(&self) -> usize {
if self.is_native() {
Self::_bits()
} else {
log2(&self.q().unwrap())
}
}
}
pub(crate) const I_2P_LB_SR: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
rlwe_q: CiphertextModulus::new_non_native(18014398509404161),
lwe_q: CiphertextModulus::new_non_native(1 << 15),
br_q: 1 << 11,
rlwe_n: PolynomialSize(1 << 11),
lwe_n: LweDimension(580),
lwe_decomposer_params: (DecompostionLogBase(1), DecompositionCount(12)),
rlrg_decomposer_params: (
DecompostionLogBase(17),
(DecompositionCount(1), DecompositionCount(1)),
),
rgrg_decomposer_params: Some((
DecompostionLogBase(7),
(DecompositionCount(6), DecompositionCount(5)),
)),
auto_decomposer_params: (DecompostionLogBase(24), DecompositionCount(1)),
non_interactive_ui_to_s_key_switch_decomposer: None,
g: 5,
w: 10,
variant: ParameterVariant::InteractiveMultiParty,
};
pub(crate) const I_4P: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
rlwe_q: CiphertextModulus::new_non_native(18014398509404161),
lwe_q: CiphertextModulus::new_non_native(1 << 16),
br_q: 1 << 11,
rlwe_n: PolynomialSize(1 << 11),
lwe_n: LweDimension(620),
lwe_decomposer_params: (DecompostionLogBase(1), DecompositionCount(13)),
rlrg_decomposer_params: (
DecompostionLogBase(17),
(DecompositionCount(1), DecompositionCount(1)),
),
rgrg_decomposer_params: Some((
DecompostionLogBase(6),
(DecompositionCount(7), DecompositionCount(6)),
)),
auto_decomposer_params: (DecompostionLogBase(24), DecompositionCount(1)),
non_interactive_ui_to_s_key_switch_decomposer: None,
g: 5,
w: 10,
variant: ParameterVariant::InteractiveMultiParty,
};
pub(crate) const I_8P: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
rlwe_q: CiphertextModulus::new_non_native(18014398509404161),
lwe_q: CiphertextModulus::new_non_native(1 << 17),
br_q: 1 << 12,
rlwe_n: PolynomialSize(1 << 11),
lwe_n: LweDimension(660),
lwe_decomposer_params: (DecompostionLogBase(1), DecompositionCount(14)),
rlrg_decomposer_params: (
DecompostionLogBase(17),
(DecompositionCount(1), DecompositionCount(1)),
),
rgrg_decomposer_params: Some((
DecompostionLogBase(5),
(DecompositionCount(9), DecompositionCount(8)),
)),
auto_decomposer_params: (DecompostionLogBase(24), DecompositionCount(1)),
non_interactive_ui_to_s_key_switch_decomposer: None,
g: 5,
w: 10,
variant: ParameterVariant::InteractiveMultiParty,
};
pub(crate) const NI_2P: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::ErrorDistribution,
rlwe_q: CiphertextModulus::new_non_native(18014398509404161),
lwe_q: CiphertextModulus::new_non_native(1 << 16),
br_q: 1 << 12,
rlwe_n: PolynomialSize(1 << 11),
lwe_n: LweDimension(520),
lwe_decomposer_params: (DecompostionLogBase(1), DecompositionCount(13)),
rlrg_decomposer_params: (
DecompostionLogBase(17),
(DecompositionCount(1), DecompositionCount(1)),
),
rgrg_decomposer_params: Some((
DecompostionLogBase(4),
(DecompositionCount(10), DecompositionCount(9)),
)),
auto_decomposer_params: (DecompostionLogBase(24), DecompositionCount(1)),
non_interactive_ui_to_s_key_switch_decomposer: Some((
DecompostionLogBase(1),
DecompositionCount(50),
)),
g: 5,
w: 10,
variant: ParameterVariant::NonInteractiveMultiParty,
};
pub(crate) const NI_4P_HB_FR: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
rlwe_q: CiphertextModulus::new_non_native(18014398509404161),
lwe_q: CiphertextModulus::new_non_native(1 << 16),
br_q: 1 << 11,
rlwe_n: PolynomialSize(1 << 11),
lwe_n: LweDimension(620),
lwe_decomposer_params: (DecompostionLogBase(1), DecompositionCount(13)),
rlrg_decomposer_params: (
DecompostionLogBase(17),
(DecompositionCount(1), DecompositionCount(1)),
),
rgrg_decomposer_params: Some((
DecompostionLogBase(3),
(DecompositionCount(13), DecompositionCount(12)),
)),
auto_decomposer_params: (DecompostionLogBase(24), DecompositionCount(1)),
non_interactive_ui_to_s_key_switch_decomposer: Some((
DecompostionLogBase(1),
DecompositionCount(50),
)),
g: 5,
w: 10,
variant: ParameterVariant::NonInteractiveMultiParty,
};
pub(crate) const NI_4P_LB_SR: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
rlwe_q: CiphertextModulus::new_non_native(18014398509404161),
lwe_q: CiphertextModulus::new_non_native(1 << 16),
br_q: 1 << 12,
rlwe_n: PolynomialSize(1 << 11),
lwe_n: LweDimension(620),
lwe_decomposer_params: (DecompostionLogBase(1), DecompositionCount(13)),
rlrg_decomposer_params: (
DecompostionLogBase(17),
(DecompositionCount(1), DecompositionCount(1)),
),
rgrg_decomposer_params: Some((
DecompostionLogBase(4),
(DecompositionCount(10), DecompositionCount(9)),
)),
auto_decomposer_params: (DecompostionLogBase(24), DecompositionCount(1)),
non_interactive_ui_to_s_key_switch_decomposer: Some((
DecompostionLogBase(1),
DecompositionCount(50),
)),
g: 5,
w: 10,
variant: ParameterVariant::NonInteractiveMultiParty,
};
pub(crate) const NI_8P: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
rlwe_q: CiphertextModulus::new_non_native(18014398509404161),
lwe_q: CiphertextModulus::new_non_native(1 << 17),
br_q: 1 << 12,
rlwe_n: PolynomialSize(1 << 11),
lwe_n: LweDimension(660),
lwe_decomposer_params: (DecompostionLogBase(1), DecompositionCount(14)),
rlrg_decomposer_params: (
DecompostionLogBase(17),
(DecompositionCount(1), DecompositionCount(1)),
),
rgrg_decomposer_params: Some((
DecompostionLogBase(2),
(DecompositionCount(20), DecompositionCount(18)),
)),
auto_decomposer_params: (DecompostionLogBase(24), DecompositionCount(1)),
non_interactive_ui_to_s_key_switch_decomposer: Some((
DecompostionLogBase(1),
DecompositionCount(50),
)),
g: 5,
w: 10,
variant: ParameterVariant::NonInteractiveMultiParty,
};
#[cfg(test)]
pub(crate) const SP_TEST_BOOL_PARAMS: BoolParameters<u64> = BoolParameters::<u64> {
rlwe_secret_key_dist: SecretKeyDistribution::TernaryDistribution,
lwe_secret_key_dist: SecretKeyDistribution::ErrorDistribution,
rlwe_q: CiphertextModulus::new_non_native(268369921u64),
lwe_q: CiphertextModulus::new_non_native(1 << 16),
br_q: 1 << 9,
rlwe_n: PolynomialSize(1 << 9),
lwe_n: LweDimension(100),
lwe_decomposer_params: (DecompostionLogBase(4), DecompositionCount(4)),
rlrg_decomposer_params: (
DecompostionLogBase(7),
(DecompositionCount(4), DecompositionCount(4)),
),
rgrg_decomposer_params: None,
auto_decomposer_params: (DecompostionLogBase(7), DecompositionCount(4)),
non_interactive_ui_to_s_key_switch_decomposer: None,
g: 5,
w: 5,
variant: ParameterVariant::SingleParty,
};
// #[cfg(test)]
// mod tests {
// #[test]
// fn find_prime() {
// let bits = 60;
// let ring_size = 1 << 11;
// let prime = crate::utils::generate_prime(bits, ring_size * 2, 1 <<
// bits).unwrap(); dbg!(prime);
// }
// }
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/bool/ni_mp_api.rs | src/bool/ni_mp_api.rs | use std::{cell::RefCell, sync::OnceLock};
use crate::{
backend::ModulusPowerOf2,
bool::parameters::ParameterVariant,
random::DefaultSecureRng,
utils::{Global, WithLocal},
ModularOpsU64, NttBackendU64,
};
use super::{
evaluator::NonInteractiveMultiPartyCrs,
keys::{
CommonReferenceSeededNonInteractiveMultiPartyServerKeyShare,
NonInteractiveServerKeyEvaluationDomain, SeededNonInteractiveMultiPartyServerKey,
ShoupNonInteractiveServerKeyEvaluationDomain,
},
parameters::{BoolParameters, CiphertextModulus, NI_2P, NI_4P_HB_FR, NI_8P},
ClientKey,
};
pub(crate) type BoolEvaluator = super::evaluator::BoolEvaluator<
Vec<Vec<u64>>,
NttBackendU64,
ModularOpsU64<CiphertextModulus<u64>>,
ModulusPowerOf2<CiphertextModulus<u64>>,
ShoupNonInteractiveServerKeyEvaluationDomain<Vec<Vec<u64>>>,
>;
thread_local! {
static BOOL_EVALUATOR: RefCell<Option<BoolEvaluator>> = RefCell::new(None);
}
static BOOL_SERVER_KEY: OnceLock<ShoupNonInteractiveServerKeyEvaluationDomain<Vec<Vec<u64>>>> =
OnceLock::new();
static MULTI_PARTY_CRS: OnceLock<NonInteractiveMultiPartyCrs<[u8; 32]>> = OnceLock::new();
pub enum ParameterSelector {
NonInteractiveLTE2Party,
NonInteractiveLTE4Party,
NonInteractiveLTE8Party,
}
pub fn set_parameter_set(select: ParameterSelector) {
match select {
ParameterSelector::NonInteractiveLTE2Party => {
BOOL_EVALUATOR.with_borrow_mut(|v| *v = Some(BoolEvaluator::new(NI_2P)));
}
ParameterSelector::NonInteractiveLTE4Party => {
BOOL_EVALUATOR.with_borrow_mut(|v| *v = Some(BoolEvaluator::new(NI_4P_HB_FR)));
}
ParameterSelector::NonInteractiveLTE8Party => {
BOOL_EVALUATOR.with_borrow_mut(|v| *v = Some(BoolEvaluator::new(NI_8P)));
}
}
}
pub fn set_common_reference_seed(seed: [u8; 32]) {
BoolEvaluator::with_local(|e| {
assert_eq!(
e.parameters().variant(),
&ParameterVariant::NonInteractiveMultiParty,
"Set parameters do not support Non interactive multi-party"
);
});
assert!(
MULTI_PARTY_CRS
.set(NonInteractiveMultiPartyCrs { seed: seed })
.is_ok(),
"Attempted to set MP SEED twice."
)
}
pub fn gen_client_key() -> ClientKey {
BoolEvaluator::with_local(|e| e.client_key())
}
pub fn gen_server_key_share(
user_id: usize,
total_users: usize,
client_key: &ClientKey,
) -> CommonReferenceSeededNonInteractiveMultiPartyServerKeyShare<
Vec<Vec<u64>>,
BoolParameters<u64>,
NonInteractiveMultiPartyCrs<[u8; 32]>,
> {
BoolEvaluator::with_local(|e| {
let cr_seed = NonInteractiveMultiPartyCrs::global();
e.gen_non_interactive_multi_party_key_share(cr_seed, user_id, total_users, client_key)
})
}
pub fn aggregate_server_key_shares(
shares: &[CommonReferenceSeededNonInteractiveMultiPartyServerKeyShare<
Vec<Vec<u64>>,
BoolParameters<u64>,
NonInteractiveMultiPartyCrs<[u8; 32]>,
>],
) -> SeededNonInteractiveMultiPartyServerKey<
Vec<Vec<u64>>,
NonInteractiveMultiPartyCrs<[u8; 32]>,
BoolParameters<u64>,
> {
BoolEvaluator::with_local(|e| {
let cr_seed = NonInteractiveMultiPartyCrs::global();
e.aggregate_non_interactive_multi_party_server_key_shares(cr_seed, shares)
})
}
impl
SeededNonInteractiveMultiPartyServerKey<
Vec<Vec<u64>>,
NonInteractiveMultiPartyCrs<[u8; 32]>,
BoolParameters<u64>,
>
{
pub fn set_server_key(&self) {
let eval_key = NonInteractiveServerKeyEvaluationDomain::<
_,
BoolParameters<u64>,
DefaultSecureRng,
NttBackendU64,
>::from(self);
assert!(
BOOL_SERVER_KEY
.set(ShoupNonInteractiveServerKeyEvaluationDomain::from(eval_key))
.is_ok(),
"Attempted to set server key twice!"
);
}
}
impl Global for NonInteractiveMultiPartyCrs<[u8; 32]> {
fn global() -> &'static Self {
MULTI_PARTY_CRS
.get()
.expect("Non-interactive multi-party common reference string not set")
}
}
// BOOL EVALUATOR //
impl WithLocal for BoolEvaluator {
fn with_local<F, R>(func: F) -> R
where
F: Fn(&Self) -> R,
{
BOOL_EVALUATOR.with_borrow(|s| func(s.as_ref().expect("Parameters not set")))
}
fn with_local_mut<F, R>(func: F) -> R
where
F: Fn(&mut Self) -> R,
{
BOOL_EVALUATOR.with_borrow_mut(|s| func(s.as_mut().expect("Parameters not set")))
}
fn with_local_mut_mut<F, R>(func: &mut F) -> R
where
F: FnMut(&mut Self) -> R,
{
BOOL_EVALUATOR.with_borrow_mut(|s| func(s.as_mut().expect("Parameters not set")))
}
}
pub(crate) type RuntimeServerKey = ShoupNonInteractiveServerKeyEvaluationDomain<Vec<Vec<u64>>>;
impl Global for RuntimeServerKey {
fn global() -> &'static Self {
BOOL_SERVER_KEY.get().expect("Server key not set!")
}
}
/// Batch of bool ciphertexts stored as vector of RLWE ciphertext under user j's
/// RLWE secret `u_j`
///
/// To use the bool ciphertexts in multi-party protocol first key switch the
/// ciphertexts from u_j to ideal RLWE secret `s` with
/// `self.key_switch(user_id)` where `user_id` is user j's id. Key switch
/// returns `BatchedFheBools` that stored key vector of key switched RLWE
/// ciphertext.
pub(super) struct NonInteractiveBatchedFheBools<C> {
data: Vec<C>,
}
/// Batch of Bool cipphertexts stored as vector of RLWE ciphertexts under the
/// ideal RLWE secret key `s` of the protocol
///
/// Bool ciphertext at `index` can be extracted from the coefficient at `index %
/// N` of `index / N`th RLWE ciphertext.
///
/// To extract bool ciphertext at `index` as LWE ciphertext use
/// `self.extract(index)`
pub(super) struct BatchedFheBools<C> {
pub(in super::super) data: Vec<C>,
}
/// Non interactive multi-party specfic encryptor decryptor routines
mod impl_enc_dec {
use crate::{
bool::{evaluator::BoolEncoding, keys::NonInteractiveMultiPartyClientKey},
multi_party::{
multi_party_aggregate_decryption_shares_and_decrypt, multi_party_decryption_share,
},
pbs::{sample_extract, PbsInfo, WithShoupRepr},
random::{NewWithSeed, RandomFillUniformInModulus},
rgsw::{rlwe_key_switch, seeded_secret_key_encrypt_rlwe},
utils::TryConvertFrom1,
Encryptor, KeySwitchWithId, Matrix, MatrixEntity, MatrixMut, MultiPartyDecryptor,
RowEntity, RowMut,
};
use itertools::Itertools;
use num_traits::{ToPrimitive, Zero};
use super::*;
type Mat = Vec<Vec<u64>>;
// Implement `extract` to extract Bool LWE ciphertext at `index` from
// `BatchedFheBools`
impl<C: MatrixMut<MatElement = u64>> BatchedFheBools<C>
where
C::R: RowEntity + RowMut,
{
pub(crate) fn extract(&self, index: usize) -> C::R {
BoolEvaluator::with_local(|e| {
let ring_size = e.parameters().rlwe_n().0;
let ct_index = index / ring_size;
let coeff_index = index % ring_size;
let mut lwe_out = C::R::zeros(e.parameters().rlwe_n().0 + 1);
sample_extract(
&mut lwe_out,
&self.data[ct_index],
e.pbs_info().modop_rlweq(),
coeff_index,
);
lwe_out
})
}
}
impl<M: MatrixEntity + MatrixMut<MatElement = u64>> From<&(Vec<M::R>, [u8; 32])>
for NonInteractiveBatchedFheBools<M>
where
<M as Matrix>::R: RowMut,
{
/// Derive `NonInteractiveBatchedFheBools` from a vector seeded RLWE
/// ciphertexts (Vec<RLWE>, Seed)
///
/// Unseed the RLWE ciphertexts and store them as vector RLWE
/// ciphertexts in `NonInteractiveBatchedFheBools`
fn from(value: &(Vec<M::R>, [u8; 32])) -> Self {
BoolEvaluator::with_local(|e| {
let parameters = e.parameters();
let ring_size = parameters.rlwe_n().0;
let rlwe_q = parameters.rlwe_q();
let mut prng = DefaultSecureRng::new_seeded(value.1);
let rlwes = value
.0
.iter()
.map(|partb| {
let mut rlwe = M::zeros(2, ring_size);
// sample A
RandomFillUniformInModulus::random_fill(
&mut prng,
rlwe_q,
rlwe.get_row_mut(0),
);
// Copy over B
rlwe.get_row_mut(1).copy_from_slice(partb.as_ref());
rlwe
})
.collect_vec();
Self { data: rlwes }
})
}
}
impl<K> Encryptor<[bool], NonInteractiveBatchedFheBools<Mat>> for K
where
K: Encryptor<[bool], (Mat, [u8; 32])>,
{
/// Encrypt a vector bool of arbitrary length as vector of unseeded RLWE
/// ciphertexts in `NonInteractiveBatchedFheBools`
fn encrypt(&self, m: &[bool]) -> NonInteractiveBatchedFheBools<Mat> {
NonInteractiveBatchedFheBools::from(&K::encrypt(&self, m))
}
}
impl<K> Encryptor<[bool], (Vec<<Mat as Matrix>::R>, [u8; 32])> for K
where
K: NonInteractiveMultiPartyClientKey,
<Mat as Matrix>::R:
TryConvertFrom1<[K::Element], CiphertextModulus<<Mat as Matrix>::MatElement>>,
{
/// Encrypt a vector of bool of arbitrary length as vector of seeded
/// RLWE ciphertexts and returns (Vec<RLWE>, Seed)
fn encrypt(&self, m: &[bool]) -> (Mat, [u8; 32]) {
BoolEvaluator::with_local(|e| {
DefaultSecureRng::with_local_mut(|rng| {
let parameters = e.parameters();
let ring_size = parameters.rlwe_n().0;
let rlwe_count = ((m.len() as f64 / ring_size as f64).ceil())
.to_usize()
.unwrap();
let mut seed = <DefaultSecureRng as NewWithSeed>::Seed::default();
rng.fill_bytes(&mut seed);
let mut prng = DefaultSecureRng::new_seeded(seed);
let sk_u = self.sk_u_rlwe();
// encrypt `m` into ceil(len(m)/N) RLWE ciphertexts
let rlwes = (0..rlwe_count)
.map(|index| {
let mut message = vec![<Mat as Matrix>::MatElement::zero(); ring_size];
m[(index * ring_size)..std::cmp::min(m.len(), (index + 1) * ring_size)]
.iter()
.enumerate()
.for_each(|(i, v)| {
if *v {
message[i] = parameters.rlwe_q().true_el()
} else {
message[i] = parameters.rlwe_q().false_el()
}
});
// encrypt message
let mut rlwe_out =
<<Mat as Matrix>::R as RowEntity>::zeros(parameters.rlwe_n().0);
seeded_secret_key_encrypt_rlwe(
&message,
&mut rlwe_out,
&sk_u,
e.pbs_info().modop_rlweq(),
e.pbs_info().nttop_rlweq(),
&mut prng,
rng,
);
rlwe_out
})
.collect_vec();
(rlwes, seed)
})
})
}
}
impl<K> MultiPartyDecryptor<bool, <Mat as Matrix>::R> for K
where
K: NonInteractiveMultiPartyClientKey,
<Mat as Matrix>::R:
TryConvertFrom1<[K::Element], CiphertextModulus<<Mat as Matrix>::MatElement>>,
{
type DecryptionShare = <Mat as Matrix>::MatElement;
fn gen_decryption_share(&self, c: &<Mat as Matrix>::R) -> Self::DecryptionShare {
BoolEvaluator::with_local(|e| {
DefaultSecureRng::with_local_mut(|rng| {
multi_party_decryption_share(
c,
self.sk_rlwe().as_slice(),
e.pbs_info().modop_rlweq(),
rng,
)
})
})
}
fn aggregate_decryption_shares(
&self,
c: &<Mat as Matrix>::R,
shares: &[Self::DecryptionShare],
) -> bool {
BoolEvaluator::with_local(|e| {
let noisy_m = multi_party_aggregate_decryption_shares_and_decrypt(
c,
shares,
e.pbs_info().modop_rlweq(),
);
e.pbs_info().rlwe_q().decode(noisy_m)
})
}
}
impl KeySwitchWithId<Mat> for Mat {
/// Key switch RLWE ciphertext `Self` from user j's RLWE secret u_j
/// to ideal RLWE secret `s` of non-interactive multi-party protocol.
///
/// - user_id: user j's user_id in the protocol
fn key_switch(&self, user_id: usize) -> Mat {
BoolEvaluator::with_local(|e| {
assert!(self.dimension() == (2, e.parameters().rlwe_n().0));
let server_key = BOOL_SERVER_KEY.get().unwrap();
let ksk = server_key.ui_to_s_ksk(user_id);
let decomposer = e.ni_ui_to_s_ks_decomposer().as_ref().unwrap();
// perform key switch
rlwe_key_switch(
self,
ksk.as_ref(),
ksk.shoup_repr(),
decomposer,
e.pbs_info().nttop_rlweq(),
e.pbs_info().modop_rlweq(),
)
})
}
}
impl<C> KeySwitchWithId<BatchedFheBools<C>> for NonInteractiveBatchedFheBools<C>
where
C: KeySwitchWithId<C>,
{
/// Key switch `Self`'s vector of RLWE ciphertexts from user j's RLWE
/// secret u_j to ideal RLWE secret `s` of non-interactive
/// multi-party protocol.
///
/// Returns vector of key switched RLWE ciphertext as `BatchedFheBools`
/// which can then be used to extract individual Bool LWE ciphertexts.
///
/// - user_id: user j's user_id in the protocol
fn key_switch(&self, user_id: usize) -> BatchedFheBools<C> {
let data = self
.data
.iter()
.map(|c| c.key_switch(user_id))
.collect_vec();
BatchedFheBools { data }
}
}
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
use rand::{thread_rng, RngCore};
use crate::{
backend::Modulus,
bool::{
keys::tests::{ideal_sk_rlwe, measure_noise_lwe},
BooleanGates,
},
utils::tests::Stats,
Encoder, Encryptor, KeySwitchWithId, MultiPartyDecryptor,
};
use super::*;
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/bool/print_noise.rs | src/bool/print_noise.rs | use std::{fmt::Debug, iter::Sum};
use itertools::izip;
use num_traits::{FromPrimitive, PrimInt, Zero};
use rand_distr::uniform::SampleUniform;
use crate::{
backend::{GetModulus, Modulus},
decomposer::{Decomposer, NumInfo, RlweDecomposer},
lwe::{decrypt_lwe, lwe_key_switch},
parameters::{BoolParameters, CiphertextModulus},
random::{DefaultSecureRng, RandomFillUniformInModulus},
rgsw::{
decrypt_rlwe, rlwe_auto, rlwe_auto_scratch_rows, RlweCiphertextMutRef, RlweKskRef,
RuntimeScratchMutRef,
},
utils::{encode_x_pow_si_with_emebedding_factor, tests::Stats, TryConvertFrom1},
ArithmeticOps, ClientKey, MatrixEntity, MatrixMut, ModInit, Ntt, NttInit, RowEntity, RowMut,
VectorOps,
};
use super::keys::tests::{ideal_sk_lwe, ideal_sk_rlwe};
pub(crate) trait CollectRuntimeServerKeyStats {
type M;
/// RGSW ciphertext X^{s[s_index]} in evaluation domain where `s` the LWE
/// secret
fn rgsw_cts_lwe_si(&self, s_index: usize) -> &Self::M;
/// Auto key in evaluation domain for automorphism g^k. For auto key for
/// automorphism corresponding to -g, set k = 0
fn galois_key_for_auto(&self, k: usize) -> &Self::M;
/// LWE key switching key
fn lwe_ksk(&self) -> &Self::M;
}
#[derive(Default)]
struct ServerKeyStats<T> {
/// Distribution of noise in RGSW ciphertexts
///
/// We collect statistics for RLWE'(-sm) separately from RLWE'(m) because
/// non-interactive protocol differents between the two. Although we expect
/// the distribution of noise in both to be the same.
brk_rgsw_cts: (Stats<T>, Stats<T>),
/// Distribtion of noise added to RLWE ciphertext after automorphism using
/// Server auto keys.
post_1_auto: Stats<T>,
/// Distribution of noise added in LWE key switching from LWE_{q, s} to
/// LWE_{q, z} where `z` is ideal LWE secret and `s` is ideal RLWE secret
/// using Server's LWE key switching key.
post_lwe_key_switch: Stats<T>,
}
impl<T: PrimInt + FromPrimitive + Debug + Sum> ServerKeyStats<T>
where
T: for<'a> Sum<&'a T>,
{
fn new() -> Self {
ServerKeyStats {
brk_rgsw_cts: (Stats::default(), Stats::default()),
post_1_auto: Stats::default(),
post_lwe_key_switch: Stats::default(),
}
}
fn add_noise_brk_rgsw_cts_nsm(&mut self, noise: &[T]) {
self.brk_rgsw_cts.0.add_many_samples(noise);
}
fn add_noise_brk_rgsw_cts_m(&mut self, noise: &[T]) {
self.brk_rgsw_cts.1.add_many_samples(noise);
}
fn add_noise_post_1_auto(&mut self, noise: &[T]) {
self.post_1_auto.add_many_samples(&noise);
}
fn add_noise_post_kwe_key_switch(&mut self, noise: &[T]) {
self.post_lwe_key_switch.add_many_samples(&noise);
}
fn merge_in(&mut self, other: &Self) {
self.brk_rgsw_cts.0.merge_in(&other.brk_rgsw_cts.0);
self.brk_rgsw_cts.1.merge_in(&other.brk_rgsw_cts.1);
self.post_1_auto.merge_in(&other.post_1_auto);
self.post_lwe_key_switch
.merge_in(&other.post_lwe_key_switch);
}
}
fn collect_server_key_stats<
M: MatrixEntity + MatrixMut,
D: Decomposer<Element = M::MatElement>,
NttOp: NttInit<CiphertextModulus<M::MatElement>> + Ntt<Element = M::MatElement>,
ModOp: VectorOps<Element = M::MatElement>
+ ArithmeticOps<Element = M::MatElement>
+ ModInit<M = CiphertextModulus<M::MatElement>>
+ GetModulus<M = CiphertextModulus<M::MatElement>, Element = M::MatElement>,
S: CollectRuntimeServerKeyStats<M = M>,
>(
parameters: BoolParameters<M::MatElement>,
client_keys: &[ClientKey],
server_key: &S,
) -> ServerKeyStats<i64>
where
M::R: RowMut + RowEntity + TryConvertFrom1<[i32], CiphertextModulus<M::MatElement>> + Clone,
M::MatElement: Copy + PrimInt + FromPrimitive + SampleUniform + Zero + Debug + NumInfo,
{
let ideal_sk_rlwe = ideal_sk_rlwe(client_keys);
let ideal_sk_lwe = ideal_sk_lwe(client_keys);
let embedding_factor = (2 * parameters.rlwe_n().0) / parameters.br_q();
let rlwe_n = parameters.rlwe_n().0;
let rlwe_q = parameters.rlwe_q();
let lwe_q = parameters.lwe_q();
let rlwe_modop = ModOp::new(rlwe_q.clone());
let rlwe_nttop = NttOp::new(rlwe_q, rlwe_n);
let lwe_modop = ModOp::new(*parameters.lwe_q());
let rlwe_x_rgsw_decomposer = parameters.rlwe_rgsw_decomposer::<D>();
let (rlwe_x_rgsw_gadget_a, rlwe_x_rgsw_gadget_b) = (
rlwe_x_rgsw_decomposer.a().gadget_vector(),
rlwe_x_rgsw_decomposer.b().gadget_vector(),
);
let lwe_ks_decomposer = parameters.lwe_decomposer::<D>();
let mut server_key_stats = ServerKeyStats::new();
let mut rng = DefaultSecureRng::new();
// RGSW ciphertext noise
// Check noise in RGSW ciphertexts of ideal LWE secret elements
{
ideal_sk_lwe.iter().enumerate().for_each(|(s_index, s_i)| {
let rgsw_ct_i = server_key.rgsw_cts_lwe_si(s_index);
// X^{s[i]}
let m_si = encode_x_pow_si_with_emebedding_factor::<M::R, _>(
*s_i,
embedding_factor,
rlwe_n,
rlwe_q,
);
// RLWE'(-sm)
let mut neg_s_eval = M::R::try_convert_from(ideal_sk_rlwe.as_slice(), rlwe_q);
rlwe_modop.elwise_neg_mut(neg_s_eval.as_mut());
rlwe_nttop.forward(neg_s_eval.as_mut());
for j in 0..rlwe_x_rgsw_decomposer.a().decomposition_count().0 {
// RLWE(B^{j} * -s[X]*X^{s_lwe[i]})
// -s[X]*X^{s_lwe[i]}*B_j
let mut m_ideal = m_si.clone();
rlwe_nttop.forward(m_ideal.as_mut());
rlwe_modop.elwise_mul_mut(m_ideal.as_mut(), neg_s_eval.as_ref());
rlwe_nttop.backward(m_ideal.as_mut());
rlwe_modop.elwise_scalar_mul_mut(m_ideal.as_mut(), &rlwe_x_rgsw_gadget_a[j]);
// RLWE(-s*X^{s_lwe[i]}*B_j)
let mut rlwe_ct = M::zeros(2, rlwe_n);
rlwe_ct
.get_row_mut(0)
.copy_from_slice(rgsw_ct_i.get_row_slice(j));
rlwe_ct.get_row_mut(1).copy_from_slice(
rgsw_ct_i.get_row_slice(j + rlwe_x_rgsw_decomposer.a().decomposition_count().0),
);
// RGSW ciphertexts are in eval domain. We put RLWE ciphertexts back in
// coefficient domain
rlwe_ct
.iter_rows_mut()
.for_each(|r| rlwe_nttop.backward(r.as_mut()));
let mut m_back = M::R::zeros(rlwe_n);
decrypt_rlwe(
&rlwe_ct,
&ideal_sk_rlwe,
&mut m_back,
&rlwe_nttop,
&rlwe_modop,
);
// diff
rlwe_modop.elwise_sub_mut(m_back.as_mut(), m_ideal.as_ref());
server_key_stats.add_noise_brk_rgsw_cts_nsm(&Vec::<i64>::try_convert_from(
m_back.as_ref(),
rlwe_q,
));
}
// RLWE'(m)
for j in 0..rlwe_x_rgsw_decomposer.b().decomposition_count().0 {
// RLWE(B^{j} * X^{s_lwe[i]})
// X^{s_lwe[i]}*B_j
let mut m_ideal = m_si.clone();
rlwe_modop.elwise_scalar_mul_mut(m_ideal.as_mut(), &rlwe_x_rgsw_gadget_b[j]);
// RLWE(X^{s_lwe[i]}*B_j)
let mut rlwe_ct = M::zeros(2, rlwe_n);
rlwe_ct.get_row_mut(0).copy_from_slice(
rgsw_ct_i.get_row_slice(
j + (2 * rlwe_x_rgsw_decomposer.a().decomposition_count().0),
),
);
rlwe_ct
.get_row_mut(1)
.copy_from_slice(rgsw_ct_i.get_row_slice(
j + (2 * rlwe_x_rgsw_decomposer.a().decomposition_count().0)
+ rlwe_x_rgsw_decomposer.b().decomposition_count().0,
));
rlwe_ct
.iter_rows_mut()
.for_each(|r| rlwe_nttop.backward(r.as_mut()));
let mut m_back = M::R::zeros(rlwe_n);
decrypt_rlwe(
&rlwe_ct,
&ideal_sk_rlwe,
&mut m_back,
&rlwe_nttop,
&rlwe_modop,
);
// diff
rlwe_modop.elwise_sub_mut(m_back.as_mut(), m_ideal.as_ref());
server_key_stats.add_noise_brk_rgsw_cts_m(&Vec::<i64>::try_convert_from(
m_back.as_ref(),
rlwe_q,
));
}
});
}
// Noise in ciphertext after 1 auto
// For each auto key g^k. Sample random polynomial m(X) and multiply with
// -s(X^{g^k}) using key corresponding to auto g^k. Then check the noise in
// resutling RLWE(m(X) * -s(X^{g^k}))
{
let neg_s = {
let mut s = M::R::try_convert_from(ideal_sk_rlwe.as_slice(), rlwe_q);
rlwe_modop.elwise_neg_mut(s.as_mut());
s
};
let g = parameters.g();
let br_q = parameters.br_q();
let g_dlogs = parameters.auto_element_dlogs();
let auto_decomposer = parameters.auto_decomposer::<D>();
let mut scratch_matrix = M::zeros(rlwe_auto_scratch_rows(&auto_decomposer), rlwe_n);
let mut scratch_matrix_ref = RuntimeScratchMutRef::new(scratch_matrix.as_mut());
g_dlogs.iter().for_each(|k| {
let g_pow_k = if *k == 0 {
-(g as isize)
} else {
(g.pow(*k as u32) % br_q) as isize
};
// Send s(X) -> s(X^{g^k})
let (auto_index_map, auto_sign_map) = crate::rgsw::generate_auto_map(rlwe_n, g_pow_k);
let mut neg_s_g_k = M::R::zeros(rlwe_n);
izip!(
neg_s.as_ref().iter(),
auto_index_map.iter(),
auto_sign_map.iter()
)
.for_each(|(el, to_index, to_sign)| {
if !to_sign {
neg_s_g_k.as_mut()[*to_index] = rlwe_modop.neg(el);
} else {
neg_s_g_k.as_mut()[*to_index] = *el;
}
});
let mut m = M::R::zeros(rlwe_n);
RandomFillUniformInModulus::random_fill(&mut rng, rlwe_q, m.as_mut());
// We want -m(X^{g^k})s(X^{g^k}) after key switch
let want_m = {
let mut m_g_k_eval = M::R::zeros(rlwe_n);
// send m(X) -> m(X^{g^k})
izip!(
m.as_ref().iter(),
auto_index_map.iter(),
auto_sign_map.iter()
)
.for_each(|(el, to_index, to_sign)| {
if !to_sign {
m_g_k_eval.as_mut()[*to_index] = rlwe_modop.neg(el);
} else {
m_g_k_eval.as_mut()[*to_index] = *el;
}
});
rlwe_nttop.forward(m_g_k_eval.as_mut());
let mut s_g_k = neg_s_g_k.clone();
rlwe_nttop.forward(s_g_k.as_mut());
rlwe_modop.elwise_mul_mut(m_g_k_eval.as_mut(), s_g_k.as_ref());
rlwe_nttop.backward(m_g_k_eval.as_mut());
m_g_k_eval
};
// RLWE auto sends part A, A(X), of RLWE to A(X^{g^k}) and then multiplies it
// with -s(X^{g^k}) using auto key. Deliberately set RLWE = (0, m(X))
// (ie. m in part A) to get back RLWE(-m(X^{g^k})s(X^{g^k}))
let mut rlwe = M::zeros(2, rlwe_n);
rlwe.get_row_mut(0).copy_from_slice(m.as_ref());
rlwe_auto(
&mut RlweCiphertextMutRef::new(rlwe.as_mut()),
&RlweKskRef::new(
server_key.galois_key_for_auto(*k).as_ref(),
auto_decomposer.decomposition_count().0,
),
&mut scratch_matrix_ref,
&auto_index_map,
&auto_sign_map,
&rlwe_modop,
&rlwe_nttop,
&auto_decomposer,
false,
);
// decrypt RLWE(-m(X)s(X^{g^k]}))
let mut back_m = M::R::zeros(rlwe_n);
decrypt_rlwe(&rlwe, &ideal_sk_rlwe, &mut back_m, &rlwe_nttop, &rlwe_modop);
// check difference
let mut diff = back_m;
rlwe_modop.elwise_sub_mut(diff.as_mut(), want_m.as_ref());
server_key_stats
.add_noise_post_1_auto(&Vec::<i64>::try_convert_from(diff.as_ref(), rlwe_q));
});
// sample random m
// key switch
}
// LWE Key switch
// LWE key switches LWE_in = LWE_{Q_ks,N, s}(m) = (b, a_0, ... a_N) -> LWE_out =
// LWE_{Q_{ks}, n, z}(m) = (b', a'_0, ..., a'n)
// If LWE_in = (0, a = {a_0, ..., a_N}), then LWE_out = LWE(-a \cdot s_{rlwe})
for _ in 0..100 {
let mut lwe_in = M::R::zeros(rlwe_n + 1);
RandomFillUniformInModulus::random_fill(&mut rng, lwe_q, &mut lwe_in.as_mut()[1..]);
// Key switch
let mut lwe_out = M::R::zeros(parameters.lwe_n().0 + 1);
lwe_key_switch(
&mut lwe_out,
&lwe_in,
server_key.lwe_ksk(),
&lwe_modop,
&lwe_ks_decomposer,
);
// -a \cdot s
let mut want_m = M::MatElement::zero();
izip!(lwe_in.as_ref().iter().skip(1), ideal_sk_rlwe.iter()).for_each(|(a, b)| {
want_m = lwe_modop.add(
&want_m,
&lwe_modop.mul(a, &lwe_q.map_element_from_i64(*b as i64)),
);
});
want_m = lwe_modop.neg(&want_m);
// decrypt lwe out
let back_m = decrypt_lwe(&lwe_out, &ideal_sk_lwe, &lwe_modop);
let noise = lwe_modop.sub(&want_m, &back_m);
server_key_stats.add_noise_post_kwe_key_switch(&vec![lwe_q.map_element_to_i64(&noise)]);
}
server_key_stats
// Auto keys noise
// Ksk noise
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
#[test]
#[cfg(feature = "interactive_mp")]
fn interactive_key_noise() {
use crate::{
aggregate_public_key_shares, aggregate_server_key_shares,
bool::{
evaluator::InteractiveMultiPartyCrs,
keys::{key_size::KeySize, ServerKeyEvaluationDomain},
},
collective_pk_share, collective_server_key_share, gen_client_key,
parameters::CiphertextModulus,
random::DefaultSecureRng,
set_common_reference_seed, set_parameter_set,
utils::WithLocal,
BoolEvaluator, DefaultDecomposer, ModularOpsU64, NttBackendU64,
};
use super::*;
set_parameter_set(crate::ParameterSelector::InteractiveLTE8Party);
set_common_reference_seed(InteractiveMultiPartyCrs::random().seed);
let parties = 8;
let mut server_key_stats = ServerKeyStats::default();
let mut server_key_share_size = 0usize;
for i in 0..2 {
let cks = (0..parties).map(|_| gen_client_key()).collect_vec();
let pk_shares = cks.iter().map(|k| collective_pk_share(k)).collect_vec();
let pk = aggregate_public_key_shares(&pk_shares);
let server_key_shares = cks
.iter()
.enumerate()
.map(|(index, k)| collective_server_key_share(k, index, parties, &pk))
.collect_vec();
// In 0th iteration measure server key size
if i == 0 {
// Server key share size of user with last id may not equal server key share
// sizes of other users if LWE dimension does not divides number of parties.
server_key_share_size = std::cmp::max(
server_key_shares.first().unwrap().size(),
server_key_shares.last().unwrap().size(),
);
}
// println!("Size: {}", server_key_shares[0].size());
let seeded_server_key = aggregate_server_key_shares(&server_key_shares);
let server_key_eval =
ServerKeyEvaluationDomain::<_, _, DefaultSecureRng, NttBackendU64>::from(
&seeded_server_key,
);
let parameters = BoolEvaluator::with_local(|e| e.parameters().clone());
server_key_stats.merge_in(&collect_server_key_stats::<
_,
DefaultDecomposer<u64>,
NttBackendU64,
ModularOpsU64<CiphertextModulus<u64>>,
_,
>(parameters, &cks, &server_key_eval));
}
println!(
"Common reference seeded server key share key size: {} Bits",
server_key_share_size
);
println!(
"Rgsw nsm std log2 {}",
server_key_stats.brk_rgsw_cts.0.std_dev().log2()
);
println!(
"Rgsw m std log2 {}",
server_key_stats.brk_rgsw_cts.1.std_dev().log2()
);
println!(
"rlwe post 1 auto std log2 {}",
server_key_stats.post_1_auto.std_dev().log2()
);
println!(
"key switching noise rlwe secret s to lwe secret z std log2 {}",
server_key_stats.post_lwe_key_switch.std_dev().log2()
);
}
const K: usize = 10;
#[test]
#[cfg(feature = "interactive_mp")]
fn interactive_mp_bool_gates() {
use rand::{thread_rng, RngCore};
use crate::{
aggregate_public_key_shares, aggregate_server_key_shares,
backend::Modulus,
bool::{
keys::{
tests::{ideal_sk_rlwe, measure_noise_lwe},
ServerKeyEvaluationDomain,
},
print_noise::collect_server_key_stats,
},
collective_pk_share, collective_server_key_share, gen_client_key,
parameters::CiphertextModulus,
random::DefaultSecureRng,
set_common_reference_seed, set_parameter_set,
utils::{tests::Stats, Global, WithLocal},
BoolEvaluator, BooleanGates, DefaultDecomposer, Encoder, Encryptor, ModInit,
ModularOpsU64, MultiPartyDecryptor, NttBackendU64, ParameterSelector, RuntimeServerKey,
};
set_parameter_set(ParameterSelector::InteractiveLTE8Party);
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let no_of_parties = 8;
let cks = (0..no_of_parties).map(|_| gen_client_key()).collect_vec();
// round 1
let pk_shares = cks.iter().map(|k| collective_pk_share(k)).collect_vec();
let pk = aggregate_public_key_shares(&pk_shares);
// round 2
let server_key_shares = cks
.iter()
.enumerate()
.map(|(user_id, k)| collective_server_key_share(k, user_id, no_of_parties, &pk))
.collect_vec();
let server_key = aggregate_server_key_shares(&server_key_shares);
server_key.set_server_key();
let mut m0 = false;
let mut m1 = true;
let mut ct0 = pk.encrypt(&m0);
let mut ct1 = pk.encrypt(&m1);
let ideal_sk_rlwe = ideal_sk_rlwe(&cks);
let parameters = BoolEvaluator::with_local(|e| e.parameters().clone());
let rlwe_modop = ModularOpsU64::new(*parameters.rlwe_q());
let mut stats = Stats::new();
for _ in 0..K {
// let now = std::time::Instant::now();
let ct_out =
BoolEvaluator::with_local_mut(|e| e.xor(&ct0, &ct1, RuntimeServerKey::global()));
// println!("Time: {:?}", now.elapsed());
let m_expected = m0 ^ m1;
let decryption_shares = cks
.iter()
.map(|k| k.gen_decryption_share(&ct_out))
.collect_vec();
let m_out = cks[0].aggregate_decryption_shares(&ct_out, &decryption_shares);
assert!(m_out == m_expected, "Expected {m_expected}, got {m_out}");
{
let noise = measure_noise_lwe(
&ct_out,
parameters.rlwe_q().encode(m_expected),
&ideal_sk_rlwe,
&rlwe_modop,
);
stats.add_sample(parameters.rlwe_q().map_element_to_i64(&noise));
}
m1 = m0;
m0 = m_expected;
ct1 = ct0;
ct0 = ct_out;
}
let server_key_stats = collect_server_key_stats::<
_,
DefaultDecomposer<u64>,
NttBackendU64,
ModularOpsU64<CiphertextModulus<u64>>,
_,
>(
parameters,
&cks,
&ServerKeyEvaluationDomain::<_, _, DefaultSecureRng, NttBackendU64>::from(&server_key),
);
println!("## Bootstrapping Statistics ##");
println!("Bootstrapped ciphertext noise std_dev: {}", stats.std_dev());
println!("## Key Statistics ##");
println!(
"Rgsw nsm std_dev {}",
server_key_stats.brk_rgsw_cts.0.std_dev()
);
println!(
"Rgsw m std_dev {}",
server_key_stats.brk_rgsw_cts.1.std_dev()
);
println!(
"rlwe post 1 auto std_dev {}",
server_key_stats.post_1_auto.std_dev()
);
println!(
"key switching noise rlwe secret s to lwe secret z std_dev {}",
server_key_stats.post_lwe_key_switch.std_dev()
);
println!();
}
#[test]
#[cfg(feature = "non_interactive_mp")]
fn non_interactive_mp_bool_gates() {
use rand::{thread_rng, RngCore};
use crate::{
aggregate_server_key_shares,
backend::Modulus,
bool::{
keys::{
tests::{ideal_sk_rlwe, measure_noise_lwe},
NonInteractiveServerKeyEvaluationDomain,
},
print_noise::collect_server_key_stats,
NonInteractiveBatchedFheBools,
},
gen_client_key, gen_server_key_share,
parameters::CiphertextModulus,
random::DefaultSecureRng,
set_common_reference_seed, set_parameter_set,
utils::{tests::Stats, Global, WithLocal},
BoolEvaluator, BooleanGates, DefaultDecomposer, Encoder, Encryptor, KeySwitchWithId,
ModInit, ModularOpsU64, MultiPartyDecryptor, NttBackendU64, ParameterSelector,
RuntimeServerKey,
};
set_parameter_set(ParameterSelector::NonInteractiveLTE8Party);
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let parties = 8;
let cks = (0..parties).map(|_| gen_client_key()).collect_vec();
let server_key_shares = cks
.iter()
.enumerate()
.map(|(user_index, ck)| gen_server_key_share(user_index, parties, ck))
.collect_vec();
let seeded_server_key = aggregate_server_key_shares(&server_key_shares);
seeded_server_key.set_server_key();
let parameters = BoolEvaluator::with_local(|e| e.parameters().clone());
let rlwe_modop = ModularOpsU64::new(*parameters.rlwe_q());
let ideal_sk_rlwe = ideal_sk_rlwe(&cks);
let mut m0 = false;
let mut m1 = true;
let mut ct0 = {
let ct: NonInteractiveBatchedFheBools<_> = cks[0].encrypt(vec![m0].as_slice());
let ct = ct.key_switch(0);
ct.extract(0)
};
let mut ct1 = {
let ct: NonInteractiveBatchedFheBools<_> = cks[1].encrypt(vec![m1].as_slice());
let ct = ct.key_switch(1);
ct.extract(0)
};
let mut stats = Stats::new();
for _ in 0..K {
// let now = std::time::Instant::now();
let ct_out =
BoolEvaluator::with_local_mut(|e| e.xor(&ct0, &ct1, RuntimeServerKey::global()));
// println!("Time: {:?}", now.elapsed());
let decryption_shares = cks
.iter()
.map(|k| k.gen_decryption_share(&ct_out))
.collect_vec();
let m_out = cks[0].aggregate_decryption_shares(&ct_out, &decryption_shares);
let m_expected = m0 ^ m1;
{
let noise = measure_noise_lwe(
&ct_out,
parameters.rlwe_q().encode(m_expected),
&ideal_sk_rlwe,
&rlwe_modop,
);
stats.add_sample(parameters.rlwe_q().map_element_to_i64(&noise));
}
assert!(m_out == m_expected, "Expected {m_expected} but got {m_out}");
m1 = m0;
m0 = m_out;
ct1 = ct0;
ct0 = ct_out;
}
// server key statistics
let server_key_stats = collect_server_key_stats::<
_,
DefaultDecomposer<u64>,
NttBackendU64,
ModularOpsU64<CiphertextModulus<u64>>,
_,
>(
parameters,
&cks,
&NonInteractiveServerKeyEvaluationDomain::<_, _, DefaultSecureRng, NttBackendU64>::from(
&seeded_server_key,
),
);
println!("## Bootstrapping Statistics ##");
println!("Bootstrapped ciphertext noise std_dev: {}", stats.std_dev());
println!("## Key Statistics ##");
println!(
"Rgsw nsm std_dev {}",
server_key_stats.brk_rgsw_cts.0.std_dev()
);
println!(
"Rgsw m std_dev {}",
server_key_stats.brk_rgsw_cts.1.std_dev()
);
println!(
"rlwe post 1 auto std_dev {}",
server_key_stats.post_1_auto.std_dev()
);
println!(
"key switching noise rlwe secret s to lwe secret z std_dev {}",
server_key_stats.post_lwe_key_switch.std_dev()
);
println!();
}
#[test]
#[cfg(feature = "non_interactive_mp")]
fn non_interactive_key_noise() {
use crate::{
aggregate_server_key_shares,
bool::{
evaluator::NonInteractiveMultiPartyCrs,
keys::{key_size::KeySize, NonInteractiveServerKeyEvaluationDomain},
},
decomposer::DefaultDecomposer,
gen_client_key, gen_server_key_share,
parameters::CiphertextModulus,
random::DefaultSecureRng,
set_common_reference_seed, set_parameter_set,
utils::WithLocal,
BoolEvaluator, ModularOpsU64, NttBackendU64,
};
use super::*;
set_parameter_set(crate::ParameterSelector::NonInteractiveLTE8Party);
set_common_reference_seed(NonInteractiveMultiPartyCrs::random().seed);
let parties = 8;
let mut server_key_stats = ServerKeyStats::default();
let mut server_key_share_size = 0;
for i in 0..2 {
let cks = (0..parties).map(|_| gen_client_key()).collect_vec();
let server_key_shares = cks
.iter()
.enumerate()
.map(|(user_id, k)| gen_server_key_share(user_id, parties, k))
.collect_vec();
// Collect server key size in the 0th iteration
if i == 0 {
// Server key share size may differ for user with last id from
// the share size of other users if the LWE dimension `n` is not
// divisible by no. of parties.
server_key_share_size = std::cmp::max(
server_key_shares.first().unwrap().size(),
server_key_shares.last().unwrap().size(),
);
}
let server_key = aggregate_server_key_shares(&server_key_shares);
let server_key_eval = NonInteractiveServerKeyEvaluationDomain::<
_,
_,
DefaultSecureRng,
NttBackendU64,
>::from(&server_key);
let parameters = BoolEvaluator::with_local(|e| e.parameters().clone());
server_key_stats.merge_in(&collect_server_key_stats::<
_,
DefaultDecomposer<u64>,
NttBackendU64,
ModularOpsU64<CiphertextModulus<u64>>,
_,
>(parameters, &cks, &server_key_eval));
}
println!(
"Common reference seeded server key share key size: {} Bits",
server_key_share_size
);
println!(
"Rgsw nsm std log2 {}",
server_key_stats.brk_rgsw_cts.0.std_dev().abs().log2()
);
println!(
"Rgsw m std log2 {}",
server_key_stats.brk_rgsw_cts.1.std_dev().abs().log2()
);
println!(
"rlwe post 1 auto std log2 {}",
server_key_stats.post_1_auto.std_dev().abs().log2()
);
println!(
"key switching noise rlwe secret s to lwe secret z std log2 {}",
server_key_stats.post_lwe_key_switch.std_dev().abs().log2()
);
}
#[test]
#[cfg(feature = "non_interactive_mp")]
fn enc_under_sk_and_key_switch() {
use rand::{thread_rng, Rng};
use crate::{
aggregate_server_key_shares,
bool::{keys::tests::ideal_sk_rlwe, ni_mp_api::NonInteractiveBatchedFheBools},
gen_client_key, gen_server_key_share,
rgsw::decrypt_rlwe,
set_common_reference_seed, set_parameter_set,
utils::{tests::Stats, TryConvertFrom1, WithLocal},
BoolEvaluator, Encoder, Encryptor, KeySwitchWithId, ModInit, ModularOpsU64,
NttBackendU64, NttInit, ParameterSelector, VectorOps,
};
set_parameter_set(ParameterSelector::NonInteractiveLTE2Party);
set_common_reference_seed([2; 32]);
let parties = 2;
let cks = (0..parties).map(|_| gen_client_key()).collect_vec();
let key_shares = cks
.iter()
.enumerate()
.map(|(user_index, ck)| gen_server_key_share(user_index, parties, ck))
.collect_vec();
let seeded_server_key = aggregate_server_key_shares(&key_shares);
seeded_server_key.set_server_key();
let parameters = BoolEvaluator::with_local(|e| e.parameters().clone());
let nttop = NttBackendU64::new(parameters.rlwe_q(), parameters.rlwe_n().0);
let rlwe_q_modop = ModularOpsU64::new(*parameters.rlwe_q());
let m = (0..parameters.rlwe_n().0)
.map(|_| thread_rng().gen_bool(0.5))
.collect_vec();
let ct: NonInteractiveBatchedFheBools<_> = cks[0].encrypt(m.as_slice());
let ct = ct.key_switch(0);
let ideal_rlwe_sk = ideal_sk_rlwe(&cks);
let message = m
.iter()
.map(|b| parameters.rlwe_q().encode(*b))
.collect_vec();
let mut m_out = vec![0u64; parameters.rlwe_n().0];
decrypt_rlwe(
&ct.data[0],
&ideal_rlwe_sk,
&mut m_out,
&nttop,
&rlwe_q_modop,
);
let mut diff = m_out;
rlwe_q_modop.elwise_sub_mut(diff.as_mut_slice(), message.as_ref());
let mut stats = Stats::new();
stats.add_many_samples(&Vec::<i64>::try_convert_from(
diff.as_slice(),
parameters.rlwe_q(),
));
println!("Noise std log2: {}", stats.std_dev().abs().log2());
}
#[test]
fn mod_switch_noise() {
// Experiment to check mod switch noise using different secret dist in
// multi-party setting
use itertools::izip;
use num_traits::ToPrimitive;
use crate::{
backend::{Modulus, ModulusPowerOf2},
parameters::SecretKeyDistribution,
random::{DefaultSecureRng, RandomFillGaussian, RandomFillUniformInModulus},
utils::{fill_random_ternary_secret_with_hamming_weight, tests::Stats},
ArithmeticOps, ModInit,
};
fn mod_switch(v: u64, q_from: u64, q_to: u64) -> f64 {
(v as f64) * (q_to as f64) / q_from as f64
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | true |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/bool/mod.rs | src/bool/mod.rs | mod evaluator;
mod keys;
pub(crate) mod parameters;
#[cfg(feature = "interactive_mp")]
mod mp_api;
#[cfg(feature = "non_interactive_mp")]
mod ni_mp_api;
#[cfg(feature = "non_interactive_mp")]
pub use ni_mp_api::*;
#[cfg(feature = "interactive_mp")]
pub use mp_api::*;
use crate::RowEntity;
pub type ClientKey = keys::ClientKey<[u8; 32], u64>;
#[cfg(any(feature = "interactive_mp", feature = "non_interactive_mp"))]
pub type FheBool = impl_bool_frontend::FheBool<Vec<u64>>;
pub(crate) trait BooleanGates {
type Ciphertext: RowEntity;
type Key;
fn and_inplace(&mut self, c0: &mut Self::Ciphertext, c1: &Self::Ciphertext, key: &Self::Key);
fn nand_inplace(&mut self, c0: &mut Self::Ciphertext, c1: &Self::Ciphertext, key: &Self::Key);
fn or_inplace(&mut self, c0: &mut Self::Ciphertext, c1: &Self::Ciphertext, key: &Self::Key);
fn nor_inplace(&mut self, c0: &mut Self::Ciphertext, c1: &Self::Ciphertext, key: &Self::Key);
fn xor_inplace(&mut self, c0: &mut Self::Ciphertext, c1: &Self::Ciphertext, key: &Self::Key);
fn xnor_inplace(&mut self, c0: &mut Self::Ciphertext, c1: &Self::Ciphertext, key: &Self::Key);
fn not_inplace(&self, c: &mut Self::Ciphertext);
fn and(
&mut self,
c0: &Self::Ciphertext,
c1: &Self::Ciphertext,
key: &Self::Key,
) -> Self::Ciphertext;
fn nand(
&mut self,
c0: &Self::Ciphertext,
c1: &Self::Ciphertext,
key: &Self::Key,
) -> Self::Ciphertext;
fn or(
&mut self,
c0: &Self::Ciphertext,
c1: &Self::Ciphertext,
key: &Self::Key,
) -> Self::Ciphertext;
fn nor(
&mut self,
c0: &Self::Ciphertext,
c1: &Self::Ciphertext,
key: &Self::Key,
) -> Self::Ciphertext;
fn xor(
&mut self,
c0: &Self::Ciphertext,
c1: &Self::Ciphertext,
key: &Self::Key,
) -> Self::Ciphertext;
fn xnor(
&mut self,
c0: &Self::Ciphertext,
c1: &Self::Ciphertext,
key: &Self::Key,
) -> Self::Ciphertext;
fn not(&self, c: &Self::Ciphertext) -> Self::Ciphertext;
}
#[cfg(any(feature = "interactive_mp", feature = "non_interactive_mp"))]
mod impl_bool_frontend {
use crate::MultiPartyDecryptor;
/// Fhe Bool ciphertext
#[derive(Clone)]
pub struct FheBool<C> {
pub(crate) data: C,
}
impl<C> FheBool<C> {
pub(crate) fn data(&self) -> &C {
&self.data
}
pub(crate) fn data_mut(&mut self) -> &mut C {
&mut self.data
}
}
impl<C, K> MultiPartyDecryptor<bool, FheBool<C>> for K
where
K: MultiPartyDecryptor<bool, C>,
{
type DecryptionShare = <K as MultiPartyDecryptor<bool, C>>::DecryptionShare;
fn aggregate_decryption_shares(
&self,
c: &FheBool<C>,
shares: &[Self::DecryptionShare],
) -> bool {
self.aggregate_decryption_shares(&c.data, shares)
}
fn gen_decryption_share(&self, c: &FheBool<C>) -> Self::DecryptionShare {
self.gen_decryption_share(&c.data)
}
}
mod ops {
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};
use crate::{
utils::{Global, WithLocal},
BooleanGates,
};
use super::super::{BoolEvaluator, RuntimeServerKey};
type FheBool = super::super::FheBool;
impl BitAnd for &FheBool {
type Output = FheBool;
fn bitand(self, rhs: Self) -> Self::Output {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
FheBool {
data: e.and(self.data(), rhs.data(), key),
}
})
}
}
impl BitAndAssign for FheBool {
fn bitand_assign(&mut self, rhs: Self) {
BoolEvaluator::with_local_mut_mut(&mut |e| {
let key = RuntimeServerKey::global();
e.and_inplace(&mut self.data_mut(), rhs.data(), key);
});
}
}
impl BitOr for &FheBool {
type Output = FheBool;
fn bitor(self, rhs: Self) -> Self::Output {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
FheBool {
data: e.or(self.data(), rhs.data(), key),
}
})
}
}
impl BitOrAssign for FheBool {
fn bitor_assign(&mut self, rhs: Self) {
BoolEvaluator::with_local_mut_mut(&mut |e| {
let key = RuntimeServerKey::global();
e.or_inplace(&mut self.data_mut(), rhs.data(), key);
});
}
}
impl BitXor for &FheBool {
type Output = FheBool;
fn bitxor(self, rhs: Self) -> Self::Output {
BoolEvaluator::with_local_mut(|e| {
let key = RuntimeServerKey::global();
FheBool {
data: e.xor(self.data(), rhs.data(), key),
}
})
}
}
impl BitXorAssign for FheBool {
fn bitxor_assign(&mut self, rhs: Self) {
BoolEvaluator::with_local_mut_mut(&mut |e| {
let key = RuntimeServerKey::global();
e.xor_inplace(&mut self.data_mut(), rhs.data(), key);
});
}
}
impl Not for &FheBool {
type Output = FheBool;
fn not(self) -> Self::Output {
BoolEvaluator::with_local(|e| FheBool {
data: e.not(self.data()),
})
}
}
}
}
#[cfg(any(feature = "interactive_mp", feature = "non_interactive_mp"))]
mod common_mp_enc_dec {
use itertools::Itertools;
use super::BoolEvaluator;
use crate::{
pbs::{sample_extract, PbsInfo},
utils::WithLocal,
Matrix, RowEntity, SampleExtractor,
};
type Mat = Vec<Vec<u64>>;
impl SampleExtractor<<Mat as Matrix>::R> for Mat {
/// Sample extract coefficient at `index` as a LWE ciphertext from RLWE
/// ciphertext `Self`
fn extract_at(&self, index: usize) -> <Mat as Matrix>::R {
// input is RLWE ciphertext
assert!(self.dimension().0 == 2);
let ring_size = self.dimension().1;
assert!(index < ring_size);
BoolEvaluator::with_local(|e| {
let mut lwe_out = <Mat as Matrix>::R::zeros(ring_size + 1);
sample_extract(&mut lwe_out, self, e.pbs_info().modop_rlweq(), index);
lwe_out
})
}
/// Extract first `how_many` coefficients of `Self` as LWE ciphertexts
fn extract_many(&self, how_many: usize) -> Vec<<Mat as Matrix>::R> {
assert!(self.dimension().0 == 2);
let ring_size = self.dimension().1;
assert!(how_many <= ring_size);
(0..how_many)
.map(|index| {
BoolEvaluator::with_local(|e| {
let mut lwe_out = <Mat as Matrix>::R::zeros(ring_size + 1);
sample_extract(&mut lwe_out, self, e.pbs_info().modop_rlweq(), index);
lwe_out
})
})
.collect_vec()
}
/// Extracts all coefficients of `Self` as LWE ciphertexts
fn extract_all(&self) -> Vec<<Mat as Matrix>::R> {
assert!(self.dimension().0 == 2);
let ring_size = self.dimension().1;
(0..ring_size)
.map(|index| {
BoolEvaluator::with_local(|e| {
let mut lwe_out = <Mat as Matrix>::R::zeros(ring_size + 1);
sample_extract(&mut lwe_out, self, e.pbs_info().modop_rlweq(), index);
lwe_out
})
})
.collect_vec()
}
}
}
#[cfg(test)]
mod print_noise;
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/bool/evaluator.rs | src/bool/evaluator.rs | use std::{
collections::HashMap,
fmt::{Debug, Display},
marker::PhantomData,
usize,
};
use itertools::{izip, Itertools};
use num_traits::{FromPrimitive, One, PrimInt, ToPrimitive, WrappingAdd, WrappingSub, Zero};
use rand_distr::uniform::SampleUniform;
use crate::{
backend::{ArithmeticOps, GetModulus, ModInit, Modulus, ShoupMatrixFMA, VectorOps},
bool::parameters::ParameterVariant,
decomposer::{Decomposer, DefaultDecomposer, NumInfo, RlweDecomposer},
lwe::{decrypt_lwe, encrypt_lwe, seeded_lwe_ksk_keygen},
multi_party::{
non_interactive_ksk_gen, non_interactive_ksk_zero_encryptions_for_other_party_i,
public_key_share,
},
ntt::{Ntt, NttInit},
pbs::{pbs, PbsInfo, PbsKey, WithShoupRepr},
random::{
DefaultSecureRng, NewWithSeed, RandomFill, RandomFillGaussianInModulus,
RandomFillUniformInModulus,
},
rgsw::{
generate_auto_map, public_key_encrypt_rgsw, rgsw_by_rgsw_inplace, rgsw_x_rgsw_scratch_rows,
rlwe_auto_scratch_rows, rlwe_x_rgsw_scratch_rows, secret_key_encrypt_rgsw,
seeded_auto_key_gen, RgswCiphertextMutRef, RgswCiphertextRef, RuntimeScratchMutRef,
},
utils::{
encode_x_pow_si_with_emebedding_factor, mod_exponent, puncture_p_rng, TryConvertFrom1,
WithLocal,
},
BooleanGates, Encoder, Matrix, MatrixEntity, MatrixMut, RowEntity, RowMut,
};
use super::{
keys::{
ClientKey, CommonReferenceSeededCollectivePublicKeyShare,
CommonReferenceSeededInteractiveMultiPartyServerKeyShare,
CommonReferenceSeededNonInteractiveMultiPartyServerKeyShare,
InteractiveMultiPartyClientKey, NonInteractiveMultiPartyClientKey,
SeededInteractiveMultiPartyServerKey, SeededNonInteractiveMultiPartyServerKey,
SeededSinglePartyServerKey, SinglePartyClientKey,
},
parameters::{BoolParameters, CiphertextModulus, DecompositionCount, DoubleDecomposerParams},
};
/// Common reference seed used for Interactive multi-party,
///
/// Seeds for public key shares and differents parts of server key shares are
/// derived from common reference seed with different puncture rountines.
///
/// ## Punctures
///
/// Initial Seed:
/// Puncture 1 -> Public key share seed
/// Puncture 2 -> Main server key share seed
/// Puncture 1 -> Auto keys cipertexts seed
/// Puncture 2 -> LWE ksk seed
#[derive(Clone, PartialEq)]
pub struct InteractiveMultiPartyCrs<S> {
pub(super) seed: S,
}
impl InteractiveMultiPartyCrs<[u8; 32]> {
pub(super) fn random() -> Self {
DefaultSecureRng::with_local_mut(|rng| {
let mut seed = [0u8; 32];
rng.fill_bytes(&mut seed);
Self { seed }
})
}
}
impl<S: Default + Copy> InteractiveMultiPartyCrs<S> {
/// Seed to generate public key share
fn public_key_share_seed<Rng: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut prng = Rng::new_with_seed(self.seed);
puncture_p_rng(&mut prng, 1)
}
/// Main server key share seed
fn key_seed<Rng: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut prng = Rng::new_with_seed(self.seed);
puncture_p_rng(&mut prng, 2)
}
pub(super) fn auto_keys_cts_seed<Rng: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut key_prng = Rng::new_with_seed(self.key_seed::<Rng>());
puncture_p_rng(&mut key_prng, 1)
}
pub(super) fn lwe_ksk_cts_seed_seed<Rng: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut key_prng = Rng::new_with_seed(self.key_seed::<Rng>());
puncture_p_rng(&mut key_prng, 2)
}
}
/// Common reference seed used for non-interactive multi-party.
///
/// Initial Seed
/// Puncture 1 -> Key Seed
/// Puncture 1 -> Rgsw ciphertext seed
/// Puncture l+1 -> Seed for zero encs and non-interactive
/// multi-party RGSW ciphertexts of
/// l^th LWE index.
/// Puncture 2 -> auto keys seed
/// Puncture 3 -> Lwe key switching key seed
/// Puncture 2 -> user specific seed for u_j to s ksk
/// Punture j+1 -> user j's seed
#[derive(Clone, PartialEq)]
pub struct NonInteractiveMultiPartyCrs<S> {
pub(super) seed: S,
}
impl NonInteractiveMultiPartyCrs<[u8; 32]> {
pub(super) fn random() -> Self {
DefaultSecureRng::with_local_mut(|rng| {
let mut seed = [0u8; 32];
rng.fill_bytes(&mut seed);
Self { seed }
})
}
}
impl<S: Default + Copy> NonInteractiveMultiPartyCrs<S> {
fn key_seed<R: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut p_rng = R::new_with_seed(self.seed);
puncture_p_rng(&mut p_rng, 1)
}
pub(crate) fn ni_rgsw_cts_main_seed<R: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut p_rng = R::new_with_seed(self.key_seed::<R>());
puncture_p_rng(&mut p_rng, 1)
}
pub(crate) fn ni_rgsw_ct_seed_for_index<R: NewWithSeed<Seed = S> + RandomFill<S>>(
&self,
lwe_index: usize,
) -> S {
let mut p_rng = R::new_with_seed(self.ni_rgsw_cts_main_seed::<R>());
puncture_p_rng(&mut p_rng, lwe_index + 1)
}
pub(crate) fn auto_keys_cts_seed<R: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut p_rng = R::new_with_seed(self.key_seed::<R>());
puncture_p_rng(&mut p_rng, 2)
}
pub(crate) fn lwe_ksk_cts_seed<R: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut p_rng = R::new_with_seed(self.key_seed::<R>());
puncture_p_rng(&mut p_rng, 3)
}
fn ui_to_s_ks_seed<R: NewWithSeed<Seed = S> + RandomFill<S>>(&self) -> S {
let mut p_rng = R::new_with_seed(self.seed);
puncture_p_rng(&mut p_rng, 2)
}
pub(crate) fn ui_to_s_ks_seed_for_user_i<R: NewWithSeed<Seed = S> + RandomFill<S>>(
&self,
user_i: usize,
) -> S {
let ks_seed = self.ui_to_s_ks_seed::<R>();
let mut p_rng = R::new_with_seed(ks_seed);
puncture_p_rng(&mut p_rng, user_i + 1)
}
}
struct ScratchMemory<M>
where
M: Matrix,
{
lwe_vector: M::R,
decomposition_matrix: M,
}
impl<M: MatrixEntity> ScratchMemory<M>
where
M::R: RowEntity,
{
fn new(parameters: &BoolParameters<M::MatElement>) -> Self {
// Vector to store LWE ciphertext with LWE dimesnion n
let lwe_vector = M::R::zeros(parameters.lwe_n().0 + 1);
// PBS perform two operations at runtime: RLWE x RGW and RLWE auto. Since the
// operations are performed serially same scratch space can be used for both.
// Hence we create scratch space that contains maximum amount of rows that
// suffices for RLWE x RGSW and RLWE auto
let decomposition_matrix = M::zeros(
std::cmp::max(
rlwe_x_rgsw_scratch_rows(parameters.rlwe_by_rgsw_decomposition_params()),
rlwe_auto_scratch_rows(parameters.auto_decomposition_param()),
),
parameters.rlwe_n().0,
);
Self {
lwe_vector,
decomposition_matrix,
}
}
}
pub(super) trait BoolEncoding {
type Element;
fn true_el(&self) -> Self::Element;
fn false_el(&self) -> Self::Element;
fn qby4(&self) -> Self::Element;
fn decode(&self, m: Self::Element) -> bool;
}
impl<T> BoolEncoding for CiphertextModulus<T>
where
CiphertextModulus<T>: Modulus<Element = T>,
T: PrimInt + NumInfo,
{
type Element = T;
fn qby4(&self) -> Self::Element {
if self.is_native() {
T::one() << ((T::BITS as usize) - 2)
} else {
self.q().unwrap() >> 2
}
}
/// Q/8
fn true_el(&self) -> Self::Element {
if self.is_native() {
T::one() << ((T::BITS as usize) - 3)
} else {
self.q().unwrap() >> 3
}
}
/// -Q/8
fn false_el(&self) -> Self::Element {
self.largest_unsigned_value() - self.true_el() + T::one()
}
fn decode(&self, m: Self::Element) -> bool {
let qby8 = self.true_el();
let m = (((m + qby8).to_f64().unwrap() * 4.0f64) / self.q_as_f64().unwrap()).round()
as usize
% 4usize;
if m == 0 {
return false;
} else if m == 1 {
return true;
} else {
panic!("Incorrect bool decryption. Got m={m} but expected m to be 0 or 1")
}
}
}
impl<B> Encoder<bool, B::Element> for B
where
B: BoolEncoding,
{
fn encode(&self, v: bool) -> B::Element {
if v {
self.true_el()
} else {
self.false_el()
}
}
}
pub(super) struct BoolPbsInfo<M: Matrix, Ntt, RlweModOp, LweModOp> {
auto_decomposer: DefaultDecomposer<M::MatElement>,
rlwe_rgsw_decomposer: (
DefaultDecomposer<M::MatElement>,
DefaultDecomposer<M::MatElement>,
),
lwe_decomposer: DefaultDecomposer<M::MatElement>,
g_k_dlog_map: Vec<usize>,
rlwe_nttop: Ntt,
rlwe_modop: RlweModOp,
lwe_modop: LweModOp,
embedding_factor: usize,
rlwe_qby4: M::MatElement,
rlwe_auto_maps: Vec<(Vec<usize>, Vec<bool>)>,
parameters: BoolParameters<M::MatElement>,
}
impl<M: Matrix, NttOp, RlweModOp, LweModOp> PbsInfo for BoolPbsInfo<M, NttOp, RlweModOp, LweModOp>
where
M::MatElement: PrimInt
+ WrappingSub
+ NumInfo
+ FromPrimitive
+ From<bool>
+ Display
+ WrappingAdd
+ Debug,
RlweModOp: ArithmeticOps<Element = M::MatElement> + ShoupMatrixFMA<M::R>,
LweModOp: ArithmeticOps<Element = M::MatElement> + VectorOps<Element = M::MatElement>,
NttOp: Ntt<Element = M::MatElement>,
{
type M = M;
type Modulus = CiphertextModulus<M::MatElement>;
type D = DefaultDecomposer<M::MatElement>;
type RlweModOp = RlweModOp;
type LweModOp = LweModOp;
type NttOp = NttOp;
fn rlwe_auto_map(&self, k: usize) -> &(Vec<usize>, Vec<bool>) {
&self.rlwe_auto_maps[k]
}
fn br_q(&self) -> usize {
*self.parameters.br_q()
}
fn lwe_decomposer(&self) -> &Self::D {
&self.lwe_decomposer
}
fn rlwe_rgsw_decomposer(&self) -> &(Self::D, Self::D) {
&self.rlwe_rgsw_decomposer
}
fn auto_decomposer(&self) -> &Self::D {
&self.auto_decomposer
}
fn embedding_factor(&self) -> usize {
self.embedding_factor
}
fn g(&self) -> isize {
self.parameters.g() as isize
}
fn w(&self) -> usize {
self.parameters.w()
}
fn g_k_dlog_map(&self) -> &[usize] {
&self.g_k_dlog_map
}
fn lwe_n(&self) -> usize {
self.parameters.lwe_n().0
}
fn lwe_q(&self) -> &Self::Modulus {
self.parameters.lwe_q()
}
fn rlwe_n(&self) -> usize {
self.parameters.rlwe_n().0
}
fn rlwe_q(&self) -> &Self::Modulus {
self.parameters.rlwe_q()
}
fn modop_lweq(&self) -> &Self::LweModOp {
&self.lwe_modop
}
fn modop_rlweq(&self) -> &Self::RlweModOp {
&self.rlwe_modop
}
fn nttop_rlweq(&self) -> &Self::NttOp {
&self.rlwe_nttop
}
}
pub(crate) struct BoolEvaluator<M, Ntt, RlweModOp, LweModOp, SKey>
where
M: Matrix,
{
pbs_info: BoolPbsInfo<M, Ntt, RlweModOp, LweModOp>,
scratch_memory: ScratchMemory<M>,
nand_test_vec: M::R,
and_test_vec: M::R,
or_test_vec: M::R,
nor_test_vec: M::R,
xor_test_vec: M::R,
xnor_test_vec: M::R,
/// Non-interactive u_i -> s key switch decomposer
ni_ui_to_s_ks_decomposer: Option<DefaultDecomposer<M::MatElement>>,
_phantom: PhantomData<SKey>,
}
impl<M: Matrix, NttOp, RlweModOp, LweModOp, Skey>
BoolEvaluator<M, NttOp, RlweModOp, LweModOp, Skey>
{
pub(crate) fn parameters(&self) -> &BoolParameters<M::MatElement> {
&self.pbs_info.parameters
}
pub(super) fn pbs_info(&self) -> &BoolPbsInfo<M, NttOp, RlweModOp, LweModOp> {
&self.pbs_info
}
pub(super) fn ni_ui_to_s_ks_decomposer(&self) -> &Option<DefaultDecomposer<M::MatElement>> {
&self.ni_ui_to_s_ks_decomposer
}
}
fn trim_rgsw_ct_matrix_from_rgrg_to_rlrg<
M: MatrixMut + MatrixEntity,
D: DoubleDecomposerParams<Count = DecompositionCount>,
>(
rgsw_ct_in: M,
rgrg_params: D,
rlrg_params: D,
) -> M
where
M::R: RowMut,
M::MatElement: Copy,
{
let (rgswrgsw_d_a, rgswrgsw_d_b) = (
rgrg_params.decomposition_count_a(),
rgrg_params.decomposition_count_b(),
);
let (rlrg_d_a, rlrg_d_b) = (
rlrg_params.decomposition_count_a(),
rlrg_params.decomposition_count_b(),
);
let rgsw_ct_rows_in = rgswrgsw_d_a.0 * 2 + rgswrgsw_d_b.0 * 2;
let rgsw_ct_rows_out = rlrg_d_a.0 * 2 + rlrg_d_b.0 * 2;
assert!(rgsw_ct_in.dimension().0 == rgsw_ct_rows_in);
assert!(rgswrgsw_d_a.0 >= rlrg_d_a.0, "RGSWxRGSW part A decomposition count {} must be >= RLWExRGSW part A decomposition count {}", rgswrgsw_d_a.0 , rlrg_d_a.0);
assert!(rgswrgsw_d_b.0 >= rlrg_d_b.0, "RGSWxRGSW part B decomposition count {} must be >= RLWExRGSW part B decomposition count {}", rgswrgsw_d_b.0 , rlrg_d_b.0);
let mut reduced_ct_i_out = M::zeros(rgsw_ct_rows_out, rgsw_ct_in.dimension().1);
// RLWE'(-sm) part A
izip!(
reduced_ct_i_out.iter_rows_mut().take(rlrg_d_a.0),
rgsw_ct_in
.iter_rows()
.skip(rgswrgsw_d_a.0 - rlrg_d_a.0)
.take(rlrg_d_a.0)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// RLWE'(-sm) part B
izip!(
reduced_ct_i_out
.iter_rows_mut()
.skip(rlrg_d_a.0)
.take(rlrg_d_a.0),
rgsw_ct_in
.iter_rows()
.skip(rgswrgsw_d_a.0 + (rgswrgsw_d_a.0 - rlrg_d_a.0))
.take(rlrg_d_a.0)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// RLWE'(m) Part A
izip!(
reduced_ct_i_out
.iter_rows_mut()
.skip(rlrg_d_a.0 * 2)
.take(rlrg_d_b.0),
rgsw_ct_in
.iter_rows()
.skip(rgswrgsw_d_a.0 * 2 + (rgswrgsw_d_b.0 - rlrg_d_b.0))
.take(rlrg_d_b.0)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// RLWE'(m) Part B
izip!(
reduced_ct_i_out
.iter_rows_mut()
.skip(rlrg_d_a.0 * 2 + rlrg_d_b.0)
.take(rlrg_d_b.0),
rgsw_ct_in
.iter_rows()
.skip(rgswrgsw_d_a.0 * 2 + rgswrgsw_d_b.0 + (rgswrgsw_d_b.0 - rlrg_d_b.0))
.take(rlrg_d_b.0)
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
reduced_ct_i_out
}
fn produce_rgsw_ciphertext_from_ni_rgsw<
M: MatrixMut + MatrixEntity,
D: RlweDecomposer,
ModOp: VectorOps<Element = M::MatElement>,
NttOp: Ntt<Element = M::MatElement>,
>(
ni_rgsw_ct: &M,
aggregated_decomposed_ni_rgsw_zero_encs: &[M],
decomposed_neg_ais: &[M],
decomposer: &D,
parameters: &BoolParameters<M::MatElement>,
uj_to_s_ksk: (&M, &M),
rlwe_modop: &ModOp,
nttop: &NttOp,
out_eval: bool,
) -> M
where
<M as Matrix>::R: RowMut + Clone,
{
let max_decomposer =
if decomposer.a().decomposition_count().0 > decomposer.b().decomposition_count().0 {
decomposer.a()
} else {
decomposer.b()
};
assert!(
ni_rgsw_ct.dimension()
== (
max_decomposer.decomposition_count().0,
parameters.rlwe_n().0
)
);
assert!(
aggregated_decomposed_ni_rgsw_zero_encs.len() == decomposer.a().decomposition_count().0,
);
assert!(decomposed_neg_ais.len() == decomposer.b().decomposition_count().0);
let mut rgsw_i = M::zeros(
decomposer.a().decomposition_count().0 * 2 + decomposer.b().decomposition_count().0 * 2,
parameters.rlwe_n().0,
);
let (rlwe_dash_nsm, rlwe_dash_m) =
rgsw_i.split_at_row_mut(decomposer.a().decomposition_count().0 * 2);
// RLWE'_{s}(-sm)
// Key switch `s * a_{i, l} + e` using ksk(u_j -> s) to produce RLWE(s *
// u_{j=user_id} * a_{i, l}).
//
// Then set RLWE_{s}(-s B^i m) = (0, u_{j=user_id} * a_{i, l} + e + B^i m) +
// RLWE(s * u_{j=user_id} * a_{i, l})
{
let (rlwe_dash_nsm_parta, rlwe_dash_nsm_partb) =
rlwe_dash_nsm.split_at_mut(decomposer.a().decomposition_count().0);
izip!(
rlwe_dash_nsm_parta.iter_mut(),
rlwe_dash_nsm_partb.iter_mut(),
ni_rgsw_ct.iter_rows().skip(
max_decomposer.decomposition_count().0 - decomposer.a().decomposition_count().0
),
aggregated_decomposed_ni_rgsw_zero_encs.iter()
)
.for_each(|(rlwe_a, rlwe_b, ni_rlwe_ct, decomp_zero_enc)| {
// KS(s * a_{i, l} + e) = RLWE(s * u_j *
// a_{i, l}) using user j's Ksk
izip!(
decomp_zero_enc.iter_rows(),
uj_to_s_ksk.0.iter_rows(),
uj_to_s_ksk.1.iter_rows()
)
.for_each(|(c, pb, pa)| {
rlwe_modop.elwise_fma_mut(rlwe_b.as_mut(), pb.as_ref(), c.as_ref());
rlwe_modop.elwise_fma_mut(rlwe_a.as_mut(), pa.as_ref(), c.as_ref());
});
// RLWE(-s beta^i m) = (0, u_j * a_{j, l} +
// e + beta^i m) + RLWE(s * u_j * a_{i, l})
if out_eval {
let mut ni_rlwe_ct = ni_rlwe_ct.clone();
nttop.forward(ni_rlwe_ct.as_mut());
rlwe_modop.elwise_add_mut(rlwe_a.as_mut(), ni_rlwe_ct.as_ref());
} else {
nttop.backward(rlwe_a.as_mut());
nttop.backward(rlwe_b.as_mut());
rlwe_modop.elwise_add_mut(rlwe_a.as_mut(), ni_rlwe_ct.as_ref());
}
});
}
// RLWE'_{s}(m)
{
let (rlwe_dash_m_parta, rlwe_dash_partb) =
rlwe_dash_m.split_at_mut(decomposer.b().decomposition_count().0);
izip!(
rlwe_dash_m_parta.iter_mut(),
rlwe_dash_partb.iter_mut(),
ni_rgsw_ct.iter_rows().skip(
max_decomposer.decomposition_count().0 - decomposer.b().decomposition_count().0
),
decomposed_neg_ais.iter()
)
.for_each(|(rlwe_a, rlwe_b, ni_rlwe_ct, decomp_neg_ai)| {
// KS(-a_{i, l}) = RLWE(u_i * -a_{i,l}) using user j's Ksk
izip!(
decomp_neg_ai.iter_rows(),
uj_to_s_ksk.0.iter_rows(),
uj_to_s_ksk.1.iter_rows()
)
.for_each(|(c, pb, pa)| {
rlwe_modop.elwise_fma_mut(rlwe_b.as_mut(), pb.as_ref(), c.as_ref());
rlwe_modop.elwise_fma_mut(rlwe_a.as_mut(), pa.as_ref(), c.as_ref());
});
// RLWE_{s}(beta^i m) = (u_j * a_{i, l} + e + beta^i m, 0) -
// RLWE(-a_{i, l} u_j)
if out_eval {
let mut ni_rlwe_ct = ni_rlwe_ct.clone();
nttop.forward(ni_rlwe_ct.as_mut());
rlwe_modop.elwise_add_mut(rlwe_b.as_mut(), ni_rlwe_ct.as_ref());
} else {
nttop.backward(rlwe_a.as_mut());
nttop.backward(rlwe_b.as_mut());
rlwe_modop.elwise_add_mut(rlwe_b.as_mut(), ni_rlwe_ct.as_ref());
}
});
}
rgsw_i
}
/// Assigns user with user_id segement of LWE secret indices for which they
/// generate RGSW(X^{s[i]}) as the leader (i.e. for RLWExRGSW). If returned
/// tuple is (start, end), user's segment is [start, end)
pub(super) fn multi_party_user_id_lwe_segment(
user_id: usize,
total_users: usize,
lwe_n: usize,
) -> (usize, usize) {
let per_user = (lwe_n as f64 / total_users as f64)
.ceil()
.to_usize()
.unwrap();
(
per_user * user_id,
std::cmp::min(per_user * (user_id + 1), lwe_n),
)
}
impl<M: Matrix, NttOp, RlweModOp, LweModOp, SKey> BoolEvaluator<M, NttOp, RlweModOp, LweModOp, SKey>
where
M: MatrixEntity + MatrixMut,
M::MatElement: PrimInt
+ Debug
+ Display
+ NumInfo
+ FromPrimitive
+ WrappingSub
+ WrappingAdd
+ SampleUniform
+ From<bool>,
NttOp: Ntt<Element = M::MatElement>,
RlweModOp: ArithmeticOps<Element = M::MatElement>
+ VectorOps<Element = M::MatElement>
+ GetModulus<Element = M::MatElement, M = CiphertextModulus<M::MatElement>>
+ ShoupMatrixFMA<M::R>,
LweModOp: ArithmeticOps<Element = M::MatElement>
+ VectorOps<Element = M::MatElement>
+ GetModulus<Element = M::MatElement, M = CiphertextModulus<M::MatElement>>,
M::R: TryConvertFrom1<[i32], CiphertextModulus<M::MatElement>> + RowEntity + Debug,
<M as Matrix>::R: RowMut,
{
pub(super) fn new(parameters: BoolParameters<M::MatElement>) -> Self
where
RlweModOp: ModInit<M = CiphertextModulus<M::MatElement>>,
LweModOp: ModInit<M = CiphertextModulus<M::MatElement>>,
NttOp: NttInit<CiphertextModulus<M::MatElement>>,
{
//TODO(Jay): Run sanity checks for modulus values in parameters
// generates dlog map s.t. (+/-)g^{k} % q = a, for all a \in Z*_{q} and k \in
// [0, q/4). We store the dlog `k` at index `a`. This makes it easier to
// simply look up `k` at runtime as vec[a]. If a = g^{k} then dlog is
// stored as k. If a = -g^{k} then dlog is stored as k = q/4. This is done to
// differentiate sign.
let g = parameters.g();
let q = *parameters.br_q();
let mut g_k_dlog_map = vec![0usize; q];
for i in 0..q / 4 {
let v = mod_exponent(g as u64, i as u64, q as u64) as usize;
// g^i
g_k_dlog_map[v] = i;
// -(g^i)
g_k_dlog_map[q - v] = i + (q / 4);
}
let embedding_factor = (2 * parameters.rlwe_n().0) / q;
let rlwe_nttop = NttOp::new(parameters.rlwe_q(), parameters.rlwe_n().0);
let rlwe_modop = RlweModOp::new(*parameters.rlwe_q());
let lwe_modop = LweModOp::new(*parameters.lwe_q());
let q = *parameters.br_q();
let qby2 = q >> 1;
let qby8 = q >> 3;
// Q/8 (Q: rlwe_q)
let true_m_el = parameters.rlwe_q().true_el();
// -Q/8
let false_m_el = parameters.rlwe_q().false_el();
let (auto_map_index, auto_map_sign) = generate_auto_map(qby2, -(g as isize));
let init_test_vec = |partition_el: usize,
before_partition_el: M::MatElement,
after_partition_el: M::MatElement| {
let mut test_vec = M::R::zeros(qby2);
for i in 0..qby2 {
if i < partition_el {
test_vec.as_mut()[i] = before_partition_el;
} else {
test_vec.as_mut()[i] = after_partition_el;
}
}
// v(X) -> v(X^{-g})
let mut test_vec_autog = M::R::zeros(qby2);
izip!(
test_vec.as_ref().iter(),
auto_map_index.iter(),
auto_map_sign.iter()
)
.for_each(|(v, to_index, to_sign)| {
if !to_sign {
// negate
test_vec_autog.as_mut()[*to_index] = rlwe_modop.neg(v);
} else {
test_vec_autog.as_mut()[*to_index] = *v;
}
});
return test_vec_autog;
};
let nand_test_vec = init_test_vec(3 * qby8, true_m_el, false_m_el);
let and_test_vec = init_test_vec(3 * qby8, false_m_el, true_m_el);
let or_test_vec = init_test_vec(qby8, false_m_el, true_m_el);
let nor_test_vec = init_test_vec(qby8, true_m_el, false_m_el);
let xor_test_vec = init_test_vec(qby8, false_m_el, true_m_el);
let xnor_test_vec = init_test_vec(qby8, true_m_el, false_m_el);
// auto map indices and sign
// Auto maps are stored as [-g, g^{1}, g^{2}, ..., g^{w}]
let mut rlwe_auto_maps = vec![];
let ring_size = parameters.rlwe_n().0;
let g = parameters.g();
let br_q = parameters.br_q();
let auto_element_dlogs = parameters.auto_element_dlogs();
assert!(auto_element_dlogs[0] == 0);
for i in auto_element_dlogs.into_iter() {
let el = if i == 0 {
-(g as isize)
} else {
(g.pow(i as u32) % br_q) as isize
};
rlwe_auto_maps.push(generate_auto_map(ring_size, el))
}
let rlwe_qby4 = parameters.rlwe_q().qby4();
let scratch_memory = ScratchMemory::new(¶meters);
let ni_ui_to_s_ks_decomposer = if parameters.variant()
== &ParameterVariant::NonInteractiveMultiParty
{
Some(parameters
.non_interactive_ui_to_s_key_switch_decomposer::<DefaultDecomposer<M::MatElement>>())
} else {
None
};
let pbs_info = BoolPbsInfo {
auto_decomposer: parameters.auto_decomposer(),
lwe_decomposer: parameters.lwe_decomposer(),
rlwe_rgsw_decomposer: parameters.rlwe_rgsw_decomposer(),
g_k_dlog_map,
embedding_factor,
lwe_modop,
rlwe_modop,
rlwe_nttop,
rlwe_qby4,
rlwe_auto_maps,
parameters: parameters,
};
BoolEvaluator {
pbs_info,
scratch_memory,
nand_test_vec,
and_test_vec,
or_test_vec,
nor_test_vec,
xnor_test_vec,
xor_test_vec,
ni_ui_to_s_ks_decomposer,
_phantom: PhantomData,
}
}
pub(crate) fn client_key(
&self,
) -> ClientKey<<DefaultSecureRng as NewWithSeed>::Seed, M::MatElement> {
ClientKey::new(self.parameters().clone())
}
pub(super) fn single_party_server_key<K: SinglePartyClientKey<Element = i32>>(
&self,
client_key: &K,
) -> SeededSinglePartyServerKey<M, BoolParameters<M::MatElement>, [u8; 32]> {
assert_eq!(self.parameters().variant(), &ParameterVariant::SingleParty);
DefaultSecureRng::with_local_mut(|rng| {
let mut main_seed = [0u8; 32];
rng.fill_bytes(&mut main_seed);
let mut main_prng = DefaultSecureRng::new_seeded(main_seed);
let rlwe_n = self.pbs_info.parameters.rlwe_n().0;
let sk_rlwe = client_key.sk_rlwe();
let sk_lwe = client_key.sk_lwe();
// generate auto keys
let mut auto_keys = HashMap::new();
let auto_gadget = self.pbs_info.auto_decomposer.gadget_vector();
let g = self.pbs_info.parameters.g();
let br_q = self.pbs_info.parameters.br_q();
let auto_els = self.pbs_info.parameters.auto_element_dlogs();
for i in auto_els.into_iter() {
let g_pow = if i == 0 {
-(g as isize)
} else {
(g.pow(i as u32) % br_q) as isize
};
let mut gk = M::zeros(
self.pbs_info.auto_decomposer.decomposition_count().0,
rlwe_n,
);
seeded_auto_key_gen(
&mut gk,
&sk_rlwe,
g_pow,
&auto_gadget,
&self.pbs_info.rlwe_modop,
&self.pbs_info.rlwe_nttop,
&mut main_prng,
rng,
);
auto_keys.insert(i, gk);
}
// generate rgsw ciphertexts RGSW(si) where si is i^th LWE secret element
let ring_size = self.pbs_info.parameters.rlwe_n().0;
let rlwe_q = self.pbs_info.parameters.rlwe_q();
let (rlrg_d_a, rlrg_d_b) = (
self.pbs_info.rlwe_rgsw_decomposer.0.decomposition_count().0,
self.pbs_info.rlwe_rgsw_decomposer.1.decomposition_count().0,
);
let rlrg_gadget_a = self.pbs_info.rlwe_rgsw_decomposer.0.gadget_vector();
let rlrg_gadget_b = self.pbs_info.rlwe_rgsw_decomposer.1.gadget_vector();
let rgsw_cts = sk_lwe
.iter()
.map(|si| {
// X^{si}; assume |emebedding_factor * si| < N
let mut m = M::R::zeros(ring_size);
let si = (self.pbs_info.embedding_factor as i32) * si;
// dbg!(si);
if si < 0 {
// X^{-i} = X^{2N - i} = -X^{N-i}
m.as_mut()[ring_size - (si.abs() as usize)] = rlwe_q.neg_one();
} else {
// X^{i}
m.as_mut()[si.abs() as usize] = M::MatElement::one();
}
let mut rgsw_si = M::zeros(rlrg_d_a * 2 + rlrg_d_b, ring_size);
secret_key_encrypt_rgsw(
&mut rgsw_si,
m.as_ref(),
&rlrg_gadget_a,
&rlrg_gadget_b,
&sk_rlwe,
&self.pbs_info.rlwe_modop,
&self.pbs_info.rlwe_nttop,
&mut main_prng,
rng,
);
rgsw_si
})
.collect_vec();
// LWE KSK from RLWE secret s -> LWE secret z
let d_lwe_gadget = self.pbs_info.lwe_decomposer.gadget_vector();
let lwe_ksk = seeded_lwe_ksk_keygen(
&sk_rlwe,
&sk_lwe,
&d_lwe_gadget,
&self.pbs_info.lwe_modop,
&mut main_prng,
rng,
);
SeededSinglePartyServerKey::from_raw(
auto_keys,
rgsw_cts,
lwe_ksk,
self.pbs_info.parameters.clone(),
main_seed,
)
})
}
pub(super) fn gen_interactive_multi_party_server_key_share<
K: InteractiveMultiPartyClientKey<Element = i32>,
>(
&self,
user_id: usize,
total_users: usize,
cr_seed: &InteractiveMultiPartyCrs<[u8; 32]>,
collective_pk: &M,
client_key: &K,
) -> CommonReferenceSeededInteractiveMultiPartyServerKeyShare<
M,
BoolParameters<M::MatElement>,
InteractiveMultiPartyCrs<[u8; 32]>,
> {
assert_eq!(
self.parameters().variant(),
&ParameterVariant::InteractiveMultiParty
);
assert!(user_id < total_users);
let sk_rlwe = client_key.sk_rlwe();
let sk_lwe = client_key.sk_lwe();
let g = self.pbs_info.parameters.g();
let ring_size = self.pbs_info.parameters.rlwe_n().0;
let rlwe_q = self.pbs_info.parameters.rlwe_q();
let lwe_q = self.pbs_info.parameters.lwe_q();
let rlweq_modop = &self.pbs_info.rlwe_modop;
let rlweq_nttop = &self.pbs_info.rlwe_nttop;
// sanity check
assert!(sk_rlwe.len() == ring_size);
assert!(sk_lwe.len() == self.pbs_info.parameters.lwe_n().0);
// auto keys
let auto_keys = self._common_rountine_multi_party_auto_keys_share_gen(
cr_seed.auto_keys_cts_seed::<DefaultSecureRng>(),
&sk_rlwe,
);
// rgsw ciphertexts of lwe secret elements
let (self_leader_rgsws, not_self_leader_rgsws) = DefaultSecureRng::with_local_mut(|rng| {
let mut self_leader_rgsw = vec![];
let mut not_self_leader_rgsws = vec![];
let (segment_start, segment_end) =
multi_party_user_id_lwe_segment(user_id, total_users, self.pbs_info().lwe_n());
// self LWE secret indices
{
// LWE secret indices for which user is the leader they need to send RGSW(m) for
// RLWE x RGSW multiplication
let rlrg_decomposer = self.pbs_info().rlwe_rgsw_decomposer();
let (rlrg_d_a, rlrg_d_b) = (
rlrg_decomposer.a().decomposition_count(),
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | true |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/bool/keys.rs | src/bool/keys.rs | use std::{collections::HashMap, marker::PhantomData};
use crate::{
backend::{ModInit, VectorOps},
pbs::WithShoupRepr,
random::{NewWithSeed, RandomFillUniformInModulus},
utils::ToShoup,
Matrix, MatrixEntity, MatrixMut, RowEntity, RowMut,
};
use super::parameters::{BoolParameters, CiphertextModulus};
pub(crate) trait SinglePartyClientKey {
type Element;
fn sk_rlwe(&self) -> Vec<Self::Element>;
fn sk_lwe(&self) -> Vec<Self::Element>;
}
pub(crate) trait InteractiveMultiPartyClientKey {
type Element;
fn sk_rlwe(&self) -> Vec<Self::Element>;
fn sk_lwe(&self) -> Vec<Self::Element>;
}
pub(crate) trait NonInteractiveMultiPartyClientKey {
type Element;
fn sk_rlwe(&self) -> Vec<Self::Element>;
fn sk_u_rlwe(&self) -> Vec<Self::Element>;
fn sk_lwe(&self) -> Vec<Self::Element>;
}
/// Client key
///
/// Key is used for all parameter varians - Single party, interactive
/// multi-party, and non-interactive multi-party. The only stored the main seed
/// and seeds of the Rlwe/Lwe secrets are derived at puncturing the seed desired
/// number of times.
///
/// ### Punctures required:
///
/// Puncture 1 -> Seed of RLWE secret used as main RLWE secret for
/// single-party, interactive/non-interactive multi-party
///
/// Puncture 2 -> Seed of LWE secret used main LWE secret for single-party,
/// interactive/non-interactive multi-party
///
/// Puncture 3 -> Seed of RLWE secret used as `u` in
/// non-interactive multi-party.
#[derive(Clone)]
pub struct ClientKey<S, E> {
seed: S,
parameters: BoolParameters<E>,
}
mod impl_ck {
use crate::{
parameters::SecretKeyDistribution,
random::{DefaultSecureRng, RandomFillGaussian},
utils::{fill_random_ternary_secret_with_hamming_weight, puncture_p_rng},
};
use super::*;
impl<E> ClientKey<[u8; 32], E> {
pub(in super::super) fn new(parameters: BoolParameters<E>) -> ClientKey<[u8; 32], E> {
let mut rng = DefaultSecureRng::new();
let mut seed = [0u8; 32];
rng.fill_bytes(&mut seed);
Self { seed, parameters }
}
}
impl<E> SinglePartyClientKey for ClientKey<[u8; 32], E> {
type Element = i32;
fn sk_lwe(&self) -> Vec<Self::Element> {
let mut p_rng = DefaultSecureRng::new_seeded(self.seed);
let lwe_seed = puncture_p_rng::<[u8; 32], DefaultSecureRng>(&mut p_rng, 2);
let mut lwe_prng = DefaultSecureRng::new_seeded(lwe_seed);
let mut out = vec![0i32; self.parameters.lwe_n().0];
match self.parameters.lwe_secret_key_dist() {
&SecretKeyDistribution::ErrorDistribution => {
RandomFillGaussian::random_fill(&mut lwe_prng, &mut out);
}
&SecretKeyDistribution::TernaryDistribution => {
fill_random_ternary_secret_with_hamming_weight(
&mut out,
self.parameters.lwe_n().0 >> 1,
&mut lwe_prng,
);
}
}
out
}
fn sk_rlwe(&self) -> Vec<Self::Element> {
assert!(
self.parameters.rlwe_secret_key_dist()
== &SecretKeyDistribution::TernaryDistribution
);
let mut p_rng = DefaultSecureRng::new_seeded(self.seed);
let rlwe_seed = puncture_p_rng::<[u8; 32], DefaultSecureRng>(&mut p_rng, 1);
let mut rlwe_prng = DefaultSecureRng::new_seeded(rlwe_seed);
let mut out = vec![0i32; self.parameters.rlwe_n().0];
fill_random_ternary_secret_with_hamming_weight(
&mut out,
self.parameters.rlwe_n().0 >> 1,
&mut rlwe_prng,
);
out
}
}
#[cfg(feature = "interactive_mp")]
impl<E> InteractiveMultiPartyClientKey for ClientKey<[u8; 32], E> {
type Element = i32;
fn sk_lwe(&self) -> Vec<Self::Element> {
<Self as SinglePartyClientKey>::sk_lwe(&self)
}
fn sk_rlwe(&self) -> Vec<Self::Element> {
<Self as SinglePartyClientKey>::sk_rlwe(&self)
}
}
#[cfg(feature = "non_interactive_mp")]
impl<E> NonInteractiveMultiPartyClientKey for ClientKey<[u8; 32], E> {
type Element = i32;
fn sk_lwe(&self) -> Vec<Self::Element> {
<Self as SinglePartyClientKey>::sk_lwe(&self)
}
fn sk_rlwe(&self) -> Vec<Self::Element> {
<Self as SinglePartyClientKey>::sk_rlwe(&self)
}
fn sk_u_rlwe(&self) -> Vec<Self::Element> {
assert!(
self.parameters.rlwe_secret_key_dist()
== &SecretKeyDistribution::TernaryDistribution
);
let mut p_rng = DefaultSecureRng::new_seeded(self.seed);
let rlwe_seed = puncture_p_rng::<[u8; 32], DefaultSecureRng>(&mut p_rng, 3);
let mut rlwe_prng = DefaultSecureRng::new_seeded(rlwe_seed);
let mut out = vec![0i32; self.parameters.rlwe_n().0];
fill_random_ternary_secret_with_hamming_weight(
&mut out,
self.parameters.rlwe_n().0 >> 1,
&mut rlwe_prng,
);
out
}
}
}
/// Public key
pub struct PublicKey<M, Rng, ModOp> {
key: M,
_phantom: PhantomData<(Rng, ModOp)>,
}
pub(super) mod impl_pk {
use super::*;
impl<M, R, Mo> PublicKey<M, R, Mo> {
pub(in super::super) fn key(&self) -> &M {
&self.key
}
}
impl<
M: MatrixMut + MatrixEntity,
Rng: NewWithSeed
+ RandomFillUniformInModulus<[M::MatElement], CiphertextModulus<M::MatElement>>,
ModOp,
> From<SeededPublicKey<M::R, Rng::Seed, BoolParameters<M::MatElement>, ModOp>>
for PublicKey<M, Rng, ModOp>
where
<M as Matrix>::R: RowMut,
M::MatElement: Copy,
{
fn from(
value: SeededPublicKey<M::R, Rng::Seed, BoolParameters<M::MatElement>, ModOp>,
) -> Self {
let mut prng = Rng::new_with_seed(value.seed);
let mut key = M::zeros(2, value.parameters.rlwe_n().0);
// sample A
RandomFillUniformInModulus::random_fill(
&mut prng,
value.parameters.rlwe_q(),
key.get_row_mut(0),
);
// Copy over B
key.get_row_mut(1).copy_from_slice(value.part_b.as_ref());
PublicKey {
key,
_phantom: PhantomData,
}
}
}
impl<
M: MatrixMut + MatrixEntity,
Rng: NewWithSeed
+ RandomFillUniformInModulus<[M::MatElement], CiphertextModulus<M::MatElement>>,
ModOp: VectorOps<Element = M::MatElement> + ModInit<M = CiphertextModulus<M::MatElement>>,
>
From<
&[CommonReferenceSeededCollectivePublicKeyShare<
M::R,
Rng::Seed,
BoolParameters<M::MatElement>,
>],
> for PublicKey<M, Rng, ModOp>
where
<M as Matrix>::R: RowMut,
Rng::Seed: Copy + PartialEq,
M::MatElement: PartialEq + Copy,
{
fn from(
value: &[CommonReferenceSeededCollectivePublicKeyShare<
M::R,
Rng::Seed,
BoolParameters<M::MatElement>,
>],
) -> Self {
assert!(value.len() > 0);
let parameters = &value[0].parameters;
let mut key = M::zeros(2, parameters.rlwe_n().0);
// sample A
let seed = value[0].cr_seed;
let mut main_rng = Rng::new_with_seed(seed);
RandomFillUniformInModulus::random_fill(
&mut main_rng,
parameters.rlwe_q(),
key.get_row_mut(0),
);
// Sum all Bs
let rlweq_modop = ModOp::new(parameters.rlwe_q().clone());
value.iter().for_each(|share_i| {
assert!(share_i.cr_seed == seed);
assert!(&share_i.parameters == parameters);
rlweq_modop.elwise_add_mut(key.get_row_mut(1), share_i.share.as_ref());
});
PublicKey {
key,
_phantom: PhantomData,
}
}
}
}
/// Seeded public key
struct SeededPublicKey<Ro, S, P, ModOp> {
part_b: Ro,
seed: S,
parameters: P,
_phantom: PhantomData<ModOp>,
}
mod impl_seeded_pk {
use super::*;
impl<R, S, ModOp>
From<&[CommonReferenceSeededCollectivePublicKeyShare<R, S, BoolParameters<R::Element>>]>
for SeededPublicKey<R, S, BoolParameters<R::Element>, ModOp>
where
ModOp: VectorOps<Element = R::Element> + ModInit<M = CiphertextModulus<R::Element>>,
S: PartialEq + Clone,
R: RowMut + RowEntity + Clone,
R::Element: Clone + PartialEq,
{
fn from(
value: &[CommonReferenceSeededCollectivePublicKeyShare<
R,
S,
BoolParameters<R::Element>,
>],
) -> Self {
assert!(value.len() > 0);
let parameters = &value[0].parameters;
let cr_seed = value[0].cr_seed.clone();
// Sum all Bs
let rlweq_modop = ModOp::new(parameters.rlwe_q().clone());
let mut part_b = value[0].share.clone();
value.iter().skip(1).for_each(|share_i| {
assert!(&share_i.cr_seed == &cr_seed);
assert!(&share_i.parameters == parameters);
rlweq_modop.elwise_add_mut(part_b.as_mut(), share_i.share.as_ref());
});
Self {
part_b,
seed: cr_seed,
parameters: parameters.clone(),
_phantom: PhantomData,
}
}
}
}
/// CRS seeded collective public key share
pub struct CommonReferenceSeededCollectivePublicKeyShare<Ro, S, P> {
/// Public key share polynomial
share: Ro,
/// Common reference seed
cr_seed: S,
/// Parameters
parameters: P,
}
impl<Ro, S, P> CommonReferenceSeededCollectivePublicKeyShare<Ro, S, P> {
pub(super) fn new(share: Ro, cr_seed: S, parameters: P) -> Self {
CommonReferenceSeededCollectivePublicKeyShare {
share,
cr_seed,
parameters,
}
}
}
/// Common reference seed seeded interactive multi-party server key share
pub struct CommonReferenceSeededInteractiveMultiPartyServerKeyShare<M: Matrix, P, S> {
/// Public key encrypted RGSW(m = X^{s[i]}) ciphertexts for LWE secret
/// indices for which `Self` is the leader. Note that when `Self` is
/// leader RGSW ciphertext is encrypted using RLWE x RGSW decomposer
self_leader_rgsws: Vec<M>,
/// Public key encrypted RGSW(m = X^{s[i]}) ciphertext for LWE secret
/// indices for which `Self` is `not` the leader. Note that when `Self`
/// is not the leader RGSW ciphertext is encrypted using RGSW1
/// decomposer for RGSW0 x RGSW1
not_self_leader_rgsws: Vec<M>,
/// Auto key shares for auto elements [-g, g, g^2, .., g^{w}] where `w`
/// is the window size parameter. Share corresponding to auto element -g
/// is stored at key `0` and share corresponding to auto element g^{k} is
/// stored at key `k`.
auto_keys: HashMap<usize, M>,
/// LWE key switching key share to key switching ciphertext LWE_{q, s}(m) to
/// LWE_{q, z}(m) where q is LWE ciphertext modulus, `s` is the ideal RLWE
/// secret with dimension N, and `z` is the ideal LWE secret of dimension n.
lwe_ksk: M::R,
/// Common reference seed
cr_seed: S,
parameters: P,
/// User id assigned by the server.
///
/// User id must be unique and a number in range [0, total_users)
user_id: usize,
}
impl<M: Matrix, P, S> CommonReferenceSeededInteractiveMultiPartyServerKeyShare<M, P, S> {
pub(super) fn new(
self_leader_rgsws: Vec<M>,
not_self_leader_rgsws: Vec<M>,
auto_keys: HashMap<usize, M>,
lwe_ksk: M::R,
cr_seed: S,
parameters: P,
user_id: usize,
) -> Self {
CommonReferenceSeededInteractiveMultiPartyServerKeyShare {
self_leader_rgsws,
not_self_leader_rgsws,
auto_keys,
lwe_ksk,
cr_seed,
parameters,
user_id,
}
}
pub(super) fn cr_seed(&self) -> &S {
&self.cr_seed
}
pub(super) fn parameters(&self) -> &P {
&self.parameters
}
pub(super) fn auto_keys(&self) -> &HashMap<usize, M> {
&self.auto_keys
}
pub(crate) fn self_leader_rgsws(&self) -> &[M] {
&self.self_leader_rgsws
}
pub(super) fn not_self_leader_rgsws(&self) -> &[M] {
&self.not_self_leader_rgsws
}
pub(super) fn lwe_ksk(&self) -> &M::R {
&self.lwe_ksk
}
pub(super) fn user_id(&self) -> usize {
self.user_id
}
}
/// Common reference seeded interactive multi-party server key
pub struct SeededInteractiveMultiPartyServerKey<M: Matrix, S, P> {
/// RGSW ciphertexts RGSW(X^{s[i]}) encrypted under ideal RLWE secret key
/// where `s` is ideal LWE secret key for each LWE secret dimension.
rgsw_cts: Vec<M>,
/// Seeded auto keys under ideal RLWE secret for RLWE automorphisms with
/// auto elements [-g, g, g^2,..., g^{w}]. Auto key corresponidng to
/// auto element -g is stored at key `0` and key corresponding to auto
/// element g^{k} is stored at key `k`
auto_keys: HashMap<usize, M>,
/// Seeded LWE key switching key under ideal LWE secret to switch LWE_{q,
/// s}(m) to LWE_{q, z}(m) where s is ideal RLWE secret and z is ideal LWE
/// secret.
lwe_ksk: M::R,
/// Common reference seed
cr_seed: S,
parameters: P,
}
impl<M: Matrix, S, P> SeededInteractiveMultiPartyServerKey<M, S, P> {
pub(super) fn new(
rgsw_cts: Vec<M>,
auto_keys: HashMap<usize, M>,
lwe_ksk: M::R,
cr_seed: S,
parameters: P,
) -> Self {
SeededInteractiveMultiPartyServerKey {
rgsw_cts,
auto_keys,
lwe_ksk,
cr_seed,
parameters,
}
}
pub(super) fn rgsw_cts(&self) -> &[M] {
&self.rgsw_cts
}
}
/// Seeded single party server key
pub struct SeededSinglePartyServerKey<M: Matrix, P, S> {
/// Rgsw cts of LWE secret elements
pub(crate) rgsw_cts: Vec<M>,
/// Auto keys. Key corresponding to g^{k} is at index `k`. Key corresponding
/// to -g is at 0
pub(crate) auto_keys: HashMap<usize, M>,
/// LWE ksk to key switching LWE ciphertext from RLWE secret to LWE secret
pub(crate) lwe_ksk: M::R,
/// Parameters
pub(crate) parameters: P,
/// Main seed
pub(crate) seed: S,
}
impl<M: Matrix, S> SeededSinglePartyServerKey<M, BoolParameters<M::MatElement>, S> {
pub(super) fn from_raw(
auto_keys: HashMap<usize, M>,
rgsw_cts: Vec<M>,
lwe_ksk: M::R,
parameters: BoolParameters<M::MatElement>,
seed: S,
) -> Self {
// sanity checks
auto_keys.iter().for_each(|v| {
assert!(
v.1.dimension()
== (
parameters.auto_decomposition_count().0,
parameters.rlwe_n().0
)
)
});
let (part_a_d, part_b_d) = parameters.rlwe_rgsw_decomposition_count();
rgsw_cts.iter().for_each(|v| {
assert!(v.dimension() == (part_a_d.0 * 2 + part_b_d.0, parameters.rlwe_n().0))
});
assert!(
lwe_ksk.as_ref().len()
== (parameters.lwe_decomposition_count().0 * parameters.rlwe_n().0)
);
SeededSinglePartyServerKey {
rgsw_cts,
auto_keys,
lwe_ksk,
parameters,
seed,
}
}
}
/// Server key in evaluation domain
pub(crate) struct ServerKeyEvaluationDomain<M, P, R, N> {
/// RGSW ciphertext RGSW(X^{s[i]}) for each LWE index in evaluation domain
rgsw_cts: Vec<M>,
/// Auto keys for all auto elements [-g, g, g^2,..., g^w] in evaluation
/// domain
galois_keys: HashMap<usize, M>,
/// LWE key switching key to key switch LWE_{q, s}(m) to LWE_{q, z}(m)
lwe_ksk: M,
parameters: P,
_phanton: PhantomData<(R, N)>,
}
pub(super) mod impl_server_key_eval_domain {
use itertools::{izip, Itertools};
use crate::{
bool::evaluator::InteractiveMultiPartyCrs,
ntt::{Ntt, NttInit},
pbs::PbsKey,
random::RandomFill,
};
use super::*;
impl<M, Mod, R, N> ServerKeyEvaluationDomain<M, Mod, R, N> {
pub(in super::super) fn rgsw_cts(&self) -> &[M] {
&self.rgsw_cts
}
}
impl<
M: MatrixMut + MatrixEntity,
R: RandomFillUniformInModulus<[M::MatElement], CiphertextModulus<M::MatElement>>
+ NewWithSeed,
N: NttInit<CiphertextModulus<M::MatElement>> + Ntt<Element = M::MatElement>,
> From<&SeededSinglePartyServerKey<M, BoolParameters<M::MatElement>, R::Seed>>
for ServerKeyEvaluationDomain<M, BoolParameters<M::MatElement>, R, N>
where
<M as Matrix>::R: RowMut,
M::MatElement: Copy,
R::Seed: Clone,
{
fn from(
value: &SeededSinglePartyServerKey<M, BoolParameters<M::MatElement>, R::Seed>,
) -> Self {
let mut main_prng = R::new_with_seed(value.seed.clone());
let parameters = &value.parameters;
let g = parameters.g() as isize;
let ring_size = value.parameters.rlwe_n().0;
let lwe_n = value.parameters.lwe_n().0;
let rlwe_q = value.parameters.rlwe_q();
let lwq_q = value.parameters.lwe_q();
let nttop = N::new(rlwe_q, ring_size);
// galois keys
let mut auto_keys = HashMap::new();
let auto_decomp_count = parameters.auto_decomposition_count().0;
let auto_element_dlogs = parameters.auto_element_dlogs();
for i in auto_element_dlogs.into_iter() {
let seeded_auto_key = value.auto_keys.get(&i).unwrap();
assert!(seeded_auto_key.dimension() == (auto_decomp_count, ring_size));
let mut data = M::zeros(auto_decomp_count * 2, ring_size);
// sample RLWE'_A(-s(X^k))
data.iter_rows_mut().take(auto_decomp_count).for_each(|ri| {
RandomFillUniformInModulus::random_fill(&mut main_prng, &rlwe_q, ri.as_mut())
});
// copy over RLWE'B_(-s(X^k))
izip!(
data.iter_rows_mut().skip(auto_decomp_count),
seeded_auto_key.iter_rows()
)
.for_each(|(to_ri, from_ri)| to_ri.as_mut().copy_from_slice(from_ri.as_ref()));
// Send to Evaluation domain
data.iter_rows_mut()
.for_each(|ri| nttop.forward(ri.as_mut()));
auto_keys.insert(i, data);
}
// RGSW ciphertexts
let (rlrg_a_decomp, rlrg_b_decomp) = parameters.rlwe_rgsw_decomposition_count();
let rgsw_cts = value
.rgsw_cts
.iter()
.map(|seeded_rgsw_si| {
assert!(
seeded_rgsw_si.dimension()
== (rlrg_a_decomp.0 * 2 + rlrg_b_decomp.0, ring_size)
);
let mut data = M::zeros(rlrg_a_decomp.0 * 2 + rlrg_b_decomp.0 * 2, ring_size);
// copy over RLWE'(-sm)
izip!(
data.iter_rows_mut().take(rlrg_a_decomp.0 * 2),
seeded_rgsw_si.iter_rows().take(rlrg_a_decomp.0 * 2)
)
.for_each(|(to_ri, from_ri)| to_ri.as_mut().copy_from_slice(from_ri.as_ref()));
// sample RLWE'_A(m)
data.iter_rows_mut()
.skip(rlrg_a_decomp.0 * 2)
.take(rlrg_b_decomp.0)
.for_each(|ri| {
RandomFillUniformInModulus::random_fill(
&mut main_prng,
&rlwe_q,
ri.as_mut(),
)
});
// copy over RLWE'_B(m)
izip!(
data.iter_rows_mut()
.skip(rlrg_a_decomp.0 * 2 + rlrg_b_decomp.0),
seeded_rgsw_si.iter_rows().skip(rlrg_a_decomp.0 * 2)
)
.for_each(|(to_ri, from_ri)| to_ri.as_mut().copy_from_slice(from_ri.as_ref()));
// send polynomials to evaluation domain
data.iter_rows_mut()
.for_each(|ri| nttop.forward(ri.as_mut()));
data
})
.collect_vec();
// LWE ksk
let lwe_ksk = {
let d = parameters.lwe_decomposition_count().0;
assert!(value.lwe_ksk.as_ref().len() == d * ring_size);
let mut data = M::zeros(d * ring_size, lwe_n + 1);
izip!(data.iter_rows_mut(), value.lwe_ksk.as_ref().iter()).for_each(
|(lwe_i, bi)| {
RandomFillUniformInModulus::random_fill(
&mut main_prng,
&lwq_q,
&mut lwe_i.as_mut()[1..],
);
lwe_i.as_mut()[0] = *bi;
},
);
data
};
ServerKeyEvaluationDomain {
rgsw_cts,
galois_keys: auto_keys,
lwe_ksk,
parameters: parameters.clone(),
_phanton: PhantomData,
}
}
}
impl<
M: MatrixMut + MatrixEntity,
Rng: NewWithSeed,
N: NttInit<CiphertextModulus<M::MatElement>> + Ntt<Element = M::MatElement>,
>
From<
&SeededInteractiveMultiPartyServerKey<
M,
InteractiveMultiPartyCrs<Rng::Seed>,
BoolParameters<M::MatElement>,
>,
> for ServerKeyEvaluationDomain<M, BoolParameters<M::MatElement>, Rng, N>
where
<M as Matrix>::R: RowMut,
Rng::Seed: Copy + Default,
Rng: RandomFillUniformInModulus<[M::MatElement], CiphertextModulus<M::MatElement>>
+ RandomFill<Rng::Seed>,
M::MatElement: Copy,
{
fn from(
value: &SeededInteractiveMultiPartyServerKey<
M,
InteractiveMultiPartyCrs<Rng::Seed>,
BoolParameters<M::MatElement>,
>,
) -> Self {
let g = value.parameters.g() as isize;
let rlwe_n = value.parameters.rlwe_n().0;
let lwe_n = value.parameters.lwe_n().0;
let rlwe_q = value.parameters.rlwe_q();
let lwe_q = value.parameters.lwe_q();
let rlwe_nttop = N::new(rlwe_q, rlwe_n);
// auto keys
let mut auto_keys = HashMap::new();
{
let mut auto_prng = Rng::new_with_seed(value.cr_seed.auto_keys_cts_seed::<Rng>());
let auto_d_count = value.parameters.auto_decomposition_count().0;
let auto_element_dlogs = value.parameters.auto_element_dlogs();
for i in auto_element_dlogs.into_iter() {
let mut key = M::zeros(auto_d_count * 2, rlwe_n);
// sample a
key.iter_rows_mut().take(auto_d_count).for_each(|ri| {
RandomFillUniformInModulus::random_fill(
&mut auto_prng,
&rlwe_q,
ri.as_mut(),
)
});
let key_part_b = value.auto_keys.get(&i).unwrap();
assert!(key_part_b.dimension() == (auto_d_count, rlwe_n));
izip!(
key.iter_rows_mut().skip(auto_d_count),
key_part_b.iter_rows()
)
.for_each(|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
});
// send to evaluation domain
key.iter_rows_mut()
.for_each(|ri| rlwe_nttop.forward(ri.as_mut()));
auto_keys.insert(i, key);
}
}
// rgsw cts
let (rlrg_d_a, rlrg_d_b) = value.parameters.rlwe_rgsw_decomposition_count();
let rgsw_ct_out = rlrg_d_a.0 * 2 + rlrg_d_b.0 * 2;
let rgsw_cts = value
.rgsw_cts
.iter()
.map(|ct_i_in| {
assert!(ct_i_in.dimension() == (rgsw_ct_out, rlwe_n));
let mut eval_ct_i_out = M::zeros(rgsw_ct_out, rlwe_n);
izip!(eval_ct_i_out.iter_rows_mut(), ct_i_in.iter_rows()).for_each(
|(to_ri, from_ri)| {
to_ri.as_mut().copy_from_slice(from_ri.as_ref());
rlwe_nttop.forward(to_ri.as_mut());
},
);
eval_ct_i_out
})
.collect_vec();
// lwe ksk
let mut lwe_ksk_prng = Rng::new_with_seed(value.cr_seed.lwe_ksk_cts_seed_seed::<Rng>());
let d_lwe = value.parameters.lwe_decomposition_count().0;
let mut lwe_ksk = M::zeros(rlwe_n * d_lwe, lwe_n + 1);
izip!(lwe_ksk.iter_rows_mut(), value.lwe_ksk.as_ref().iter()).for_each(
|(lwe_i, bi)| {
RandomFillUniformInModulus::random_fill(
&mut lwe_ksk_prng,
&lwe_q,
&mut lwe_i.as_mut()[1..],
);
lwe_i.as_mut()[0] = *bi;
},
);
ServerKeyEvaluationDomain {
rgsw_cts,
galois_keys: auto_keys,
lwe_ksk,
parameters: value.parameters.clone(),
_phanton: PhantomData,
}
}
}
impl<M: Matrix, P, R, N> PbsKey for ServerKeyEvaluationDomain<M, P, R, N> {
type AutoKey = M;
type LweKskKey = M;
type RgswCt = M;
fn galois_key_for_auto(&self, k: usize) -> &Self::AutoKey {
self.galois_keys.get(&k).unwrap()
}
fn rgsw_ct_lwe_si(&self, si: usize) -> &Self::RgswCt {
&self.rgsw_cts[si]
}
fn lwe_ksk(&self) -> &Self::LweKskKey {
&self.lwe_ksk
}
}
#[cfg(test)]
impl<M, P, R, N> super::super::print_noise::CollectRuntimeServerKeyStats
for ServerKeyEvaluationDomain<M, P, R, N>
{
type M = M;
fn galois_key_for_auto(&self, k: usize) -> &Self::M {
self.galois_keys.get(&k).unwrap()
}
fn lwe_ksk(&self) -> &Self::M {
&self.lwe_ksk
}
fn rgsw_cts_lwe_si(&self, s_index: usize) -> &Self::M {
&self.rgsw_cts[s_index]
}
}
}
/// Non-interactive multi-party server key in evaluation domain.
///
/// The key is derived from Seeded non-interactive mmulti-party server key
/// `SeededNonInteractiveMultiPartyServerKey`.
pub(crate) struct NonInteractiveServerKeyEvaluationDomain<M, P, R, N> {
/// RGSW ciphertexts RGSW(X^{s[i]}) under ideal RLWE secret key in
/// evaluation domain
rgsw_cts: Vec<M>,
/// Auto keys for all auto elements [-g, g, g^2, g^w] in evaluation
/// domain
auto_keys: HashMap<usize, M>,
/// LWE key switching key to key switch LWE_{q, s}(m) to LWE_{q, z}(m)
lwe_ksk: M,
/// Key switching key from user j's secret u_j to ideal RLWE secret key `s`
/// in evaluation domain. User j's key switching key is at j'th index.
ui_to_s_ksks: Vec<M>,
parameters: P,
_phanton: PhantomData<(R, N)>,
}
pub(super) mod impl_non_interactive_server_key_eval_domain {
use itertools::{izip, Itertools};
use crate::{bool::evaluator::NonInteractiveMultiPartyCrs, random::RandomFill, Ntt, NttInit};
use super::*;
impl<M, P, R, N> NonInteractiveServerKeyEvaluationDomain<M, P, R, N> {
pub(in super::super) fn rgsw_cts(&self) -> &[M] {
&self.rgsw_cts
}
}
impl<M, Rng, N>
From<
&SeededNonInteractiveMultiPartyServerKey<
M,
NonInteractiveMultiPartyCrs<Rng::Seed>,
BoolParameters<M::MatElement>,
>,
> for NonInteractiveServerKeyEvaluationDomain<M, BoolParameters<M::MatElement>, Rng, N>
where
M: MatrixMut + MatrixEntity + Clone,
Rng: NewWithSeed
+ RandomFillUniformInModulus<[M::MatElement], CiphertextModulus<M::MatElement>>
+ RandomFill<<Rng as NewWithSeed>::Seed>,
N: Ntt<Element = M::MatElement> + NttInit<CiphertextModulus<M::MatElement>>,
M::R: RowMut,
M::MatElement: Copy,
Rng::Seed: Clone + Copy + Default,
{
fn from(
value: &SeededNonInteractiveMultiPartyServerKey<
M,
NonInteractiveMultiPartyCrs<Rng::Seed>,
BoolParameters<M::MatElement>,
>,
) -> Self {
let rlwe_nttop = N::new(value.parameters.rlwe_q(), value.parameters.rlwe_n().0);
let ring_size = value.parameters.rlwe_n().0;
// RGSW cts
// copy over rgsw cts and send to evaluation domain
let mut rgsw_cts = value.rgsw_cts.clone();
rgsw_cts.iter_mut().for_each(|c| {
c.iter_rows_mut()
.for_each(|ri| rlwe_nttop.forward(ri.as_mut()))
});
// Auto keys
// populate pseudo random part of auto keys. Then send auto keys to
// evaluation domain
let mut auto_keys = HashMap::new();
let auto_seed = value.cr_seed.auto_keys_cts_seed::<Rng>();
let mut auto_prng = Rng::new_with_seed(auto_seed);
let auto_element_dlogs = value.parameters.auto_element_dlogs();
let d_auto = value.parameters.auto_decomposition_count().0;
auto_element_dlogs.iter().for_each(|el| {
let auto_part_b = value
.auto_keys
.get(el)
.expect(&format!("Auto key for element g^{el} not found"));
assert!(auto_part_b.dimension() == (d_auto, ring_size));
let mut auto_ct = M::zeros(d_auto * 2, ring_size);
// sample part A
auto_ct.iter_rows_mut().take(d_auto).for_each(|ri| {
RandomFillUniformInModulus::random_fill(
&mut auto_prng,
value.parameters.rlwe_q(),
ri.as_mut(),
)
});
// Copy over part B
izip!(
auto_ct.iter_rows_mut().skip(d_auto),
auto_part_b.iter_rows()
)
.for_each(|(to_ri, from_ri)| to_ri.as_mut().copy_from_slice(from_ri.as_ref()));
// send to evaluation domain
auto_ct
.iter_rows_mut()
.for_each(|r| rlwe_nttop.forward(r.as_mut()));
auto_keys.insert(*el, auto_ct);
});
// LWE ksk
// populate pseudo random part of lwe ciphertexts in ksk and copy over part b
// elements
let lwe_ksk_seed = value.cr_seed.lwe_ksk_cts_seed::<Rng>();
let mut lwe_ksk_prng = Rng::new_with_seed(lwe_ksk_seed);
let mut lwe_ksk = M::zeros(
value.parameters.lwe_decomposition_count().0 * ring_size,
value.parameters.lwe_n().0 + 1,
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | true |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/benches/ntt.rs | benches/ntt.rs | use bin_rs::{Ntt, NttBackendU64, NttInit};
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
use itertools::Itertools;
use rand::{thread_rng, Rng};
use rand_distr::Uniform;
fn forward_matrix(a: &mut [Vec<u64>], nttop: &NttBackendU64) {
a.iter_mut().for_each(|r| nttop.forward(r.as_mut_slice()));
}
fn forward_lazy_matrix(a: &mut [Vec<u64>], nttop: &NttBackendU64) {
a.iter_mut()
.for_each(|r| nttop.forward_lazy(r.as_mut_slice()));
}
fn backward_matrix(a: &mut [Vec<u64>], nttop: &NttBackendU64) {
a.iter_mut().for_each(|r| nttop.backward(r.as_mut_slice()));
}
fn backward_lazy_matrix(a: &mut [Vec<u64>], nttop: &NttBackendU64) {
a.iter_mut()
.for_each(|r| nttop.backward_lazy(r.as_mut_slice()));
}
fn benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("ntt");
// 55
for prime in [36028797017456641] {
for ring_size in [1 << 11] {
let ntt = NttBackendU64::new(&prime, ring_size);
let mut rng = thread_rng();
let a = (&mut rng)
.sample_iter(Uniform::new(0, prime))
.take(ring_size)
.collect_vec();
let d = 2;
let a_matrix = (0..d)
.map(|_| {
(&mut rng)
.sample_iter(Uniform::new(0, prime))
.take(ring_size)
.collect_vec()
})
.collect_vec();
{
group.bench_function(
BenchmarkId::new("forward", format!("q={prime}/N={ring_size}")),
|b| {
b.iter_batched_ref(
|| a.clone(),
|mut a| black_box(ntt.forward(&mut a)),
criterion::BatchSize::PerIteration,
)
},
);
group.bench_function(
BenchmarkId::new("forward_lazy", format!("q={prime}/N={ring_size}")),
|b| {
b.iter_batched_ref(
|| a.clone(),
|mut a| black_box(ntt.forward_lazy(&mut a)),
criterion::BatchSize::PerIteration,
)
},
);
group.bench_function(
BenchmarkId::new("forward_matrix", format!("q={prime}/N={ring_size}/d={d}")),
|b| {
b.iter_batched_ref(
|| a_matrix.clone(),
|a_matrix| black_box(forward_matrix(a_matrix, &ntt)),
criterion::BatchSize::PerIteration,
)
},
);
group.bench_function(
BenchmarkId::new(
"forward_lazy_matrix",
format!("q={prime}/N={ring_size}/d={d}"),
),
|b| {
b.iter_batched_ref(
|| a_matrix.clone(),
|a_matrix| black_box(forward_lazy_matrix(a_matrix, &ntt)),
criterion::BatchSize::PerIteration,
)
},
);
}
{
group.bench_function(
BenchmarkId::new("backward", format!("q={prime}/N={ring_size}")),
|b| {
b.iter_batched_ref(
|| a.clone(),
|mut a| black_box(ntt.backward(&mut a)),
criterion::BatchSize::PerIteration,
)
},
);
group.bench_function(
BenchmarkId::new("backward_lazy", format!("q={prime}/N={ring_size}")),
|b| {
b.iter_batched_ref(
|| a.clone(),
|mut a| black_box(ntt.backward_lazy(&mut a)),
criterion::BatchSize::PerIteration,
)
},
);
group.bench_function(
BenchmarkId::new("backward_matrix", format!("q={prime}/N={ring_size}")),
|b| {
b.iter_batched_ref(
|| a_matrix.clone(),
|a_matrix| black_box(backward_matrix(a_matrix, &ntt)),
criterion::BatchSize::PerIteration,
)
},
);
group.bench_function(
BenchmarkId::new(
"backward_lazy_matrix",
format!("q={prime}/N={ring_size}/d={d}"),
),
|b| {
b.iter_batched_ref(
|| a_matrix.clone(),
|a_matrix| black_box(backward_lazy_matrix(a_matrix, &ntt)),
criterion::BatchSize::PerIteration,
)
},
);
}
}
}
group.finish();
}
criterion_group!(ntt, benchmark);
criterion_main!(ntt);
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/benches/modulus.rs | benches/modulus.rs | use bin_rs::{
ArithmeticLazyOps, ArithmeticOps, Decomposer, DefaultDecomposer, ModInit, ModularOpsU64,
ShoupMatrixFMA, VectorOps,
};
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
use itertools::{izip, Itertools};
use rand::{thread_rng, Rng};
use rand_distr::Uniform;
fn decompose_r(r: &[u64], decomp_r: &mut [Vec<u64>], decomposer: &DefaultDecomposer<u64>) {
let ring_size = r.len();
// let d = decomposer.decomposition_count();
// let mut count = 0;
for ri in 0..ring_size {
// let el_decomposed = decomposer.decompose(&r[ri]);
decomposer
.decompose_iter(&r[ri])
.enumerate()
.into_iter()
.for_each(|(j, el)| {
decomp_r[j][ri] = el;
});
}
}
fn matrix_fma(out: &mut [u64], a: &Vec<Vec<u64>>, b: &Vec<Vec<u64>>, modop: &ModularOpsU64<u64>) {
izip!(a.iter(), b.iter()).for_each(|(a_r, b_r)| {
izip!(out.iter_mut(), a_r.iter(), b_r.iter())
.for_each(|(o, ai, bi)| *o = modop.add_lazy(o, &modop.mul_lazy(ai, bi)));
});
}
fn benchmark_decomposer(c: &mut Criterion) {
let mut group = c.benchmark_group("decomposer");
// let decomposers = vec![];
// 55
for prime in [36028797017456641] {
for ring_size in [1 << 11] {
let logb = 11;
let decomposer = DefaultDecomposer::new(prime, logb, 2);
let mut rng = thread_rng();
let dist = Uniform::new(0, prime);
let a = (&mut rng).sample_iter(dist).take(ring_size).collect_vec();
group.bench_function(
BenchmarkId::new(
"decompose",
format!(
"q={prime}/N={ring_size}/logB={logb}/d={}",
*decomposer.decomposition_count().as_ref()
),
),
|b| {
b.iter_batched_ref(
|| {
(
a.clone(),
vec![
vec![0u64; ring_size];
*decomposer.decomposition_count().as_ref()
],
)
},
|(r, decomp_r)| (decompose_r(r, decomp_r, &decomposer)),
criterion::BatchSize::PerIteration,
)
},
);
}
}
group.finish();
}
fn benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("modulus");
// 55
for prime in [36028797017456641] {
for ring_size in [1 << 11] {
let modop = ModularOpsU64::new(prime);
let mut rng = thread_rng();
let dist = Uniform::new(0, prime);
let a0 = (&mut rng).sample_iter(dist).take(ring_size).collect_vec();
let a1 = (&mut rng).sample_iter(dist).take(ring_size).collect_vec();
let a2 = (&mut rng).sample_iter(dist).take(ring_size).collect_vec();
let d = 1;
let a0_matrix = (0..d)
.into_iter()
.map(|_| (&mut rng).sample_iter(dist).take(ring_size).collect_vec())
.collect_vec();
// a0 in shoup representation
let a0_shoup_matrix = a0_matrix
.iter()
.map(|r| {
r.iter()
.map(|v| {
// $(v * 2^{\beta}) / p$
((*v as u128 * (1u128 << 64)) / prime as u128) as u64
})
.collect_vec()
})
.collect_vec();
let a1_matrix = (0..d)
.into_iter()
.map(|_| (&mut rng).sample_iter(dist).take(ring_size).collect_vec())
.collect_vec();
group.bench_function(
BenchmarkId::new("matrix_fma_lazy", format!("q={prime}/N={ring_size}/d={d}")),
|b| {
b.iter_batched_ref(
|| (vec![0u64; ring_size]),
|(out)| black_box(matrix_fma(out, &a0_matrix, &a1_matrix, &modop)),
criterion::BatchSize::PerIteration,
)
},
);
group.bench_function(
BenchmarkId::new(
"matrix_shoup_fma_lazy",
format!("q={prime}/N={ring_size}/d={d}"),
),
|b| {
b.iter_batched_ref(
|| (vec![0u64; ring_size]),
|(out)| {
black_box(modop.shoup_matrix_fma(
out,
&a0_matrix,
&a0_shoup_matrix,
&a1_matrix,
))
},
criterion::BatchSize::PerIteration,
)
},
);
}
}
group.finish();
}
criterion_group!(decomposer, benchmark_decomposer);
criterion_group!(modulus, benchmark);
criterion_main!(modulus, decomposer);
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/examples/non_interactive_fheuint8.rs | examples/non_interactive_fheuint8.rs | use itertools::Itertools;
use phantom_zone::*;
use rand::{thread_rng, Rng, RngCore};
fn function1(a: u8, b: u8, c: u8, d: u8) -> u8 {
((a + b) * c) * d
}
fn function1_fhe(a: &FheUint8, b: &FheUint8, c: &FheUint8, d: &FheUint8) -> FheUint8 {
&(&(a + b) * c) * d
}
fn function2(a: u8, b: u8, c: u8, d: u8) -> u8 {
(a * b) + (c * d)
}
fn function2_fhe(a: &FheUint8, b: &FheUint8, c: &FheUint8, d: &FheUint8) -> FheUint8 {
&(a * b) + &(c * d)
}
fn main() {
set_parameter_set(ParameterSelector::NonInteractiveLTE4Party);
// set application's common reference seed
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let no_of_parties = 4;
// Clide side //
// Generate client keys
let cks = (0..no_of_parties).map(|_| gen_client_key()).collect_vec();
// client 0 encrypts its private inputs
let c0_a = thread_rng().gen::<u8>();
// Clients encrypt their private inputs in a seeded batched ciphertext using
// their private RLWE secret `u_j`.
let c0_enc = cks[0].encrypt(vec![c0_a].as_slice());
// client 1 encrypts its private inputs
let c1_a = thread_rng().gen::<u8>();
let c1_enc = cks[1].encrypt(vec![c1_a].as_slice());
// client 2 encrypts its private inputs
let c2_a = thread_rng().gen::<u8>();
let c2_enc = cks[2].encrypt(vec![c2_a].as_slice());
// client 3 encrypts its private inputs
let c3_a = thread_rng().gen::<u8>();
let c3_enc = cks[3].encrypt(vec![c3_a].as_slice());
// Clients independently generate their server key shares
//
// We assign user_id 0 to client 0, user_id 1 to client 1, user_id 2 to client
// 2, user_id 3 to client 3.
//
// Note that `user_id`s must be unique among the clients and must be less than
// total number of clients.
let server_key_shares = cks
.iter()
.enumerate()
.map(|(id, k)| gen_server_key_share(id, no_of_parties, k))
.collect_vec();
// Each client uploads their server key shares and encrypted private inputs to
// the server in a single shot message.
// Server side //
// Server receives server key shares from each client and proceeds to aggregate
// them to produce the server key. After this point, server can use the server
// key to evaluate any arbitrary function on encrypted private inputs from
// the fixed set of clients
// aggregate server shares and generate the server key
let server_key = aggregate_server_key_shares(&server_key_shares);
server_key.set_server_key();
// Server proceeds to extract private inputs sent by clients
//
// To extract client 0's (with user_id=0) private inputs we first key switch
// client 0's private inputs from theit secret `u_j` to ideal secret of the mpc
// protocol. To indicate we're key switching client 0's private input we
// supply client 0's `user_id` i.e. we call `key_switch(0)`. Then we extract
// the first ciphertext by calling `extract_at(0)`.
//
// Since client 0 only encrypts 1 input in batched ciphertext, calling
// extract_at(index) for `index` > 0 will panic. If client 0 had more private
// inputs then we can either extract them all at once with `extract_all` or
// first `many` of them with `extract_many(many)`
let ct_c0_a = c0_enc.unseed::<Vec<Vec<u64>>>().key_switch(0).extract_at(0);
let ct_c1_a = c1_enc.unseed::<Vec<Vec<u64>>>().key_switch(1).extract_at(0);
let ct_c2_a = c2_enc.unseed::<Vec<Vec<u64>>>().key_switch(2).extract_at(0);
let ct_c3_a = c3_enc.unseed::<Vec<Vec<u64>>>().key_switch(3).extract_at(0);
// After extracting each client's private inputs, server proceeds to evaluate
// function1
let now = std::time::Instant::now();
let ct_out_f1 = function1_fhe(&ct_c0_a, &ct_c1_a, &ct_c2_a, &ct_c3_a);
println!("Function1 FHE evaluation time: {:?}", now.elapsed());
// Server has finished running compute. Clients can proceed to decrypt the
// output ciphertext using multi-party decryption.
// Client side //
// In multi-party decryption, each client needs to come online, download output
// ciphertext from the server, produce "output ciphertext" dependent decryption
// share, and send it to other parties (either via p2p or via server). After
// receving decryption shares from other parties, clients can independently
// decrypt output ciphertext.
// each client produces decryption share
let decryption_shares = cks
.iter()
.map(|k| k.gen_decryption_share(&ct_out_f1))
.collect_vec();
// With all decryption shares, clients can aggregate the shares and decrypt the
// ciphertext
let out_f1 = cks[0].aggregate_decryption_shares(&ct_out_f1, &decryption_shares);
// we check correctness of function1
let want_out_f1 = function1(c0_a, c1_a, c2_a, c3_a);
assert_eq!(out_f1, want_out_f1);
// -----------
// Server key can be re-used for different functions with different private
// client inputs for the same set of clients.
//
// Here we run `function2_fhe` for the same set of client but with new inputs.
// Clients only have to upload their private inputs to the server this time.
// Each client encrypts their private input
let c0_a = thread_rng().gen::<u8>();
let c0_enc = cks[0].encrypt(vec![c0_a].as_slice());
let c1_a = thread_rng().gen::<u8>();
let c1_enc = cks[1].encrypt(vec![c1_a].as_slice());
let c2_a = thread_rng().gen::<u8>();
let c2_enc = cks[2].encrypt(vec![c2_a].as_slice());
let c3_a = thread_rng().gen::<u8>();
let c3_enc = cks[3].encrypt(vec![c3_a].as_slice());
// Clients upload only their new private inputs to the server
// Server side //
// Server receives clients private inputs and extracts them
let ct_c0_a = c0_enc.unseed::<Vec<Vec<u64>>>().key_switch(0).extract_at(0);
let ct_c1_a = c1_enc.unseed::<Vec<Vec<u64>>>().key_switch(1).extract_at(0);
let ct_c2_a = c2_enc.unseed::<Vec<Vec<u64>>>().key_switch(2).extract_at(0);
let ct_c3_a = c3_enc.unseed::<Vec<Vec<u64>>>().key_switch(3).extract_at(0);
// Server proceeds to evaluate `function2_fhe`
let now = std::time::Instant::now();
let ct_out_f2 = function2_fhe(&ct_c0_a, &ct_c1_a, &ct_c2_a, &ct_c3_a);
println!("Function2 FHE evaluation time: {:?}", now.elapsed());
// Client side //
// Each client generates decrytion share for `ct_out_f2`
let decryption_shares = cks
.iter()
.map(|k| k.gen_decryption_share(&ct_out_f2))
.collect_vec();
// Clients independently aggregate the shares and decrypt
let out_f2 = cks[0].aggregate_decryption_shares(&ct_out_f2, &decryption_shares);
// We check correctness of function2
let want_out_f2 = function2(c0_a, c1_a, c2_a, c3_a);
assert_eq!(out_f2, want_out_f2);
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/examples/interactive_fheuint8.rs | examples/interactive_fheuint8.rs | use itertools::Itertools;
use phantom_zone::*;
use rand::{thread_rng, Rng, RngCore};
fn function1(a: u8, b: u8, c: u8, d: u8) -> u8 {
((a + b) * c) * d
}
fn function1_fhe(a: &FheUint8, b: &FheUint8, c: &FheUint8, d: &FheUint8) -> FheUint8 {
&(&(a + b) * c) * d
}
fn function2(a: u8, b: u8, c: u8, d: u8) -> u8 {
(a * b) + (c * d)
}
fn function2_fhe(a: &FheUint8, b: &FheUint8, c: &FheUint8, d: &FheUint8) -> FheUint8 {
&(a * b) + &(c * d)
}
fn main() {
// Select parameter set
set_parameter_set(ParameterSelector::InteractiveLTE4Party);
// set application's common reference seed
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let no_of_parties = 4;
// Client side //
// Clients generate their private keys
let cks = (0..no_of_parties)
.into_iter()
.map(|_| gen_client_key())
.collect_vec();
// -- Round 1 -- //
// In round 1 each client generates their share for the collective public key.
// They send public key shares to each other with or out without the server.
// After receiving others public key shares clients independently aggregate
// the shares and produce the collective public key `pk`
let pk_shares = cks.iter().map(|k| collective_pk_share(k)).collect_vec();
// Clients aggregate public key shares to produce collective public key `pk`
let pk = aggregate_public_key_shares(&pk_shares);
// -- Round 2 -- //
// In round 2 each client generates server key share using the public key `pk`.
// Clients may also encrypt their private inputs using collective public key
// `pk`. Each client then uploads their server key share and private input
// ciphertexts to the server.
// Clients generate server key shares
//
// We assign user_id 0 to client 0, user_id 1 to client 1, user_id 2 to client
// 2, and user_id 4 to client 4.
//
// Note that `user_id`'s must be unique among the clients and must be less than
// total number of clients.
let server_key_shares = cks
.iter()
.enumerate()
.map(|(user_id, k)| collective_server_key_share(k, user_id, no_of_parties, &pk))
.collect_vec();
// Each client encrypts their private inputs using the collective public key
// `pk`. Unlike non-inteactive MPC protocol, private inputs are
// encrypted using collective public key.
let c0_a = thread_rng().gen::<u8>();
let c0_enc = pk.encrypt(vec![c0_a].as_slice());
let c1_a = thread_rng().gen::<u8>();
let c1_enc = pk.encrypt(vec![c1_a].as_slice());
let c2_a = thread_rng().gen::<u8>();
let c2_enc = pk.encrypt(vec![c2_a].as_slice());
let c3_a = thread_rng().gen::<u8>();
let c3_enc = pk.encrypt(vec![c3_a].as_slice());
// Clients upload their server key along with private encrypted inputs to
// the server
// Server side //
// Server receives server key shares from each client and proceeds to
// aggregate the shares and produce the server key
let server_key = aggregate_server_key_shares(&server_key_shares);
server_key.set_server_key();
// Server proceeds to extract clients private inputs
//
// Clients encrypt their FheUint8s inputs packed in a batched ciphertext.
// The server must extract clients private inputs from the batch ciphertext
// either (1) using `extract_at(index)` to extract `index`^{th} FheUint8
// ciphertext (2) or using `extract_all()` to extract all available FheUint8s
// (3) or using `extract_many(many)` to extract first `many` available FheUint8s
let c0_a_enc = c0_enc.extract_at(0);
let c1_a_enc = c1_enc.extract_at(0);
let c2_a_enc = c2_enc.extract_at(0);
let c3_a_enc = c3_enc.extract_at(0);
// Server proceeds to evaluate function1 on clients private inputs
let ct_out_f1 = function1_fhe(&c0_a_enc, &c1_a_enc, &c2_a_enc, &c3_a_enc);
// After server has finished evaluating the circuit on client private
// inputs, clients can proceed to multi-party decryption protocol to
// decrypt output ciphertext
// Client Side //
// In multi-party decryption protocol, client must come online, download the
// output ciphertext from the server, product "output ciphertext" dependent
// decryption share, and send it to other parties. After receiving
// decryption shares of other parties, clients independently aggregate the
// decrytion shares and decrypt the output ciphertext.
// Clients generate decryption shares
let decryption_shares = cks
.iter()
.map(|k| k.gen_decryption_share(&ct_out_f1))
.collect_vec();
// After receiving decryption shares from other parties, clients aggregate the
// shares and decrypt output ciphertext
let out_f1 = cks[0].aggregate_decryption_shares(&ct_out_f1, &decryption_shares);
// Check correctness of function1 output
let want_f1 = function1(c0_a, c1_a, c2_a, c3_a);
assert!(out_f1 == want_f1);
// --------
// Once server key is produced it can be re-used across different functions
// with different private client inputs for the same set of clients.
//
// Here we run `function2_fhe` for the same of clients but with different
// private inputs. Clients do not need to participate in the 2 round
// protocol again, instead they only upload their new private inputs to the
// server.
// Clients encrypt their private inputs
let c0_a = thread_rng().gen::<u8>();
let c0_enc = pk.encrypt(vec![c0_a].as_slice());
let c1_a = thread_rng().gen::<u8>();
let c1_enc = pk.encrypt(vec![c1_a].as_slice());
let c2_a = thread_rng().gen::<u8>();
let c2_enc = pk.encrypt(vec![c2_a].as_slice());
let c3_a = thread_rng().gen::<u8>();
let c3_enc = pk.encrypt(vec![c3_a].as_slice());
// Clients uploads only their new private inputs to the server
// Server side //
// Server receives private inputs from the clients, extracts them, and
// proceeds to evaluate `function2_fhe`
let c0_a_enc = c0_enc.extract_at(0);
let c1_a_enc = c1_enc.extract_at(0);
let c2_a_enc = c2_enc.extract_at(0);
let c3_a_enc = c3_enc.extract_at(0);
let ct_out_f2 = function2_fhe(&c0_a_enc, &c1_a_enc, &c2_a_enc, &c3_a_enc);
// Client side //
// Clients generate decryption shares for `ct_out_f2`
let decryption_shares = cks
.iter()
.map(|k| k.gen_decryption_share(&ct_out_f2))
.collect_vec();
// Clients aggregate decryption shares and decrypt `ct_out_f2`
let out_f2 = cks[0].aggregate_decryption_shares(&ct_out_f2, &decryption_shares);
// We check correctness of function2
let want_f2 = function2(c0_a, c1_a, c2_a, c3_a);
assert!(want_f2 == out_f2);
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/examples/if_and_else.rs | examples/if_and_else.rs | use itertools::Itertools;
use phantom_zone::*;
use rand::{thread_rng, Rng, RngCore};
/// Code that runs when conditional branch is `True`
fn circuit_branch_true(a: &FheUint8, b: &FheUint8) -> FheUint8 {
a + b
}
/// Code that runs when conditional branch is `False`
fn circuit_branch_false(a: &FheUint8, b: &FheUint8) -> FheUint8 {
a * b
}
// Conditional branching (ie. If and else) are generally expensive in encrypted
// domain. The code must execute all the branches, and, as apparent, the
// runtime cost grows exponentially with no. of conditional branches.
//
// In general we recommend to write branchless code. In case the code cannot be
// modified to be branchless, the code must execute all branches and use a
// muxer to select correct output at the end.
//
// Below we showcase example of a single conditional branch in encrypted domain.
// The code executes both the branches (i.e. program runs both If and Else) and
// selects output of one of the branches with a mux.
fn main() {
set_parameter_set(ParameterSelector::NonInteractiveLTE2Party);
// set application's common reference seed
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let no_of_parties = 2;
// Generate client keys
let cks = (0..no_of_parties).map(|_| gen_client_key()).collect_vec();
// Generate server key shares
let server_key_shares = cks
.iter()
.enumerate()
.map(|(id, k)| gen_server_key_share(id, no_of_parties, k))
.collect_vec();
// Aggregate server key shares and set the server key
let server_key = aggregate_server_key_shares(&server_key_shares);
server_key.set_server_key();
// -------
// User 0 encrypts their private input `v_a` and User 1 encrypts their
// private input `v_b`. We want to execute:
//
// if v_a < v_b:
// return v_a + v_b
// else:
// return v_a * v_b
//
// We define two functions
// (1) `circuit_branch_true`: which executes v_a + v_b in encrypted domain.
// (2) `circuit_branch_false`: which executes v_a * v_b in encrypted
// domain.
//
// The circuit runs both `circuit_branch_true` and `circuit_branch_false` and
// then selects the output of `circuit_branch_true` if `v_a < v_b == TRUE`
// otherwise selects the output of `circuit_branch_false` if `v_a < v_b ==
// FALSE` using mux.
// Clients private inputs
let v_a = thread_rng().gen::<u8>();
let v_b = thread_rng().gen::<u8>();
let v_a_enc = cks[0]
.encrypt(vec![v_a].as_slice())
.unseed::<Vec<Vec<u64>>>()
.key_switch(0)
.extract_at(0);
let v_b_enc = cks[1]
.encrypt(vec![v_b].as_slice())
.unseed::<Vec<Vec<u64>>>()
.key_switch(1)
.extract_at(0);
// Run both branches
let out_true_enc = circuit_branch_true(&v_a_enc, &v_b_enc);
let out_false_enc = circuit_branch_false(&v_a_enc, &v_b_enc);
// define condition select v_a < v_b
let selector_bit = v_a_enc.lt(&v_b_enc);
// select output of `circuit_branch_true` if selector_bit == TRUE otherwise
// select output of `circuit_branch_false`
let out_enc = out_true_enc.mux(&out_false_enc, &selector_bit);
let out = cks[0].aggregate_decryption_shares(
&out_enc,
&cks.iter()
.map(|k| k.gen_decryption_share(&out_enc))
.collect_vec(),
);
let want_out = if v_a < v_b {
v_a.wrapping_add(v_b)
} else {
v_a.wrapping_mul(v_b)
};
assert_eq!(out, want_out);
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/examples/bomberman.rs | examples/bomberman.rs | use std::fmt::Debug;
use itertools::Itertools;
use phantom_zone::*;
use rand::{thread_rng, Rng, RngCore};
struct Coordinates<T>(T, T);
impl<T> Coordinates<T> {
fn new(x: T, y: T) -> Self {
Coordinates(x, y)
}
fn x(&self) -> &T {
&self.0
}
fn y(&self) -> &T {
&self.1
}
}
impl<T> Debug for Coordinates<T>
where
T: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Coordinates")
.field("x", self.x())
.field("y", self.y())
.finish()
}
}
fn coordinates_is_equal(a: &Coordinates<FheUint8>, b: &Coordinates<FheUint8>) -> FheBool {
&(a.x().eq(b.x())) & &(a.y().eq(b.y()))
}
/// Traverse the map with `p0` moves and check whether any of the moves equal
/// bomb coordinates (in encrypted domain)
fn traverse_map(p0: &[Coordinates<FheUint8>], bomb_coords: &[Coordinates<FheUint8>]) -> FheBool {
// First move
let mut out = coordinates_is_equal(&p0[0], &bomb_coords[0]);
bomb_coords.iter().skip(1).for_each(|b_coord| {
out |= coordinates_is_equal(&p0[0], &b_coord);
});
// rest of the moves
p0.iter().skip(1).for_each(|m_coord| {
bomb_coords.iter().for_each(|b_coord| {
out |= coordinates_is_equal(m_coord, b_coord);
});
});
out
}
// Do you recall bomberman? It's an interesting game where the bomberman has to
// cross the map without stepping on strategically placed bombs all over the
// map. Below we implement a very basic prototype of bomberman with 4 players.
//
// The map has 256 tiles with bottom left-most tile labelled with coordinates
// (0,0) and top right-most tile labelled with coordinates (255, 255). There are
// 4 players: Player 0, Player 1, Player 2, Player 3. Player 0's task is to walk
// across the map with fixed no. of moves while preventing itself from stepping
// on any of the bombs placed on the map by Player 1, 2, and 3.
//
// The twist is that Player 0's moves and the locations of bombs placed by other
// players are encrypted. Player 0 moves across the map in encrypted domain.
// Only a boolean output indicating whether player 0 survived after all the
// moves or killed itself by stepping onto a bomb is revealed at the end. If
// player 0 survives, Player 1, 2, 3 never learn what moves did Player 0 make.
// If Player 0 kills itself by stepping onto a bomb, it only learns that bomb
// was placed on one of the coordinates it moved to. Moreover, Player 1, 2, 3
// never learn locations of each other bombs or whose bomb killed Player 0.
fn main() {
set_parameter_set(ParameterSelector::NonInteractiveLTE4Party);
// set application's common reference seed
let mut seed = [0; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let no_of_parties = 4;
// Client side //
// Players generate client keys
let cks = (0..no_of_parties).map(|_| gen_client_key()).collect_vec();
// Players generate server keys
let server_key_shares = cks
.iter()
.enumerate()
.map(|(index, k)| gen_server_key_share(index, no_of_parties, k))
.collect_vec();
// Player 0 describes its moves as sequence of coordinates on the map
let no_of_moves = 10;
let player_0_moves = (0..no_of_moves)
.map(|_| Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen()))
.collect_vec();
// Coordinates of bomb placed by Player 1
let player_1_bomb = Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen());
// Coordinates of bomb placed by Player 2
let player_2_bomb = Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen());
// Coordinates of bomb placed by Player 3
let player_3_bomb = Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen());
println!("P0 moves coordinates: {:?}", &player_0_moves);
println!("P1 bomb coordinates : {:?}", &player_1_bomb);
println!("P2 bomb coordinates : {:?}", &player_2_bomb);
println!("P3 bomb coordinates : {:?}", &player_3_bomb);
// Players encrypt their private inputs
let player_0_enc = cks[0].encrypt(
player_0_moves
.iter()
.flat_map(|c| vec![*c.x(), *c.y()])
.collect_vec()
.as_slice(),
);
let player_1_enc = cks[1].encrypt(vec![*player_1_bomb.x(), *player_1_bomb.y()].as_slice());
let player_2_enc = cks[2].encrypt(vec![*player_2_bomb.x(), *player_2_bomb.y()].as_slice());
let player_3_enc = cks[3].encrypt(vec![*player_3_bomb.x(), *player_3_bomb.y()].as_slice());
// Players upload the encrypted inputs and server key shares to the server
// Server side //
let server_key = aggregate_server_key_shares(&server_key_shares);
server_key.set_server_key();
// server parses Player inputs
let player_0_moves_enc = {
let c = player_0_enc
.unseed::<Vec<Vec<u64>>>()
.key_switch(0)
.extract_all();
c.into_iter()
.chunks(2)
.into_iter()
.map(|mut x_y| Coordinates::new(x_y.next().unwrap(), x_y.next().unwrap()))
.collect_vec()
};
let player_1_bomb_enc = {
let c = player_1_enc.unseed::<Vec<Vec<u64>>>().key_switch(1);
Coordinates::new(c.extract_at(0), c.extract_at(1))
};
let player_2_bomb_enc = {
let c = player_2_enc.unseed::<Vec<Vec<u64>>>().key_switch(2);
Coordinates::new(c.extract_at(0), c.extract_at(1))
};
let player_3_bomb_enc = {
let c = player_3_enc.unseed::<Vec<Vec<u64>>>().key_switch(3);
Coordinates::new(c.extract_at(0), c.extract_at(1))
};
// Server runs the game
let player_0_dead_ct = traverse_map(
&player_0_moves_enc,
&vec![player_1_bomb_enc, player_2_bomb_enc, player_3_bomb_enc],
);
// Client side //
// Players generate decryption shares and send them to each other
let decryption_shares = cks
.iter()
.map(|k| k.gen_decryption_share(&player_0_dead_ct))
.collect_vec();
// Players decrypt to find whether Player 0 survived
let player_0_dead = cks[0].aggregate_decryption_shares(&player_0_dead_ct, &decryption_shares);
if player_0_dead {
println!("Oops! Player 0 dead");
} else {
println!("Wohoo! Player 0 survived");
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/examples/meeting_friends.rs | examples/meeting_friends.rs | use itertools::Itertools;
use phantom_zone::*;
use rand::{thread_rng, Rng, RngCore};
struct Location<T>(T, T);
impl<T> Location<T> {
fn new(x: T, y: T) -> Self {
Location(x, y)
}
fn x(&self) -> &T {
&self.0
}
fn y(&self) -> &T {
&self.1
}
}
fn should_meet(a: &Location<u8>, b: &Location<u8>, b_threshold: &u8) -> bool {
let diff_x = a.x() - b.x();
let diff_y = a.y() - b.y();
let d_sq = &(&diff_x * &diff_x) + &(&diff_y * &diff_y);
d_sq.le(b_threshold)
}
/// Calculates distance square between a's and b's location. Returns a boolean
/// indicating whether diatance sqaure is <= `b_threshold`.
fn should_meet_fhe(
a: &Location<FheUint8>,
b: &Location<FheUint8>,
b_threshold: &FheUint8,
) -> FheBool {
let diff_x = a.x() - b.x();
let diff_y = a.y() - b.y();
let d_sq = &(&diff_x * &diff_x) + &(&diff_y * &diff_y);
d_sq.le(b_threshold)
}
// Ever wondered who are the long distance friends (friends of friends or
// friends of friends of friends...) that live nearby ? But how do you find
// them? Surely no-one will simply reveal their exact location just because
// there's a slight chance that a long distance friend lives nearby.
//
// Here we write a simple application with two users `a` and `b`. User `a` wants
// to find (long distance) friends that live in their neighbourhood. User `b` is
// open to meeting new friends within some distance of their location. Both user
// `a` and `b` encrypt their locations and upload their encrypted locations to
// the server. User `b` also encrypts the distance square threshold within which
// they are interested in meeting new friends and sends encrypted distance
// square threshold to the server.
// The server calculates the square of the distance between user a's location
// and user b's location and produces encrypted boolean output indicating
// whether square of distance is <= user b's supplied distance square threshold.
// User `a` then comes online, downloads output ciphertext, produces their
// decryption share for user `b`, and uploads the decryption share to the
// server. User `b` comes online, downloads output ciphertext and user a's
// decryption share, produces their own decryption share, and then decrypts the
// encrypted boolean output. If the output is `True`, it indicates user `a` is
// within the distance square threshold defined by user `b`.
fn main() {
set_parameter_set(ParameterSelector::NonInteractiveLTE2Party);
// set application's common reference seed
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let no_of_parties = 2;
// Client Side //
// Generate client keys
let cks = (0..no_of_parties).map(|_| gen_client_key()).collect_vec();
// We assign user_id 0 to user `a` and user_id 1 user `b`
let a_id = 0;
let b_id = 1;
let user_a_secret = &cks[0];
let user_b_secret = &cks[1];
// User `a` and `b` generate server key shares
let a_server_key_share = gen_server_key_share(a_id, no_of_parties, user_a_secret);
let b_server_key_share = gen_server_key_share(b_id, no_of_parties, user_b_secret);
// User `a` and `b` encrypt their locations
let user_a_secret = &cks[0];
let user_a_location = Location::new(thread_rng().gen::<u8>(), thread_rng().gen::<u8>());
let user_a_enc =
user_a_secret.encrypt(vec![*user_a_location.x(), *user_a_location.y()].as_slice());
let user_b_location = Location::new(thread_rng().gen::<u8>(), thread_rng().gen::<u8>());
// User `b` also encrypts the distance square threshold
let user_b_threshold = 40;
let user_b_enc = user_b_secret
.encrypt(vec![*user_b_location.x(), *user_b_location.y(), user_b_threshold].as_slice());
// Server Side //
// Both user `a` and `b` upload their private inputs and server key shares to
// the server in single shot message
let server_key = aggregate_server_key_shares(&vec![a_server_key_share, b_server_key_share]);
server_key.set_server_key();
// Server parses private inputs from user `a` and `b`
let user_a_location_enc = {
let c = user_a_enc.unseed::<Vec<Vec<u64>>>().key_switch(a_id);
Location::new(c.extract_at(0), c.extract_at(1))
};
let (user_b_location_enc, user_b_threshold_enc) = {
let c = user_b_enc.unseed::<Vec<Vec<u64>>>().key_switch(b_id);
(
Location::new(c.extract_at(0), c.extract_at(1)),
c.extract_at(2),
)
};
// run the circuit
let out_c = should_meet_fhe(
&user_a_location_enc,
&user_b_location_enc,
&user_b_threshold_enc,
);
// Client Side //
// user `a` comes online, downloads `out_c`, produces a decryption share, and
// uploads the decryption share to the server.
let a_dec_share = user_a_secret.gen_decryption_share(&out_c);
// user `b` comes online downloads user `a`'s decryption share, generates their
// own decryption share, decrypts the output ciphertext. If the output is
// True, user `b` contacts user `a` to meet.
let b_dec_share = user_b_secret.gen_decryption_share(&out_c);
let out_bool =
user_b_secret.aggregate_decryption_shares(&out_c, &vec![b_dec_share, a_dec_share]);
assert_eq!(
out_bool,
should_meet(&user_a_location, &user_b_location, &user_b_threshold)
);
if out_bool {
println!("A lives nearby. B should meet A.");
} else {
println!("A lives too far away!")
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/examples/div_by_zero.rs | examples/div_by_zero.rs | use itertools::Itertools;
use phantom_zone::*;
use rand::{thread_rng, Rng, RngCore};
fn main() {
set_parameter_set(ParameterSelector::NonInteractiveLTE2Party);
// set application's common reference seed
let mut seed = [0u8; 32];
thread_rng().fill_bytes(&mut seed);
set_common_reference_seed(seed);
let no_of_parties = 2;
// Generate client keys
let cks = (0..no_of_parties).map(|_| gen_client_key()).collect_vec();
// Generate server key shares
let server_key_shares = cks
.iter()
.enumerate()
.map(|(id, k)| gen_server_key_share(id, no_of_parties, k))
.collect_vec();
// Aggregate server key shares and set the server key
let server_key = aggregate_server_key_shares(&server_key_shares);
server_key.set_server_key();
// --------
// We attempt to divide by 0 in encrypted domain and then check whether div by 0
// error flag is set to True.
let numerator = thread_rng().gen::<u8>();
let numerator_enc = cks[0]
.encrypt(vec![numerator].as_slice())
.unseed::<Vec<Vec<u64>>>()
.key_switch(0)
.extract_at(0);
let zero_enc = cks[1]
.encrypt(vec![0].as_slice())
.unseed::<Vec<Vec<u64>>>()
.key_switch(1)
.extract_at(0);
let (quotient_enc, remainder_enc) = numerator_enc.div_rem(&zero_enc);
// When attempting to divide by zero, for uint8 quotient is always 255 and
// remainder = numerator
let quotient = cks[0].aggregate_decryption_shares(
"ient_enc,
&cks.iter()
.map(|k| k.gen_decryption_share("ient_enc))
.collect_vec(),
);
let remainder = cks[0].aggregate_decryption_shares(
&remainder_enc,
&cks.iter()
.map(|k| k.gen_decryption_share(&remainder_enc))
.collect_vec(),
);
assert!(quotient == 255);
assert!(remainder == numerator);
// Div by zero error flag must be True
let div_by_zero_enc = div_zero_error_flag().expect("We performed division. Flag must be set");
let div_by_zero = cks[0].aggregate_decryption_shares(
&div_by_zero_enc,
&cks.iter()
.map(|k| k.gen_decryption_share(&div_by_zero_enc))
.collect_vec(),
);
assert!(div_by_zero == true);
// -------
// div by zero error flag is thread local. If we were to run another circuit
// without stopping the thread (i.e. within the same program as previous
// one), we must reset errors flags set by previous circuit with
// `reset_error_flags()` to prevent error flags of previous circuit affecting
// the flags of the next circuit.
reset_error_flags();
// We divide again but with non-zero denominator this time and check that div
// by zero flag is set to False
let numerator = thread_rng().gen::<u8>();
let mut denominator = thread_rng().gen::<u8>();
while denominator == 0 {
denominator = thread_rng().gen::<u8>();
}
let numerator_enc = cks[0]
.encrypt(vec![numerator].as_slice())
.unseed::<Vec<Vec<u64>>>()
.key_switch(0)
.extract_at(0);
let denominator_enc = cks[1]
.encrypt(vec![denominator].as_slice())
.unseed::<Vec<Vec<u64>>>()
.key_switch(1)
.extract_at(0);
let (quotient_enc, remainder_enc) = numerator_enc.div_rem(&denominator_enc);
let quotient = cks[0].aggregate_decryption_shares(
"ient_enc,
&cks.iter()
.map(|k| k.gen_decryption_share("ient_enc))
.collect_vec(),
);
let remainder = cks[0].aggregate_decryption_shares(
&remainder_enc,
&cks.iter()
.map(|k| k.gen_decryption_share(&remainder_enc))
.collect_vec(),
);
assert!(quotient == numerator.div_euclid(denominator));
assert!(remainder == numerator.rem_euclid(denominator));
// Div by zero error flag must be set to False
let div_by_zero_enc = div_zero_error_flag().expect("We performed division. Flag must be set");
let div_by_zero = cks[0].aggregate_decryption_shares(
&div_by_zero_enc,
&cks.iter()
.map(|k| k.gen_decryption_share(&div_by_zero_enc))
.collect_vec(),
);
assert!(div_by_zero == false);
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/lib.rs | ipc/wallet/src/lib.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use std::str::FromStr;
use anyhow::anyhow;
use serde::{Deserialize, Serialize};
mod evm;
mod fvm;
#[cfg(feature = "with-ethers")]
pub use crate::evm::{random_eth_key_info, EthKeyAddress};
pub use crate::evm::{
KeyInfo as EvmKeyInfo, KeyStore as EvmKeyStore, PersistentKeyInfo, PersistentKeyStore,
DEFAULT_KEYSTORE_NAME,
};
pub use crate::fvm::*;
/// WalletType determines the kind of keys and wallets
/// supported in the keystore
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "network_type")]
pub enum WalletType {
Evm,
Fvm,
}
impl FromStr for WalletType {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"evm" => Self::Evm,
"fvm" => Self::Fvm,
_ => return Err(anyhow!("invalid wallet type")),
})
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/evm/memory.rs | ipc/wallet/src/evm/memory.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Memory key store
use crate::evm::{KeyInfo, KeyStore};
use anyhow::{anyhow, Result};
use std::collections::HashMap;
use std::hash::Hash;
#[derive(Default)]
pub struct MemoryKeyStore<T> {
pub(crate) data: HashMap<T, KeyInfo>,
pub(crate) default: Option<T>,
}
impl<T: Clone + Eq + Hash + TryFrom<KeyInfo> + Default + ToString> KeyStore for MemoryKeyStore<T> {
type Key = T;
fn get(&self, addr: &Self::Key) -> Result<Option<KeyInfo>> {
Ok(self.data.get(addr).cloned())
}
fn list(&self) -> Result<Vec<Self::Key>> {
Ok(self.data.keys().cloned().collect())
}
fn put(&mut self, info: KeyInfo) -> Result<Self::Key> {
let addr = Self::Key::try_from(info.clone())
.map_err(|_| anyhow!("cannot convert private key to public key"))?;
self.data.insert(addr.clone(), info);
Ok(addr)
}
fn remove(&mut self, addr: &Self::Key) -> Result<()> {
// if the address is the default, remove also from the
// default key
if self.default == Some(addr.clone()) {
self.default = None;
self.remove(&Self::Key::default())?;
}
self.data.remove(addr);
Ok(())
}
fn set_default(&mut self, addr: &Self::Key) -> Result<()> {
let info = self.get(addr)?;
match info {
Some(i) => self.data.insert(Self::Key::default(), i),
None => return Err(anyhow!("can't set default key: not found in keystore")),
};
self.default = Some(addr.clone());
Ok(())
}
fn get_default(&mut self) -> Result<Option<Self::Key>> {
// check the map if it doesn't exists
if self.default.is_none() {
if let Some(info) = self.get(&Self::Key::default())? {
self.default = Some(
Self::Key::try_from(info)
.map_err(|_| anyhow!("couldn't get address from key info"))?,
);
return Ok(self.default.clone());
}
}
// if it exists return it directly
Ok(self.default.clone())
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/evm/mod.rs | ipc/wallet/src/evm/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Ethereum wallet key store.
mod memory;
mod persistent;
use anyhow::Result;
use std::fmt::{Display, Formatter};
use std::hash::Hash;
use zeroize::Zeroize;
#[cfg(feature = "with-ethers")]
use std::str::FromStr;
pub use crate::evm::persistent::{PersistentKeyInfo, PersistentKeyStore};
pub const DEFAULT_KEYSTORE_NAME: &str = "evm_keystore.json";
/// The key store trait for different evm key store
pub trait KeyStore {
/// The type of the key that is stored
type Key: Clone + Eq + Hash + TryFrom<KeyInfo>;
/// Get the key info by address string
fn get(&self, addr: &Self::Key) -> Result<Option<KeyInfo>>;
/// List all addresses in the key store
fn list(&self) -> Result<Vec<Self::Key>>;
/// Put a new info to the addr
fn put(&mut self, info: KeyInfo) -> Result<Self::Key>;
/// Remove address from the key store
fn remove(&mut self, addr: &Self::Key) -> Result<()>;
/// Set default wallet
fn set_default(&mut self, addr: &Self::Key) -> Result<()>;
/// Get default wallet
fn get_default(&mut self) -> Result<Option<Self::Key>>;
}
/// The struct that contains evm private key info
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct KeyInfo {
private_key: Vec<u8>,
}
impl KeyInfo {
pub fn new(private_key: Vec<u8>) -> Self {
Self { private_key }
}
}
impl KeyInfo {
pub fn private_key(&self) -> &[u8] {
&self.private_key
}
}
impl Drop for KeyInfo {
fn drop(&mut self) {
self.private_key.zeroize();
}
}
#[cfg(feature = "with-ethers")]
impl TryFrom<KeyInfo> for ethers::types::Address {
type Error = anyhow::Error;
fn try_from(value: KeyInfo) -> std::result::Result<Self, Self::Error> {
use ethers::signers::Signer;
let key = ethers::signers::Wallet::from_bytes(&value.private_key)?;
Ok(key.address())
}
}
#[cfg(feature = "with-ethers")]
impl FromStr for EthKeyAddress {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let inner = ethers::types::Address::from_str(s)?;
Ok(EthKeyAddress { inner })
}
}
#[cfg(feature = "with-ethers")]
pub fn random_eth_key_info() -> KeyInfo {
let key = ethers::core::k256::SecretKey::random(&mut rand::thread_rng());
KeyInfo::new(key.to_bytes().to_vec())
}
#[cfg(feature = "with-ethers")]
#[derive(Debug, Clone, Eq, Hash, PartialEq, Default)]
pub struct EthKeyAddress {
inner: ethers::types::Address,
}
#[cfg(feature = "with-ethers")]
impl From<ethers::types::Address> for EthKeyAddress {
fn from(inner: ethers::types::Address) -> Self {
EthKeyAddress { inner }
}
}
#[cfg(feature = "with-ethers")]
impl TryFrom<EthKeyAddress> for fvm_shared::address::Address {
type Error = hex::FromHexError;
fn try_from(value: EthKeyAddress) -> std::result::Result<Self, Self::Error> {
Ok(fvm_shared::address::Address::from(
&ipc_types::EthAddress::from_str(&value.to_string())?,
))
}
}
#[cfg(feature = "with-ethers")]
impl From<EthKeyAddress> for ethers::types::Address {
fn from(val: EthKeyAddress) -> Self {
val.inner
}
}
#[cfg(feature = "with-ethers")]
impl Display for EthKeyAddress {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self == &Self::default() {
write!(f, "default-key")
} else {
write!(f, "{:?}", self.inner)
}
}
}
#[cfg(feature = "with-ethers")]
impl TryFrom<KeyInfo> for EthKeyAddress {
type Error = anyhow::Error;
fn try_from(value: KeyInfo) -> std::result::Result<Self, Self::Error> {
Ok(Self {
inner: ethers::types::Address::try_from(value)?,
})
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/evm/persistent.rs | ipc/wallet/src/evm/persistent.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Persistent file key store
use crate::evm::memory::MemoryKeyStore;
use crate::evm::{KeyInfo, KeyStore};
use anyhow::anyhow;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::hash::Hash;
use std::io::{BufReader, BufWriter, ErrorKind};
use std::path::PathBuf;
use zeroize::Zeroize;
#[derive(Default)]
pub struct PersistentKeyStore<T> {
memory: MemoryKeyStore<T>,
file_path: PathBuf,
}
/// The persistent key information written to disk
#[derive(Serialize, Deserialize)]
pub struct PersistentKeyInfo {
/// The address associated with the private key. We can derive this from the private key
/// but for the ease of debugging, we keep this field
address: String,
/// Hex encoded private key
private_key: String,
}
impl PersistentKeyInfo {
pub fn new(address: String, private_key: String) -> Self {
Self {
address,
private_key,
}
}
pub fn private_key(&self) -> &str {
&self.private_key
}
}
impl Drop for PersistentKeyInfo {
fn drop(&mut self) {
self.private_key.zeroize();
}
}
impl<T: Clone + Eq + Hash + TryFrom<KeyInfo> + Default + ToString> KeyStore
for PersistentKeyStore<T>
{
type Key = T;
fn get(&self, addr: &Self::Key) -> Result<Option<KeyInfo>> {
self.memory.get(addr)
}
fn list(&self) -> Result<Vec<Self::Key>> {
self.memory.list()
}
fn put(&mut self, info: KeyInfo) -> Result<Self::Key> {
let addr = self.memory.put(info)?;
self.flush_no_encryption()?;
Ok(addr)
}
fn remove(&mut self, addr: &Self::Key) -> Result<()> {
self.memory.remove(addr)?;
self.flush_no_encryption()
}
fn set_default(&mut self, addr: &Self::Key) -> Result<()> {
self.memory.set_default(addr)?;
self.flush_no_encryption()
}
fn get_default(&mut self) -> Result<Option<Self::Key>> {
let default = self.memory.get_default()?;
self.flush_no_encryption()?;
Ok(default)
}
}
impl<T: Clone + Eq + Hash + TryFrom<KeyInfo> + Default + ToString> PersistentKeyStore<T> {
pub fn new(path: PathBuf) -> Result<Self> {
if let Some(p) = path.parent() {
if !p.exists() {
return Err(anyhow!("parent does not exist for key store"));
}
}
let p = match File::open(&path) {
Ok(p) => p,
Err(e) => {
return if e.kind() == ErrorKind::NotFound {
log::info!("key store does not exist, initialized to empty key store");
Ok(Self {
memory: MemoryKeyStore {
data: Default::default(),
default: None,
},
file_path: path,
})
} else {
Err(anyhow!("cannot create key store: {e:}"))
};
}
};
let reader = BufReader::new(p);
let persisted_key_info: Vec<PersistentKeyInfo> =
serde_json::from_reader(reader).map_err(|e| {
anyhow!(
"failed to deserialize keyfile, initializing new keystore at: {:?} due to: {e:}",
path
)
})?;
let mut key_infos = HashMap::new();
for info in persisted_key_info.iter() {
let key_info = KeyInfo {
private_key: hex::decode(&info.private_key)?,
};
let mut addr = T::default();
// only infer the address if this is not the default key
if info.address != addr.to_string() {
addr = T::try_from(key_info.clone())
.map_err(|_| anyhow!("cannot convert private key to address"))?;
}
key_infos.insert(addr, key_info);
}
// check if there is default in the keystore
let default = match key_infos.get(&T::default()) {
Some(i) => Some(
T::try_from(i.clone()).map_err(|_| anyhow!("couldn't get info for default key"))?,
),
None => None,
};
Ok(Self {
memory: MemoryKeyStore {
data: key_infos,
default,
},
file_path: path,
})
}
/// Write all keys to file without any encryption.
fn flush_no_encryption(&self) -> Result<()> {
let dir = self
.file_path
.parent()
.ok_or_else(|| anyhow!("Key store parent path not exists"))?;
fs::create_dir_all(dir)?;
let file = File::create(&self.file_path)?;
// TODO: do we need to set path permission?
let writer = BufWriter::new(file);
let to_persist = self
.memory
.data
.iter()
.map(|(key, val)| {
let private_key = hex::encode(&val.private_key);
let address = key.to_string();
PersistentKeyInfo {
address,
private_key,
}
})
.collect::<Vec<_>>();
serde_json::to_writer_pretty(writer, &to_persist)
.map_err(|e| anyhow!("failed to serialize and write key info: {e}"))?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::evm::KeyInfo;
use crate::{EvmKeyStore, PersistentKeyStore};
use std::fmt::{Display, Formatter};
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
struct Key {
data: String,
}
impl TryFrom<KeyInfo> for Key {
type Error = ();
fn try_from(value: KeyInfo) -> Result<Self, Self::Error> {
Ok(Key {
data: hex::encode(value.private_key.clone()),
})
}
}
impl Default for Key {
fn default() -> Self {
Self {
data: String::from("default-key"),
}
}
}
impl Display for Key {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.data)
}
}
#[test]
fn test_read_write_keystore() {
let keystore_folder = tempfile::tempdir().unwrap().into_path();
let keystore_location = keystore_folder.join("eth_keystore");
let mut ks = PersistentKeyStore::new(keystore_location.clone()).unwrap();
let key_info = KeyInfo {
private_key: vec![0, 1, 2],
};
let addr = Key::try_from(key_info.clone()).unwrap();
ks.put(key_info.clone()).unwrap();
let key_from_store = ks.get(&addr).unwrap();
assert!(key_from_store.is_some());
assert_eq!(key_from_store.unwrap(), key_info);
// Create the key store again
let ks = PersistentKeyStore::new(keystore_location).unwrap();
let key_from_store = ks.get(&addr).unwrap();
assert!(key_from_store.is_some());
assert_eq!(key_from_store.unwrap(), key_info);
}
#[test]
fn test_default() {
let keystore_folder = tempfile::tempdir().unwrap().into_path();
let keystore_location = keystore_folder.join("eth_keystore");
let mut ks = PersistentKeyStore::new(keystore_location.clone()).unwrap();
let key_info = KeyInfo {
private_key: vec![0, 1, 2],
};
let addr = Key::try_from(key_info.clone()).unwrap();
// can't set default if the key hasn't been put yet.
assert!(ks.set_default(&addr).is_err());
ks.put(key_info.clone()).unwrap();
ks.set_default(&addr).unwrap();
assert_eq!(ks.get_default().unwrap().unwrap(), addr);
// set other default
let new_key = KeyInfo {
private_key: vec![0, 1, 3],
};
let new_addr = Key::try_from(new_key.clone()).unwrap();
ks.put(new_key.clone()).unwrap();
ks.set_default(&new_addr).unwrap();
assert_eq!(ks.get_default().unwrap().unwrap(), new_addr);
// Create the key store again
let mut ks = PersistentKeyStore::new(keystore_location).unwrap();
let key_from_store = ks.get(&addr).unwrap();
assert!(key_from_store.is_some());
assert_eq!(key_from_store.unwrap(), key_info);
let key_from_store = ks.get(&Key::default()).unwrap();
assert!(key_from_store.is_some());
// the default is also recovered from persistent storage
assert_eq!(ks.get_default().unwrap().unwrap(), new_addr);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/fvm/errors.rs | ipc/wallet/src/fvm/errors.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::io;
use thiserror::Error;
#[derive(Debug, PartialEq, Eq, Error)]
pub enum Error {
/// info that corresponds to key does not exist
#[error("Key info not found")]
KeyInfo,
/// Key already exists in key store
#[error("Key already exists")]
KeyExists,
#[error("Key does not exist")]
KeyNotExists,
#[error("Key not found")]
NoKey,
#[error("IO Error: {0}")]
IO(String),
#[error("{0}")]
Other(String),
#[error("Could not convert from KeyInfo to Key")]
KeyInfoConversion,
}
impl From<io::Error> for Error {
fn from(f: io::Error) -> Self {
Error::IO(f.to_string())
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/fvm/serialization.rs | ipc/wallet/src/fvm/serialization.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
pub mod json {
use base64::{prelude::BASE64_STANDARD, Engine};
use fvm_shared::crypto::signature::{Signature, SignatureType};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
// Wrapper for serializing and deserializing a Signature from JSON.
#[derive(Deserialize, Serialize)]
#[serde(transparent)]
pub struct SignatureJson(#[serde(with = "self")] pub Signature);
/// Wrapper for serializing a Signature reference to JSON.
#[derive(Serialize)]
#[serde(transparent)]
pub struct SignatureJsonRef<'a>(#[serde(with = "self")] pub &'a Signature);
#[derive(Serialize, Deserialize)]
struct JsonHelper {
#[serde(rename = "Type")]
sig_type: SignatureType,
#[serde(rename = "Data")]
bytes: String,
}
pub fn serialize<S>(m: &Signature, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
JsonHelper {
sig_type: m.signature_type(),
bytes: BASE64_STANDARD.encode(&m.bytes),
}
.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Signature, D::Error>
where
D: Deserializer<'de>,
{
let JsonHelper { sig_type, bytes } = Deserialize::deserialize(deserializer)?;
Ok(Signature {
sig_type,
bytes: BASE64_STANDARD.decode(bytes).map_err(de::Error::custom)?,
})
}
#[allow(dead_code)]
pub mod opt {
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
use super::{Signature, SignatureJson, SignatureJsonRef};
pub fn serialize<S>(v: &Option<Signature>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
v.as_ref().map(SignatureJsonRef).serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Signature>, D::Error>
where
D: Deserializer<'de>,
{
let s: Option<SignatureJson> = Deserialize::deserialize(deserializer)?;
Ok(s.map(|v| v.0))
}
}
pub mod signature_type {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::*;
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
enum JsonHelperEnum {
Bls,
Secp256k1,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SignatureTypeJson(#[serde(with = "self")] pub SignatureType);
pub fn serialize<S>(m: &SignatureType, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let json = match *m {
SignatureType::BLS => JsonHelperEnum::Bls,
SignatureType::Secp256k1 => JsonHelperEnum::Secp256k1,
};
json.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<SignatureType, D::Error>
where
D: Deserializer<'de>,
{
let json_enum: JsonHelperEnum = Deserialize::deserialize(deserializer)?;
let signature_type = match json_enum {
JsonHelperEnum::Bls => SignatureType::BLS,
JsonHelperEnum::Secp256k1 => SignatureType::Secp256k1,
};
Ok(signature_type)
}
}
}
#[cfg(test)]
mod tests {
use fvm_shared::crypto::signature::{Signature, SignatureType};
use quickcheck_macros::quickcheck;
use super::json::{signature_type::SignatureTypeJson, SignatureJson, SignatureJsonRef};
// Auxiliary impl to support quickcheck
#[derive(Clone, Debug, PartialEq, Eq, Copy)]
struct SigTypeWrapper(SignatureType);
impl quickcheck::Arbitrary for SigTypeWrapper {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let sig_type = match u8::arbitrary(g) % 2 {
0 => SignatureType::BLS,
1 => SignatureType::Secp256k1,
_ => unreachable!(),
};
SigTypeWrapper(sig_type)
}
}
// Auxiliary impl to support quickcheck
#[derive(Clone, Debug, PartialEq)]
struct SignatureWrapper(Signature);
impl quickcheck::Arbitrary for SignatureWrapper {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let sig_type = SigTypeWrapper::arbitrary(g).0;
let bytes = Vec::<u8>::arbitrary(g);
SignatureWrapper(Signature { sig_type, bytes })
}
}
#[quickcheck]
fn signature_roundtrip(signature: SignatureWrapper) {
let signature = signature.0;
let serialized = serde_json::to_string(&SignatureJsonRef(&signature)).unwrap();
let parsed: SignatureJson = serde_json::from_str(&serialized).unwrap();
assert_eq!(signature, parsed.0);
}
#[quickcheck]
fn signaturetype_roundtrip(sigtype: SigTypeWrapper) {
let sigtype = sigtype.0;
let serialized = serde_json::to_string(&SignatureTypeJson(sigtype)).unwrap();
let parsed: SignatureTypeJson = serde_json::from_str(&serialized).unwrap();
assert_eq!(sigtype, parsed.0);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/fvm/wallet_helpers.rs | ipc/wallet/src/fvm/wallet_helpers.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use blake2b_simd::Params;
use bls_signatures::{PrivateKey as BlsPrivate, Serialize};
use fvm_shared::{
address::Address,
crypto::signature::{Signature, SignatureType},
};
use libsecp256k1::{Message as SecpMessage, PublicKey as SecpPublic, SecretKey as SecpPrivate};
use rand::rngs::OsRng;
use super::errors::Error;
/// Generates BLAKE2b hash of fixed 32 bytes size.
pub fn blake2b_256(ingest: &[u8]) -> [u8; 32] {
let digest = Params::new()
.hash_length(32)
.to_state()
.update(ingest)
.finalize();
let mut ret = [0u8; 32];
ret.clone_from_slice(digest.as_bytes());
ret
}
/// Return the public key for a given private key and `SignatureType`
pub fn to_public(sig_type: SignatureType, private_key: &[u8]) -> Result<Vec<u8>, Error> {
match sig_type {
SignatureType::BLS => Ok(BlsPrivate::from_bytes(private_key)
.map_err(|err| Error::Other(err.to_string()))?
.public_key()
.as_bytes()),
SignatureType::Secp256k1 => {
let private_key = SecpPrivate::parse_slice(private_key)
.map_err(|err| Error::Other(err.to_string()))?;
let public_key = SecpPublic::from_secret_key(&private_key);
Ok(public_key.serialize().to_vec())
}
}
}
/// Return a new Address that is of a given `SignatureType` and uses the
/// supplied public key
pub fn new_address(sig_type: SignatureType, public_key: &[u8]) -> Result<Address, Error> {
match sig_type {
SignatureType::BLS => {
let addr = Address::new_bls(public_key).map_err(|err| Error::Other(err.to_string()))?;
Ok(addr)
}
SignatureType::Secp256k1 => {
let addr =
Address::new_secp256k1(public_key).map_err(|err| Error::Other(err.to_string()))?;
Ok(addr)
}
}
}
/// Sign takes in `SignatureType`, private key and message. Returns a Signature
/// for that message
pub fn sign(sig_type: SignatureType, private_key: &[u8], msg: &[u8]) -> Result<Signature, Error> {
match sig_type {
SignatureType::BLS => {
let priv_key =
BlsPrivate::from_bytes(private_key).map_err(|err| Error::Other(err.to_string()))?;
// this returns a signature from bls-signatures, so we need to convert this to a
// crypto signature
let sig = priv_key.sign(msg);
let crypto_sig = Signature::new_bls(sig.as_bytes());
Ok(crypto_sig)
}
SignatureType::Secp256k1 => {
let priv_key = SecpPrivate::parse_slice(private_key)
.map_err(|err| Error::Other(err.to_string()))?;
let msg_hash = blake2b_256(msg);
let message = SecpMessage::parse(&msg_hash);
let (sig, recovery_id) = libsecp256k1::sign(&message, &priv_key);
let mut new_bytes = [0; 65];
new_bytes[..64].copy_from_slice(&sig.serialize());
new_bytes[64] = recovery_id.serialize();
let crypto_sig = Signature::new_secp256k1(new_bytes.to_vec());
Ok(crypto_sig)
}
}
}
/// Generate a new private key
pub fn generate(sig_type: SignatureType) -> Result<Vec<u8>, Error> {
let rng = &mut OsRng;
match sig_type {
SignatureType::BLS => {
let key = BlsPrivate::generate(rng);
Ok(key.as_bytes())
}
SignatureType::Secp256k1 => {
let key = SecpPrivate::random(rng);
Ok(key.serialize().to_vec())
}
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/fvm/utils.rs | ipc/wallet/src/fvm/utils.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::fs::File;
use std::io::Result;
/// Restricts permissions on a file to user-only: 0600
#[cfg(unix)]
pub fn set_user_perm(file: &File) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
use log::info;
let mut perm = file.metadata()?.permissions();
#[allow(clippy::useless_conversion)] // Otherwise it does not build on macos
perm.set_mode((libc::S_IWUSR | libc::S_IRUSR).into());
file.set_permissions(perm)?;
info!("Permissions set to 0600 on {:?}", file);
Ok(())
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/fvm/keystore.rs | ipc/wallet/src/fvm/keystore.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{
fmt::Display,
fs::{self, create_dir, File},
io::{BufReader, BufWriter, ErrorKind, Read, Write},
path::{Path, PathBuf},
};
use ahash::{HashMap, HashMapExt};
use argon2::{
password_hash::SaltString, Argon2, ParamsBuilder, PasswordHasher, RECOMMENDED_SALT_LEN,
};
use base64::{prelude::BASE64_STANDARD, Engine};
use fvm_shared::crypto::signature::SignatureType;
use log::{debug, error};
use rand::{rngs::OsRng, RngCore};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use xsalsa20poly1305::{
aead::{generic_array::GenericArray, Aead},
KeyInit, XSalsa20Poly1305, NONCE_SIZE,
};
use super::errors::Error;
pub const KEYSTORE_NAME: &str = "keystore.json";
pub const ENCRYPTED_KEYSTORE_NAME: &str = "keystore";
/// Environmental variable which holds the `KeyStore` encryption phrase.
pub const FOREST_KEYSTORE_PHRASE_ENV: &str = "FOREST_KEYSTORE_PHRASE";
type SaltByteArray = [u8; RECOMMENDED_SALT_LEN];
// TODO need to update keyinfo to not use SignatureType, use string instead to
// save keys like jwt secret
/// `KeyInfo` structure, this contains the type of key (stored as a string) and
/// the private key. Note how the private key is stored as a byte vector
#[derive(Clone, PartialEq, Debug, Eq, Serialize, Deserialize)]
pub struct KeyInfo {
key_type: SignatureType,
// Vec<u8> is used because The private keys for BLS and SECP256K1 are not of the same type
private_key: Vec<u8>,
}
#[derive(Clone, PartialEq, Debug, Eq, Serialize, Deserialize)]
pub struct PersistentKeyInfo {
key_type: SignatureType,
private_key: String,
}
impl KeyInfo {
/// Return a new `KeyInfo` given the key type and private key
pub fn new(key_type: SignatureType, private_key: Vec<u8>) -> Self {
KeyInfo {
key_type,
private_key,
}
}
/// Return a reference to the key's signature type
pub fn key_type(&self) -> &SignatureType {
&self.key_type
}
/// Return a reference to the private key
pub fn private_key(&self) -> &Vec<u8> {
&self.private_key
}
}
pub mod json {
use crate::fvm::serialization::json::signature_type::SignatureTypeJson;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use super::*;
/// Wrapper for serializing and de-serializing a `KeyInfo` from JSON.
#[derive(Clone, Deserialize, Serialize, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub struct KeyInfoJson(#[serde(with = "self")] pub KeyInfo);
/// Wrapper for serializing a `KeyInfo` reference to JSON.
#[derive(Serialize)]
#[serde(transparent)]
pub struct KeyInfoJsonRef<'a>(#[serde(with = "self")] pub &'a KeyInfo);
impl From<KeyInfoJson> for KeyInfo {
fn from(key: KeyInfoJson) -> KeyInfo {
key.0
}
}
#[derive(Serialize, Deserialize)]
struct JsonHelper {
#[serde(rename = "Type")]
sig_type: SignatureTypeJson,
#[serde(rename = "PrivateKey")]
private_key: String,
}
pub fn serialize<S>(k: &KeyInfo, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
JsonHelper {
sig_type: SignatureTypeJson(k.key_type),
private_key: BASE64_STANDARD.encode(&k.private_key),
}
.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<KeyInfo, D::Error>
where
D: Deserializer<'de>,
{
let JsonHelper {
sig_type,
private_key,
} = Deserialize::deserialize(deserializer)?;
Ok(KeyInfo {
key_type: sig_type.0,
private_key: BASE64_STANDARD
.decode(private_key)
.map_err(de::Error::custom)?,
})
}
}
/// `KeyStore` structure, this contains a set of `KeyInfos` indexed by address.
#[derive(Clone, PartialEq, Debug, Eq)]
pub struct KeyStore {
key_info: HashMap<String, KeyInfo>,
persistence: Option<PersistentKeyStore>,
encryption: Option<EncryptedKeyStore>,
}
pub enum KeyStoreConfig {
Memory,
Persistent(PathBuf),
Encrypted(PathBuf, String),
}
/// Persistent `KeyStore` in JSON clear text in `KEYSTORE_LOCATION`
#[derive(Clone, PartialEq, Debug, Eq)]
struct PersistentKeyStore {
file_path: PathBuf,
}
/// Encrypted `KeyStore`
/// `Argon2id` hash key derivation
/// `XSalsa20Poly1305` authenticated encryption
/// CBOR encoding
#[derive(Clone, PartialEq, Debug, Eq)]
struct EncryptedKeyStore {
salt: SaltByteArray,
encryption_key: Vec<u8>,
}
#[derive(Debug, Error)]
pub enum EncryptedKeyStoreError {
/// Possibly indicates incorrect passphrase
#[error("Error decrypting data")]
DecryptionError,
/// An error occurred while encrypting keys
#[error("Error encrypting data")]
EncryptionError,
/// Unlock called without `encrypted_keystore` being enabled in
/// `config.toml`
#[error("Error with forest configuration")]
ConfigurationError,
}
impl KeyStore {
pub fn new(config: KeyStoreConfig) -> Result<Self, Error> {
match config {
KeyStoreConfig::Memory => Ok(Self {
key_info: HashMap::new(),
persistence: None,
encryption: None,
}),
KeyStoreConfig::Persistent(location) => {
let file_path = location.join(KEYSTORE_NAME);
match File::open(&file_path) {
Ok(file) => {
let reader = BufReader::new(file);
// Existing cleartext JSON keystore
let persisted_key_info: HashMap<String, PersistentKeyInfo> =
serde_json::from_reader(reader)
.map_err(|e| {
error!(
"failed to deserialize keyfile, initializing new keystore at: {:?}",
file_path
);
e
})
.unwrap_or_default();
let mut key_info = HashMap::new();
for (key, value) in persisted_key_info.iter() {
key_info.insert(
key.to_string(),
KeyInfo {
private_key: BASE64_STANDARD
.decode(value.private_key.clone())
.map_err(|error| Error::Other(error.to_string()))?,
key_type: value.key_type,
},
);
}
Ok(Self {
key_info,
persistence: Some(PersistentKeyStore { file_path }),
encryption: None,
})
}
Err(e) => {
if e.kind() == ErrorKind::NotFound {
debug!(
"Keystore does not exist, initializing new keystore at: {:?}",
file_path
);
Ok(Self {
key_info: HashMap::new(),
persistence: Some(PersistentKeyStore { file_path }),
encryption: None,
})
} else {
Err(Error::Other(e.to_string()))
}
}
}
}
KeyStoreConfig::Encrypted(location, passphrase) => {
if !location.exists() {
create_dir(location.clone())?;
}
let file_path = location.join(Path::new(ENCRYPTED_KEYSTORE_NAME));
if !file_path.exists() {
File::create(file_path.clone())?;
}
match File::open(&file_path) {
Ok(file) => {
let mut reader = BufReader::new(file);
let mut buf = vec![];
let read_bytes = reader.read_to_end(&mut buf)?;
if read_bytes == 0 {
// New encrypted keystore if file exists but is zero bytes (i.e., touch)
debug!(
"Keystore does not exist, initializing new keystore at {:?}",
file_path
);
let (salt, encryption_key) =
EncryptedKeyStore::derive_key(&passphrase, None).map_err(
|error| {
error!("Failed to create key from passphrase");
Error::Other(error.to_string())
},
)?;
Ok(Self {
key_info: HashMap::new(),
persistence: Some(PersistentKeyStore { file_path }),
encryption: Some(EncryptedKeyStore {
salt,
encryption_key,
}),
})
} else {
// Existing encrypted keystore
// Split off data from prepended salt
let data = buf.split_off(RECOMMENDED_SALT_LEN);
let mut prev_salt = [0; RECOMMENDED_SALT_LEN];
prev_salt.copy_from_slice(&buf);
let (salt, encryption_key) =
EncryptedKeyStore::derive_key(&passphrase, Some(prev_salt))
.map_err(|error| {
error!("Failed to create key from passphrase");
Error::Other(error.to_string())
})?;
let decrypted_data = EncryptedKeyStore::decrypt(&encryption_key, &data)
.map_err(|error| Error::Other(error.to_string()))?;
let key_info = serde_ipld_dagcbor::from_slice(&decrypted_data)
.map_err(|e| {
error!("Failed to deserialize keyfile, initializing new");
e
})
.unwrap_or_default();
Ok(Self {
key_info,
persistence: Some(PersistentKeyStore { file_path }),
encryption: Some(EncryptedKeyStore {
salt,
encryption_key,
}),
})
}
}
Err(_) => {
debug!("Encrypted keystore does not exist, initializing new keystore");
let (salt, encryption_key) =
EncryptedKeyStore::derive_key(&passphrase, None).map_err(|error| {
error!("Failed to create key from passphrase");
Error::Other(error.to_string())
})?;
Ok(Self {
key_info: HashMap::new(),
persistence: Some(PersistentKeyStore { file_path }),
encryption: Some(EncryptedKeyStore {
salt,
encryption_key,
}),
})
}
}
}
}
}
pub fn flush(&self) -> anyhow::Result<()> {
match &self.persistence {
Some(persistent_keystore) => {
let dir = persistent_keystore
.file_path
.parent()
.ok_or_else(|| Error::Other("Invalid Path".to_string()))?;
fs::create_dir_all(dir)?;
let file = File::create(&persistent_keystore.file_path)?;
// Restrict permissions on files containing private keys
#[cfg(unix)]
crate::utils::set_user_perm(&file)?;
let mut writer = BufWriter::new(file);
match &self.encryption {
Some(encrypted_keystore) => {
// Flush For EncryptedKeyStore
let data = serde_ipld_dagcbor::to_vec(&self.key_info).map_err(|e| {
Error::Other(format!("failed to serialize and write key info: {e}"))
})?;
let encrypted_data =
EncryptedKeyStore::encrypt(&encrypted_keystore.encryption_key, &data)?;
let mut salt_vec = encrypted_keystore.salt.to_vec();
salt_vec.extend(encrypted_data);
writer.write_all(&salt_vec)?;
Ok(())
}
None => {
let mut key_info: HashMap<String, PersistentKeyInfo> = HashMap::new();
for (key, value) in self.key_info.iter() {
key_info.insert(
key.to_string(),
PersistentKeyInfo {
private_key: BASE64_STANDARD.encode(value.private_key.clone()),
key_type: value.key_type,
},
);
}
// Flush for PersistentKeyStore
serde_json::to_writer_pretty(writer, &key_info).map_err(|e| {
Error::Other(format!("failed to serialize and write key info: {e}"))
})?;
Ok(())
}
}
}
None => {
// NoOp for MemKeyStore
Ok(())
}
}
}
/// Return all of the keys that are stored in the `KeyStore`
pub fn list(&self) -> Vec<String> {
self.key_info.keys().cloned().collect()
}
/// Return `KeyInfo` that corresponds to a given key
pub fn get(&self, k: &str) -> Result<KeyInfo, Error> {
self.key_info.get(k).cloned().ok_or(Error::KeyInfo)
}
/// Save a key/`KeyInfo` pair to the `KeyStore`
pub fn put(&mut self, key: String, key_info: KeyInfo) -> Result<(), Error> {
if self.key_info.contains_key(&key) {
return Err(Error::KeyExists);
}
self.key_info.insert(key, key_info);
if self.persistence.is_some() {
self.flush().map_err(|err| Error::Other(err.to_string()))?;
}
Ok(())
}
/// Remove the key and corresponding `KeyInfo` from the `KeyStore`
pub fn remove(&mut self, key: String) -> anyhow::Result<KeyInfo> {
let key_out = self.key_info.remove(&key).ok_or(Error::KeyInfo)?;
if self.persistence.is_some() {
self.flush()?;
}
Ok(key_out)
}
}
impl EncryptedKeyStore {
fn derive_key(
passphrase: &str,
prev_salt: Option<SaltByteArray>,
) -> anyhow::Result<(SaltByteArray, Vec<u8>)> {
let salt = match prev_salt {
Some(prev_salt) => prev_salt,
None => {
let mut salt = [0; RECOMMENDED_SALT_LEN];
OsRng.fill_bytes(&mut salt);
salt
}
};
let mut param_builder = ParamsBuilder::new();
// #define crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE 67108864U
// see <https://github.com/jedisct1/libsodium/blob/089f850608737f9d969157092988cb274fe7f8d4/src/libsodium/include/sodium/crypto_pwhash_argon2id.h#L70>
const CRYPTO_PWHASH_ARGON2ID_MEMLIMIT_INTERACTIVE: u32 = 67108864;
// #define crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE 2U
// see <https://github.com/jedisct1/libsodium/blob/089f850608737f9d969157092988cb274fe7f8d4/src/libsodium/include/sodium/crypto_pwhash_argon2id.h#L66>
const CRYPTO_PWHASH_ARGON2ID_OPSLIMIT_INTERACTIVE: u32 = 2;
param_builder
.m_cost(CRYPTO_PWHASH_ARGON2ID_MEMLIMIT_INTERACTIVE / 1024)
.t_cost(CRYPTO_PWHASH_ARGON2ID_OPSLIMIT_INTERACTIVE);
// https://docs.rs/sodiumoxide/latest/sodiumoxide/crypto/secretbox/xsalsa20poly1305/constant.KEYBYTES.html
// KEYBYTES = 0x20
// param_builder.output_len(32)?;
let hasher = Argon2::new(
argon2::Algorithm::Argon2id,
argon2::Version::V0x13,
param_builder.build().map_err(map_err_to_anyhow)?,
);
let salt_string = SaltString::encode_b64(&salt).map_err(map_err_to_anyhow)?;
let pw_hash = hasher
.hash_password(passphrase.as_bytes(), &salt_string)
.map_err(map_err_to_anyhow)?;
if let Some(hash) = pw_hash.hash {
Ok((salt, hash.as_bytes().to_vec()))
} else {
anyhow::bail!(EncryptedKeyStoreError::EncryptionError)
}
}
fn encrypt(encryption_key: &[u8], msg: &[u8]) -> anyhow::Result<Vec<u8>> {
let mut nonce = [0; NONCE_SIZE];
OsRng.fill_bytes(&mut nonce);
let nonce = GenericArray::from_slice(&nonce);
let key = GenericArray::from_slice(encryption_key);
let cipher = XSalsa20Poly1305::new(key);
let mut ciphertext = cipher.encrypt(nonce, msg).map_err(map_err_to_anyhow)?;
ciphertext.extend(nonce.iter());
Ok(ciphertext)
}
fn decrypt(encryption_key: &[u8], msg: &[u8]) -> anyhow::Result<Vec<u8>> {
let cyphertext_len = msg.len() - NONCE_SIZE;
let ciphertext = &msg[..cyphertext_len];
let nonce = GenericArray::from_slice(&msg[cyphertext_len..]);
let key = GenericArray::from_slice(encryption_key);
let cipher = XSalsa20Poly1305::new(key);
let plaintext = cipher
.decrypt(nonce, ciphertext)
.map_err(map_err_to_anyhow)?;
Ok(plaintext)
}
}
fn map_err_to_anyhow<T: Display>(e: T) -> anyhow::Error {
anyhow::Error::msg(e.to_string())
}
#[cfg(test)]
mod test {
use anyhow::*;
use base64::{prelude::BASE64_STANDARD, Engine};
use quickcheck_macros::quickcheck;
use super::*;
use crate::{
json::{KeyInfoJson, KeyInfoJsonRef},
wallet,
};
const PASSPHRASE: &str = "foobarbaz";
#[test]
fn test_generate_key() {
let (salt, encryption_key) = EncryptedKeyStore::derive_key(PASSPHRASE, None).unwrap();
let (second_salt, second_key) =
EncryptedKeyStore::derive_key(PASSPHRASE, Some(salt)).unwrap();
assert_eq!(
encryption_key, second_key,
"Derived key must be deterministic"
);
assert_eq!(salt, second_salt, "Salts must match");
}
#[test]
fn test_encrypt_message() -> Result<()> {
let (_, private_key) = EncryptedKeyStore::derive_key(PASSPHRASE, None)?;
let message = "foo is coming";
let ciphertext = EncryptedKeyStore::encrypt(&private_key, message.as_bytes())?;
let second_pass = EncryptedKeyStore::encrypt(&private_key, message.as_bytes())?;
ensure!(
ciphertext != second_pass,
"Ciphertexts use secure initialization vectors"
);
Ok(())
}
#[test]
fn test_decrypt_message() -> Result<()> {
let (_, private_key) = EncryptedKeyStore::derive_key(PASSPHRASE, None)?;
let message = "foo is coming";
let ciphertext = EncryptedKeyStore::encrypt(&private_key, message.as_bytes())?;
let plaintext = EncryptedKeyStore::decrypt(&private_key, &ciphertext)?;
ensure!(plaintext == message.as_bytes());
Ok(())
}
#[test]
fn test_read_old_encrypted_keystore() -> Result<()> {
let dir: PathBuf = "tests/keystore_encrypted_old".into();
ensure!(dir.exists());
let ks = KeyStore::new(KeyStoreConfig::Encrypted(dir, PASSPHRASE.to_string()))?;
ensure!(ks.persistence.is_some());
Ok(())
}
#[test]
fn test_read_write_encrypted_keystore() -> Result<()> {
let keystore_location = tempfile::tempdir()?.into_path();
let ks = KeyStore::new(KeyStoreConfig::Encrypted(
keystore_location.clone(),
PASSPHRASE.to_string(),
))?;
ks.flush()?;
let ks_read = KeyStore::new(KeyStoreConfig::Encrypted(
keystore_location,
PASSPHRASE.to_string(),
))?;
ensure!(ks == ks_read);
Ok(())
}
#[test]
fn test_read_write_keystore() -> Result<()> {
let keystore_location = tempfile::tempdir()?.into_path();
let mut ks = KeyStore::new(KeyStoreConfig::Persistent(keystore_location.clone()))?;
let key = wallet::generate_key(SignatureType::BLS)?;
let addr = format!("wallet-{}", key.address);
ks.put(addr.clone(), key.key_info)?;
ks.flush().unwrap();
let default = ks.get(&addr).unwrap();
// Manually parse keystore.json
let keystore_file = keystore_location.join(KEYSTORE_NAME);
let reader = BufReader::new(File::open(keystore_file)?);
let persisted_keystore: HashMap<String, PersistentKeyInfo> =
serde_json::from_reader(reader)?;
let default_key_info = persisted_keystore.get(&addr).unwrap();
let actual = BASE64_STANDARD.decode(default_key_info.private_key.clone())?;
assert_eq!(
default.private_key, actual,
"persisted key matches key from key store"
);
// Read existing keystore.json
let ks_read = KeyStore::new(KeyStoreConfig::Persistent(keystore_location))?;
ensure!(ks == ks_read);
Ok(())
}
impl quickcheck::Arbitrary for KeyInfo {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let sigtype = g
.choose(&[
fvm_shared::crypto::signature::SignatureType::BLS,
fvm_shared::crypto::signature::SignatureType::Secp256k1,
])
.unwrap();
KeyInfo {
key_type: *sigtype,
private_key: Vec::arbitrary(g),
}
}
}
#[quickcheck]
fn keyinfo_roundtrip(keyinfo: KeyInfo) {
let serialized: String = serde_json::to_string(&KeyInfoJsonRef(&keyinfo)).unwrap();
let parsed: KeyInfoJson = serde_json::from_str(&serialized).unwrap();
assert_eq!(keyinfo, parsed.0);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/fvm/mod.rs | ipc/wallet/src/fvm/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
pub mod errors;
pub mod keystore;
mod serialization;
pub mod utils;
pub mod wallet;
pub mod wallet_helpers;
pub use errors::*;
pub use keystore::*;
pub use utils::*;
pub use wallet::*;
pub use wallet_helpers::*;
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/wallet/src/fvm/wallet.rs | ipc/wallet/src/fvm/wallet.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
// Copyright 2019-2023 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{convert::TryFrom, str::FromStr};
use ahash::{HashMap, HashMapExt};
use fvm_shared::{
address::Address,
crypto::signature::{Signature, SignatureType},
};
use serde::{Deserialize, Serialize};
use crate::fvm::{errors::Error, wallet_helpers, KeyInfo, KeyStore};
/// A key, this contains a `KeyInfo`, an address, and a public key.
#[derive(Clone, PartialEq, Debug, Eq, Serialize, Deserialize)]
pub struct Key {
pub key_info: KeyInfo,
// Vec<u8> is used because The public keys for BLS and SECP256K1 are not of the same type
pub public_key: Vec<u8>,
pub address: Address,
}
impl TryFrom<KeyInfo> for Key {
type Error = crate::errors::Error;
fn try_from(key_info: KeyInfo) -> Result<Self, Self::Error> {
let public_key = wallet_helpers::to_public(*key_info.key_type(), key_info.private_key())?;
let address = wallet_helpers::new_address(*key_info.key_type(), &public_key)?;
Ok(Key {
key_info,
public_key,
address,
})
}
}
// This is a Wallet, it contains 2 HashMaps:
// - keys which is a HashMap of Keys resolved by their Address
// - keystore which is a HashMap of KeyInfos resolved by their Address
/// A wallet is a collection of private keys with optional persistence and
/// optional encryption.
#[derive(Clone, PartialEq, Debug, Eq)]
pub struct Wallet {
keys: HashMap<Address, Key>,
keystore: KeyStore,
}
impl Wallet {
/// Return a new wallet with a given `KeyStore`
pub fn new(keystore: KeyStore) -> Self {
Wallet {
keys: HashMap::new(),
keystore,
}
}
/// Return a wallet from a given amount of keys.
pub fn new_from_keys(keystore: KeyStore, key_vec: impl IntoIterator<Item = Key>) -> Self {
let mut keys: HashMap<Address, Key> = HashMap::new();
for item in key_vec.into_iter() {
keys.insert(item.address, item);
}
Wallet { keys, keystore }
}
// If this key does not exist in the keys hashmap, check if this key is in
// the keystore, if it is, then add it to keys, otherwise return Error
/// Return the key that is resolved by a given address,
pub fn find_key(&mut self, addr: &Address) -> Result<Key, Error> {
if let Some(k) = self.keys.get(addr) {
return Ok(k.clone());
}
let key_string = format!("wallet-{addr}");
let key_info = match self.keystore.get(&key_string) {
Ok(k) => k,
Err(_) => {
// replace with testnet prefix
self.keystore
.get(&format!("wallet-t{}", &addr.to_string()[1..]))?
}
};
let new_key = Key::try_from(key_info)?;
self.keys.insert(*addr, new_key.clone());
Ok(new_key)
}
/// Return the resultant `Signature` after signing a given message
pub fn sign(&mut self, addr: &Address, msg: &[u8]) -> Result<Signature, Error> {
// this will return an error if the key cannot be found in either the keys
// hashmap or it is not found in the keystore
let key = self.find_key(addr).map_err(|_| Error::KeyNotExists)?;
wallet_helpers::sign(*key.key_info.key_type(), key.key_info.private_key(), msg)
}
/// Return the `KeyInfo` for a given address
pub fn export(&mut self, addr: &Address) -> Result<KeyInfo, Error> {
let k = self.find_key(addr)?;
Ok(k.key_info)
}
/// Add `KeyInfo` to the wallet, return the address that resolves to this
/// newly added `KeyInfo`
pub fn import(&mut self, key_info: KeyInfo) -> Result<Address, Error> {
let k = Key::try_from(key_info)?;
let addr = format!("wallet-{}", k.address);
self.keystore.put(addr, k.key_info)?;
Ok(k.address)
}
/// Return a vector that contains all of the addresses in the wallet's
/// `KeyStore`
pub fn list_addrs(&self) -> Result<Vec<Address>, Error> {
list_addrs(&self.keystore)
}
pub fn remove(&mut self, addr: &Address) -> anyhow::Result<()> {
self.keystore.remove(addr.to_string())?;
Ok(())
}
/// Return the address of the default `KeyInfo` in the wallet
pub fn get_default(&self) -> Result<Address, Error> {
let key_info = self.keystore.get("default")?;
let k = Key::try_from(key_info)?;
Ok(k.address)
}
/// Set a default `KeyInfo` to the wallet
pub fn set_default(&mut self, addr: Address) -> anyhow::Result<()> {
let addr_string = format!("wallet-{addr}");
let key_info = self.keystore.get(&addr_string)?;
if self.keystore.get("default").is_ok() {
self.keystore.remove("default".to_string())?; // This line should
// unregister current
// default key then
// continue
}
self.keystore.put("default".to_string(), key_info)?;
Ok(())
}
/// Generate a new address that fits the requirement of the given
/// `SignatureType`
pub fn generate_addr(&mut self, typ: SignatureType) -> anyhow::Result<Address> {
let key = generate_key(typ)?;
let addr = format!("wallet-{}", key.address);
self.keystore.put(addr, key.key_info.clone())?;
self.keys.insert(key.address, key.clone());
let value = self.keystore.get("default");
if value.is_err() {
self.keystore
.put("default".to_string(), key.key_info.clone())
.map_err(|err| Error::Other(err.to_string()))?;
}
Ok(key.address)
}
/// Return whether or not the Wallet contains a key that is resolved by the
/// supplied address
pub fn has_key(&mut self, addr: &Address) -> bool {
self.find_key(addr).is_ok()
}
}
/// Return the default address for `KeyStore`
pub fn get_default(keystore: &KeyStore) -> Result<Option<Address>, Error> {
if let Ok(key_info) = keystore.get("default") {
let k = Key::try_from(key_info)?;
Ok(Some(k.address))
} else {
Ok(None)
}
}
/// Return vector of addresses sorted by their string representation in
/// `KeyStore`
pub fn list_addrs(keystore: &KeyStore) -> Result<Vec<Address>, Error> {
let mut all = keystore.list();
all.sort();
let mut out = Vec::new();
for i in all {
if let Some(addr_str) = i.strip_prefix("wallet-") {
if let Ok(addr) = Address::from_str(addr_str) {
out.push(addr);
}
}
}
Ok(out)
}
/// Returns a key corresponding to given address
pub fn find_key(addr: &Address, keystore: &KeyStore) -> Result<Key, Error> {
let key_string = format!("wallet-{addr}");
let key_info = keystore.get(&key_string)?;
let new_key = Key::try_from(key_info)?;
Ok(new_key)
}
pub fn try_find(addr: &Address, keystore: &KeyStore) -> Result<KeyInfo, Error> {
let key_string = format!("wallet-{addr}");
match keystore.get(&key_string) {
Ok(k) => Ok(k),
Err(_) => {
let mut new_addr = addr.to_string();
// Try to replace prefix with testnet, for backwards compatibility
// * We might be able to remove this, look into variants
new_addr.replace_range(0..1, "t");
let key_string = format!("wallet-{new_addr}");
let key_info = match keystore.get(&key_string) {
Ok(k) => k,
Err(_) => keystore.get(&format!("wallet-f{}", &new_addr[1..]))?,
};
Ok(key_info)
}
}
}
/// Return `KeyInfo` for given address in `KeyStore`
pub fn export_key_info(addr: &Address, keystore: &KeyStore) -> Result<KeyInfo, Error> {
let key = find_key(addr, keystore)?;
Ok(key.key_info)
}
/// Generate new key of given `SignatureType`
pub fn generate_key(typ: SignatureType) -> Result<Key, Error> {
let private_key = wallet_helpers::generate(typ)?;
let key_info = KeyInfo::new(typ, private_key);
Key::try_from(key_info)
}
/// Import `KeyInfo` into `KeyStore`
pub fn import(key_info: KeyInfo, keystore: &mut KeyStore) -> anyhow::Result<Address> {
let k = Key::try_from(key_info)?;
let addr = format!("wallet-{}", k.address);
keystore.put(addr, k.key_info)?;
Ok(k.address)
}
#[cfg(test)]
mod tests {
use crate::blake2b_256;
use anyhow::ensure;
use libsecp256k1::{Message as SecpMessage, SecretKey as SecpPrivate};
use super::*;
use crate::{generate, KeyStoreConfig};
fn construct_priv_keys() -> Vec<Key> {
let mut secp_keys = Vec::new();
let mut bls_keys = Vec::new();
for _ in 1..5 {
let secp_priv_key = generate(SignatureType::Secp256k1).unwrap();
let secp_key_info = KeyInfo::new(SignatureType::Secp256k1, secp_priv_key);
let secp_key = Key::try_from(secp_key_info).unwrap();
secp_keys.push(secp_key);
let bls_priv_key = generate(SignatureType::BLS).unwrap();
let bls_key_info = KeyInfo::new(SignatureType::BLS, bls_priv_key);
let bls_key = Key::try_from(bls_key_info).unwrap();
bls_keys.push(bls_key);
}
secp_keys.append(bls_keys.as_mut());
secp_keys
}
fn generate_wallet() -> Wallet {
let key_vec = construct_priv_keys();
Wallet::new_from_keys(KeyStore::new(KeyStoreConfig::Memory).unwrap(), key_vec)
}
#[test]
fn contains_key() {
let key_vec = construct_priv_keys();
let found_key = key_vec[0].clone();
let addr = key_vec[0].address;
let mut wallet =
Wallet::new_from_keys(KeyStore::new(KeyStoreConfig::Memory).unwrap(), key_vec);
// make sure that this address resolves to the right key
assert_eq!(wallet.find_key(&addr).unwrap(), found_key);
// make sure that has_key returns true as well
assert!(wallet.has_key(&addr));
let new_priv_key = generate(SignatureType::BLS).unwrap();
let pub_key =
wallet_helpers::to_public(SignatureType::BLS, new_priv_key.as_slice()).unwrap();
let address = Address::new_bls(pub_key.as_slice()).unwrap();
// test to see if the new key has been created and added to the wallet
assert!(!wallet.has_key(&address));
// test to make sure that the newly made key cannot be added to the wallet
// because it is not found in the keystore
assert_eq!(wallet.find_key(&address).unwrap_err(), Error::KeyInfo);
// sanity check to make sure that the key has not been added to the wallet
assert!(!wallet.has_key(&address));
}
#[test]
fn sign() {
let key_vec = construct_priv_keys();
let priv_key_bytes = key_vec[2].key_info.private_key().clone();
let addr = key_vec[2].address;
let keystore = KeyStore::new(KeyStoreConfig::Memory).unwrap();
let mut wallet = Wallet::new_from_keys(keystore, key_vec);
let msg = [0u8; 64];
let msg_sig = wallet.sign(&addr, &msg).unwrap();
let msg_complete = blake2b_256(&msg);
let message = SecpMessage::parse(&msg_complete);
let priv_key = SecpPrivate::parse_slice(&priv_key_bytes).unwrap();
let (sig, recovery_id) = libsecp256k1::sign(&message, &priv_key);
let mut new_bytes = [0; 65];
new_bytes[..64].copy_from_slice(&sig.serialize());
new_bytes[64] = recovery_id.serialize();
let actual = Signature::new_secp256k1(new_bytes.to_vec());
assert_eq!(msg_sig, actual)
}
#[test]
fn import_export() -> anyhow::Result<()> {
let key_vec = construct_priv_keys();
let key = key_vec[0].clone();
let keystore = KeyStore::new(KeyStoreConfig::Memory).unwrap();
let mut wallet = Wallet::new_from_keys(keystore, key_vec);
let key_info = wallet.export(&key.address).unwrap();
// test to see if export returns the correct key_info
assert_eq!(key_info, key.key_info);
let new_priv_key = generate(SignatureType::Secp256k1).unwrap();
let pub_key =
wallet_helpers::to_public(SignatureType::Secp256k1, new_priv_key.as_slice()).unwrap();
let test_addr = Address::new_secp256k1(pub_key.as_slice()).unwrap();
let key_info_err = wallet.export(&test_addr).unwrap_err();
// test to make sure that an error is raised when an incorrect address is added
assert_eq!(key_info_err, Error::KeyInfo);
let test_key_info = KeyInfo::new(SignatureType::Secp256k1, new_priv_key);
// make sure that key_info has been imported to wallet
assert!(wallet.import(test_key_info.clone()).is_ok());
let duplicate_error = wallet.import(test_key_info).unwrap_err();
// make sure that error is thrown when attempted to re-import a duplicate
// key_info
ensure!(duplicate_error == Error::KeyExists);
Ok(())
}
#[test]
fn list_addr() {
let key_vec = construct_priv_keys();
let mut addr_string_vec = Vec::new();
let mut key_store = KeyStore::new(KeyStoreConfig::Memory).unwrap();
for i in &key_vec {
addr_string_vec.push(i.address.to_string());
let addr_string = format!("wallet-{}", i.address);
key_store.put(addr_string, i.key_info.clone()).unwrap();
}
addr_string_vec.sort();
let mut addr_vec = Vec::new();
for addr in addr_string_vec {
addr_vec.push(Address::from_str(addr.as_str()).unwrap())
}
let wallet = Wallet::new(key_store);
let test_addr_vec = wallet.list_addrs().unwrap();
// check to see if the addrs in wallet are the same as the key_vec before it was
// added to the wallet
assert_eq!(test_addr_vec, addr_vec);
}
#[test]
fn generate_new_key() {
let mut wallet = generate_wallet();
let addr = wallet.generate_addr(SignatureType::BLS).unwrap();
let key = wallet.keystore.get("default").unwrap();
// make sure that the newly generated key is the default key - checking by key
// type
assert_eq!(&SignatureType::BLS, key.key_type());
let address = format!("wallet-{addr}");
let key_info = wallet.keystore.get(&address).unwrap();
let key = wallet.keys.get(&addr).unwrap();
// these assertions will make sure that the key has actually been added to the
// wallet
assert_eq!(key_info.key_type(), &SignatureType::BLS);
assert_eq!(key.address, addr);
}
#[test]
fn get_set_default() {
let key_store = KeyStore::new(KeyStoreConfig::Memory).unwrap();
let mut wallet = Wallet::new(key_store);
// check to make sure that there is no default
assert_eq!(wallet.get_default().unwrap_err(), Error::KeyInfo);
let new_priv_key = generate(SignatureType::Secp256k1).unwrap();
let pub_key =
wallet_helpers::to_public(SignatureType::Secp256k1, new_priv_key.as_slice()).unwrap();
let test_addr = Address::new_secp256k1(pub_key.as_slice()).unwrap();
let key_info = KeyInfo::new(SignatureType::Secp256k1, new_priv_key);
let test_addr_string = format!("wallet-{test_addr}");
wallet.keystore.put(test_addr_string, key_info).unwrap();
// check to make sure that the set_default function completed without error
assert!(wallet.set_default(test_addr).is_ok());
// check to make sure that the test_addr is actually the default addr for the
// wallet
assert_eq!(wallet.get_default().unwrap(), test_addr);
}
#[test]
fn secp_verify() {
let secp_priv_key = generate(SignatureType::Secp256k1).unwrap();
let secp_key_info = KeyInfo::new(SignatureType::Secp256k1, secp_priv_key);
let secp_key = Key::try_from(secp_key_info).unwrap();
let addr = secp_key.address;
let key_store = KeyStore::new(KeyStoreConfig::Memory).unwrap();
let mut wallet = Wallet::new_from_keys(key_store, vec![secp_key]);
let msg = [0u8; 64];
let sig = wallet.sign(&addr, &msg).unwrap();
sig.verify(&msg, &addr).unwrap();
// invalid verify check
let invalid_addr = wallet.generate_addr(SignatureType::Secp256k1).unwrap();
assert!(sig.verify(&msg, &invalid_addr).is_err())
}
#[test]
fn bls_verify_test() {
let bls_priv_key = generate(SignatureType::BLS).unwrap();
let bls_key_info = KeyInfo::new(SignatureType::BLS, bls_priv_key);
let bls_key = Key::try_from(bls_key_info).unwrap();
let addr = bls_key.address;
let key_store = KeyStore::new(KeyStoreConfig::Memory).unwrap();
let mut wallet = Wallet::new_from_keys(key_store, vec![bls_key]);
let msg = [0u8; 64];
let sig = wallet.sign(&addr, &msg).unwrap();
sig.verify(&msg, &addr).unwrap();
// invalid verify check
let invalid_addr = wallet.generate_addr(SignatureType::BLS).unwrap();
assert!(sig.verify(&msg, &invalid_addr).is_err())
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/subnet.rs | ipc/api/src/subnet.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
/// This type definitions are borrowed from
/// https://github.com/consensus-shipyard/ipc-actors/blob/main/subnet-actor/src/types.rs
/// to ensure that they are in sync in this project.
/// However, we should either deprecate the native actors, or make
/// them use the types from this sdk directly.
use crate::subnet_id::SubnetID;
use fvm_ipld_encoding::repr::*;
use fvm_shared::{address::Address, clock::ChainEpoch, econ::TokenAmount};
use serde::{Deserialize, Serialize};
/// ID used in the builtin-actors bundle manifest
pub const MANIFEST_ID: &str = "ipc_subnet_actor";
/// Determines the permission mode for validators.
#[repr(u8)]
#[derive(
Copy,
Debug,
Clone,
Serialize_repr,
Deserialize_repr,
PartialEq,
Eq,
strum::EnumString,
strum::VariantNames,
)]
#[strum(serialize_all = "snake_case")]
pub enum PermissionMode {
/// Validator power is determined by the collateral staked
Collateral,
/// Validator power is assigned by the owner of the subnet
Federated,
/// Validator power is determined by the initial collateral staked and does not change anymore
Static,
}
/// Defines the supply source of a subnet on its parent subnet.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct SupplySource {
/// The kind of supply.
pub kind: SupplyKind,
/// The address of the ERC20 token if that supply kind is selected.
pub token_address: Option<Address>,
}
/// Determines the type of supply used by the subnet.
#[repr(u8)]
#[derive(
Copy,
Debug,
Clone,
Serialize_repr,
Deserialize_repr,
PartialEq,
Eq,
strum::EnumString,
strum::VariantNames,
)]
#[strum(serialize_all = "snake_case")]
pub enum SupplyKind {
Native,
ERC20,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ConstructParams {
pub parent: SubnetID,
pub ipc_gateway_addr: Address,
pub consensus: ConsensusType,
pub min_validator_stake: TokenAmount,
pub min_validators: u64,
pub bottomup_check_period: ChainEpoch,
pub active_validators_limit: u16,
pub min_cross_msg_fee: TokenAmount,
pub permission_mode: PermissionMode,
pub supply_source: SupplySource,
}
/// Consensus types supported by hierarchical consensus
#[derive(PartialEq, Eq, Clone, Copy, Debug, Deserialize_repr, Serialize_repr)]
#[repr(u64)]
pub enum ConsensusType {
Fendermint,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/evm.rs | ipc/api/src/evm.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Type conversion for IPC Agent struct with solidity contract struct
use crate::address::IPCAddress;
use crate::checkpoint::BottomUpCheckpoint;
use crate::checkpoint::BottomUpMsgBatch;
use crate::cross::{IpcEnvelope, IpcMsgKind};
use crate::staking::StakingChange;
use crate::staking::StakingChangeRequest;
use crate::subnet::SupplySource;
use crate::subnet_id::SubnetID;
use crate::{eth_to_fil_amount, ethers_address_to_fil_address};
use anyhow::anyhow;
use ethers::types::U256;
use fvm_shared::address::{Address, Payload};
use fvm_shared::clock::ChainEpoch;
use fvm_shared::econ::TokenAmount;
use ipc_actors_abis::{
gateway_getter_facet, gateway_manager_facet, gateway_messenger_facet, lib_gateway,
register_subnet_facet, subnet_actor_checkpointing_facet, subnet_actor_diamond,
subnet_actor_getter_facet, top_down_finality_facet, xnet_messaging_facet,
};
/// The type conversion for IPC structs to evm solidity contracts. We need this convenient macro because
/// the abigen is creating the same struct but under different modules. This save a lot of
/// code.
macro_rules! base_type_conversion {
($module:ident) => {
impl TryFrom<&SubnetID> for $module::SubnetID {
type Error = anyhow::Error;
fn try_from(subnet: &SubnetID) -> Result<Self, Self::Error> {
Ok($module::SubnetID {
root: subnet.root_id(),
route: subnet_id_to_evm_addresses(subnet)?,
})
}
}
impl TryFrom<$module::SubnetID> for SubnetID {
type Error = anyhow::Error;
fn try_from(value: $module::SubnetID) -> Result<Self, Self::Error> {
let children = value
.route
.iter()
.map(ethers_address_to_fil_address)
.collect::<anyhow::Result<Vec<_>>>()?;
Ok(SubnetID::new(value.root, children))
}
}
};
}
/// Implement the cross network message types. To use this macro, make sure the $module has already
/// implemented the base types.
macro_rules! cross_msg_types {
($module:ident) => {
impl TryFrom<IPCAddress> for $module::Ipcaddress {
type Error = anyhow::Error;
fn try_from(value: IPCAddress) -> Result<Self, Self::Error> {
Ok($module::Ipcaddress {
subnet_id: $module::SubnetID::try_from(&value.subnet()?)?,
raw_address: $module::FvmAddress::try_from(value.raw_addr()?)?,
})
}
}
impl TryFrom<$module::Ipcaddress> for IPCAddress {
type Error = anyhow::Error;
fn try_from(value: $module::Ipcaddress) -> Result<Self, Self::Error> {
let addr = Address::try_from(value.raw_address)?;
let i = IPCAddress::new(&SubnetID::try_from(value.subnet_id)?, &addr)?;
Ok(i)
}
}
impl TryFrom<IpcEnvelope> for $module::IpcEnvelope {
type Error = anyhow::Error;
fn try_from(value: IpcEnvelope) -> Result<Self, Self::Error> {
let val = fil_to_eth_amount(&value.value)?;
let c = $module::IpcEnvelope {
kind: value.kind as u8,
from: $module::Ipcaddress::try_from(value.from).map_err(|e| {
anyhow!("cannot convert `from` ipc address msg due to: {e:}")
})?,
to: $module::Ipcaddress::try_from(value.to)
.map_err(|e| anyhow!("cannot convert `to`` ipc address due to: {e:}"))?,
value: val,
nonce: value.nonce,
message: ethers::core::types::Bytes::from(value.message),
};
Ok(c)
}
}
impl TryFrom<$module::IpcEnvelope> for IpcEnvelope {
type Error = anyhow::Error;
fn try_from(value: $module::IpcEnvelope) -> Result<Self, Self::Error> {
let s = IpcEnvelope {
from: IPCAddress::try_from(value.from)?,
to: IPCAddress::try_from(value.to)?,
value: eth_to_fil_amount(&value.value)?,
kind: IpcMsgKind::try_from(value.kind)?,
message: value.message.to_vec(),
nonce: value.nonce,
};
Ok(s)
}
}
};
}
/// The type conversion between different bottom up checkpoint definition in ethers and sdk
macro_rules! bottom_up_checkpoint_conversion {
($module:ident) => {
impl TryFrom<BottomUpCheckpoint> for $module::BottomUpCheckpoint {
type Error = anyhow::Error;
fn try_from(checkpoint: BottomUpCheckpoint) -> Result<Self, Self::Error> {
Ok($module::BottomUpCheckpoint {
subnet_id: $module::SubnetID::try_from(&checkpoint.subnet_id)?,
block_height: ethers::core::types::U256::from(checkpoint.block_height),
block_hash: vec_to_bytes32(checkpoint.block_hash)?,
next_configuration_number: checkpoint.next_configuration_number,
msgs: checkpoint
.msgs
.into_iter()
.map($module::IpcEnvelope::try_from)
.collect::<Result<Vec<_>, _>>()?,
})
}
}
impl TryFrom<$module::BottomUpCheckpoint> for BottomUpCheckpoint {
type Error = anyhow::Error;
fn try_from(value: $module::BottomUpCheckpoint) -> Result<Self, Self::Error> {
Ok(BottomUpCheckpoint {
subnet_id: SubnetID::try_from(value.subnet_id)?,
block_height: value.block_height.as_u128() as ChainEpoch,
block_hash: value.block_hash.to_vec(),
next_configuration_number: value.next_configuration_number,
msgs: value
.msgs
.into_iter()
.map(IpcEnvelope::try_from)
.collect::<Result<Vec<_>, _>>()?,
})
}
}
};
}
/// The type conversion between different bottom up message batch definition in ethers and sdk
macro_rules! bottom_up_msg_batch_conversion {
($module:ident) => {
impl TryFrom<BottomUpMsgBatch> for $module::BottomUpMsgBatch {
type Error = anyhow::Error;
fn try_from(batch: BottomUpMsgBatch) -> Result<Self, Self::Error> {
Ok($module::BottomUpMsgBatch {
subnet_id: $module::SubnetID::try_from(&batch.subnet_id)?,
block_height: ethers::core::types::U256::from(batch.block_height),
msgs: batch
.msgs
.into_iter()
.map($module::IpcEnvelope::try_from)
.collect::<Result<Vec<_>, _>>()?,
})
}
}
};
}
base_type_conversion!(xnet_messaging_facet);
base_type_conversion!(subnet_actor_getter_facet);
base_type_conversion!(gateway_manager_facet);
base_type_conversion!(subnet_actor_checkpointing_facet);
base_type_conversion!(gateway_getter_facet);
base_type_conversion!(gateway_messenger_facet);
base_type_conversion!(lib_gateway);
cross_msg_types!(gateway_getter_facet);
cross_msg_types!(xnet_messaging_facet);
cross_msg_types!(gateway_messenger_facet);
cross_msg_types!(lib_gateway);
cross_msg_types!(subnet_actor_checkpointing_facet);
bottom_up_checkpoint_conversion!(gateway_getter_facet);
bottom_up_checkpoint_conversion!(subnet_actor_checkpointing_facet);
bottom_up_msg_batch_conversion!(gateway_getter_facet);
impl TryFrom<SupplySource> for subnet_actor_diamond::SupplySource {
type Error = anyhow::Error;
fn try_from(value: SupplySource) -> Result<Self, Self::Error> {
let token_address = if let Some(token_address) = value.token_address {
payload_to_evm_address(token_address.payload())?
} else {
ethers::types::Address::zero()
};
Ok(Self {
kind: value.kind as u8,
token_address,
})
}
}
impl TryFrom<SupplySource> for register_subnet_facet::SupplySource {
type Error = anyhow::Error;
fn try_from(value: SupplySource) -> Result<Self, Self::Error> {
let token_address = if let Some(token_address) = value.token_address {
payload_to_evm_address(token_address.payload())?
} else {
ethers::types::Address::zero()
};
Ok(Self {
kind: value.kind as u8,
token_address,
})
}
}
/// Convert the ipc SubnetID type to a vec of evm addresses. It extracts all the children addresses
/// in the subnet id and turns them as a vec of evm addresses.
pub fn subnet_id_to_evm_addresses(
subnet: &SubnetID,
) -> anyhow::Result<Vec<ethers::types::Address>> {
let children = subnet.children();
children
.iter()
.map(|addr| payload_to_evm_address(addr.payload()))
.collect::<anyhow::Result<_>>()
}
/// Util function to convert Fil address payload to evm address. Only delegated address is supported.
pub fn payload_to_evm_address(payload: &Payload) -> anyhow::Result<ethers::types::Address> {
match payload {
Payload::Delegated(delegated) => {
let slice = delegated.subaddress();
Ok(ethers::types::Address::from_slice(&slice[0..20]))
}
_ => Err(anyhow!("address provided is not delegated")),
}
}
/// Converts a Fil TokenAmount into an ethers::U256 amount.
pub fn fil_to_eth_amount(amount: &TokenAmount) -> anyhow::Result<U256> {
let str = amount.atto().to_string();
Ok(U256::from_dec_str(&str)?)
}
impl TryFrom<StakingChange> for top_down_finality_facet::StakingChange {
type Error = anyhow::Error;
fn try_from(value: StakingChange) -> Result<Self, Self::Error> {
Ok(top_down_finality_facet::StakingChange {
op: value.op as u8,
payload: ethers::core::types::Bytes::from(value.payload),
validator: payload_to_evm_address(value.validator.payload())?,
})
}
}
impl TryFrom<StakingChangeRequest> for top_down_finality_facet::StakingChangeRequest {
type Error = anyhow::Error;
fn try_from(value: StakingChangeRequest) -> Result<Self, Self::Error> {
Ok(top_down_finality_facet::StakingChangeRequest {
change: top_down_finality_facet::StakingChange::try_from(value.change)?,
configuration_number: value.configuration_number,
})
}
}
pub fn vec_to_bytes32(v: Vec<u8>) -> anyhow::Result<[u8; 32]> {
if v.len() != 32 {
return Err(anyhow!("invalid length"));
}
let mut r = [0u8; 32];
r.copy_from_slice(&v);
Ok(r)
}
#[cfg(test)]
mod tests {
use crate::evm::subnet_id_to_evm_addresses;
use crate::subnet_id::SubnetID;
use fvm_shared::address::Address;
use ipc_types::EthAddress;
use std::str::FromStr;
#[test]
fn test_subnet_id_to_evm_addresses() {
let eth_addr = EthAddress::from_str("0x0000000000000000000000000000000000000000").unwrap();
let addr = Address::from(eth_addr);
let addr2 = Address::from_str("f410ffzyuupbyl2uiucmzr3lu3mtf3luyknthaz4xsrq").unwrap();
let id = SubnetID::new(0, vec![addr, addr2]);
let addrs = subnet_id_to_evm_addresses(&id).unwrap();
let a =
ethers::types::Address::from_str("0x0000000000000000000000000000000000000000").unwrap();
let b =
ethers::types::Address::from_str("0x2e714a3c385ea88a09998ed74db265dae9853667").unwrap();
assert_eq!(addrs, vec![a, b]);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/lib.rs | ipc/api/src/lib.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use ethers::utils::hex;
use fvm_shared::{address::Address, econ::TokenAmount};
use ipc_types::EthAddress;
use serde::de::Error as SerdeError;
use serde::{Deserialize, Serialize, Serializer};
use std::str::FromStr;
pub mod address;
pub mod checkpoint;
pub mod cross;
pub mod error;
pub mod gateway;
#[cfg(feature = "fil-actor")]
mod runtime;
pub mod subnet;
pub mod subnet_id;
pub mod validator;
pub mod evm;
pub mod staking;
/// Converts an ethers::U256 TokenAmount into a FIL amount.
pub fn eth_to_fil_amount(amount: ðers::types::U256) -> anyhow::Result<TokenAmount> {
let v = fvm_shared::bigint::BigInt::from_str(&amount.to_string())?;
Ok(TokenAmount::from_atto(v))
}
pub fn ethers_address_to_fil_address(addr: ðers::types::Address) -> anyhow::Result<Address> {
let raw_addr = format!("{addr:?}");
log::debug!("raw evm subnet addr: {raw_addr:}");
let eth_addr = EthAddress::from_str(&raw_addr)?;
Ok(Address::from(eth_addr))
}
/// Marker type for serialising data to/from string
pub struct HumanReadable;
#[macro_export]
macro_rules! serialise_human_readable_str {
($typ:ty) => {
impl serde_with::SerializeAs<$typ> for $crate::HumanReadable {
fn serialize_as<S>(value: &$typ, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
value.to_string().serialize(serializer)
} else {
value.serialize(serializer)
}
}
}
};
}
#[macro_export]
macro_rules! deserialize_human_readable_str {
($typ:ty) => {
use serde::de::Error as DeserializeError;
use serde::{Deserialize, Serialize};
impl<'de> serde_with::DeserializeAs<'de, $typ> for $crate::HumanReadable {
fn deserialize_as<D>(deserializer: D) -> Result<$typ, D::Error>
where
D: serde::de::Deserializer<'de>,
{
if deserializer.is_human_readable() {
let s = String::deserialize(deserializer)?;
<$typ>::from_str(&s).map_err(|_| {
D::Error::custom(format!(
"cannot parse from str {}",
core::any::type_name::<$typ>()
))
})
} else {
<$typ>::deserialize(deserializer)
}
}
}
};
}
#[macro_export]
macro_rules! as_human_readable_str {
($typ:ty) => {
$crate::serialise_human_readable_str!($typ);
$crate::deserialize_human_readable_str!($typ);
};
}
impl serde_with::SerializeAs<Vec<u8>> for HumanReadable {
fn serialize_as<S>(source: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
hex::encode(source).serialize(serializer)
}
}
impl<'de> serde_with::DeserializeAs<'de, Vec<u8>> for HumanReadable {
fn deserialize_as<D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: serde::de::Deserializer<'de>,
{
if deserializer.is_human_readable() {
let s = String::deserialize(deserializer)?;
Ok(hex::decode(s)
.map_err(|e| D::Error::custom(format!("cannot parse from str {e}")))?)
} else {
Vec::<u8>::deserialize(deserializer)
}
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/address.rs | ipc/api/src/address.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use crate::error::Error;
use crate::subnet_id::SubnetID;
use crate::{deserialize_human_readable_str, HumanReadable};
use fvm_shared::address::{Address, Protocol};
use serde::ser::Error as SerializeError;
use serde_tuple::{Deserialize_tuple, Serialize_tuple};
use std::{fmt, str::FromStr};
const IPC_SEPARATOR_ADDR: &str = ":";
#[derive(Clone, PartialEq, Eq, Debug, Hash, Serialize_tuple, Deserialize_tuple)]
pub struct IPCAddress {
subnet_id: SubnetID,
raw_address: Address,
}
impl IPCAddress {
/// Generates new IPC address
pub fn new(sn: &SubnetID, addr: &Address) -> Result<Self, Error> {
Ok(Self {
subnet_id: sn.clone(),
raw_address: *addr,
})
}
/// Returns subnets of a IPC address
pub fn subnet(&self) -> Result<SubnetID, Error> {
Ok(self.subnet_id.clone())
}
/// Returns the raw address of a IPC address (without subnet context)
pub fn raw_addr(&self) -> Result<Address, Error> {
Ok(self.raw_address)
}
/// Returns encoded bytes of Address
#[cfg(feature = "fil-actor")]
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
Ok(fil_actors_runtime::cbor::serialize(self, "ipc-address")?.to_vec())
}
#[cfg(feature = "fil-actor")]
pub fn from_bytes(bz: &[u8]) -> Result<Self, Error> {
let i: Self = fil_actors_runtime::cbor::deserialize(
&fvm_ipld_encoding::RawBytes::new(bz.to_vec()),
"ipc-address",
)?;
Ok(i)
}
pub fn to_string(&self) -> Result<String, Error> {
Ok(format!(
"{}{}{}",
self.subnet_id, IPC_SEPARATOR_ADDR, self.raw_address
))
}
/// Checks if a raw address has a valid Filecoin address protocol
/// compatible with cross-net messages targetting a contract
pub fn is_valid_contract_address(addr: &Address) -> bool {
matches!(addr.protocol(), Protocol::Delegated | Protocol::Actor)
}
/// Checks if a raw address has a valid Filecoin address protocol
/// compatible with cross-net messages targetting a user account
pub fn is_valid_account_address(addr: &Address) -> bool {
// we support `Delegated` as a type for a valid account address
// so we can send funds to eth addresses using cross-net primitives.
// this may require additional care when executing in FEVM so we don't
// send funds to a smart contract.
matches!(
addr.protocol(),
Protocol::Delegated | Protocol::BLS | Protocol::Secp256k1 | Protocol::ID
)
}
}
impl fmt::Display for IPCAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.subnet_id, IPC_SEPARATOR_ADDR)?;
write!(f, "{}", self.raw_address)
}
}
impl FromStr for IPCAddress {
type Err = Error;
fn from_str(addr: &str) -> Result<Self, Error> {
let r: Vec<&str> = addr.split(IPC_SEPARATOR_ADDR).collect();
if r.len() != 2 {
Err(Error::InvalidIPCAddr)
} else {
Ok(Self {
raw_address: Address::from_str(r[1])?,
subnet_id: SubnetID::from_str(r[0])?,
})
}
}
}
impl serde_with::SerializeAs<IPCAddress> for HumanReadable {
fn serialize_as<S>(address: &IPCAddress, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
address
.to_string()
.map_err(|e| {
S::Error::custom(format!("cannot convert ipc address to string: {e}"))
})?
.serialize(serializer)
} else {
address.serialize(serializer)
}
}
}
deserialize_human_readable_str!(IPCAddress);
#[cfg(test)]
mod tests {
use crate::address::IPCAddress;
use crate::subnet_id::SubnetID;
use fvm_shared::address::Address;
use std::str::FromStr;
use std::vec;
#[test]
fn test_ipc_address() {
let act = Address::new_id(1001);
let sub_id = SubnetID::new(123, vec![act]);
let bls = Address::from_str("f3vvmn62lofvhjd2ugzca6sof2j2ubwok6cj4xxbfzz4yuxfkgobpihhd2thlanmsh3w2ptld2gqkn2jvlss4a").unwrap();
let haddr = IPCAddress::new(&sub_id, &bls).unwrap();
let str = haddr.to_string().unwrap();
let blss = IPCAddress::from_str(&str).unwrap();
assert_eq!(haddr.raw_addr().unwrap(), bls);
assert_eq!(haddr.subnet().unwrap(), sub_id);
assert_eq!(haddr, blss);
}
#[test]
fn test_ipc_from_str() {
let sub_id = SubnetID::new(123, vec![Address::new_id(100)]);
let addr = IPCAddress::new(&sub_id, &Address::new_id(101)).unwrap();
let st = addr.to_string().unwrap();
let addr_out = IPCAddress::from_str(&st).unwrap();
assert_eq!(addr, addr_out);
let addr_out = IPCAddress::from_str(&format!("{}", addr)).unwrap();
assert_eq!(addr, addr_out);
}
#[cfg(feature = "fil-actor")]
#[test]
fn test_ipc_serialization() {
let sub_id = SubnetID::new(123, vec![Address::new_id(100)]);
let addr = IPCAddress::new(&sub_id, &Address::new_id(101)).unwrap();
let st = addr.to_bytes().unwrap();
let addr_out = IPCAddress::from_bytes(&st).unwrap();
assert_eq!(addr, addr_out);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/error.rs | ipc/api/src/error.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use thiserror::Error;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum Error {
#[error("invalid subnet id {0}: {1}")]
InvalidID(String, String),
#[error("invalid IPC address")]
InvalidIPCAddr,
#[error("fvm shared address error")]
FVMAddressError(fvm_shared::address::Error),
#[cfg(feature = "fil-actor")]
#[error("actor error")]
Actor(fil_actors_runtime::ActorError),
}
#[cfg(feature = "fil-actor")]
impl From<fil_actors_runtime::ActorError> for Error {
fn from(e: fil_actors_runtime::ActorError) -> Self {
Self::Actor(e)
}
}
impl From<fvm_shared::address::Error> for Error {
fn from(e: fvm_shared::address::Error) -> Self {
Error::FVMAddressError(e)
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/gateway.rs | ipc/api/src/gateway.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
/// This type definitions are borrowed from
/// https://github.com/consensus-shipyard/ipc-actors/tree/main/gateway
/// to ensure that they are in sync in this project.
/// However, we should either deprecate the native actors, or make
/// them use the types from this sdk directly.
///
use crate::subnet_id::SubnetID;
use cid::Cid;
use fvm_ipld_encoding::tuple::{Deserialize_tuple, Serialize_tuple};
use fvm_shared::address::Address;
#[derive(Serialize_tuple, Deserialize_tuple, Clone)]
pub struct FundParams {
pub subnet: SubnetID,
pub to: Address,
}
#[derive(Serialize_tuple, Deserialize_tuple, Clone)]
pub struct ReleaseParams {
pub to: Address,
}
#[derive(Serialize_tuple, Deserialize_tuple, Clone)]
pub struct PropagateParams {
/// The postbox message cid
pub postbox_cid: Cid,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/runtime.rs | ipc/api/src/runtime.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use crate::checkpoint::{BottomUpCheckpoint, Validators};
use fil_actors_runtime::runtime::Runtime;
use fvm_shared::address::Address;
use fvm_shared::econ::TokenAmount;
impl BottomUpCheckpoint {
/// Agents may set the source of a checkpoint using f2-based subnetIDs, \
/// but actors are expected to use f0-based subnetIDs, thus the need to enforce
/// that the source is a f0-based subnetID.
pub fn enforce_f0_source(&mut self, rt: &impl Runtime) -> anyhow::Result<()> {
self.data.source = self.source().f0_id(rt);
Ok(())
}
}
impl Validators {
/// Get the weight of a validator
/// It expects ID addresses as an input
pub fn get_validator_weight(&self, rt: &impl Runtime, addr: &Address) -> Option<TokenAmount> {
self.validators
.validators()
.iter()
.find(|x| match rt.resolve_address(&x.addr) {
Some(id) => id == *addr,
None => false,
})
.map(|v| v.weight.clone())
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/staking.rs | ipc/api/src/staking.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Staking module related types and functions
use crate::{eth_to_fil_amount, ethers_address_to_fil_address};
use ethers::utils::hex;
use fvm_shared::address::Address;
use fvm_shared::econ::TokenAmount;
use ipc_actors_abis::{lib_staking_change_log, subnet_actor_getter_facet};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
pub type ConfigurationNumber = u64;
#[derive(Clone, Debug, num_enum::TryFromPrimitive, Deserialize, Serialize)]
#[non_exhaustive]
#[repr(u8)]
pub enum StakingOperation {
Deposit = 0,
Withdraw = 1,
SetMetadata = 2,
SetFederatedPower = 3,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StakingChangeRequest {
pub configuration_number: ConfigurationNumber,
pub change: StakingChange,
}
/// The change request to validator staking
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StakingChange {
pub op: StakingOperation,
pub payload: Vec<u8>,
pub validator: Address,
}
impl TryFrom<lib_staking_change_log::NewStakingChangeRequestFilter> for StakingChangeRequest {
type Error = anyhow::Error;
fn try_from(
value: lib_staking_change_log::NewStakingChangeRequestFilter,
) -> Result<Self, Self::Error> {
Ok(Self {
configuration_number: value.configuration_number,
change: StakingChange {
op: StakingOperation::try_from(value.op)?,
payload: value.payload.to_vec(),
validator: ethers_address_to_fil_address(&value.validator)?,
},
})
}
}
/// The staking validator information
#[derive(Clone, Debug)]
pub struct ValidatorStakingInfo {
confirmed_collateral: TokenAmount,
total_collateral: TokenAmount,
metadata: Vec<u8>,
}
impl Display for ValidatorStakingInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"ValidatorStaking(confirmed_collateral: {}, total_collateral: {}, metadata: 0x{})",
self.confirmed_collateral,
self.total_collateral,
hex::encode(&self.metadata)
)
}
}
impl TryFrom<subnet_actor_getter_facet::ValidatorInfo> for ValidatorStakingInfo {
type Error = anyhow::Error;
fn try_from(value: subnet_actor_getter_facet::ValidatorInfo) -> Result<Self, Self::Error> {
Ok(Self {
confirmed_collateral: eth_to_fil_amount(&value.confirmed_collateral)?,
total_collateral: eth_to_fil_amount(&value.total_collateral)?,
metadata: value.metadata.to_vec(),
})
}
}
/// The full validator information with
#[derive(Clone, Debug)]
pub struct ValidatorInfo {
pub staking: ValidatorStakingInfo,
/// If the validator is active in block production
pub is_active: bool,
/// If the validator is current waiting to be promoted to active
pub is_waiting: bool,
}
impl Display for ValidatorInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"ValidatorInfo(staking: {}, is_active: {}, is_waiting: {})",
self.staking, self.is_active, self.is_waiting
)
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/checkpoint.rs | ipc/api/src/checkpoint.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Cross network messages related struct and utility functions.
use crate::cross::IpcEnvelope;
use crate::subnet_id::SubnetID;
use crate::HumanReadable;
use cid::multihash::Code;
use cid::multihash::MultihashDigest;
use cid::Cid;
use ethers::utils::hex;
use fvm_ipld_encoding::DAG_CBOR;
use fvm_shared::address::Address;
use fvm_shared::clock::ChainEpoch;
use fvm_shared::econ::TokenAmount;
use lazy_static::lazy_static;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Serialize, Serializer};
use serde_with::serde_as;
use std::fmt::{Display, Formatter};
lazy_static! {
// Default CID used for the genesis checkpoint. Using
// TCid::default() leads to corrupting the fvm datastore
// for storing the cid of an inaccessible HAMT.
pub static ref CHECKPOINT_GENESIS_CID: Cid =
Cid::new_v1(DAG_CBOR, Code::Blake2b256.digest("genesis".as_bytes()));
}
pub type Signature = Vec<u8>;
/// The event emitted
#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct QuorumReachedEvent {
pub obj_kind: u8,
pub height: ChainEpoch,
/// The checkpoint hash
pub obj_hash: Vec<u8>,
pub quorum_weight: TokenAmount,
}
impl Display for QuorumReachedEvent {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"QuorumReachedEvent<height: {}, checkpoint: {}, quorum_weight: {}>",
self.height,
hex::encode(&self.obj_hash),
self.quorum_weight
)
}
}
/// The collection of items for the bottom up checkpoint submission
#[serde_as]
#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct BottomUpCheckpointBundle {
pub checkpoint: BottomUpCheckpoint,
/// The list of signatures that have signed the checkpoint hash
#[serde_as(as = "Vec<HumanReadable>")]
pub signatures: Vec<Signature>,
/// The list of addresses that have signed the checkpoint hash
pub signatories: Vec<Address>,
}
/// The collection of items for the bottom up checkpoint submission
#[serde_as]
#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct BottomUpMsgBatch {
/// Child subnet ID, for replay protection from other subnets where the exact same validators operate
#[serde_as(as = "HumanReadable")]
pub subnet_id: SubnetID,
/// The height of the child subnet at which the batch was cut
pub block_height: ChainEpoch,
/// Batch of messages to execute
pub msgs: Vec<IpcEnvelope>,
}
#[serde_as]
#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct BottomUpCheckpoint {
/// Child subnet ID, for replay protection from other subnets where the exact same validators operate.
/// Alternatively it can be appended to the hash before signing, similar to how we use the chain ID.
pub subnet_id: SubnetID,
/// The height of the child subnet at which this checkpoint was cut.
/// Has to follow the previous checkpoint by checkpoint period.
pub block_height: ChainEpoch,
/// The hash of the block.
#[serde_as(as = "HumanReadable")]
pub block_hash: Vec<u8>,
/// The number of the membership (validator set) which is going to sign the next checkpoint.
/// This one expected to be signed by the validators from the membership reported in the previous checkpoint.
/// 0 could mean "no change".
pub next_configuration_number: u64,
/// The list of messages for execution
pub msgs: Vec<IpcEnvelope>,
}
pub fn serialize_vec_bytes_to_vec_hex<T: AsRef<[u8]>, S>(
data: &[T],
s: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = s.serialize_seq(Some(data.len()))?;
for element in data {
seq.serialize_element(&hex::encode(element))?;
}
seq.end()
}
#[cfg(test)]
mod tests {
use crate::address::IPCAddress;
use crate::checkpoint::Signature;
use crate::subnet_id::SubnetID;
use crate::HumanReadable;
use fvm_shared::address::Address;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use std::str::FromStr;
#[test]
fn test_serialization_vec_vec_u8() {
#[serde_as]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct T {
#[serde_as(as = "Vec<HumanReadable>")]
d: Vec<Signature>,
#[serde_as(as = "HumanReadable")]
subnet_id: SubnetID,
#[serde_as(as = "HumanReadable")]
ipc_address: IPCAddress,
}
let subnet_id =
SubnetID::from_str("/r31415926/f2xwzbdu7z5sam6hc57xxwkctciuaz7oe5omipwbq").unwrap();
let ipc_address = IPCAddress::new(&subnet_id, &Address::new_id(101)).unwrap();
let t = T {
d: vec![vec![1; 30], vec![2; 30]],
subnet_id,
ipc_address,
};
let s = serde_json::to_string(&t).unwrap();
assert_eq!(
s,
r#"{"d":["010101010101010101010101010101010101010101010101010101010101","020202020202020202020202020202020202020202020202020202020202"],"subnet_id":"/r31415926/f2xwzbdu7z5sam6hc57xxwkctciuaz7oe5omipwbq","ipc_address":"/r31415926/f2xwzbdu7z5sam6hc57xxwkctciuaz7oe5omipwbq:f0101"}"#
);
let r: T = serde_json::from_str(&s).unwrap();
assert_eq!(r, t);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/validator.rs | ipc/api/src/validator.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use fvm_shared::{address::Address, econ::TokenAmount};
use ipc_actors_abis::subnet_actor_getter_facet;
use crate::{
eth_to_fil_amount, ethers_address_to_fil_address,
evm::{fil_to_eth_amount, payload_to_evm_address},
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Validator {
pub addr: Address,
pub metadata: Vec<u8>,
pub weight: TokenAmount,
}
impl TryFrom<Validator> for subnet_actor_getter_facet::Validator {
type Error = anyhow::Error;
fn try_from(value: Validator) -> Result<Self, Self::Error> {
Ok(subnet_actor_getter_facet::Validator {
addr: payload_to_evm_address(value.addr.payload())?,
weight: fil_to_eth_amount(&value.weight)?,
metadata: ethers::core::types::Bytes::from(value.metadata),
})
}
}
pub fn into_contract_validators(
vals: Vec<Validator>,
) -> anyhow::Result<Vec<subnet_actor_getter_facet::Validator>> {
let result: Result<Vec<subnet_actor_getter_facet::Validator>, _> = vals
.into_iter()
.map(|validator| validator.try_into())
.collect();
result
}
pub fn from_contract_validators(
vals: Vec<subnet_actor_getter_facet::Validator>,
) -> anyhow::Result<Vec<Validator>> {
let result: Result<Vec<Validator>, _> = vals
.into_iter()
.map(|validator| {
Ok(Validator {
addr: ethers_address_to_fil_address(&validator.addr)?,
weight: eth_to_fil_amount(&validator.weight)?,
metadata: validator.metadata.to_vec(),
})
})
.collect();
result
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/subnet_id.rs | ipc/api/src/subnet_id.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use fnv::FnvHasher;
use fvm_shared::address::Address;
use lazy_static::lazy_static;
use serde_tuple::{Deserialize_tuple, Serialize_tuple};
use std::fmt;
use std::fmt::Write;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use crate::as_human_readable_str;
use crate::error::Error;
/// MaxChainID is the maximum chain ID value
/// possible. This is the MAX_CHAIN_ID currently
/// supported by Ethereum chains.
pub const MAX_CHAIN_ID: u64 = 4503599627370476;
/// SubnetID is a unique identifier for a subnet.
/// It is composed of the chainID of the root network, and the address of
/// all the subnet actors from the root to the corresponding level in the
/// hierarchy where the subnet is spawned.
#[derive(PartialEq, Eq, Hash, Clone, Debug, Serialize_tuple, Deserialize_tuple)]
pub struct SubnetID {
root: u64,
children: Vec<Address>,
}
as_human_readable_str!(SubnetID);
lazy_static! {
pub static ref UNDEF: SubnetID = SubnetID {
root: 0,
children: vec![],
};
}
impl SubnetID {
pub fn new(root_id: u64, children: Vec<Address>) -> Self {
Self {
root: root_id,
children,
}
}
/// Create a new subnet id from the root network id and the subnet actor
pub fn new_from_parent(parent: &SubnetID, subnet_act: Address) -> Self {
let mut children = parent.children();
children.push(subnet_act);
Self {
root: parent.root_id(),
children,
}
}
/// Ensures that the SubnetID only uses f0 addresses for the subnet actor
/// hosted in the current network. The rest of the route is left
/// as-is. We only have information to translate from f2 to f0 for the
/// last subnet actor in the root.
#[cfg(feature = "fil-actor")]
pub fn f0_id(&self, rt: &impl fil_actors_runtime::runtime::Runtime) -> SubnetID {
let mut children = self.children();
// replace the resolved child (if any)
if let Some(actor_addr) = children.last_mut() {
if let Some(f0) = rt.resolve_address(actor_addr) {
*actor_addr = f0;
}
}
SubnetID::new(self.root_id(), children)
}
/// Creates a new rootnet SubnetID
pub fn new_root(root_id: u64) -> Self {
Self {
root: root_id,
children: vec![],
}
}
/// Returns true if the current subnet is the root network
pub fn is_root(&self) -> bool {
self.children_as_ref().is_empty()
}
/// Returns the chainID of the root network.
pub fn root_id(&self) -> u64 {
self.root
}
/// Returns the chainID of the current subnet
pub fn chain_id(&self) -> u64 {
if self.is_root() {
return self.root_id();
}
let mut hasher = FnvHasher::default();
hasher.write(self.to_string().as_bytes());
hasher.finish() % MAX_CHAIN_ID
}
/// Returns the route from the root to the current subnet
pub fn children(&self) -> Vec<Address> {
self.children.clone()
}
/// Returns the route from the root to the current subnet
pub fn children_as_ref(&self) -> &Vec<Address> {
&self.children
}
/// Returns the serialized version of the subnet id
#[cfg(feature = "fil-actor")]
pub fn to_bytes(&self) -> Vec<u8> {
fil_actors_runtime::cbor::serialize(self, "subnetID")
.unwrap()
.into()
}
/// Returns the address of the actor governing the subnet in the parent
/// If there is no subnet actor it returns the address ID=0
pub fn subnet_actor(&self) -> Address {
if let Some(addr) = self.children.last() {
*addr
} else {
// protect against the case that the children slice is empty
Address::new_id(0)
}
}
/// Returns the parenet of the current subnet
pub fn parent(&self) -> Option<SubnetID> {
// if the subnet is the root, it has no parent
if self.children_as_ref().is_empty() {
return None;
}
let children = self.children();
Some(SubnetID::new(
self.root_id(),
children[..children.len() - 1].to_vec(),
))
}
/// Computes the common parent of the current subnet and the one given
/// as argument. It returns the number of common children and the subnet.
pub fn common_parent(&self, other: &SubnetID) -> Option<(usize, SubnetID)> {
// check if we have the same root first
if self.root_id() != other.root_id() {
return None;
}
let common = self
.children_as_ref()
.iter()
.zip(other.children_as_ref())
.take_while(|(a, b)| a == b)
.count();
let children = self.children()[..common].to_vec();
Some((common, SubnetID::new(self.root_id(), children)))
}
/// In the path determined by the current subnet id, it moves
/// down in the path from the subnet id given as argument.
pub fn down(&self, from: &SubnetID) -> Option<SubnetID> {
// check if the current network's path is larger than
// the one to be traversed.
if self.children_as_ref().len() <= from.children_as_ref().len() {
return None;
}
if let Some((i, _)) = self.common_parent(from) {
let children = self.children()[..i + 1].to_vec();
return Some(SubnetID::new(self.root_id(), children));
}
None
}
/// In the path determined by the current subnet id, it moves
/// up in the path from the subnet id given as argument.
pub fn up(&self, from: &SubnetID) -> Option<SubnetID> {
// check if the current network's path is larger than
// the one to be traversed.
if self.children_as_ref().len() < from.children_as_ref().len() {
return None;
}
if let Some((i, _)) = self.common_parent(from) {
let children = self.children()[..i - 1].to_vec();
return Some(SubnetID::new(self.root_id(), children));
}
None
}
}
impl fmt::Display for SubnetID {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let children_str = self
.children_as_ref()
.iter()
.fold(String::new(), |mut output, s| {
let _ = write!(output, "/{s}");
output
});
write!(f, "/r{}{}", self.root_id(), children_str)
}
}
impl Default for SubnetID {
fn default() -> Self {
UNDEF.clone()
}
}
impl FromStr for SubnetID {
type Err = Error;
fn from_str(id: &str) -> Result<Self, Error> {
if !id.starts_with("/r") {
return Err(Error::InvalidID(
id.into(),
"expected to start with '/r'".into(),
));
}
let segments: Vec<&str> = id.split('/').skip(1).collect();
let root = segments[0][1..]
.parse::<u64>()
.map_err(|_| Error::InvalidID(id.into(), "invalid root ID".into()))?;
let mut children = Vec::new();
for addr in segments[1..].iter() {
let addr = Address::from_str(addr).map_err(|e| {
Error::InvalidID(id.into(), format!("invalid child address {addr}: {e}"))
})?;
children.push(addr);
}
Ok(Self { root, children })
}
}
#[cfg(test)]
mod tests {
use crate::subnet_id::SubnetID;
use fvm_shared::address::Address;
use std::str::FromStr;
#[test]
fn test_parse_root_net() {
let subnet_id = SubnetID::from_str("/r123").unwrap();
assert_eq!(subnet_id.root, 123);
}
#[test]
fn test_parse_subnet_id() {
// NOTE: It would not work with `t` prefix addresses unless the current network is changed.
let id = "/r31415926/f2xwzbdu7z5sam6hc57xxwkctciuaz7oe5omipwbq";
let subnet_id = SubnetID::from_str(id).unwrap();
assert_eq!(subnet_id.root, 31415926);
assert!(!subnet_id.children.is_empty());
}
#[test]
fn test_cannot_parse_subnet_id_with_wrong_prefix() {
// NOTE: The default network prefix is `f`.
let id = "/r31415926/t2xwzbdu7z5sam6hc57xxwkctciuaz7oe5omipwbq";
match SubnetID::from_str(id) {
Err(crate::error::Error::InvalidID(_, msg)) => {
assert!(msg.contains("invalid child"));
assert!(msg.contains("t2xwzbdu7z5sam6hc57xxwkctciuaz7oe5omipwbq"));
assert!(msg.contains("network"));
}
other => panic!("unexpected parse result: {other:?}"),
}
}
#[test]
fn test_parse_empty_subnet_id() {
assert!(SubnetID::from_str("").is_err())
}
#[test]
fn test_subnet_id() {
let act = Address::new_id(1001);
let sub_id = SubnetID::new(123, vec![act]);
let sub_id_str = sub_id.to_string();
assert_eq!(sub_id_str, "/r123/f01001");
let rtt_id = SubnetID::from_str(&sub_id_str).unwrap();
assert_eq!(sub_id, rtt_id);
let rootnet = SubnetID::new(123, vec![]);
assert_eq!(rootnet.to_string(), "/r123");
let root_sub = SubnetID::from_str(&rootnet.to_string()).unwrap();
assert_eq!(root_sub, rootnet);
}
#[test]
fn test_chain_id() {
let act = Address::new_id(1001);
let sub_id = SubnetID::new(123, vec![act]);
let chain_id = sub_id.chain_id();
assert_eq!(chain_id, 1011873294913613);
let root = sub_id.parent().unwrap();
let chain_id = root.chain_id();
assert_eq!(chain_id, 123);
}
#[test]
fn test_common_parent() {
common_parent("/r123/f01", "/r123/f01/f02", "/r123/f01", 1);
common_parent("/r123/f01/f02/f03", "/r123/f01/f02", "/r123/f01/f02", 2);
common_parent("/r123/f01/f03/f04", "/r123/f02/f03/f04", "/r123", 0);
common_parent(
"/r123/f01/f03/f04",
"/r123/f01/f03/f04/f05",
"/r123/f01/f03/f04",
3,
);
// The common parent of the same subnet is the current subnet
common_parent(
"/r123/f01/f03/f04",
"/r123/f01/f03/f04",
"/r123/f01/f03/f04",
3,
);
}
#[test]
#[should_panic]
fn test_panic_different_root() {
common_parent("/r122/f01", "/r123/f01/f02", "/r123/f01", 1);
}
#[test]
fn test_down() {
down(
"/r123/f01/f02/f03",
"/r123/f01",
Some(SubnetID::from_str("/r123/f01/f02").unwrap()),
);
down(
"/r123/f01/f02/f03",
"/r123/f01/f02",
Some(SubnetID::from_str("/r123/f01/f02/f03").unwrap()),
);
down(
"/r123/f01/f03/f04",
"/r123/f01/f03",
Some(SubnetID::from_str("/r123/f01/f03/f04").unwrap()),
);
down("/r123", "/r123/f01", None);
down("/r123/f01", "/r123/f01", None);
down("/r123/f02/f03", "/r123/f01/f03/f04", None);
down("/r123", "/r123/f01", None);
}
#[test]
fn test_up() {
up(
"/r123/f01/f02/f03",
"/r123/f01",
Some(SubnetID::from_str("/r123").unwrap()),
);
up(
"/r123/f01/f02/f03",
"/r123/f01/f02",
Some(SubnetID::from_str("/r123/f01").unwrap()),
);
up("/r123", "/r123/f01", None);
up("/r123/f02/f03", "/r123/f01/f03/f04", None);
up(
"/r123/f01/f02/f03",
"/r123/f01/f02",
Some(SubnetID::from_str("/r123/f01").unwrap()),
);
up(
"/r123/f01/f02/f03",
"/r123/f01/f02/f03",
Some(SubnetID::from_str("/r123/f01/f02").unwrap()),
);
}
fn common_parent(a: &str, b: &str, res: &str, index: usize) {
let id = SubnetID::from_str(a).unwrap();
assert_eq!(
id.common_parent(&SubnetID::from_str(b).unwrap()).unwrap(),
(index, SubnetID::from_str(res).unwrap()),
);
}
fn down(a: &str, b: &str, res: Option<SubnetID>) {
let id = SubnetID::from_str(a).unwrap();
assert_eq!(id.down(&SubnetID::from_str(b).unwrap()), res);
}
fn up(a: &str, b: &str, res: Option<SubnetID>) {
let id = SubnetID::from_str(a).unwrap();
assert_eq!(id.up(&SubnetID::from_str(b).unwrap()), res);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/api/src/cross.rs | ipc/api/src/cross.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Cross network messages related struct and utility functions.
use crate::address::IPCAddress;
use crate::subnet_id::SubnetID;
use crate::HumanReadable;
use anyhow::anyhow;
use fvm_shared::address::Address;
use fvm_shared::econ::TokenAmount;
use serde::{Deserialize, Serialize};
use serde_tuple::{Deserialize_tuple, Serialize_tuple};
use serde_with::serde_as;
#[serde_as]
#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct IpcEnvelope {
/// Type of message being propagated.
pub kind: IpcMsgKind,
/// destination of the message
/// It makes sense to extract from the encoded message
/// all shared fields required by all message, so they
/// can be inspected without having to decode the message.
#[serde_as(as = "HumanReadable")]
pub to: IPCAddress,
/// Value included in the envelope
pub value: TokenAmount,
/// address sending the message
pub from: IPCAddress,
/// abi.encoded message
#[serde_as(as = "HumanReadable")]
pub message: Vec<u8>,
/// outgoing nonce for the envelope.
/// This nonce is set by the gateway when committing the message for propagation
pub nonce: u64,
}
impl IpcEnvelope {
pub fn new_release_msg(
sub_id: &SubnetID,
from: &Address,
to: &Address,
value: TokenAmount,
) -> anyhow::Result<Self> {
let to = IPCAddress::new(
&match sub_id.parent() {
Some(s) => s,
None => return Err(anyhow!("error getting parent for subnet addr")),
},
to,
)?;
let from = IPCAddress::new(sub_id, from)?;
Ok(Self {
kind: IpcMsgKind::Transfer,
from,
to,
value,
nonce: 0,
message: Default::default(),
})
}
pub fn new_fund_msg(
sub_id: &SubnetID,
from: &Address,
to: &Address,
value: TokenAmount,
) -> anyhow::Result<Self> {
let from = IPCAddress::new(
&match sub_id.parent() {
Some(s) => s,
None => return Err(anyhow!("error getting parent for subnet addr")),
},
from,
)?;
let to = IPCAddress::new(sub_id, to)?;
// the nonce and the rest of message fields are set when the message is committed.
Ok(Self {
kind: IpcMsgKind::Transfer,
from,
to,
value,
nonce: 0,
message: Default::default(),
})
}
pub fn ipc_type(&self) -> anyhow::Result<IPCMsgType> {
let sto = self.to.subnet()?;
let sfrom = self.from.subnet()?;
if is_bottomup(&sfrom, &sto) {
return Ok(IPCMsgType::BottomUp);
}
Ok(IPCMsgType::TopDown)
}
pub fn apply_type(&self, curr: &SubnetID) -> anyhow::Result<IPCMsgType> {
let sto = self.to.subnet()?;
let sfrom = self.from.subnet()?;
if curr.common_parent(&sto) == sfrom.common_parent(&sto)
&& self.ipc_type()? == IPCMsgType::BottomUp
{
return Ok(IPCMsgType::BottomUp);
}
Ok(IPCMsgType::TopDown)
}
}
/// Type of cross-net messages currently supported
#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize, strum::Display)]
#[repr(u8)]
pub enum IpcMsgKind {
/// for cross-net messages that move native token, i.e. fund/release.
/// and in the future multi-level token transactions.
Transfer,
/// general-purpose cross-net transaction that call smart contracts.
Call,
/// receipt from the execution of cross-net messages
/// (currently limited to `Transfer` messages)
Receipt,
}
impl TryFrom<u8> for IpcMsgKind {
type Error = anyhow::Error;
fn try_from(value: u8) -> Result<Self, Self::Error> {
Ok(match value {
0 => IpcMsgKind::Transfer,
1 => IpcMsgKind::Call,
2 => IpcMsgKind::Receipt,
_ => return Err(anyhow!("invalid ipc msg kind")),
})
}
}
#[derive(PartialEq, Eq)]
pub enum IPCMsgType {
BottomUp,
TopDown,
}
pub fn is_bottomup(from: &SubnetID, to: &SubnetID) -> bool {
let index = match from.common_parent(to) {
Some((ind, _)) => ind,
None => return false,
};
// more children than the common parent
from.children_as_ref().len() > index
}
#[derive(PartialEq, Eq, Clone, Debug, Default, Serialize_tuple, Deserialize_tuple)]
pub struct CrossMsgs {
// FIXME: Consider to make this an AMT if we expect
// a lot of cross-messages to be propagated.
pub msgs: Vec<IpcEnvelope>,
}
#[derive(Serialize_tuple, Deserialize_tuple, Clone)]
struct ApplyMsgParams {
pub cross_msg: IpcEnvelope,
}
impl CrossMsgs {
pub fn new() -> Self {
Self::default()
}
}
#[cfg(feature = "fil-actor")]
impl IpcEnvelope {
pub fn send(
self,
rt: &impl fil_actors_runtime::runtime::Runtime,
rto: &Address,
) -> Result<RawBytes, fil_actors_runtime::ActorError> {
let blk = if !self.wrapped {
let msg = self.msg;
rt.send(rto, msg.method, msg.params.into(), msg.value)?
} else {
let method = self.msg.method;
let value = self.msg.value.clone();
let params =
fvm_ipld_encoding::ipld_block::IpldBlock::serialize_cbor(&ApplyMsgParams {
cross_msg: self,
})?;
rt.send(rto, method, params, value)?
};
Ok(match blk {
Some(b) => b.data.into(), // FIXME: this assumes cbor serialization. We should maybe return serialized IpldBlock
None => RawBytes::default(),
})
}
}
#[cfg(test)]
mod tests {
use crate::cross::*;
use std::str::FromStr;
#[test]
fn test_is_bottomup() {
bottom_up("/r123/f01", "/r123/f01/f02", false);
bottom_up("/r123/f01", "/r123", true);
bottom_up("/r123/f01", "/r123/f01/f02", false);
bottom_up("/r123/f01", "/r123/f02/f02", true);
bottom_up("/r123/f01/f02", "/r123/f01/f02", false);
bottom_up("/r123/f01/f02", "/r123/f01/f02/f03", false);
}
fn bottom_up(a: &str, b: &str, res: bool) {
assert_eq!(
is_bottomup(
&SubnetID::from_str(a).unwrap(),
&SubnetID::from_str(b).unwrap()
),
res
);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/link.rs | ipc/types/src/link.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use crate::actor_error;
use std::any::type_name;
use std::marker::PhantomData;
use super::{CodeType, TCid, TCidContent};
use crate::tcid_ops;
use anyhow::Result;
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_encoding::CborStore;
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use std::ops::{Deref, DerefMut};
/// Static typing information for `Cid` fields to help read and write data safely.
///
/// # Example
/// ```
/// use ipc_types::{TCid, TLink};
/// use fvm_ipld_blockstore::MemoryBlockstore;
/// use fvm_ipld_encoding::tuple::*;
/// use fvm_ipld_encoding::Cbor;
///
/// #[derive(Serialize_tuple, Deserialize_tuple)]
/// struct MyType {
/// my_field: u64
/// }
/// impl Cbor for MyType {}
///
/// let store = MemoryBlockstore::new();
///
/// let mut my_ref: TCid<TLink<MyType>> = TCid::new_link(&store, &MyType { my_field: 0 }).unwrap();
///
/// my_ref.update(&store, |x| {
/// x.my_field += 1;
/// Ok(())
/// }).unwrap();
///
/// assert_eq!(1, my_ref.load(&store).unwrap().my_field);
/// ```
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct TLink<T> {
_phantom_t: PhantomData<T>,
}
impl<T> TCidContent for TLink<T> {}
pub struct StoreContent<'s, S: Blockstore, T> {
store: &'s S,
content: T,
}
impl<'s, S: 's + Blockstore, T> Deref for StoreContent<'s, S, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.content
}
}
impl<'s, S: 's + Blockstore, T> DerefMut for StoreContent<'s, S, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.content
}
}
/// Operations on primitive types that can directly be read/written from/to CBOR.
impl<T, C: CodeType> TCid<TLink<T>, C>
where
T: Serialize + DeserializeOwned,
{
/// Initialize a `TCid` by storing a value as CBOR in the store and capturing the `Cid`.
pub fn new_link<S: Blockstore>(store: &S, value: &T) -> Result<Self> {
let cid = store.put_cbor(value, C::code())?;
Ok(Self::from(cid))
}
/// Read the underlying `Cid` from the store, if it exists.
pub fn maybe_load<'s, S: Blockstore>(
&self,
store: &'s S,
) -> Result<Option<StoreContent<'s, S, T>>> {
Ok(store
.get_cbor(&self.cid)?
.map(|content| StoreContent { store, content }))
}
/// Put the value into the store and overwrite the `Cid`.
pub fn flush<'s, S: Blockstore>(
&mut self,
value: StoreContent<'s, S, T>,
) -> Result<StoreContent<'s, S, T>> {
let cid = value.store.put_cbor(&value.content, C::code())?;
self.cid = cid;
Ok(value)
}
}
tcid_ops!(TLink<T : Serialize + DeserializeOwned>, C: CodeType => StoreContent<'s, S, T>);
/// This `Default` implementation is there in case we need to derive `Default` for something
/// that contains a `TCid`, but also to be used as a null pointer, in cases where using an
/// `Option<TCid<TLink<T>>>` is not the right choice.
///
/// For example if something has a previous link to a parent item in all cases bug Genesis,
/// it could be more convenient to use non-optional values, than to match cases all the time.
///
/// The reason we are not using `T::default()` to generate the CID is because it is highly
/// unlikely that the actual store we deal with won't have an entry for that, so we would
/// not be able to retrieve it anyway, and also because in Go we would have just a raw
/// `Cid` field, which, when empty, serializes as `"nil"`. We want to be compatible with that.
///
/// Also, using `T::default()` with non-optional fields would lead to infinite recursion.
impl<T, C: CodeType> Default for TCid<TLink<T>, C> {
fn default() -> Self {
Self::from(cid::Cid::default())
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/lib.rs | ipc/types/src/lib.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use std::{fmt::Display, marker::PhantomData};
use cid::{multihash::Code, Cid};
pub use self::actor_error::*;
pub mod actor_error;
mod amt;
mod ethaddr;
mod hamt;
mod link;
mod taddress;
mod uints;
pub use amt::TAmt;
pub use ethaddr::*;
use fvm_ipld_amt::Amt;
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_hamt::{BytesKey, Error as HamtError, Hamt};
pub use hamt::THamt;
pub use link::TLink;
use serde::{de::DeserializeOwned, Serialize};
pub use taddress::*;
pub const HAMT_BIT_WIDTH: u32 = 5;
/// Map type to be used within actors. The underlying type is a HAMT.
pub type Map<'bs, BS, V> = Hamt<&'bs BS, V, BytesKey>;
/// Array type used within actors. The underlying type is an AMT.
pub type Array<'bs, V, BS> = Amt<V, &'bs BS>;
/// Create a hamt with a custom bitwidth.
#[inline]
pub fn make_empty_map<BS, V>(store: &'_ BS, bitwidth: u32) -> Map<'_, BS, V>
where
BS: Blockstore,
V: DeserializeOwned + Serialize,
{
Map::<_, V>::new_with_bit_width(store, bitwidth)
}
/// Create a map with a root cid.
#[inline]
pub fn make_map_with_root<'bs, BS, V>(
root: &Cid,
store: &'bs BS,
) -> Result<Map<'bs, BS, V>, HamtError>
where
BS: Blockstore,
V: DeserializeOwned + Serialize,
{
Map::<_, V>::load_with_bit_width(root, store, HAMT_BIT_WIDTH)
}
/// Create a map with a root cid.
#[inline]
pub fn make_map_with_root_and_bitwidth<'bs, BS, V>(
root: &Cid,
store: &'bs BS,
bitwidth: u32,
) -> Result<Map<'bs, BS, V>, HamtError>
where
BS: Blockstore,
V: DeserializeOwned + Serialize,
{
Map::<_, V>::load_with_bit_width(root, store, bitwidth)
}
/// Helper type to be able to define `Code` as a generic parameter.
pub trait CodeType {
fn code() -> Code;
}
/// Marker trait for types that were meant to be used inside a TCid.
pub trait TCidContent {}
/// `TCid` is typed content, represented by a `Cid`.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct TCid<T: TCidContent, C = codes::Blake2b256> {
cid: Cid,
_phantom_t: PhantomData<T>,
_phantom_c: PhantomData<C>,
}
impl<T: TCidContent, C: CodeType> TCid<T, C> {
pub fn cid(&self) -> Cid {
self.cid
}
pub fn code(&self) -> Code {
C::code()
}
}
impl<T: TCidContent, C> From<Cid> for TCid<T, C> {
fn from(cid: Cid) -> Self {
TCid {
cid,
_phantom_t: PhantomData,
_phantom_c: PhantomData,
}
}
}
/// Serializes exactly as its underlying `Cid`.
impl<T: TCidContent, C> serde::Serialize for TCid<T, C> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.cid.serialize(serializer)
}
}
/// Deserializes exactly as its underlying `Cid`.
impl<'d, T: TCidContent, C> serde::Deserialize<'d> for TCid<T, C> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'d>,
{
let cid = Cid::deserialize(deserializer)?;
Ok(Self::from(cid))
}
}
impl<T: TCidContent, C> Display for TCid<T, C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.cid.fmt(f)
}
}
/// Assuming that the type implements `maybe_load` and `flush`,
/// implement some convenience methods.
///
/// NOTE: This can be achieved with a trait and an associated type as well, but unfortunately
/// it got too complex for Rust Analyzer to provide code completion, which makes it less ergonomic.
/// At least this way there's no need to import the trait that contains these ops.
#[macro_export]
macro_rules! tcid_ops {
(
$typ:ident <
$($gen:ident $($const:ident)? $(: $b:ident $(+ $bs:ident)* )? ),+
>
$(, $code:ident : $ct:ident)?
=> $item:ty
) => {
/// Operations on content types that, once loaded, are rooted
/// and bound to a block store, and need to be flushed back.
impl<
$($($const)? $gen $(: $b $(+ $bs)* )? ),+
$(, $code : $ct)?
> TCid<$typ<$($gen),+> $(, $code)?>
{
/// Check that the underlying `Cid` is for the empty use case.
///
/// What that means depends on the content.
pub fn is_default(&self) -> bool {
self.cid == Self::default().cid()
}
/// Read the underlying `Cid` from the store or return a `ActorError::illegal_state` error if not found.
/// Use this method for content that should have already been correctly initialized and maintained.
/// For content that may not be present, consider using `maybe_load` instead.
pub fn load<'s, S: fvm_ipld_blockstore::Blockstore>(&self, store: &'s S) -> Result<$item> {
match self.maybe_load(store)? {
Some(content) => Ok(content),
None => Err(actor_error!(
illegal_state;
"error loading {}: Cid ({}) did not match any in database",
type_name::<Self>(),
self.cid.to_string()
).into()),
}
}
/// Load, modify and flush a value, returning something as a result.
pub fn modify<'s, S: fvm_ipld_blockstore::Blockstore, R>(
&mut self,
store: &'s S,
f: impl FnOnce(&mut $item) -> anyhow::Result<R>,
) -> anyhow::Result<R> {
let mut value = self.load(store)?;
let result = f(&mut value)?;
self.flush(value)?;
Ok(result)
}
/// Load, modify and flush a value.
pub fn update<'s, S: fvm_ipld_blockstore::Blockstore>(
&mut self,
store: &'s S,
f: impl FnOnce(&mut $item) -> anyhow::Result<()>,
) -> anyhow::Result<()> {
self.modify(store, f)
}
}
}
}
pub mod codes {
use super::CodeType;
/// Define a unit struct for a `Code` element that
/// can be used as a generic parameter.
macro_rules! code_types {
($($code:ident => $typ:ident),+) => {
$(
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct $typ;
impl CodeType for $typ {
fn code() -> cid::multihash::Code {
cid::multihash::Code::$code
}
}
)*
};
}
// XXX: For some reason none of the other code types work,
// not even on their own as a variable:
// let c = multihash::Code::Keccak256;
// ERROR: no variant or associated item named `Keccak256` found for enum `Code`
// in the current scope variant or associated item not found in `Code`
code_types! {
Blake2b256 => Blake2b256
}
}
#[cfg(test)]
mod test {
use super::*;
use cid::Cid;
use fvm_ipld_blockstore::MemoryBlockstore;
use fvm_ipld_encoding::tuple::*;
use fvm_ipld_hamt::BytesKey;
#[derive(Default, Serialize_tuple, Deserialize_tuple, PartialEq)]
struct TestRecord {
foo: u64,
bar: Vec<u8>,
}
#[derive(Default, Serialize_tuple, Deserialize_tuple)]
struct TestRecordTyped {
pub optional: Option<TCid<TLink<TestRecord>>>,
pub map: TCid<THamt<String, TestRecord>>,
}
impl TestRecordTyped {
fn new(store: &MemoryBlockstore) -> Self {
Self {
optional: None,
map: TCid::new_hamt(store).unwrap(),
}
}
}
#[derive(Default, Serialize_tuple, Deserialize_tuple)]
struct TestRecordUntyped {
pub optional: Option<Cid>,
pub map: Cid,
}
#[test]
fn default_cid_and_default_hamt_equal() {
let cid_typed: TCid<TLink<TestRecordTyped>> = TCid::default();
let cid_untyped: TCid<TLink<TestRecordUntyped>> = TCid::default();
// The stronger typing allows us to use proper default values,
// but this should not be a breaking change, they should be treated as null pointers.
assert_eq!(cid_typed.cid(), cid_untyped.cid());
}
#[test]
fn default_value_read_fails() {
let cid_typed: TCid<TLink<TestRecordTyped>> = TCid::default();
let store = MemoryBlockstore::new();
assert!(cid_typed.load(&store).is_err());
}
#[test]
fn ref_modify() {
let store = MemoryBlockstore::new();
let mut r: TCid<TLink<TestRecord>> =
TCid::new_link(&store, &TestRecord::default()).unwrap();
r.modify(&store, |c| {
c.foo += 1;
Ok(())
})
.unwrap();
assert_eq!(r.load(&store).unwrap().foo, 1);
}
#[test]
fn hamt_modify() {
let store = MemoryBlockstore::new();
let mut rec = TestRecordTyped::new(&store);
let eggs = rec
.map
.modify(&store, |map| {
map.set(
BytesKey::from("spam"),
TestRecord {
foo: 1,
bar: Vec::new(),
},
)?;
Ok("eggs")
})
.unwrap();
assert_eq!(eggs, "eggs");
let map = rec.map.load(&store).unwrap();
let foo = map.get(&BytesKey::from("spam")).unwrap().map(|x| x.foo);
assert_eq!(foo, Some(1))
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/hamt.rs | ipc/types/src/hamt.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use crate::actor_error;
use std::any::type_name;
use std::marker::PhantomData;
use super::{make_empty_map, make_map_with_root_and_bitwidth};
use crate::tcid_ops;
use anyhow::{anyhow, Result};
use fvm_ipld_blockstore::{Blockstore, MemoryBlockstore};
use fvm_ipld_hamt::Error as HamtError;
use fvm_ipld_hamt::Hamt;
use fvm_shared::HAMT_BIT_WIDTH;
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use super::{TCid, TCidContent};
/// Static typing information for HAMT fields, a.k.a. `Map`.
///
/// # Example
/// ```
/// use ipc_types::{TCid, THamt};
/// use fvm_ipld_blockstore::MemoryBlockstore;
/// use fvm_ipld_encoding::tuple::*;
/// use fvm_ipld_encoding::Cbor;
/// use fvm_ipld_hamt::BytesKey;
///
/// #[derive(Serialize_tuple, Deserialize_tuple)]
/// struct MyType {
/// my_field: TCid<THamt<String, u64>>
/// }
/// impl Cbor for MyType {}
///
/// let store = MemoryBlockstore::new();
///
/// let mut my_inst = MyType {
/// my_field: TCid::new_hamt(&store).unwrap()
/// };
///
/// let key = BytesKey::from("foo");
///
/// my_inst.my_field.update(&store, |x| {
/// x.set(key.clone(), 1).map_err(|e| e.into()).map(|_| ())
/// }).unwrap();
///
/// assert_eq!(&1, my_inst.my_field.load(&store).unwrap().get(&key).unwrap().unwrap())
/// ```
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct THamt<K, V, const W: u32 = HAMT_BIT_WIDTH> {
_phantom_k: PhantomData<K>,
_phantom_v: PhantomData<V>,
}
impl<K, V, const W: u32> TCidContent for THamt<K, V, W> {}
impl<K, V, const W: u32> TCid<THamt<K, V, W>>
where
V: Serialize + DeserializeOwned,
{
/// Initialize an empty data structure, flush it to the store and capture the `Cid`.
pub fn new_hamt<S: Blockstore>(store: &S) -> Result<Self> {
let cid = make_empty_map::<_, V>(store, W)
.flush()
.map_err(|e| anyhow!("Failed to create empty map: {:?}", e))?;
Ok(Self::from(cid))
}
/// Load the data pointing at the store with the underlying `Cid` as its root, if it exists.
pub fn maybe_load<'s, S: Blockstore>(&self, store: &'s S) -> Result<Option<Hamt<&'s S, V>>> {
match make_map_with_root_and_bitwidth::<S, V>(&self.cid, store, W) {
Ok(content) => Ok(Some(content)),
Err(HamtError::CidNotFound(_)) => Ok(None),
Err(other) => Err(anyhow!(other)),
}
}
/// Flush the data to the store and overwrite the `Cid`.
pub fn flush<'s, S: Blockstore>(
&mut self,
mut value: Hamt<&'s S, V>,
) -> Result<Hamt<&'s S, V>> {
let cid = value
.flush()
.map_err(|e| anyhow!("error flushing {}: {:?}", type_name::<Self>(), e))?;
self.cid = cid;
Ok(value)
}
}
tcid_ops!(THamt<K, V : Serialize + DeserializeOwned, W const: u32> => Hamt<&'s S, V>);
/// This `Default` implementation is unsound in that while it
/// creates `TCid` instances with a correct `Cid` value, this value
/// is not stored anywhere, so there is no guarantee that any retrieval
/// attempt from a random store won't fail.
///
/// The main purpose is to allow the `#[derive(Default)]` to be
/// applied on types that use a `TCid` field, if that's unavoidable.
impl<K, V, const W: u32> Default for TCid<THamt<K, V, W>>
where
V: Serialize + DeserializeOwned,
{
fn default() -> Self {
Self::new_hamt(&MemoryBlockstore::new()).unwrap()
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/ethaddr.rs | ipc/types/src/ethaddr.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use std::str::FromStr;
use crate::uints::U256;
use fvm_ipld_encoding::{serde, strict_bytes};
use fvm_shared::address::Address;
use fvm_shared::ActorID;
const EAM_ACTOR_ID: u64 = 10;
/// A Filecoin address as represented in the FEVM runtime (also called EVM-form).
#[derive(serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, Copy)]
pub struct EthAddress(#[serde(with = "strict_bytes")] pub [u8; 20]);
/// Converts a U256 to an EthAddress by taking the lower 20 bytes.
///
/// Per the EVM spec, this simply discards the high bytes.
impl From<U256> for EthAddress {
fn from(v: U256) -> Self {
let mut bytes = [0u8; 32];
v.to_big_endian(&mut bytes);
Self(bytes[12..].try_into().unwrap())
}
}
impl std::fmt::Debug for EthAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&hex::encode(self.0))
}
}
impl FromStr for EthAddress {
type Err = hex::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Check if it has the 0x prefix
if s.len() > 2 && &s[..2] == "0x" {
return Self::from_str(&s[2..]);
}
let bytes = hex::decode(s)?;
if bytes.len() != 20 {
return Err(hex::FromHexError::InvalidStringLength);
}
let mut addr = [0u8; 20];
addr.copy_from_slice(&bytes);
Ok(Self(addr))
}
}
impl From<EthAddress> for Address {
fn from(addr: EthAddress) -> Self {
From::from(&addr)
}
}
impl From<&EthAddress> for Address {
fn from(addr: &EthAddress) -> Self {
if let Some(id) = addr.as_id() {
Address::new_id(id)
} else {
Address::new_delegated(EAM_ACTOR_ID, addr.as_ref()).unwrap()
}
}
}
impl EthAddress {
/// Returns a "null" address.
pub const fn null() -> Self {
Self([0u8; 20])
}
/// Returns an EVM-form ID address from actor ID.
pub fn from_id(id: u64) -> EthAddress {
let mut bytes = [0u8; 20];
bytes[0] = 0xff;
bytes[12..].copy_from_slice(&id.to_be_bytes());
EthAddress(bytes)
}
/// Interpret the EVM word as an ID address in EVM-form, and return a Filecoin ID address if
/// that's the case.
///
/// An ID address starts with 0xff (msb), and contains the u64 in the last 8 bytes.
/// We assert that everything in between are 0x00, otherwise we've gotten an illegal address.
///
/// 0 1-11 12
/// 0xff \[0x00...] [id address...]
pub fn as_id(&self) -> Option<ActorID> {
if !self.is_id() {
return None;
}
Some(u64::from_be_bytes(self.0[12..].try_into().unwrap()))
}
/// Returns this Address as an EVM word.
#[inline]
pub fn as_evm_word(&self) -> U256 {
U256::from_big_endian(&self.0)
}
/// Returns true if this is the null/zero EthAddress.
#[inline]
pub fn is_null(&self) -> bool {
self.0 == [0; 20]
}
/// Returns true if the EthAddress refers to an address in the precompile range.
/// [reference](https://github.com/filecoin-project/ref-fvm/issues/1164#issuecomment-1371304676)
#[inline]
pub fn is_precompile(&self) -> bool {
// Exact index is not checked since it is unknown to the EAM what precompiles exist in the EVM actor.
// 0 indexes of both ranges are not assignable as well but are _not_ precompile address.
let [prefix, middle @ .., _index] = self.0;
(prefix == 0xfe || prefix == 0x00) && middle == [0u8; 18]
}
/// Returns true if the EthAddress is an actor ID embedded in an eth address.
#[inline]
pub fn is_id(&self) -> bool {
self.0[0] == 0xff && self.0[1..12].iter().all(|&i| i == 0)
}
}
impl AsRef<[u8]> for EthAddress {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use super::EthAddress;
use crate::uints::U256;
// padding (12 bytes)
const TYPE_PADDING: &[u8] = &[0; 12];
// ID address marker (1 byte)
const ID_ADDRESS_MARKER: &[u8] = &[0xff];
// ID address marker (1 byte)
const GOOD_ADDRESS_PADDING: &[u8] = &[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]; // padding for inner u64 (11 bytes)
#[test]
fn ethaddr_from_str() {
EthAddress::from_str("0x6BE1Ccf648c74800380d0520D797a170c808b624").unwrap();
}
macro_rules! id_address_test {
($($name:ident: $input:expr => $expectation:expr,)*) => {
$(
#[test]
fn $name() {
let evm_bytes = $input.concat();
let evm_addr = EthAddress::from(U256::from(evm_bytes.as_slice()));
assert_eq!(
evm_addr.as_id(),
$expectation
);
// test inverse conversion, if a valid ID address was supplied
if let Some(fil_id) = $expectation {
assert_eq!(EthAddress::from_id(fil_id), evm_addr);
}
}
)*
};
}
id_address_test! {
good_address_1: [
TYPE_PADDING,
ID_ADDRESS_MARKER,
GOOD_ADDRESS_PADDING,
vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01].as_slice() // ID address (u64 big endian) (8 bytes)
] => Some(1),
good_address_2: [
TYPE_PADDING,
ID_ADDRESS_MARKER,
GOOD_ADDRESS_PADDING,
vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff].as_slice() // ID address (u64 big endian) (8 bytes)
] => Some(u16::MAX as u64),
bad_marker: [
TYPE_PADDING,
&[0xfa],
GOOD_ADDRESS_PADDING,
vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01].as_slice() // ID address (u64 big endian) (8 bytes)
] => None,
bad_padding: [
TYPE_PADDING,
ID_ADDRESS_MARKER,
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], // bad padding
vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01].as_slice() // ID address (u64 big endian) (8 bytes)
] => None,
bad_marker_and_padding: [
TYPE_PADDING,
&[0xfa],
&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], // bad padding
vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01].as_slice() // ID address (u64 big endian) (8 bytes)
] => None,
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/taddress.rs | ipc/types/src/taddress.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
#![allow(clippy::upper_case_acronyms)] // this is to disable warning for BLS
use std::{convert::TryFrom, fmt::Display, marker::PhantomData, str::FromStr};
use serde::de::Error;
use fvm_shared::address::{Address, Payload};
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct TAddress<T> {
addr: Address,
_phantom: PhantomData<T>,
}
impl<T> TAddress<T> {
pub fn new(addr: Address) -> Self {
Self {
addr,
_phantom: Default::default(),
}
}
#[allow(dead_code)]
pub fn to_bytes(&self) -> Vec<u8> {
self.addr.to_bytes()
}
/// The untyped `Address` representation.
#[allow(dead_code)]
pub fn addr(&self) -> &Address {
&self.addr
}
}
trait RawAddress {
fn is_compatible(addr: Address) -> bool;
}
/// Define a unit struct for address types that can be used as a generic parameter.
macro_rules! raw_address_types {
($($typ:ident),+) => {
$(
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct $typ;
impl RawAddress for $typ {
fn is_compatible(addr: Address) -> bool {
match addr.payload() {
Payload::$typ(_) => true,
_ => false
}
}
}
)*
};
}
// Based on `Payload` variants.
raw_address_types! {
ID,
Secp256k1,
Actor,
BLS
}
impl<T> From<TAddress<T>> for Address {
fn from(t: TAddress<T>) -> Self {
t.addr
}
}
impl<A: RawAddress> TryFrom<Address> for TAddress<A> {
type Error = fvm_shared::address::Error;
fn try_from(value: Address) -> Result<Self, Self::Error> {
if !A::is_compatible(value) {
return Err(fvm_shared::address::Error::InvalidPayload);
}
Ok(Self {
addr: value,
_phantom: PhantomData,
})
}
}
/// Serializes exactly as its underlying `Address`.
impl<T> serde::Serialize for TAddress<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.addr.serialize(serializer)
}
}
/// Deserializes exactly as its underlying `Address` but might be rejected if it's not the expected type.
impl<'d, T> serde::Deserialize<'d> for TAddress<T>
where
Self: TryFrom<Address>,
<Self as TryFrom<Address>>::Error: Display,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'d>,
{
let raw = Address::deserialize(deserializer)?;
match Self::try_from(raw) {
Ok(addr) => Ok(addr),
Err(e) => Err(D::Error::custom(format!("wrong address type: {e}"))),
}
}
}
/// Apparently CBOR has problems using `Address` as a key in `HashMap`.
/// This type can be used to wrap an address and turn it into `String`
/// for the purpose of CBOR serialization.
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct TAddressKey<T>(pub TAddress<T>);
/// Serializes to the `String` format of the underlying `Address`.
impl<T> serde::Serialize for TAddressKey<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.addr.to_string().serialize(serializer)
}
}
/// Deserializes from `String` format. May be rejected if the address is not the expected type.
impl<'d, T> serde::Deserialize<'d> for TAddressKey<T>
where
TAddress<T>: TryFrom<Address>,
<TAddress<T> as TryFrom<Address>>::Error: Display,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'d>,
{
let str = String::deserialize(deserializer)?;
let raw = Address::from_str(&str)
.map_err(|e| D::Error::custom(format!("not an address string: {e:?}")))?;
let addr = TAddress::<T>::try_from(raw)
.map_err(|e| D::Error::custom(format!("wrong address type: {e}")))?;
Ok(Self(addr))
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/amt.rs | ipc/types/src/amt.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use crate::actor_error;
use std::any::type_name;
use std::marker::PhantomData;
use crate::tcid_ops;
use super::{TCid, TCidContent};
use anyhow::{anyhow, Result};
use fvm_ipld_amt::Amt;
use fvm_ipld_amt::Error as AmtError;
use fvm_ipld_blockstore::{Blockstore, MemoryBlockstore};
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
/// Same as `fvm_ipld_amt::DEFAULT_BIT_WIDTH`.
const AMT_BIT_WIDTH: u32 = 3;
/// Static typing information for AMT fields, a.k.a. `Array`.
///
/// # Example
/// ```
/// use ipc_types::{TCid, TAmt};
/// use fvm_ipld_blockstore::MemoryBlockstore;
/// use fvm_ipld_encoding::tuple::*;
/// use fvm_ipld_encoding::Cbor;
///
/// #[derive(Serialize_tuple, Deserialize_tuple)]
/// struct MyType {
/// my_field: TCid<TAmt<String>>
/// }
/// impl Cbor for MyType {}
///
/// let store = MemoryBlockstore::new();
///
/// let mut my_inst = MyType {
/// my_field: TCid::new_amt(&store).unwrap()
/// };
///
/// my_inst.my_field.update(&store, |x| {
/// x.set(0, "bar".into()).map_err(|e| e.into())
/// }).unwrap();
///
/// assert_eq!(&"bar", my_inst.my_field.load(&store).unwrap().get(0).unwrap().unwrap())
/// ```
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct TAmt<V, const W: u32 = AMT_BIT_WIDTH> {
_phantom_v: PhantomData<V>,
}
impl<V, const W: u32> TCidContent for TAmt<V, W> {}
impl<V, const W: u32> TCid<TAmt<V, W>>
where
V: Serialize + DeserializeOwned,
{
/// Initialize an empty data structure, flush it to the store and capture the `Cid`.
pub fn new_amt<S: Blockstore>(store: &S) -> Result<Self> {
let cid = Amt::<V, _>::new_with_bit_width(store, W)
.flush()
.map_err(|e| anyhow!("Failed to create empty array: {}", e))?;
Ok(Self::from(cid))
}
/// Load the data pointing at the store with the underlying `Cid` as its root, if it exists.
pub fn maybe_load<'s, S: Blockstore>(&self, store: &'s S) -> Result<Option<Amt<V, &'s S>>> {
match Amt::<V, _>::load(&self.cid, store) {
Ok(content) => Ok(Some(content)),
Err(AmtError::CidNotFound(_)) => Ok(None),
Err(other) => Err(anyhow!(other)),
}
}
pub fn flush<'s, S: Blockstore>(&mut self, mut value: Amt<V, &'s S>) -> Result<Amt<V, &'s S>> {
let cid = value
.flush()
.map_err(|e| anyhow!("error flushing {}: {}", type_name::<Self>(), e))?;
self.cid = cid;
Ok(value)
}
}
tcid_ops!(TAmt<V : Serialize + DeserializeOwned, W const: u32> => Amt<V, &'s S>);
/// This `Default` implementation is unsound in that while it
/// creates `TAmt` instances with a correct `Cid` value, this value
/// is not stored anywhere, so there is no guarantee that any retrieval
/// attempt from a random store won't fail.
///
/// The main purpose is to allow the `#[derive(Default)]` to be
/// applied on types that use a `TAmt` field, if that's unavoidable.
impl<V, const W: u32> Default for TCid<TAmt<V, W>>
where
V: Serialize + DeserializeOwned,
{
fn default() -> Self {
Self::new_amt(&MemoryBlockstore::new()).unwrap()
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/uints.rs | ipc/types/src/uints.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
// to silence construct_uint! clippy warnings
// see https://github.com/paritytech/parity-common/issues/660
#![allow(clippy::ptr_offset_with_cast, clippy::assign_op_pattern)]
use serde::{Deserialize, Serialize};
//use substrate_bn::arith;
use {
fvm_shared::bigint::BigInt, fvm_shared::econ::TokenAmount, std::cmp::Ordering, std::fmt,
uint::construct_uint,
};
construct_uint! { pub struct U256(4); } // ethereum word size
construct_uint! { pub struct U512(8); } // used for addmod and mulmod opcodes
// Convenience method for comparing against a small value.
impl PartialOrd<u64> for U256 {
fn partial_cmp(&self, other: &u64) -> Option<Ordering> {
if self.0[3] > 0 || self.0[2] > 0 || self.0[1] > 0 {
Some(Ordering::Greater)
} else {
self.0[0].partial_cmp(other)
}
}
}
impl PartialEq<u64> for U256 {
fn eq(&self, other: &u64) -> bool {
self.0[0] == *other && self.0[1] == 0 && self.0[2] == 0 && self.0[3] == 0
}
}
impl U256 {
pub const BITS: u32 = 256;
pub const ZERO: Self = U256::from_u64(0);
pub const ONE: Self = U256::from_u64(1);
pub const I128_MIN: Self = U256([0, 0, 0, i64::MIN as u64]);
#[inline(always)]
pub const fn from_u128_words(high: u128, low: u128) -> U256 {
U256([
low as u64,
(low >> u64::BITS) as u64,
high as u64,
(high >> u64::BITS) as u64,
])
}
#[inline(always)]
pub const fn from_u64(value: u64) -> U256 {
U256([value, 0, 0, 0])
}
#[inline(always)]
pub const fn i256_is_negative(&self) -> bool {
(self.0[3] as i64) < 0
}
/// turns a i256 value to negative
#[inline(always)]
pub fn i256_neg(&self) -> U256 {
if self.is_zero() {
U256::ZERO
} else {
!*self + U256::ONE
}
}
#[inline(always)]
pub fn i256_cmp(&self, other: &U256) -> Ordering {
// true > false:
// - true < positive:
match other.i256_is_negative().cmp(&self.i256_is_negative()) {
Ordering::Equal => self.cmp(other),
sign_cmp => sign_cmp,
}
}
#[inline]
pub fn i256_div(&self, other: &U256) -> U256 {
if self.is_zero() || other.is_zero() {
// EVM defines X/0 to be 0.
return U256::ZERO;
}
let mut first = *self;
let mut second = *other;
// Record and strip the signs. We add them back at the end.
let first_neg = first.i256_is_negative();
let second_neg = second.i256_is_negative();
if first_neg {
first = first.i256_neg()
}
if second_neg {
second = second.i256_neg()
}
let d = first / second;
// Flip the sign back if necessary.
if d.is_zero() || first_neg == second_neg {
d
} else {
d.i256_neg()
}
}
#[inline]
pub fn i256_mod(&self, other: &U256) -> U256 {
if self.is_zero() || other.is_zero() {
// X % 0 or 0 % X is always 0.
return U256::ZERO;
}
let mut first = *self;
let mut second = *other;
// Record and strip the sign.
let negative = first.i256_is_negative();
if negative {
first = first.i256_neg();
}
if second.i256_is_negative() {
second = second.i256_neg()
}
let r = first % second;
// Restore the sign.
if negative && !r.is_zero() {
r.i256_neg()
} else {
r
}
}
pub fn to_bytes(self) -> [u8; 32] {
let mut buf = [0u8; 32];
self.to_big_endian(&mut buf);
buf
}
/// Returns the low 64 bits, saturating the value to u64 max if it is larger
pub fn to_u64_saturating(self) -> u64 {
if self.bits() > 64 {
u64::MAX
} else {
self.0[0]
}
}
}
impl U512 {
pub fn low_u256(&self) -> U256 {
let [a, b, c, d, ..] = self.0;
U256([a, b, c, d])
}
}
impl From<&TokenAmount> for U256 {
fn from(amount: &TokenAmount) -> U256 {
let (_, bytes) = amount.atto().to_bytes_be();
U256::from(bytes.as_slice())
}
}
impl From<U256> for U512 {
fn from(v: U256) -> Self {
let [a, b, c, d] = v.0;
U512([a, b, c, d, 0, 0, 0, 0])
}
}
impl From<&U256> for TokenAmount {
fn from(ui: &U256) -> TokenAmount {
let mut bits = [0u8; 32];
ui.to_big_endian(&mut bits);
TokenAmount::from_atto(BigInt::from_bytes_be(fvm_shared::bigint::Sign::Plus, &bits))
}
}
impl Serialize for U256 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut bytes = [0u8; 32];
self.to_big_endian(&mut bytes);
serializer.serialize_bytes(zeroless_view(&bytes))
}
}
impl<'de> Deserialize<'de> for U256 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = U256;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "at most 32 bytes")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if v.len() > 32 {
return Err(serde::de::Error::invalid_length(v.len(), &self));
}
Ok(U256::from_big_endian(v))
}
}
deserializer.deserialize_bytes(Visitor)
}
}
fn zeroless_view(v: &impl AsRef<[u8]>) -> &[u8] {
let v = v.as_ref();
&v[v.iter().take_while(|&&b| b == 0).count()..]
}
#[cfg(test)]
mod tests {
use fvm_ipld_encoding::{BytesDe, BytesSer, RawBytes};
use {super::*, core::num::Wrapping};
#[test]
fn div_i256() {
assert_eq!(Wrapping(i8::MIN) / Wrapping(-1), Wrapping(i8::MIN));
assert_eq!(i8::MAX / -1, -i8::MAX);
let zero = U256::ZERO;
let one = U256::ONE;
let one_hundred = U256::from(100);
let fifty = U256::from(50);
let two = U256::from(2);
let neg_one_hundred = U256::from(100);
let minus_one = U256::from(1);
let max_value = U256::from(2).pow(255.into()) - 1;
let neg_max_value = U256::from(2).pow(255.into()) - 1;
assert_eq!(U256::I128_MIN.i256_div(&minus_one), U256::I128_MIN);
assert_eq!(U256::I128_MIN.i256_div(&one), U256::I128_MIN);
assert_eq!(
U256::I128_MIN.i256_div(&two),
U256([0, 0, 0, i64::MIN as u64 + (i64::MIN as u64 >> 1)])
);
assert_eq!(one.i256_div(&U256::I128_MIN), zero);
assert_eq!(max_value.i256_div(&one), max_value);
assert_eq!(max_value.i256_div(&minus_one), neg_max_value);
assert_eq!(one_hundred.i256_div(&minus_one), neg_one_hundred);
assert_eq!(one_hundred.i256_div(&two), fifty);
assert_eq!(zero.i256_div(&zero), zero);
assert_eq!(one.i256_div(&zero), zero);
assert_eq!(zero.i256_div(&one), zero);
}
#[test]
fn mod_i256() {
let zero = U256::ZERO;
let one = U256::ONE;
let one_hundred = U256::from(100);
let two = U256::from(2);
let three = U256::from(3);
let neg_one_hundred = U256::from(100).i256_neg();
let minus_one = U256::from(1).i256_neg();
let neg_three = U256::from(3).i256_neg();
let max_value = U256::from(2).pow(255.into()) - 1;
// zero
assert_eq!(minus_one.i256_mod(&U256::ZERO), U256::ZERO);
assert_eq!(max_value.i256_mod(&U256::ZERO), U256::ZERO);
assert_eq!(U256::ZERO.i256_mod(&U256::ZERO), U256::ZERO);
assert_eq!(minus_one.i256_mod(&two), minus_one);
assert_eq!(U256::I128_MIN.i256_mod(&one), 0);
assert_eq!(one.i256_mod(&U256::I128_MIN), one);
assert_eq!(one.i256_mod(&U256::from(i128::MAX)), one);
assert_eq!(max_value.i256_mod(&minus_one), zero);
assert_eq!(neg_one_hundred.i256_mod(&minus_one), zero);
assert_eq!(one_hundred.i256_mod(&two), zero);
assert_eq!(one_hundred.i256_mod(&neg_three), one);
assert_eq!(neg_one_hundred.i256_mod(&three), minus_one);
let a = U256::from(95).i256_neg();
let b = U256::from(256);
assert_eq!(a % b, U256::from(161))
}
#[test]
fn negative_i256() {
assert_eq!(U256::ZERO.i256_neg(), U256::ZERO);
let one = U256::ONE.i256_neg();
assert!(one.i256_is_negative());
let neg_one = U256::from(&[0xff; 32]);
let pos_one = neg_one.i256_neg();
assert_eq!(pos_one, U256::ONE);
}
#[test]
fn u256_serde() {
let encoded = RawBytes::serialize(U256::from(0x4d2)).unwrap();
let BytesDe(bytes) = encoded.deserialize().unwrap();
assert_eq!(bytes, &[0x04, 0xd2]);
let decoded: U256 = encoded.deserialize().unwrap();
assert_eq!(decoded, 0x4d2);
}
#[test]
fn u256_empty() {
let encoded = RawBytes::serialize(U256::from(0)).unwrap();
let BytesDe(bytes) = encoded.deserialize().unwrap();
assert!(bytes.is_empty());
}
#[test]
fn u256_overflow() {
let encoded = RawBytes::serialize(BytesSer(&[1; 33])).unwrap();
encoded
.deserialize::<U256>()
.expect_err("should have failed to decode an over-large u256");
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/types/src/actor_error.rs | ipc/types/src/actor_error.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use fvm_ipld_encoding::de::DeserializeOwned;
use fvm_ipld_encoding::ipld_block::IpldBlock;
use std::fmt::Display;
use fvm_shared::error::ExitCode;
use thiserror::Error;
/// The error type returned by actor method calls.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("ActorError(exit_code: {exit_code:?}, msg: {msg})")]
pub struct ActorError {
/// The exit code for this invocation.
/// Codes less than `FIRST_USER_EXIT_CODE` are prohibited and will be overwritten by the VM.
exit_code: ExitCode,
/// Optional exit data
data: Option<IpldBlock>,
/// Message for debugging purposes,
msg: String,
}
impl ActorError {
/// Creates a new ActorError. This method does not check that the code is in the
/// range of valid actor abort codes.
pub fn unchecked(code: ExitCode, msg: String) -> Self {
Self {
exit_code: code,
msg,
data: None,
}
}
pub fn unchecked_with_data(code: ExitCode, msg: String, data: Option<IpldBlock>) -> Self {
Self {
exit_code: code,
msg,
data,
}
}
/// Creates a new ActorError. This method checks if the exit code is within the allowed range,
/// and automatically converts it into a user code.
pub fn checked(code: ExitCode, msg: String, data: Option<IpldBlock>) -> Self {
let exit_code = match code {
// This means the called actor did something wrong. We can't "make up" a
// reasonable exit code.
ExitCode::SYS_MISSING_RETURN
| ExitCode::SYS_ILLEGAL_INSTRUCTION
| ExitCode::SYS_ILLEGAL_EXIT_CODE => ExitCode::USR_UNSPECIFIED,
// We don't expect any other system errors.
code if code.is_system_error() => ExitCode::USR_ASSERTION_FAILED,
// Otherwise, pass it through.
code => code,
};
Self {
exit_code,
msg,
data,
}
}
pub fn illegal_argument(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_ILLEGAL_ARGUMENT,
msg,
data: None,
}
}
pub fn not_found(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_NOT_FOUND,
msg,
data: None,
}
}
pub fn forbidden(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_FORBIDDEN,
msg,
data: None,
}
}
pub fn insufficient_funds(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_INSUFFICIENT_FUNDS,
msg,
data: None,
}
}
pub fn illegal_state(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_ILLEGAL_STATE,
msg,
data: None,
}
}
pub fn serialization(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_SERIALIZATION,
msg,
data: None,
}
}
pub fn unhandled_message(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_UNHANDLED_MESSAGE,
msg,
data: None,
}
}
pub fn unspecified(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_UNSPECIFIED,
msg,
data: None,
}
}
pub fn assertion_failed(msg: String) -> Self {
Self {
exit_code: ExitCode::USR_ASSERTION_FAILED,
msg,
data: None,
}
}
/// Returns the exit code of the error.
pub fn exit_code(&self) -> ExitCode {
self.exit_code
}
/// Error message of the actor error.
pub fn msg(&self) -> &str {
&self.msg
}
/// Extracts the optional associated data without copying.
pub fn take_data(&mut self) -> Option<IpldBlock> {
std::mem::take(&mut self.data)
}
/// Prefix error message with a string message.
pub fn wrap(mut self, msg: impl AsRef<str>) -> Self {
self.msg = format!("{}: {}", msg.as_ref(), self.msg);
self
}
}
/// Converts a raw encoding error into an ErrSerialization.
impl From<fvm_ipld_encoding::Error> for ActorError {
fn from(e: fvm_ipld_encoding::Error) -> Self {
Self {
exit_code: ExitCode::USR_SERIALIZATION,
msg: e.to_string(),
data: None,
}
}
}
/// Converts an actor deletion error into an actor error with the appropriate exit code. This
/// facilitates propagation.
#[cfg(feature = "fil-actor")]
impl From<fvm_sdk::error::ActorDeleteError> for ActorError {
fn from(e: fvm_sdk::error::ActorDeleteError) -> Self {
Self {
exit_code: ExitCode::USR_ILLEGAL_ARGUMENT,
msg: e.to_string(),
data: None,
}
}
}
/// Converts a state-read error into an an actor error with the appropriate exit code (illegal actor).
/// This facilitates propagation.
#[cfg(feature = "fil-actor")]
impl From<fvm_sdk::error::StateReadError> for ActorError {
fn from(e: fvm_sdk::error::StateReadError) -> Self {
Self {
exit_code: ExitCode::USR_ILLEGAL_STATE,
data: None,
msg: e.to_string(),
}
}
}
/// Converts a state update error into an an actor error with the appropriate exit code.
/// This facilitates propagation.
#[cfg(feature = "fil-actor")]
impl From<fvm_sdk::error::StateUpdateError> for ActorError {
fn from(e: fvm_sdk::error::StateUpdateError) -> Self {
Self {
exit_code: match e {
fvm_sdk::error::StateUpdateError::ActorDeleted => ExitCode::USR_ILLEGAL_STATE,
fvm_sdk::error::StateUpdateError::ReadOnly => ExitCode::USR_READ_ONLY,
},
data: None,
msg: e.to_string(),
}
}
}
/// Convenience macro for generating Actor Errors
#[macro_export]
macro_rules! actor_error {
// Error with only one stringable expression
( $code:ident; $msg:expr ) => { $crate::ActorError::$code($msg.to_string()) };
// String with positional arguments
( $code:ident; $msg:literal $(, $ex:expr)+ ) => {
$crate::ActorError::$code(format!($msg, $($ex,)*))
};
// Error with only one stringable expression, with comma separator
( $code:ident, $msg:expr ) => { $crate::actor_error!($code; $msg) };
// String with positional arguments, with comma separator
( $code:ident, $msg:literal $(, $ex:expr)+ ) => {
$crate::actor_error!($code; $msg $(, $ex)*)
};
}
// Adds context to an actor error's descriptive message.
pub trait ActorContext<T> {
fn context<C>(self, context: C) -> Result<T, ActorError>
where
C: Display + 'static;
fn with_context<C, F>(self, f: F) -> Result<T, ActorError>
where
C: Display + 'static,
F: FnOnce() -> C;
}
impl<T> ActorContext<T> for Result<T, ActorError> {
fn context<C>(self, context: C) -> Result<T, ActorError>
where
C: Display + 'static,
{
self.map_err(|mut err| {
err.msg = format!("{}: {}", context, err.msg);
err
})
}
fn with_context<C, F>(self, f: F) -> Result<T, ActorError>
where
C: Display + 'static,
F: FnOnce() -> C,
{
self.map_err(|mut err| {
err.msg = format!("{}: {}", f(), err.msg);
err
})
}
}
// Adapts a target into an actor error.
pub trait AsActorError<T>: Sized {
fn exit_code(self, code: ExitCode) -> Result<T, ActorError>;
fn context_code<C>(self, code: ExitCode, context: C) -> Result<T, ActorError>
where
C: Display + 'static;
fn with_context_code<C, F>(self, code: ExitCode, f: F) -> Result<T, ActorError>
where
C: Display + 'static,
F: FnOnce() -> C;
}
// Note: E should be std::error::Error, revert to this after anyhow:Error is no longer used.
impl<T, E: Display> AsActorError<T> for Result<T, E> {
fn exit_code(self, code: ExitCode) -> Result<T, ActorError> {
self.map_err(|err| ActorError {
exit_code: code,
msg: err.to_string(),
data: None,
})
}
fn context_code<C>(self, code: ExitCode, context: C) -> Result<T, ActorError>
where
C: Display + 'static,
{
self.map_err(|err| ActorError {
exit_code: code,
msg: format!("{context}: {err}"),
data: None,
})
}
fn with_context_code<C, F>(self, code: ExitCode, f: F) -> Result<T, ActorError>
where
C: Display + 'static,
F: FnOnce() -> C,
{
self.map_err(|err| ActorError {
exit_code: code,
msg: format!("{}: {}", f(), err),
data: None,
})
}
}
impl<T> AsActorError<T> for Option<T> {
fn exit_code(self, code: ExitCode) -> Result<T, ActorError> {
self.ok_or_else(|| ActorError {
exit_code: code,
msg: "None".to_string(),
data: None,
})
}
fn context_code<C>(self, code: ExitCode, context: C) -> Result<T, ActorError>
where
C: Display + 'static,
{
self.ok_or_else(|| ActorError {
exit_code: code,
msg: context.to_string(),
data: None,
})
}
fn with_context_code<C, F>(self, code: ExitCode, f: F) -> Result<T, ActorError>
where
C: Display + 'static,
F: FnOnce() -> C,
{
self.ok_or_else(|| ActorError {
exit_code: code,
msg: f().to_string(),
data: None,
})
}
}
pub fn deserialize_block<T>(ret: Option<IpldBlock>) -> Result<T, ActorError>
where
T: DeserializeOwned,
{
ret.context_code(
ExitCode::USR_ASSERTION_FAILED,
"return expected".to_string(),
)?
.deserialize()
.exit_code(ExitCode::USR_SERIALIZATION)
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lib.rs | ipc/provider/src/lib.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Ipc agent sdk, contains the json rpc client to interact with the IPC agent rpc server.
use crate::manager::{GetBlockHashResult, TopDownQueryPayload};
use anyhow::anyhow;
use base64::Engine;
use config::Config;
use fvm_shared::{
address::Address, clock::ChainEpoch, crypto::signature::SignatureType, econ::TokenAmount,
};
use ipc_api::checkpoint::{BottomUpCheckpointBundle, QuorumReachedEvent};
use ipc_api::evm::payload_to_evm_address;
use ipc_api::staking::{StakingChangeRequest, ValidatorInfo};
use ipc_api::subnet::{PermissionMode, SupplySource};
use ipc_api::{
cross::IpcEnvelope,
subnet::{ConsensusType, ConstructParams},
subnet_id::SubnetID,
};
use ipc_wallet::{
EthKeyAddress, EvmKeyStore, KeyStore, KeyStoreConfig, PersistentKeyStore, Wallet,
};
use lotus::message::wallet::WalletKeyType;
use manager::{EthSubnetManager, SubnetGenesisInfo, SubnetInfo, SubnetManager};
use serde::{Deserialize, Serialize};
use std::{
borrow::Borrow,
collections::HashMap,
path::{Path, PathBuf},
str::FromStr,
sync::{Arc, RwLock},
};
use zeroize::Zeroize;
pub mod checkpoint;
pub mod config;
pub mod jsonrpc;
pub mod lotus;
pub mod manager;
const DEFAULT_REPO_PATH: &str = ".ipc";
const DEFAULT_CONFIG_NAME: &str = "config.toml";
/// The subnet manager connection that holds the subnet config and the manager instance.
pub struct Connection {
subnet: config::Subnet,
manager: Box<dyn SubnetManager + 'static>,
}
impl Connection {
/// Get the subnet config.
pub fn subnet(&self) -> &config::Subnet {
&self.subnet
}
/// Get the subnet manager instance.
pub fn manager(&self) -> &dyn SubnetManager {
self.manager.borrow()
}
}
#[derive(Clone)]
pub struct IpcProvider {
sender: Option<Address>,
config: Arc<Config>,
fvm_wallet: Option<Arc<RwLock<Wallet>>>,
evm_keystore: Option<Arc<RwLock<PersistentKeyStore<EthKeyAddress>>>>,
}
impl IpcProvider {
fn new(
config: Arc<Config>,
fvm_wallet: Arc<RwLock<Wallet>>,
evm_keystore: Arc<RwLock<PersistentKeyStore<EthKeyAddress>>>,
) -> Self {
Self {
sender: None,
config,
fvm_wallet: Some(fvm_wallet),
evm_keystore: Some(evm_keystore),
}
}
/// Initializes an `IpcProvider` from the config specified in the
/// argument's config path.
pub fn new_from_config(config_path: String) -> anyhow::Result<Self> {
let config = Arc::new(Config::from_file(config_path)?);
let fvm_wallet = Arc::new(RwLock::new(Wallet::new(new_fvm_wallet_from_config(
config.clone(),
)?)));
let evm_keystore = Arc::new(RwLock::new(new_evm_keystore_from_config(config.clone())?));
Ok(Self::new(config, fvm_wallet, evm_keystore))
}
/// Initializes a new `IpcProvider` configured to interact with
/// a single subnet.
pub fn new_with_subnet(
keystore_path: Option<String>,
subnet: config::Subnet,
) -> anyhow::Result<Self> {
let mut config = Config::new();
config.add_subnet(subnet);
let config = Arc::new(config);
if let Some(repo_path) = keystore_path {
let fvm_wallet = Arc::new(RwLock::new(Wallet::new(new_fvm_keystore_from_path(
&repo_path,
)?)));
let evm_keystore = Arc::new(RwLock::new(new_evm_keystore_from_path(&repo_path)?));
Ok(Self::new(config, fvm_wallet, evm_keystore))
} else {
Ok(Self {
sender: None,
config,
fvm_wallet: None,
evm_keystore: None,
})
}
}
/// Initialized an `IpcProvider` using the default config path.
pub fn new_default() -> anyhow::Result<Self> {
Self::new_from_config(default_config_path())
}
/// Get the connection instance for the subnet.
pub fn connection(&self, subnet: &SubnetID) -> Option<Connection> {
let subnets = &self.config.subnets;
match subnets.get(subnet) {
Some(subnet) => match &subnet.config {
config::subnet::SubnetConfig::Fevm(_) => {
let wallet = self.evm_keystore.clone();
let manager =
match EthSubnetManager::from_subnet_with_wallet_store(subnet, wallet) {
Ok(w) => Some(w),
Err(e) => {
tracing::warn!("error initializing evm manager: {e}");
return None;
}
};
Some(Connection {
manager: Box::new(manager.unwrap()),
subnet: subnet.clone(),
})
}
},
None => None,
}
}
/// Get the connection of a subnet, or return an error.
fn get_connection(&self, subnet: &SubnetID) -> anyhow::Result<Connection> {
match self.connection(subnet) {
None => Err(anyhow!(
"subnet not found: {subnet}; known subnets: {:?}",
self.config
.subnets
.keys()
.map(|id| id.to_string())
.collect::<Vec<_>>()
)),
Some(conn) => Ok(conn),
}
}
/// Set the default account for the provider
pub fn with_sender(&mut self, from: Address) {
self.sender = Some(from);
}
/// Returns the evm wallet if it is configured, and throws an error if no wallet configured.
///
/// This method should be used when we want the wallet retrieval to throw an error
/// if it is not configured (i.e. when the provider needs to sign transactions).
pub fn evm_wallet(&self) -> anyhow::Result<Arc<RwLock<PersistentKeyStore<EthKeyAddress>>>> {
if let Some(wallet) = &self.evm_keystore {
Ok(wallet.clone())
} else {
Err(anyhow!("No evm wallet found in provider"))
}
}
// FIXME: Reconcile these into a single wallet method that
// accepts an `ipc_wallet::WalletType` as an input.
pub fn fvm_wallet(&self) -> anyhow::Result<Arc<RwLock<Wallet>>> {
if let Some(wallet) = &self.fvm_wallet {
Ok(wallet.clone())
} else {
Err(anyhow!("No fvm wallet found in provider"))
}
}
fn check_sender(
&mut self,
subnet: &config::Subnet,
from: Option<Address>,
) -> anyhow::Result<Address> {
// if there is from use that.
if let Some(from) = from {
return Ok(from);
}
// if not use the sender.
if let Some(sender) = self.sender {
return Ok(sender);
}
// and finally, if there is no sender, use the default and
// set it as the default sender.
match &subnet.config {
config::subnet::SubnetConfig::Fevm(_) => {
if self.sender.is_none() {
let wallet = self.evm_wallet()?;
let addr = match wallet.write().unwrap().get_default()? {
None => return Err(anyhow!("no default evm account configured")),
Some(addr) => Address::try_from(addr)?,
};
self.sender = Some(addr);
return Ok(addr);
}
}
};
Err(anyhow!("error fetching a valid sender"))
}
/// Lists available subnet connections
pub fn list_connections(&self) -> HashMap<SubnetID, config::Subnet> {
self.config.subnets.clone()
}
}
/// IpcProvider spawns a daemon-less client to interact with IPC subnets.
///
/// At this point the provider assumes that the user providers a `config.toml`
/// with the subnet configuration. This has been inherited by the daemon
/// configuration and will be slowly deprecated.
impl IpcProvider {
// FIXME: Once the arguments for subnet creation are stabilized,
// use a SubnetOpts struct to provide the creation arguments and
// remove this allow
#[allow(clippy::too_many_arguments)]
pub async fn create_subnet(
&mut self,
from: Option<Address>,
parent: SubnetID,
min_validators: u64,
min_validator_stake: TokenAmount,
bottomup_check_period: ChainEpoch,
active_validators_limit: u16,
min_cross_msg_fee: TokenAmount,
permission_mode: PermissionMode,
supply_source: SupplySource,
) -> anyhow::Result<Address> {
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
let constructor_params = ConstructParams {
parent,
ipc_gateway_addr: subnet_config.gateway_addr(),
consensus: ConsensusType::Fendermint,
min_validators,
min_validator_stake,
bottomup_check_period,
active_validators_limit,
min_cross_msg_fee,
permission_mode,
supply_source,
};
conn.manager()
.create_subnet(sender, constructor_params)
.await
}
pub async fn join_subnet(
&mut self,
subnet: SubnetID,
from: Option<Address>,
collateral: TokenAmount,
) -> anyhow::Result<ChainEpoch> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
let addr = payload_to_evm_address(sender.payload())?;
let keystore = self.evm_wallet()?;
let key_info = keystore
.read()
.unwrap()
.get(&addr.into())?
.ok_or_else(|| anyhow!("key does not exists"))?;
let sk = libsecp256k1::SecretKey::parse_slice(key_info.private_key())?;
let public_key = libsecp256k1::PublicKey::from_secret_key(&sk).serialize();
let hex_public_key = hex::encode(public_key);
log::info!("joining subnet with public key: {hex_public_key:?}");
conn.manager()
.join_subnet(subnet, sender, collateral, public_key.into())
.await
}
pub async fn pre_fund(
&mut self,
subnet: SubnetID,
from: Option<Address>,
balance: TokenAmount,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().pre_fund(subnet, sender, balance).await
}
pub async fn pre_release(
&mut self,
subnet: SubnetID,
from: Option<Address>,
amount: TokenAmount,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().pre_release(subnet, sender, amount).await
}
pub async fn stake(
&mut self,
subnet: SubnetID,
from: Option<Address>,
collateral: TokenAmount,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().stake(subnet, sender, collateral).await
}
pub async fn unstake(
&mut self,
subnet: SubnetID,
from: Option<Address>,
collateral: TokenAmount,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().unstake(subnet, sender, collateral).await
}
pub async fn leave_subnet(
&mut self,
subnet: SubnetID,
from: Option<Address>,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().leave_subnet(subnet, sender).await
}
pub async fn claim_collateral(
&mut self,
subnet: SubnetID,
from: Option<Address>,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().claim_collateral(subnet, sender).await
}
pub async fn kill_subnet(
&mut self,
subnet: SubnetID,
from: Option<Address>,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().kill_subnet(subnet, sender).await
}
pub async fn list_child_subnets(
&self,
gateway_addr: Option<Address>,
subnet: &SubnetID,
) -> anyhow::Result<HashMap<SubnetID, SubnetInfo>> {
let conn = self.get_connection(subnet)?;
let subnet_config = conn.subnet();
let gateway_addr = match gateway_addr {
None => subnet_config.gateway_addr(),
Some(addr) => addr,
};
conn.manager().list_child_subnets(gateway_addr).await
}
/// Funds an account in a child subnet, if `to` is `None`, the self account
/// is funded.
pub async fn fund(
&mut self,
subnet: SubnetID,
gateway_addr: Option<Address>,
from: Option<Address>,
to: Option<Address>,
amount: TokenAmount,
) -> anyhow::Result<ChainEpoch> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
let gateway_addr = match gateway_addr {
None => subnet_config.gateway_addr(),
Some(addr) => addr,
};
conn.manager()
.fund(subnet, gateway_addr, sender, to.unwrap_or(sender), amount)
.await
}
/// Funds an account in a child subnet with erc20 token, provided that the supply source kind is
/// `ERC20`. If `from` is None, it will use the default address config in `ipc.toml`.
/// If `to` is `None`, the `from` account will be funded.
pub async fn fund_with_token(
&mut self,
subnet: SubnetID,
from: Option<Address>,
to: Option<Address>,
amount: TokenAmount,
) -> anyhow::Result<ChainEpoch> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager()
.fund_with_token(subnet, sender, to.unwrap_or(sender), amount)
.await
}
/// Approve an erc20 token for transfer by the gateway. Can be used in preparation for fund_with_token.
/// If `from` is None, it will use the default address config in `ipc.toml`.
/// If `to` is `None`, the `from` account will be funded.
pub async fn approve_token(
&mut self,
subnet: SubnetID,
from: Option<Address>,
amount: TokenAmount,
) -> anyhow::Result<ChainEpoch> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = match self.connection(&parent) {
None => return Err(anyhow!("target parent subnet not found")),
Some(conn) => conn,
};
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager().approve_token(subnet, sender, amount).await
}
/// Release to an account in a child subnet, if `to` is `None`, the self account
/// is funded.
pub async fn release(
&mut self,
subnet: SubnetID,
gateway_addr: Option<Address>,
from: Option<Address>,
to: Option<Address>,
amount: TokenAmount,
) -> anyhow::Result<ChainEpoch> {
let conn = match self.connection(&subnet) {
None => return Err(anyhow!("target subnet not found: {subnet}")),
Some(conn) => conn,
};
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
let gateway_addr = match gateway_addr {
None => subnet_config.gateway_addr(),
Some(addr) => addr,
};
conn.manager()
.release(gateway_addr, sender, to.unwrap_or(sender), amount)
.await
}
/// Propagate a cross-net message forward. For `postbox_msg_key`, we are using bytes because different
/// runtime have different representations. For FVM, it should be `CID` as bytes. For EVM, it is
/// `bytes32`.
pub async fn propagate(
&self,
_subnet: SubnetID,
_gateway_addr: Address,
_from: Address,
_postbox_msg_key: Vec<u8>,
) -> anyhow::Result<()> {
todo!()
}
/// Send value between two addresses in a subnet
pub async fn send_value(
&mut self,
subnet: &SubnetID,
from: Option<Address>,
to: Address,
amount: TokenAmount,
) -> anyhow::Result<()> {
let conn = self.get_connection(subnet)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
// FIXME: This limits that only value to f-addresses can be sent
// with the provider (which requires translating eth-addresses into
// their corresponding delegated address). This should be fixed with the
// new address wrapper type planned: https://github.com/consensus-shipyard/ipc-agent/issues/263
// let to = match Address::from_str(&request.to) {
// Ok(addr) => addr,
// Err(_) => {
// // we need to check if an 0x address was passed and convert
// // to a delegated address
// ethers_address_to_fil_address(ðers::types::Address::from_str(&request.to)?)?
// }
// };
conn.manager().send_value(sender, to, amount).await
}
/// Get the balance of an address
pub async fn wallet_balance(
&self,
subnet: &SubnetID,
address: &Address,
) -> anyhow::Result<TokenAmount> {
let conn = self.get_connection(subnet)?;
conn.manager().wallet_balance(address).await
}
pub async fn chain_head(&self, subnet: &SubnetID) -> anyhow::Result<ChainEpoch> {
let conn = self.get_connection(subnet)?;
conn.manager().chain_head_height().await
}
/// Obtain the genesis epoch of the input subnet.
pub async fn genesis_epoch(&self, subnet: &SubnetID) -> anyhow::Result<ChainEpoch> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager().genesis_epoch(subnet).await
}
/// Get the validator information.
pub async fn get_validator_info(
&self,
subnet: &SubnetID,
validator: &Address,
) -> anyhow::Result<ValidatorInfo> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager().get_validator_info(subnet, validator).await
}
/// Get the changes in subnet validators. This is fetched from parent.
pub async fn get_validator_changeset(
&self,
subnet: &SubnetID,
epoch: ChainEpoch,
) -> anyhow::Result<TopDownQueryPayload<Vec<StakingChangeRequest>>> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager().get_validator_changeset(subnet, epoch).await
}
/// Get genesis info for a child subnet. This can be used to deterministically
/// generate the genesis of the subnet
pub async fn get_genesis_info(&self, subnet: &SubnetID) -> anyhow::Result<SubnetGenesisInfo> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager().get_genesis_info(subnet).await
}
pub async fn get_top_down_msgs(
&self,
subnet: &SubnetID,
epoch: ChainEpoch,
) -> anyhow::Result<TopDownQueryPayload<Vec<IpcEnvelope>>> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager().get_top_down_msgs(subnet, epoch).await
}
pub async fn get_block_hash(
&self,
subnet: &SubnetID,
height: ChainEpoch,
) -> anyhow::Result<GetBlockHashResult> {
let conn = self.get_connection(subnet)?;
conn.manager().get_block_hash(height).await
}
pub async fn get_chain_id(&self, subnet: &SubnetID) -> anyhow::Result<String> {
let conn = self.get_connection(subnet)?;
conn.manager().get_chain_id().await
}
pub async fn get_commit_sha(&self, subnet: &SubnetID) -> anyhow::Result<[u8; 32]> {
let conn = self.get_connection(subnet)?;
conn.manager().get_commit_sha().await
}
pub async fn get_chain_head_height(&self, subnet: &SubnetID) -> anyhow::Result<ChainEpoch> {
let conn = self.get_connection(subnet)?;
conn.manager().chain_head_height().await
}
pub async fn get_bottom_up_bundle(
&self,
subnet: &SubnetID,
height: ChainEpoch,
) -> anyhow::Result<Option<BottomUpCheckpointBundle>> {
let conn = match self.connection(subnet) {
None => return Err(anyhow!("target subnet not found")),
Some(conn) => conn,
};
conn.manager().checkpoint_bundle_at(height).await
}
pub async fn last_bottom_up_checkpoint_height(
&self,
subnet: &SubnetID,
) -> anyhow::Result<ChainEpoch> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager()
.last_bottom_up_checkpoint_height(subnet)
.await
}
pub async fn quorum_reached_events(
&self,
subnet: &SubnetID,
height: ChainEpoch,
) -> anyhow::Result<Vec<QuorumReachedEvent>> {
let conn = self.get_connection(subnet)?;
conn.manager().quorum_reached_events(height).await
}
/// Advertises the endpoint of a bootstrap node for the subnet.
pub async fn add_bootstrap(
&mut self,
subnet: &SubnetID,
from: Option<Address>,
endpoint: String,
) -> anyhow::Result<()> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
let subnet_config = conn.subnet();
let sender = self.check_sender(subnet_config, from)?;
conn.manager()
.add_bootstrap(subnet, &sender, endpoint)
.await
}
/// Lists the bootstrap nodes of a subnet
pub async fn list_bootstrap_nodes(&self, subnet: &SubnetID) -> anyhow::Result<Vec<String>> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager().list_bootstrap_nodes(subnet).await
}
/// Returns the latest finality from the parent committed in a child subnet.
pub async fn latest_parent_finality(&self, subnet: &SubnetID) -> anyhow::Result<ChainEpoch> {
let conn = self.get_connection(subnet)?;
conn.manager().latest_parent_finality().await
}
pub async fn set_federated_power(
&self,
from: &Address,
subnet: &SubnetID,
validators: &[Address],
public_keys: &[Vec<u8>],
federated_power: &[u128],
) -> anyhow::Result<ChainEpoch> {
let parent = subnet.parent().ok_or_else(|| anyhow!("no parent found"))?;
let conn = self.get_connection(&parent)?;
conn.manager()
.set_federated_power(from, subnet, validators, public_keys, federated_power)
.await
}
}
/// Lotus JSON keytype format
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct LotusJsonKeyType {
pub r#type: String,
pub private_key: String,
}
impl FromStr for LotusJsonKeyType {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let v = serde_json::from_str(s)?;
Ok(v)
}
}
impl Drop for LotusJsonKeyType {
fn drop(&mut self) {
self.private_key.zeroize();
}
}
// Here I put in some other category the wallet-related
// function so we can reconcile them easily when we decide to tackle
// https://github.com/consensus-shipyard/ipc-agent/issues/308
// This should become its own module within the provider, we should have different
// categories for each group of commands
impl IpcProvider {
pub fn new_fvm_key(&self, tp: WalletKeyType) -> anyhow::Result<Address> {
let tp = match tp {
WalletKeyType::BLS => SignatureType::BLS,
WalletKeyType::Secp256k1 => SignatureType::Secp256k1,
WalletKeyType::Secp256k1Ledger => return Err(anyhow!("ledger key type not supported")),
};
self.fvm_wallet()?.write().unwrap().generate_addr(tp)
}
pub fn new_evm_key(&self) -> anyhow::Result<EthKeyAddress> {
let key_info = ipc_wallet::random_eth_key_info();
let wallet = self.evm_wallet()?;
let out = wallet.write().unwrap().put(key_info);
out
}
pub fn import_fvm_key(&self, keyinfo: &str) -> anyhow::Result<Address> {
let wallet = self.fvm_wallet()?;
let mut wallet = wallet.write().unwrap();
let keyinfo = LotusJsonKeyType::from_str(keyinfo)?;
let key_type = if WalletKeyType::from_str(&keyinfo.r#type)? == WalletKeyType::BLS {
SignatureType::BLS
} else {
SignatureType::Secp256k1
};
let key_info = ipc_wallet::json::KeyInfoJson(ipc_wallet::KeyInfo::new(
key_type,
base64::engine::general_purpose::STANDARD.decode(&keyinfo.private_key)?,
));
let key_info = ipc_wallet::KeyInfo::from(key_info);
Ok(wallet.import(key_info)?)
}
pub fn import_evm_key_from_privkey(&self, private_key: &str) -> anyhow::Result<EthKeyAddress> {
let keystore = self.evm_wallet()?;
let mut keystore = keystore.write().unwrap();
let private_key = if !private_key.starts_with("0x") {
hex::decode(private_key)?
} else {
hex::decode(&private_key[2..])?
};
keystore.put(ipc_wallet::EvmKeyInfo::new(private_key))
}
pub fn import_evm_key_from_json(&self, keyinfo: &str) -> anyhow::Result<EthKeyAddress> {
let persisted: ipc_wallet::PersistentKeyInfo = serde_json::from_str(keyinfo)?;
let persisted: String = persisted.private_key().parse()?;
self.import_evm_key_from_privkey(&persisted)
}
}
fn new_fvm_wallet_from_config(config: Arc<Config>) -> anyhow::Result<KeyStore> {
let repo_str = &config.keystore_path;
if let Some(repo_str) = repo_str {
new_fvm_keystore_from_path(repo_str)
} else {
Err(anyhow!(
"No keystore repo found in config. Try using absolute path"
))
}
}
pub fn new_evm_keystore_from_config(
config: Arc<Config>,
) -> anyhow::Result<PersistentKeyStore<EthKeyAddress>> {
let repo_str = &config.keystore_path;
if let Some(repo_str) = repo_str {
new_evm_keystore_from_path(repo_str)
} else {
Err(anyhow!("No keystore repo found in config"))
}
}
pub fn new_evm_keystore_from_path(
repo_str: &str,
) -> anyhow::Result<PersistentKeyStore<EthKeyAddress>> {
let repo = Path::new(&repo_str).join(ipc_wallet::DEFAULT_KEYSTORE_NAME);
let repo = expand_tilde(repo);
PersistentKeyStore::new(repo).map_err(|e| anyhow!("Failed to create evm keystore: {}", e))
}
pub fn new_fvm_keystore_from_path(repo_str: &str) -> anyhow::Result<KeyStore> {
let repo = Path::new(&repo_str);
let repo = expand_tilde(repo);
let keystore_config = KeyStoreConfig::Persistent(repo);
// TODO: we currently only support persistent keystore in the default repo directory.
KeyStore::new(keystore_config).map_err(|e| anyhow!("Failed to create keystore: {}", e))
}
pub fn default_repo_path() -> String {
let home = match std::env::var("HOME") {
Ok(home) => home,
Err(_) => panic!("cannot get home"),
};
format!("{home:}/{:}", DEFAULT_REPO_PATH)
}
pub fn default_config_path() -> String {
format!("{}/{:}", default_repo_path(), DEFAULT_CONFIG_NAME)
}
/// Expand paths that begin with "~" to `$HOME`.
pub fn expand_tilde<P: AsRef<Path>>(path: P) -> PathBuf {
let p = path.as_ref().to_path_buf();
if !p.starts_with("~") {
return p;
}
if p == Path::new("~") {
return dirs::home_dir().unwrap_or(p);
}
dirs::home_dir()
.map(|mut h| {
if h == Path::new("/") {
// `~/foo` becomes just `/foo` instead of `//foo` if `/` is home.
p.strip_prefix("~").unwrap().to_path_buf()
} else {
h.push(p.strip_prefix("~/").unwrap());
h
}
})
.unwrap_or(p)
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/checkpoint.rs | ipc/provider/src/checkpoint.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Bottom up checkpoint manager
use crate::config::Subnet;
use crate::manager::{BottomUpCheckpointRelayer, EthSubnetManager};
use anyhow::{anyhow, Result};
use futures_util::future::try_join_all;
use fvm_shared::address::Address;
use fvm_shared::clock::ChainEpoch;
use ipc_api::checkpoint::{BottomUpCheckpointBundle, QuorumReachedEvent};
use ipc_wallet::{EthKeyAddress, PersistentKeyStore};
use std::cmp::max;
use std::fmt::{Display, Formatter};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tokio::sync::Semaphore;
/// Tracks the config required for bottom up checkpoint submissions
/// parent/child subnet and checkpoint period.
pub struct CheckpointConfig {
parent: Subnet,
child: Subnet,
period: ChainEpoch,
}
/// Manages the submission of bottom up checkpoint. It checks if the submitter has already
/// submitted in the `last_checkpoint_height`, if not, it will submit the checkpoint at that height.
/// Then it will submit at the next submission height for the new checkpoint.
pub struct BottomUpCheckpointManager<T> {
metadata: CheckpointConfig,
parent_handler: Arc<T>,
child_handler: T,
/// The number of blocks away from the chain head that is considered final
finalization_blocks: ChainEpoch,
submission_semaphore: Arc<Semaphore>,
}
impl<T: BottomUpCheckpointRelayer> BottomUpCheckpointManager<T> {
pub async fn new(
parent: Subnet,
child: Subnet,
parent_handler: T,
child_handler: T,
max_parallelism: usize,
) -> Result<Self> {
let period = parent_handler
.checkpoint_period(&child.id)
.await
.map_err(|e| anyhow!("cannot get bottom up checkpoint period: {e}"))?;
Ok(Self {
metadata: CheckpointConfig {
parent,
child,
period,
},
parent_handler: Arc::new(parent_handler),
child_handler,
finalization_blocks: 0,
submission_semaphore: Arc::new(Semaphore::new(max_parallelism)),
})
}
pub fn with_finalization_blocks(mut self, finalization_blocks: ChainEpoch) -> Self {
self.finalization_blocks = finalization_blocks;
self
}
}
impl BottomUpCheckpointManager<EthSubnetManager> {
pub async fn new_evm_manager(
parent: Subnet,
child: Subnet,
keystore: Arc<RwLock<PersistentKeyStore<EthKeyAddress>>>,
max_parallelism: usize,
) -> Result<Self> {
let parent_handler =
EthSubnetManager::from_subnet_with_wallet_store(&parent, Some(keystore.clone()))?;
let child_handler =
EthSubnetManager::from_subnet_with_wallet_store(&child, Some(keystore))?;
Self::new(
parent,
child,
parent_handler,
child_handler,
max_parallelism,
)
.await
}
}
impl<T: BottomUpCheckpointRelayer> Display for BottomUpCheckpointManager<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"bottom-up relayer, parent: {:}, child: {:}",
self.metadata.parent.id, self.metadata.child.id
)
}
}
impl<T: BottomUpCheckpointRelayer + Send + Sync + 'static> BottomUpCheckpointManager<T> {
/// Getter for the parent subnet this checkpoint manager is handling
pub fn parent_subnet(&self) -> &Subnet {
&self.metadata.parent
}
/// Getter for the target subnet this checkpoint manager is handling
pub fn child_subnet(&self) -> &Subnet {
&self.metadata.child
}
/// The checkpoint period that the current manager is submitting upon
pub fn checkpoint_period(&self) -> ChainEpoch {
self.metadata.period
}
/// Run the bottom up checkpoint submission daemon in the foreground
pub async fn run(self, submitter: Address, submission_interval: Duration) {
tracing::info!("launching {self} for {submitter}");
loop {
if let Err(e) = self.submit_next_epoch(submitter).await {
tracing::error!("cannot submit checkpoint for submitter: {submitter} due to {e}");
}
tokio::time::sleep(submission_interval).await;
}
}
/// Checks if the relayer has already submitted at the next submission epoch, if not it submits it.
async fn submit_next_epoch(&self, submitter: Address) -> Result<()> {
let last_checkpoint_epoch = self
.parent_handler
.last_bottom_up_checkpoint_height(&self.metadata.child.id)
.await
.map_err(|e| {
anyhow!("cannot obtain the last bottom up checkpoint height due to: {e:}")
})?;
tracing::info!("last submission height: {last_checkpoint_epoch}");
let current_height = self.child_handler.current_epoch().await?;
let finalized_height = max(1, current_height - self.finalization_blocks);
tracing::debug!("last submission height: {last_checkpoint_epoch}, current height: {current_height}, finalized_height: {finalized_height}");
if finalized_height <= last_checkpoint_epoch {
return Ok(());
}
let start = last_checkpoint_epoch + 1;
tracing::debug!(
"start querying quorum reached events from : {start} to {finalized_height}"
);
let mut count = 0;
let mut all_submit_tasks = vec![];
for h in start..=finalized_height {
let events = self.child_handler.quorum_reached_events(h).await?;
if events.is_empty() {
tracing::debug!("no reached events at height : {h}");
continue;
}
tracing::debug!("found reached events at height : {h}");
for event in events {
// Note that the event will be emitted later than the checkpoint height.
// For example, if the checkpoint height is 400 but it's actually created
// in fendermint at height 403. This means the event.height == 400 which is
// already committed.
if event.height <= last_checkpoint_epoch {
tracing::debug!("event height already committed: {}", event.height);
continue;
}
let bundle = self
.child_handler
.checkpoint_bundle_at(event.height)
.await?
.ok_or_else(|| {
anyhow!(
"expected checkpoint at height {} but none found",
event.height
)
})?;
log::debug!("bottom up bundle: {bundle:?}");
// We support parallel checkpoint submission using FIFO order with a limited parallelism (controlled by
// the size of submission_semaphore).
// We need to acquire a permit (from a limited permit pool) before submitting a checkpoint.
// We may wait here until a permit is available.
let parent_handler_clone = Arc::clone(&self.parent_handler);
let submission_permit = self
.submission_semaphore
.clone()
.acquire_owned()
.await
.unwrap();
all_submit_tasks.push(tokio::task::spawn(async move {
let height = event.height;
let result =
Self::submit_checkpoint(parent_handler_clone, submitter, bundle, event)
.await
.inspect_err(|err| {
tracing::error!(
"Fail to submit checkpoint at height {height}: {err}"
);
});
drop(submission_permit);
result
}));
count += 1;
tracing::debug!("This round has asynchronously submitted {count} checkpoints",);
}
}
tracing::debug!("Waiting for all submissions to finish");
// Return error if any of the submit task failed.
try_join_all(all_submit_tasks).await?;
Ok(())
}
async fn submit_checkpoint(
parent_handler: Arc<T>,
submitter: Address,
bundle: BottomUpCheckpointBundle,
event: QuorumReachedEvent,
) -> Result<(), anyhow::Error> {
let epoch = parent_handler
.submit_checkpoint(
&submitter,
bundle.checkpoint,
bundle.signatures,
bundle.signatories,
)
.await
.map_err(|e| {
anyhow!(
"cannot submit bottom up checkpoint at height {} due to: {e}",
event.height
)
})?;
tracing::info!(
"submitted bottom up checkpoint({}) in parent at height {}",
event.height,
epoch
);
Ok(())
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/client.rs | ipc/provider/src/lotus/client.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use std::collections::HashMap;
use std::fmt::Debug;
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use base64::Engine;
use cid::multihash::MultihashDigest;
use cid::Cid;
use fvm_ipld_encoding::{to_vec, RawBytes};
use fvm_shared::address::Address;
use fvm_shared::bigint::BigInt;
use fvm_shared::clock::ChainEpoch;
use fvm_shared::crypto::signature::Signature;
use fvm_shared::econ::TokenAmount;
use ipc_api::subnet_id::SubnetID;
use ipc_wallet::Wallet;
use num_traits::cast::ToPrimitive;
use serde::de::DeserializeOwned;
use serde_json::json;
use crate::jsonrpc::{JsonRpcClient, JsonRpcClientImpl, NO_PARAMS};
use crate::lotus::message::chain::{ChainHeadResponse, GetTipSetByHeightResponse};
use crate::lotus::message::mpool::{
EstimateGasResponse, MpoolPushMessage, MpoolPushMessageResponse, MpoolPushMessageResponseInner,
};
use crate::lotus::message::state::{ReadStateResponse, StateWaitMsgResponse};
use crate::lotus::message::wallet::{WalletKeyType, WalletListResponse};
use crate::lotus::message::CIDMap;
use crate::lotus::{LotusClient, NetworkVersion};
pub type DefaultLotusJsonRPCClient = LotusJsonRPCClient<JsonRpcClientImpl>;
// RPC methods
mod methods {
pub const MPOOL_PUSH_MESSAGE: &str = "Filecoin.MpoolPushMessage";
pub const MPOOL_PUSH: &str = "Filecoin.MpoolPush";
pub const MPOOL_GET_NONCE: &str = "Filecoin.MpoolGetNonce";
pub const STATE_WAIT_MSG: &str = "Filecoin.StateWaitMsg";
pub const STATE_NETWORK_NAME: &str = "Filecoin.StateNetworkName";
pub const STATE_NETWORK_VERSION: &str = "Filecoin.StateNetworkVersion";
pub const STATE_ACTOR_CODE_CIDS: &str = "Filecoin.StateActorCodeCIDs";
pub const WALLET_NEW: &str = "Filecoin.WalletNew";
pub const WALLET_LIST: &str = "Filecoin.WalletList";
pub const WALLET_BALANCE: &str = "Filecoin.WalletBalance";
pub const WALLET_DEFAULT_ADDRESS: &str = "Filecoin.WalletDefaultAddress";
pub const STATE_READ_STATE: &str = "Filecoin.StateReadState";
pub const CHAIN_HEAD: &str = "Filecoin.ChainHead";
pub const GET_TIPSET_BY_HEIGHT: &str = "Filecoin.ChainGetTipSetByHeight";
pub const ESTIMATE_MESSAGE_GAS: &str = "Filecoin.GasEstimateMessageGas";
}
/// The default state wait confidence value
/// NOTE: we can afford 0 epochs confidence (and even one)
/// with instant-finality consensus, but with Filecoin mainnet this should be increased
/// in case there are reorgs.
const STATE_WAIT_CONFIDENCE: u8 = 0;
/// We dont set a limit on the look back epoch, i.e. check against latest block
const STATE_WAIT_LOOK_BACK_NO_LIMIT: i8 = -1;
/// We are not replacing any previous messages.
/// TODO: when set to false, lotus raises `found message with equal nonce as the one we are looking`
/// TODO: error. Should check this again.
const STATE_WAIT_ALLOW_REPLACE: bool = true;
/// The struct implementation for Lotus Client API. It allows for multiple different trait
/// extension.
/// # Examples
/// ```no_run
/// use ipc_provider::{lotus::LotusClient, lotus::client::LotusJsonRPCClient};
/// use ipc_provider::jsonrpc::JsonRpcClientImpl;
/// use ipc_api::subnet_id::SubnetID;
///
/// #[tokio::main]
/// async fn main() {
/// let h = JsonRpcClientImpl::new("<DEFINE YOUR URL HERE>".parse().unwrap(), None);
/// let n = LotusJsonRPCClient::new(h, SubnetID::default());
/// println!(
/// "wallets: {:?}",
/// n.wallet_new(ipc_provider::lotus::message::wallet::WalletKeyType::Secp256k1).await
/// );
/// }
/// ```
pub struct LotusJsonRPCClient<T: JsonRpcClient> {
client: T,
subnet: SubnetID,
wallet_store: Option<Arc<RwLock<Wallet>>>,
}
impl<T: JsonRpcClient> LotusJsonRPCClient<T> {
pub fn new(client: T, subnet: SubnetID) -> Self {
Self {
client,
subnet,
wallet_store: None,
}
}
pub fn new_with_wallet_store(
client: T,
subnet: SubnetID,
wallet_store: Arc<RwLock<Wallet>>,
) -> Self {
Self {
client,
subnet,
wallet_store: Some(wallet_store),
}
}
}
#[async_trait]
impl<T: JsonRpcClient + Send + Sync> LotusClient for LotusJsonRPCClient<T> {
async fn mpool_push_message(
&self,
msg: MpoolPushMessage,
) -> Result<MpoolPushMessageResponseInner> {
let nonce = msg
.nonce
.map(|n| serde_json::Value::Number(n.into()))
.unwrap_or(serde_json::Value::Null);
let to_value = |t: Option<TokenAmount>| {
t.map(|n| serde_json::Value::Number(n.atto().to_u64().unwrap().into()))
.unwrap_or(serde_json::Value::Null)
};
let gas_limit = to_value(msg.gas_limit);
let gas_premium = to_value(msg.gas_premium);
let gas_fee_cap = to_value(msg.gas_fee_cap);
let max_fee = to_value(msg.max_fee);
// refer to: https://lotus.filecoin.io/reference/lotus/mpool/#mpoolpushmessage
let params = json!([
{
"to": msg.to.to_string(),
"from": msg.from.to_string(),
"value": msg.value.atto().to_string(),
"method": msg.method,
"params": msg.params,
// THESE ALL WILL AUTO POPULATE if null
"nonce": nonce,
"gas_limit": gas_limit,
"gas_fee_cap": gas_fee_cap,
"gas_premium": gas_premium,
"cid": CIDMap::from(msg.cid),
"version": serde_json::Value::Null,
},
{
"max_fee": max_fee
}
]);
let r = self
.client
.request::<MpoolPushMessageResponse>(methods::MPOOL_PUSH_MESSAGE, params)
.await?;
tracing::debug!("received mpool_push_message response: {r:?}");
Ok(r.message)
}
async fn mpool_push(&self, mut msg: MpoolPushMessage) -> Result<Cid> {
if msg.nonce.is_none() {
let nonce = self.mpool_nonce(&msg.from).await?;
tracing::info!(
"sender: {:} with nonce: {nonce:} in subnet: {:}",
msg.from,
self.subnet
);
msg.nonce = Some(nonce);
}
if msg.version.is_none() {
msg.version = Some(0);
}
self.estimate_message_gas(&mut msg).await?;
tracing::debug!("estimated gas for message: {msg:?}");
let signature = self.sign_mpool_message(&msg)?;
let params = create_signed_message_params(msg, signature);
tracing::debug!(
"message to push to mpool: {params:?} in subnet: {:?}",
self.subnet
);
let r = self
.client
.request::<CIDMap>(methods::MPOOL_PUSH, params)
.await?;
tracing::debug!("received mpool_push_message response: {r:?}");
Cid::try_from(r)
}
async fn state_wait_msg(&self, cid: Cid) -> Result<StateWaitMsgResponse> {
// refer to: https://lotus.filecoin.io/reference/lotus/state/#statewaitmsg
let params = json!([
CIDMap::from(cid),
STATE_WAIT_CONFIDENCE,
STATE_WAIT_LOOK_BACK_NO_LIMIT,
STATE_WAIT_ALLOW_REPLACE,
]);
let r = self
.client
.request::<StateWaitMsgResponse>(methods::STATE_WAIT_MSG, params)
.await?;
tracing::debug!("received state_wait_msg response: {r:?}");
Ok(r)
}
async fn state_network_name(&self) -> Result<String> {
// refer to: https://lotus.filecoin.io/reference/lotus/state/#statenetworkname
let r = self
.client
.request::<String>(methods::STATE_NETWORK_NAME, serde_json::Value::Null)
.await?;
tracing::debug!("received state_network_name response: {r:?}");
Ok(r)
}
async fn state_network_version(&self, tip_sets: Vec<Cid>) -> Result<NetworkVersion> {
// refer to: https://lotus.filecoin.io/reference/lotus/state/#statenetworkversion
let params = json!([tip_sets.into_iter().map(CIDMap::from).collect::<Vec<_>>()]);
let r = self
.client
.request::<NetworkVersion>(methods::STATE_NETWORK_VERSION, params)
.await?;
tracing::debug!("received state_network_version response: {r:?}");
Ok(r)
}
async fn state_actor_code_cids(
&self,
network_version: NetworkVersion,
) -> Result<HashMap<String, Cid>> {
// refer to: https://github.com/filecoin-project/lotus/blob/master/documentation/en/api-v1-unstable-methods.md#stateactormanifestcid
let params = json!([network_version]);
let r = self
.client
.request::<HashMap<String, CIDMap>>(methods::STATE_ACTOR_CODE_CIDS, params)
.await?;
let mut cids = HashMap::new();
for (key, cid_map) in r.into_iter() {
cids.insert(key, Cid::try_from(cid_map)?);
}
tracing::debug!("received state_actor_manifest_cid response: {cids:?}");
Ok(cids)
}
async fn wallet_default(&self) -> Result<Address> {
// refer to: https://lotus.filecoin.io/reference/lotus/wallet/#walletdefaultaddress
let r = self
.client
.request::<String>(methods::WALLET_DEFAULT_ADDRESS, json!({}))
.await?;
tracing::debug!("received wallet_default response: {r:?}");
let addr = Address::from_str(&r)?;
Ok(addr)
}
async fn wallet_list(&self) -> Result<WalletListResponse> {
// refer to: https://lotus.filecoin.io/reference/lotus/wallet/#walletlist
let r = self
.client
.request::<WalletListResponse>(methods::WALLET_LIST, json!({}))
.await?;
tracing::debug!("received wallet_list response: {r:?}");
Ok(r)
}
async fn wallet_new(&self, key_type: WalletKeyType) -> Result<String> {
let key_type_str = key_type.as_ref();
// refer to: https://lotus.filecoin.io/reference/lotus/wallet/#walletnew
let r = self
.client
.request::<String>(methods::WALLET_NEW, json!([key_type_str]))
.await?;
tracing::debug!("received wallet_new response: {r:?}");
Ok(r)
}
async fn wallet_balance(&self, address: &Address) -> Result<TokenAmount> {
// refer to: https://lotus.filecoin.io/reference/lotus/wallet/#walletbalance
let r = self
.client
.request::<String>(methods::WALLET_BALANCE, json!([address.to_string()]))
.await?;
tracing::debug!("received wallet_balance response: {r:?}");
let v = BigInt::from_str(&r)?;
Ok(TokenAmount::from_atto(v))
}
async fn read_state<State: DeserializeOwned + Debug>(
&self,
address: Address,
tipset: Cid,
) -> Result<ReadStateResponse<State>> {
// refer to: https://lotus.filecoin.io/reference/lotus/state/#statereadstate
let r = self
.client
.request::<ReadStateResponse<State>>(
methods::STATE_READ_STATE,
json!([address.to_string(), [CIDMap::from(tipset)]]),
)
.await?;
tracing::debug!("received read_state response: {r:?}");
Ok(r)
}
async fn chain_head(&self) -> Result<ChainHeadResponse> {
let r = self
.client
.request::<ChainHeadResponse>(methods::CHAIN_HEAD, NO_PARAMS)
.await?;
tracing::debug!("received chain_head response: {r:?}");
Ok(r)
}
async fn current_epoch(&self) -> Result<ChainEpoch> {
Ok(self.chain_head().await?.height as ChainEpoch)
}
async fn get_tipset_by_height(
&self,
epoch: ChainEpoch,
tip_set: Cid,
) -> Result<GetTipSetByHeightResponse> {
let r = self
.client
.request::<GetTipSetByHeightResponse>(
methods::GET_TIPSET_BY_HEIGHT,
json!([epoch, [CIDMap::from(tip_set)]]),
)
.await?;
tracing::debug!("received get_tipset_by_height response: {r:?}");
Ok(r)
}
}
impl<T: JsonRpcClient + Send + Sync> LotusJsonRPCClient<T> {
fn sign_mpool_message(&self, msg: &MpoolPushMessage) -> anyhow::Result<Signature> {
if self.wallet_store.is_none() {
return Err(anyhow!("key store not set, function not supported"));
}
let message = fvm_shared::message::Message {
version: msg
.version
.ok_or_else(|| anyhow!("version should not be empty"))? as u64,
from: msg.from,
to: msg.to,
sequence: msg
.nonce
.ok_or_else(|| anyhow!("nonce should not be empty"))?,
value: msg.value.clone(),
method_num: msg.method,
params: RawBytes::from(msg.params.clone()),
gas_limit: msg
.gas_limit
.as_ref()
.ok_or_else(|| anyhow!("gas_limit should not be empty"))?
.atto()
.to_u64()
.unwrap(),
gas_fee_cap: msg
.gas_fee_cap
.as_ref()
.ok_or_else(|| anyhow!("gas_fee_cap should not be empty"))?
.clone(),
gas_premium: msg
.gas_premium
.as_ref()
.ok_or_else(|| anyhow!("gas_premium should not be empty"))?
.clone(),
};
let hash = cid::multihash::Code::Blake2b256.digest(&to_vec(&message)?);
let msg_cid = Cid::new_v1(fvm_ipld_encoding::DAG_CBOR, hash).to_bytes();
let mut wallet_store = self.wallet_store.as_ref().unwrap().write().unwrap();
Ok(wallet_store.sign(&msg.from, &msg_cid)?)
}
async fn estimate_message_gas(&self, msg: &mut MpoolPushMessage) -> anyhow::Result<()> {
let params = json!([
{
"Version": msg.version.unwrap_or(0),
"To": msg.to.to_string(),
"From": msg.from.to_string(),
"Value": msg.value.atto().to_string(),
"Method": msg.method,
"Params": msg.params,
"Nonce": msg.nonce,
"GasLimit": 0,
"GasFeeCap": "0",
"GasPremium": "0",
"CID": CIDMap::from(msg.cid),
},
{},
[]
]);
let gas = self
.client
.request::<EstimateGasResponse>(methods::ESTIMATE_MESSAGE_GAS, params)
.await?;
msg.gas_fee_cap = gas.gas_fee_cap;
msg.gas_limit = gas.gas_limit;
msg.gas_premium = gas.gas_premium;
Ok(())
}
async fn mpool_nonce(&self, address: &Address) -> anyhow::Result<u64> {
let params = json!([address.to_string()]);
let r = self
.client
.request::<u64>(methods::MPOOL_GET_NONCE, params)
.await;
if let Err(e) = r {
if e.to_string().contains("resolution lookup failed") {
return Ok(0);
}
return Err(e);
}
Ok(r.unwrap())
}
}
impl LotusJsonRPCClient<JsonRpcClientImpl> {
/// A constructor that returns a `LotusJsonRPCClient` from a `Subnet`. The returned
/// `LotusJsonRPCClient` makes requests to the URL defined in the `Subnet`.
pub fn from_subnet(subnet: &crate::config::Subnet) -> Self {
let url = subnet.rpc_http().clone();
let auth_token = subnet.auth_token();
let jsonrpc_client = JsonRpcClientImpl::new(url, auth_token.as_deref());
LotusJsonRPCClient::new(jsonrpc_client, subnet.id.clone())
}
pub fn from_subnet_with_wallet_store(
subnet: &crate::config::Subnet,
wallet_store: Arc<RwLock<Wallet>>,
) -> Self {
let url = subnet.rpc_http().clone();
let auth_token = subnet.auth_token();
let jsonrpc_client = JsonRpcClientImpl::new(url, auth_token.as_deref());
LotusJsonRPCClient::new_with_wallet_store(jsonrpc_client, subnet.id.clone(), wallet_store)
}
}
fn create_signed_message_params(msg: MpoolPushMessage, signature: Signature) -> serde_json::Value {
let nonce = msg
.nonce
.map(|n| serde_json::Value::Number(n.into()))
.unwrap_or(serde_json::Value::Null);
let to_value_str = |t: Option<TokenAmount>| {
t.map(|n| serde_json::Value::String(n.atto().to_u64().unwrap().to_string()))
.unwrap_or(serde_json::Value::Null)
};
let to_value = |t: Option<TokenAmount>| {
t.map(|n| serde_json::Value::Number(n.atto().to_u64().unwrap().into()))
.unwrap_or(serde_json::Value::Null)
};
let gas_limit = to_value(msg.gas_limit);
let gas_premium = to_value_str(msg.gas_premium);
let gas_fee_cap = to_value_str(msg.gas_fee_cap);
let Signature { sig_type, bytes } = signature;
let sig_encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
let params_encoded = base64::engine::general_purpose::STANDARD.encode(msg.params);
// refer to: https://lotus.filecoin.io/reference/lotus/mpool/#mpoolpush
json!([
{
"Message": {
"Version": msg.version.unwrap_or(0),
"To": msg.to.to_string(),
"From": msg.from.to_string(),
"Value": msg.value.atto().to_string(),
"Method": msg.method,
"Params": params_encoded,
// THESE ALL WILL AUTO POPULATE if null
"Nonce": nonce,
"GasLimit": gas_limit,
"GasFeeCap": gas_fee_cap,
"GasPremium": gas_premium,
"CID": CIDMap::from(msg.cid),
},
"Signature": {
"Type": sig_type as u8,
"Data": sig_encoded,
}
}
])
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/mod.rs | ipc/provider/src/lotus/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use std::collections::HashMap;
use std::fmt::Debug;
use anyhow::Result;
use async_trait::async_trait;
use cid::Cid;
use fvm_shared::address::Address;
use fvm_shared::clock::ChainEpoch;
use fvm_shared::econ::TokenAmount;
use serde::de::DeserializeOwned;
use crate::lotus::message::chain::GetTipSetByHeightResponse;
use message::chain::ChainHeadResponse;
use message::mpool::{MpoolPushMessage, MpoolPushMessageResponseInner};
use message::state::{ReadStateResponse, StateWaitMsgResponse};
use message::wallet::{WalletKeyType, WalletListResponse};
pub mod client;
pub mod message;
/// The network version of lotus network.
/// see https://github.com/filecoin-project/go-state-types/blob/f6fd668a32b4b4a0bc39fd69d8a5f8fb11f49461/network/version.go#L7
pub type NetworkVersion = u32;
/// The Lotus client api to interact with the Lotus node.
#[async_trait]
pub trait LotusClient {
/// Push the message to memory pool, see: https://lotus.filecoin.io/reference/lotus/mpool/#mpoolpushmessage
async fn mpool_push_message(
&self,
msg: MpoolPushMessage,
) -> Result<MpoolPushMessageResponseInner>;
/// Push the unsigned message to memory pool. This will ask the local key store to sign the message.
/// In this case, make sure `from` is actually present in the local key store.
/// See: https://lotus.filecoin.io/reference/lotus/mpool/#mpoolpush
async fn mpool_push(&self, mut msg: MpoolPushMessage) -> Result<Cid>;
/// Wait for the message cid of a particular nonce, see: https://lotus.filecoin.io/reference/lotus/state/#statewaitmsg
async fn state_wait_msg(&self, cid: Cid) -> Result<StateWaitMsgResponse>;
/// Returns the name of the network the node is synced to, see https://lotus.filecoin.io/reference/lotus/state/#statenetworkname
async fn state_network_name(&self) -> Result<String>;
/// Returns the network version at the given tipset, see https://lotus.filecoin.io/reference/lotus/state/#statenetworkversion
async fn state_network_version(&self, tip_sets: Vec<Cid>) -> Result<NetworkVersion>;
/// Returns the CID of the builtin actors manifest for the given network version, see https://github.com/filecoin-project/lotus/blob/master/documentation/en/api-v1-unstable-methods.md#stateactormanifestcid
async fn state_actor_code_cids(
&self,
network_version: NetworkVersion,
) -> Result<HashMap<String, Cid>>;
/// Get the default wallet of the node, see: https://lotus.filecoin.io/reference/lotus/wallet/#walletdefaultaddress
async fn wallet_default(&self) -> Result<Address>;
/// List the wallets in the node, see: https://lotus.filecoin.io/reference/lotus/wallet/#walletlist
async fn wallet_list(&self) -> Result<WalletListResponse>;
/// Create a new wallet, see: https://lotus.filecoin.io/reference/lotus/wallet/#walletnew
async fn wallet_new(&self, key_type: WalletKeyType) -> Result<String>;
/// Get the balance of an address
async fn wallet_balance(&self, address: &Address) -> Result<TokenAmount>;
/// Read the state of the address at tipset, see: https://lotus.filecoin.io/reference/lotus/state/#statereadstate
async fn read_state<State: DeserializeOwned + Debug>(
&self,
address: Address,
tipset: Cid,
) -> Result<ReadStateResponse<State>>;
/// Returns the current head of the chain.
/// See: https://lotus.filecoin.io/reference/lotus/chain/#chainhead
async fn chain_head(&self) -> Result<ChainHeadResponse>;
/// Returns the heaviest epoch for the chain
async fn current_epoch(&self) -> Result<ChainEpoch>;
/// GetTipsetByHeight from the underlying chain
async fn get_tipset_by_height(
&self,
epoch: ChainEpoch,
tip_set: Cid,
) -> Result<GetTipSetByHeightResponse>;
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/tests.rs | ipc/provider/src/lotus/message/tests.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use fvm_shared::address::Address;
use std::str::FromStr;
use crate::lotus::message::deserialize::{
deserialize_ipc_address_from_map, deserialize_subnet_id_from_map,
deserialize_token_amount_from_str,
};
use crate::manager::SubnetInfo;
use fvm_shared::econ::TokenAmount;
use ipc_api::address::IPCAddress;
use ipc_api::subnet_id::SubnetID;
#[test]
fn test_ipc_address_from_map() {
use serde::Deserialize;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct IPCAddressWrapper {
#[allow(dead_code)]
#[serde(rename = "From")]
#[serde(deserialize_with = "deserialize_ipc_address_from_map")]
from: IPCAddress,
}
let raw_str = r#"
{
"From": {
"SubnetId": {
"Root": 123,
"Children": ["f064"]
},
"RawAddress": "f064"
}
}"#;
let w: Result<IPCAddressWrapper, _> = serde_json::from_str(raw_str);
assert!(w.is_ok());
assert_eq!(
w.unwrap().from,
IPCAddress::new(
&SubnetID::from_str("/r123/f064").unwrap(),
&Address::from_str("f064").unwrap()
)
.unwrap()
)
}
#[test]
fn test_subnet_from_map() {
use serde::Deserialize;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct SubnetIdWrapper {
#[allow(dead_code)]
#[serde(rename = "ID")]
#[serde(deserialize_with = "deserialize_subnet_id_from_map")]
id: SubnetID,
}
let raw_str = r#"
{
"ID": {
"Root": 123,
"Children": ["f01", "f064"]
}
}"#;
let w: Result<SubnetIdWrapper, _> = serde_json::from_str(raw_str);
assert!(w.is_ok());
assert_eq!(w.unwrap().id, SubnetID::from_str("/r123/f01/f064").unwrap())
}
#[test]
fn test_subnet_from_map_error() {
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct SubnetIdWrapper {
#[allow(dead_code)]
#[serde(rename = "ID")]
#[serde(deserialize_with = "deserialize_subnet_id_from_map")]
id: SubnetID,
}
let raw_str = r#"
{
"Id": {
"Root": 65,
"Children": "f064"
}
}"#;
let w: Result<SubnetIdWrapper, _> = serde_json::from_str(raw_str);
assert!(w.is_err());
}
#[test]
fn test_token_amount_from_str() {
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Wrapper {
#[allow(dead_code)]
#[serde(deserialize_with = "deserialize_token_amount_from_str")]
token_amount: TokenAmount,
}
let raw_str = r#"
{
"TokenAmount": "20000000000000000000"
}"#;
let w: Result<Wrapper, _> = serde_json::from_str(raw_str);
assert!(w.is_ok());
assert_eq!(w.unwrap().token_amount, TokenAmount::from_whole(20));
}
#[test]
fn test_subnet_info_to_str() {
let s = SubnetInfo {
id: Default::default(),
stake: Default::default(),
circ_supply: Default::default(),
genesis_epoch: 0,
};
let w = serde_json::to_string(&s);
assert!(w.is_ok());
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/state.rs | ipc/provider/src/lotus/message/state.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use anyhow::anyhow;
use base64::Engine;
use fil_actors_runtime::cbor;
use fvm_ipld_encoding::RawBytes;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use crate::lotus::message::CIDMap;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct StateWaitMsgResponse {
#[allow(dead_code)]
message: CIDMap,
#[allow(dead_code)]
pub(crate) receipt: Receipt,
#[allow(dead_code)]
tip_set: Vec<CIDMap>,
pub height: u64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ReadStateResponse<State> {
#[allow(dead_code)]
pub balance: String,
#[allow(dead_code)]
pub code: CIDMap,
#[allow(dead_code)]
pub state: State,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Receipt {
#[allow(dead_code)]
exit_code: u32,
#[serde(rename = "Return")]
pub result: Option<String>,
#[allow(dead_code)]
gas_used: u64,
}
impl Receipt {
pub fn parse_result_into<T: Default + DeserializeOwned>(self) -> anyhow::Result<T> {
if self.result.is_none() {
return Ok(Default::default());
}
let r = base64::engine::general_purpose::STANDARD
.decode(self.result.unwrap())
.map_err(|e| {
tracing::error!("cannot base64 decode due to {e:?}");
anyhow!("cannot decode return string")
})?;
cbor::deserialize::<T>(
&RawBytes::new(r),
"deserialize create subnet return response",
)
.map_err(|e| {
tracing::error!("cannot decode bytes due to {e:?}");
anyhow!("cannot cbor deserialize return data")
})
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/deserialize.rs | ipc/provider/src/lotus/message/deserialize.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Deserialization utils for lotus/ipc types.
use fvm_shared::address::Address;
use fvm_shared::bigint::BigInt;
use fvm_shared::econ::TokenAmount;
use ipc_api::address::IPCAddress;
use ipc_api::subnet_id::SubnetID;
use serde::de::{Error, MapAccess};
use serde::{Deserialize, Deserializer};
use std::fmt::Formatter;
use std::str::FromStr;
/// A serde deserialization method to deserialize a ipc address from map
pub fn deserialize_ipc_address_from_map<'de, D>(
deserializer: D,
) -> anyhow::Result<IPCAddress, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct IPCAddressInner {
#[serde(deserialize_with = "deserialize_subnet_id_from_map")]
pub subnet_id: SubnetID,
#[serde(deserialize_with = "deserialize_address_from_str")]
pub raw_address: Address,
}
let inner = IPCAddressInner::deserialize(deserializer)?;
let ipc = IPCAddress::new(&inner.subnet_id, &inner.raw_address).map_err(D::Error::custom)?;
Ok(ipc)
}
/// A serde deserialization method to deserialize a subnet id from map
pub fn deserialize_subnet_id_from_map<'de, D>(deserializer: D) -> anyhow::Result<SubnetID, D::Error>
where
D: Deserializer<'de>,
{
struct SubnetIdVisitor;
impl<'de> serde::de::Visitor<'de> for SubnetIdVisitor {
type Value = SubnetID;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a map")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut root = None;
let mut children = None;
while let Some((key, value)) = map
.next_entry()?
.map(|(k, v): (String, &'de serde_json::value::RawValue)| (k, v))
{
match key.as_str() {
"Root" => {
let s = value.get();
// ideally root should be an integer, if it starts with ", it is sent as a
// string, we strip away the starting and ending quote.
let id: u64 = if s.starts_with('"') {
s[1..s.len() - 1].parse().map_err(A::Error::custom)?
} else {
s.parse().map_err(A::Error::custom)?
};
root = Some(id);
}
"Children" => {
let s = value.get();
let v: Vec<String> = serde_json::from_str(s).map_err(A::Error::custom)?;
let addr: Result<Vec<Address>, A::Error> = v
.iter()
.map(|s| Address::from_str(s).map_err(A::Error::custom))
.collect();
children = Some(addr?);
}
_ => {}
}
}
if root.is_none() || children.is_none() {
return Err(A::Error::custom("parent or actor not present"));
}
Ok(SubnetID::new(root.unwrap(), children.unwrap()))
}
}
deserializer.deserialize_map(SubnetIdVisitor)
}
/// A serde deserialization method to deserialize a token amount from string
pub fn deserialize_token_amount_from_str<'de, D>(
deserializer: D,
) -> anyhow::Result<TokenAmount, D::Error>
where
D: Deserializer<'de>,
{
struct TokenAmountVisitor;
impl<'de> serde::de::Visitor<'de> for TokenAmountVisitor {
type Value = TokenAmount;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: Error,
{
let u = BigInt::from_str(v).map_err(E::custom)?;
Ok(TokenAmount::from_atto(u))
}
}
deserializer.deserialize_str(TokenAmountVisitor)
}
/// A serde deserialization method to deserialize a token amount from string
pub fn deserialize_some_token_amount_from_str<'de, D>(
deserializer: D,
) -> anyhow::Result<Option<TokenAmount>, D::Error>
where
D: Deserializer<'de>,
{
struct TokenAmountVisitor;
impl<'de> serde::de::Visitor<'de> for TokenAmountVisitor {
type Value = Option<TokenAmount>;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: Error,
{
let u = BigInt::from_str(v).map_err(E::custom)?;
Ok(Some(TokenAmount::from_atto(u)))
}
}
deserializer.deserialize_str(TokenAmountVisitor)
}
/// A serde deserialization method to deserialize a token amount from i64
pub fn deserialize_some_token_amount_from_num<'de, D>(
deserializer: D,
) -> anyhow::Result<Option<TokenAmount>, D::Error>
where
D: Deserializer<'de>,
{
let val: serde_json::Value = serde::Deserialize::deserialize(deserializer)?;
match val {
serde_json::Value::Number(n) => {
let u = n
.as_u64()
.ok_or_else(|| D::Error::custom("cannot parse to u64"))?;
Ok(Some(TokenAmount::from_atto(u)))
}
_ => Err(D::Error::custom("unknown type: {val:?}")),
}
}
/// A serde deserialization method to deserialize an address from string
pub fn deserialize_address_from_str<'de, D>(deserializer: D) -> anyhow::Result<Address, D::Error>
where
D: Deserializer<'de>,
{
struct AddressVisitor;
impl<'de> serde::de::Visitor<'de> for AddressVisitor {
type Value = Address;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: Error,
{
Address::from_str(v).map_err(E::custom)
}
}
deserializer.deserialize_str(AddressVisitor)
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/chain.rs | ipc/provider/src/lotus/message/chain.rs | use cid::Cid;
// Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::lotus::message::CIDMap;
/// A simplified struct representing a `Block` response that does not decode the responses fully.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Block {
parent_state_root: CIDMap,
}
/// A simplified struct representing a `ChainGetTipSetByHeight` response that does not fully
/// decode the `blocks` field.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct GetTipSetByHeightResponse {
pub cids: Vec<CIDMap>,
blocks: Vec<Block>,
}
impl GetTipSetByHeightResponse {
pub fn tip_set_cids(&self) -> anyhow::Result<Vec<Cid>> {
let r: Result<Vec<_>, _> = self
.cids
.iter()
.map(|cid_map| {
let cid = Cid::try_from(cid_map)?;
Ok(cid)
})
.collect();
r
}
pub fn blocks_state_roots(&self) -> anyhow::Result<Vec<Cid>> {
self.blocks
.iter()
.map(|b| Cid::try_from(&b.parent_state_root))
.collect()
}
}
/// A simplified struct representing a `ChainHead` response that does not decode the `blocks` field.
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ChainHeadResponse {
#[allow(dead_code)]
pub cids: Vec<CIDMap>,
#[allow(dead_code)]
pub blocks: Vec<Value>,
#[allow(dead_code)]
pub height: u64,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/serialize.rs | ipc/provider/src/lotus/message/serialize.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use fvm_shared::econ::TokenAmount;
use ipc_api::subnet_id::SubnetID;
use serde::Serializer;
pub fn serialize_subnet_id_to_str<S>(id: &SubnetID, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(&id.to_string())
}
pub fn serialize_token_amount_to_atto<S>(amount: &TokenAmount, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(&amount.atto().to_string())
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/mod.rs | ipc/provider/src/lotus/message/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! This module contains the various response types to be used byt the lotus api.
use std::str::FromStr;
use anyhow::anyhow;
use cid::Cid;
use serde::{Deserialize, Serialize};
#[cfg(test)]
mod tests;
pub mod chain;
pub mod deserialize;
pub mod ipc;
pub mod mpool;
pub mod serialize;
pub mod state;
pub mod wallet;
/// Helper struct to interact with lotus node
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct CIDMap {
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "/")]
pub cid: Option<String>,
}
impl TryFrom<CIDMap> for Cid {
type Error = anyhow::Error;
fn try_from(cid_map: CIDMap) -> Result<Self, Self::Error> {
let cid_option: Option<Cid> = cid_map.into();
cid_option.ok_or_else(|| anyhow!("cid not found"))
}
}
impl TryFrom<&CIDMap> for Cid {
type Error = anyhow::Error;
fn try_from(cid_map: &CIDMap) -> Result<Self, Self::Error> {
let cid_option = cid_map
.cid
.as_ref()
.map(|cid| Cid::from_str(cid).expect("invalid cid str"));
cid_option.ok_or_else(|| anyhow!("cid not found"))
}
}
impl From<CIDMap> for Option<Cid> {
fn from(m: CIDMap) -> Self {
m.cid
.map(|cid| Cid::from_str(&cid).expect("invalid cid str"))
}
}
impl From<Option<Cid>> for CIDMap {
fn from(c: Option<Cid>) -> Self {
c.map(|cid| CIDMap {
cid: Some(cid.to_string()),
})
.unwrap_or(CIDMap { cid: None })
}
}
impl From<Cid> for CIDMap {
fn from(c: Cid) -> Self {
CIDMap {
cid: Some(c.to_string()),
}
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/wallet.rs | ipc/provider/src/lotus/message/wallet.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use anyhow::anyhow;
use fvm_shared::crypto::signature::SignatureType;
use serde::{Deserialize, Serialize};
use strum::{AsRefStr, Display, EnumString};
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Display, EnumString, AsRefStr)]
pub enum WalletKeyType {
#[strum(serialize = "bls", ascii_case_insensitive)]
BLS,
#[strum(serialize = "secp256k1", ascii_case_insensitive)]
Secp256k1,
#[strum(serialize = "secp256k1-ledger", ascii_case_insensitive)]
Secp256k1Ledger,
}
impl TryFrom<WalletKeyType> for SignatureType {
type Error = anyhow::Error;
fn try_from(value: WalletKeyType) -> Result<Self, Self::Error> {
match value {
WalletKeyType::BLS => Ok(SignatureType::BLS),
WalletKeyType::Secp256k1 => Ok(SignatureType::Secp256k1),
WalletKeyType::Secp256k1Ledger => Err(anyhow!("type not supported")),
}
}
}
impl TryFrom<SignatureType> for WalletKeyType {
type Error = anyhow::Error;
fn try_from(value: SignatureType) -> Result<Self, Self::Error> {
match value {
SignatureType::BLS => Ok(WalletKeyType::BLS),
SignatureType::Secp256k1 => Ok(WalletKeyType::Secp256k1),
}
}
}
pub type WalletListResponse = Vec<String>;
#[cfg(test)]
mod tests {
use std::str::FromStr;
use crate::lotus::message::wallet::WalletKeyType;
#[test]
fn test_key_types() {
let t = WalletKeyType::Secp256k1;
assert_eq!(t.as_ref(), "secp256k1");
let t = WalletKeyType::from_str(t.as_ref()).unwrap();
assert_eq!(t, WalletKeyType::Secp256k1);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/mpool.rs | ipc/provider/src/lotus/message/mpool.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use crate::lotus::message::deserialize::{
deserialize_address_from_str, deserialize_some_token_amount_from_num,
deserialize_some_token_amount_from_str, deserialize_token_amount_from_str,
};
use crate::lotus::message::CIDMap;
use cid::Cid;
use fvm_shared::address::Address;
use fvm_shared::econ::TokenAmount;
use fvm_shared::MethodNum;
use serde::Deserialize;
use std::str::FromStr;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct MpoolPushMessageResponse {
pub message: MpoolPushMessageResponseInner,
#[serde(rename = "CID")]
pub cid: CIDMap,
}
/// The internal message payload that node rpc sends for `MpoolPushMessageResponse`.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct MpoolPushMessageResponseInner {
to: String,
from: String,
pub value: String,
pub method: MethodNum,
pub params: String,
pub nonce: u64,
#[serde(rename = "GasLimit")]
pub gas_limit: u64,
#[serde(rename = "GasFeeCap")]
pub gas_fee_cap: String,
#[serde(rename = "GasPremium")]
pub gas_premium: String,
pub version: u16,
#[serde(rename = "CID")]
pub cid: CIDMap,
}
impl MpoolPushMessageResponseInner {
pub fn cid(&self) -> anyhow::Result<Cid> {
Cid::try_from(self.cid.clone())
}
pub fn to(&self) -> anyhow::Result<Address> {
Ok(Address::from_str(&self.to)?)
}
pub fn from(&self) -> anyhow::Result<Address> {
Ok(Address::from_str(&self.from)?)
}
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct MpoolPushMessage {
#[serde(deserialize_with = "deserialize_address_from_str")]
pub to: Address,
#[serde(deserialize_with = "deserialize_address_from_str")]
pub from: Address,
#[serde(deserialize_with = "deserialize_token_amount_from_str")]
pub value: TokenAmount,
pub method: MethodNum,
pub params: Vec<u8>,
pub nonce: Option<u64>,
#[serde(deserialize_with = "deserialize_some_token_amount_from_num")]
pub gas_limit: Option<TokenAmount>,
#[serde(deserialize_with = "deserialize_some_token_amount_from_str")]
pub gas_fee_cap: Option<TokenAmount>,
#[serde(deserialize_with = "deserialize_some_token_amount_from_str")]
pub gas_premium: Option<TokenAmount>,
pub cid: Option<Cid>,
pub version: Option<u16>,
pub max_fee: Option<TokenAmount>,
}
impl MpoolPushMessage {
pub fn new(to: Address, from: Address, method: MethodNum, params: Vec<u8>) -> Self {
MpoolPushMessage {
to,
from,
method,
params,
value: TokenAmount::from_atto(0),
nonce: None,
gas_limit: None,
gas_fee_cap: None,
gas_premium: None,
cid: None,
version: None,
max_fee: None,
}
}
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct EstimateGasResponse {
#[serde(deserialize_with = "deserialize_some_token_amount_from_num")]
pub gas_limit: Option<TokenAmount>,
#[serde(deserialize_with = "deserialize_some_token_amount_from_str")]
pub gas_fee_cap: Option<TokenAmount>,
#[serde(deserialize_with = "deserialize_some_token_amount_from_str")]
pub gas_premium: Option<TokenAmount>,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/lotus/message/ipc.rs | ipc/provider/src/lotus/message/ipc.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use fvm_ipld_encoding::RawBytes;
use fvm_shared::clock::ChainEpoch;
use fvm_shared::econ::TokenAmount;
use fvm_shared::MethodNum;
use ipc_api::address::IPCAddress;
use ipc_api::subnet_id::SubnetID;
use serde::{Deserialize, Serialize};
use crate::lotus::message::deserialize::{
deserialize_ipc_address_from_map, deserialize_subnet_id_from_map,
deserialize_token_amount_from_str,
};
use crate::lotus::message::serialize::{
serialize_subnet_id_to_str, serialize_token_amount_to_atto,
};
use crate::lotus::message::CIDMap;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct IPCGetPrevCheckpointForChildResponse {
#[serde(rename = "CID")]
pub cid: Option<CIDMap>,
}
/// The state of a gateway actor. The struct omits all fields that are not relevant for the
/// execution of the IPC agent.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct IPCReadGatewayStateResponse {
pub bottom_up_check_period: ChainEpoch,
pub top_down_check_period: ChainEpoch,
pub applied_topdown_nonce: u64,
pub top_down_checkpoint_voting: Voting,
pub initialized: bool,
}
/// The state of a subnet actor. The struct omits all fields that are not relevant for the
/// execution of the IPC agent.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct IPCReadSubnetActorStateResponse {
pub bottom_up_check_period: ChainEpoch,
pub validator_set: ValidatorSet,
pub min_validators: u64,
pub bottom_up_checkpoint_voting: Voting,
}
/// A subset of the voting structure with information
/// about a checkpoint voting
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Voting {
pub genesis_epoch: i64,
pub last_voting_executed: i64,
}
/// SubnetInfo is an auxiliary struct that collects relevant information about the state of a subnet
///
/// Note that the serialization and deserialization casing are different. Reason because for deserialization,
/// it is from the fvm actor, which is `PascalCase`. When serialize, we are using rust's default casing
#[derive(Debug, Serialize, Deserialize)]
pub struct SubnetInfo {
/// Id of the subnet.
#[serde(rename(deserialize = "ID"))]
#[serde(deserialize_with = "deserialize_subnet_id_from_map")]
#[serde(serialize_with = "serialize_subnet_id_to_str")]
pub id: SubnetID,
/// Collateral staked in the subnet.
#[serde(rename(deserialize = "Stake"))]
#[serde(deserialize_with = "deserialize_token_amount_from_str")]
#[serde(serialize_with = "serialize_token_amount_to_atto")]
pub stake: TokenAmount,
/// Circulating supply available in the subnet.
#[serde(rename(deserialize = "CircSupply"))]
#[serde(deserialize_with = "deserialize_token_amount_from_str")]
#[serde(serialize_with = "serialize_token_amount_to_atto")]
pub circ_supply: TokenAmount,
pub genesis_epoch: ChainEpoch,
}
/// We need to redefine the struct here due to:
/// In the actor, it is `Deserialize_tuple`, but when returned from json rpc endpoints, it's
/// actually `json` struct. The deserialization is not working because the agent is interpreting
/// the tuple as json.
#[derive(Deserialize, Serialize, Debug)]
pub struct ValidatorSet {
pub validators: Option<Vec<Validator>>,
// sequence number that uniquely identifies a validator set
pub configuration_number: u64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct QueryValidatorSetResponse {
/// The validator set for the subnet fetched from the parent.
pub validator_set: ValidatorSet,
/// Minimum number of validators required by the subnet
pub min_validators: u64,
/// Genesis epoch at which the subnet was registered
pub genesis_epoch: i64,
}
/// The validator struct. See `ValidatorSet` comment on why we need this duplicated definition.
#[derive(Deserialize, Serialize, Debug)]
pub struct Validator {
pub addr: String,
pub net_addr: String,
pub worker_addr: Option<String>,
pub weight: String,
}
#[derive(PartialEq, Eq, Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct CrossMsgsWrapper {
pub msg: StorableMsgsWrapper,
pub wrapped: bool,
}
#[derive(PartialEq, Eq, Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct StorableMsgsWrapper {
#[serde(deserialize_with = "deserialize_ipc_address_from_map")]
pub from: IPCAddress,
#[serde(deserialize_with = "deserialize_ipc_address_from_map")]
pub to: IPCAddress,
pub method: MethodNum,
pub params: RawBytes,
pub value: TokenAmount,
pub nonce: u64,
pub fee: TokenAmount,
}
#[cfg(test)]
mod tests {
use crate::lotus::message::ipc::IPCReadSubnetActorStateResponse;
#[test]
fn deserialize_ipc_subnet_state() {
let raw = r#"
{"Name":"test2","ParentID":{"Parent":"/r31415926","Actor":"t00"},"IPCGatewayAddr":"f064","Consensus":3,"MinValidatorStake":"1000000000000000000","TotalStake":"10000000000000000000","Stake":{"/":"bafy2bzacebentzoqaapingrxwknlxqcusl23rqaa7cwb42u76fgvb25nxpmhq"},"Genesis":null,"BottomUpCheckPeriod":10,"TopDownCheckPeriod":10,"GenesisEpoch":0,"CommittedCheckpoints":{"/":"bafy2bzaceamp42wmmgr2g2ymg46euououzfyck7szknvfacqscohrvaikwfay"},"ValidatorSet":{"validators":[{"addr":"t1cp4q4lqsdhob23ysywffg2tvbmar5cshia4rweq","net_addr":"test","weight":"10000000000000000000"}],"configuration_number":1},"MinValidators":1,"PreviousExecutedCheckpoint":{"/":"bafy2bzacedkoa623kvi5gfis2yks7xxjl73vg7xwbojz4tpq63dd5jpfz757i"},"BottomUpCheckpointVoting":{"GenesisEpoch":0,"SubmissionPeriod":10,"LastVotingExecuted":0,"ExecutableEpochQueue":null,"EpochVoteSubmission":{"/":"bafy2bzaceamp42wmmgr2g2ymg46euououzfyck7szknvfacqscohrvaikwfay"},"Ratio":{"Num":2,"Denom":3}}}
"#;
let r = serde_json::from_str::<IPCReadSubnetActorStateResponse>(raw);
assert!(r.is_ok());
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/jsonrpc/tests.rs | ipc/provider/src/jsonrpc/tests.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use futures_util::StreamExt;
use serde_json::json;
use url::Url;
use crate::jsonrpc::{JsonRpcClient, JsonRpcClientImpl, NO_PARAMS};
/// The default endpoints for public lotus node. If the urls fail in running tests, need to
/// check these endpoints again.
const HTTP_ENDPOINT: &str = "https://api.node.glif.io/rpc/v0";
const WS_ENDPOINT: &str = "wss://wss.node.glif.io/apigw/lotus/rpc/v0";
#[tokio::test]
async fn test_request_error() {
let url = Url::parse(HTTP_ENDPOINT).unwrap();
let client = JsonRpcClientImpl::new(url, None);
// Make a request with missing params
let response = client
.request::<serde_json::Value>("Filecoin.ChainGetBlock", NO_PARAMS)
.await;
assert!(response.is_err());
}
#[tokio::test]
#[ignore]
async fn test_request_with_params() {
let url = Url::parse(HTTP_ENDPOINT).unwrap();
let client = JsonRpcClientImpl::new(url, None);
let params = json!([{"/":"bafy2bzacecwgnejfzcq7a4zvvownmb4oae6xzyu323z5wuuufesbtikortt6k"}]);
let response = client
.request::<serde_json::Value>("Filecoin.ChainGetBlock", params)
.await;
assert!(response.is_ok());
}
#[tokio::test]
async fn test_request_with_params_error() {
let url = Url::parse(HTTP_ENDPOINT).unwrap();
let client = JsonRpcClientImpl::new(url, None);
let response = client
.request::<serde_json::Value>("Filecoin.ChainGetBlock", NO_PARAMS)
.await;
assert!(response.is_err());
}
#[tokio::test]
#[ignore]
async fn test_subscribe() {
let url = Url::parse(WS_ENDPOINT).unwrap();
let client = JsonRpcClientImpl::new(url, None);
let mut chan = client.subscribe("Filecoin.ChainNotify").await.unwrap();
for _ in 1..=3 {
chan.next().await.unwrap();
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/jsonrpc/mod.rs | ipc/provider/src/jsonrpc/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use anyhow::{anyhow, Result};
use async_channel::{Receiver, Sender};
use async_trait::async_trait;
use futures_util::{SinkExt, StreamExt};
use reqwest::header::HeaderValue;
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde_json::json;
use serde_json::Value;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::spawn;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::MaybeTlsStream;
use tokio_tungstenite::{connect_async, WebSocketStream};
use url::Url;
#[cfg(test)]
mod tests;
const DEFAULT_JSON_RPC_VERSION: &str = "2.0";
const DEFAULT_JSON_RPC_ID: u8 = 1;
/// Request timeout of the RPC client. It should be enough to accommodate
/// the time required to validate transaction on-chain.
const DEFAULT_REQ_TIMEOUT: Duration = Duration::from_secs(250);
/// A convenience constant that represents empty params in a JSON-RPC request.
pub const NO_PARAMS: Value = json!([]);
/// A simple async JSON-RPC client that can send one-shot request via HTTP/HTTPS
/// and subscribe to push-based notifications via Websockets. The returned
/// results are of type [`Value`] from the [`serde_json`] crate.
#[async_trait]
pub trait JsonRpcClient {
/// Sends a JSON-RPC request with `method` and `params` via HTTP/HTTPS.
async fn request<T: DeserializeOwned>(&self, method: &str, params: Value) -> Result<T>;
/// Subscribes to notifications via a Websocket. This returns a [`Receiver`]
/// channel that is used to receive the messages sent by the server.
/// TODO: https://github.com/consensus-shipyard/ipc-agent/issues/7.
async fn subscribe(&self, method: &str) -> Result<Receiver<Value>>;
}
/// The implementation of [`JsonRpcClient`].
pub struct JsonRpcClientImpl {
http_client: Client,
url: Url,
bearer_token: Option<String>,
}
impl JsonRpcClientImpl {
/// Creates a client that sends all requests to `url`.
pub fn new(url: Url, bearer_token: Option<&str>) -> Self {
Self {
http_client: Client::default(),
url,
bearer_token: bearer_token.map(String::from),
}
}
}
#[async_trait]
impl JsonRpcClient for JsonRpcClientImpl {
async fn request<T: DeserializeOwned>(&self, method: &str, params: Value) -> Result<T> {
let request_body = build_jsonrpc_request(method, params)?;
let mut builder = self.http_client.post(self.url.as_str()).json(&request_body);
builder = builder.timeout(DEFAULT_REQ_TIMEOUT);
// Add the authorization bearer token if present
if self.bearer_token.is_some() {
builder = builder.bearer_auth(self.bearer_token.as_ref().unwrap());
}
let response = builder.send().await?;
let response_body = response.text().await?;
tracing::debug!("received raw response body: {:?}", response_body);
let value =
serde_json::from_str::<JsonRpcResponse<T>>(response_body.as_ref()).map_err(|e| {
tracing::error!("cannot parse json rpc client response: {:?}", response_body);
anyhow!(
"cannot parse json rpc response: {:} due to {:}",
response_body,
e.to_string()
)
})?;
if value.id != DEFAULT_JSON_RPC_ID || value.jsonrpc != DEFAULT_JSON_RPC_VERSION {
return Err(anyhow!("json_rpc id or version not matching."));
}
Result::from(value)
}
async fn subscribe(&self, method: &str) -> Result<Receiver<Value>> {
let mut request = self.url.as_str().into_client_request()?;
// Add the authorization bearer token if present
if self.bearer_token.is_some() {
let token_string = format!("Bearer {}", self.bearer_token.as_ref().unwrap());
let header_value = HeaderValue::from_str(token_string.as_str())?;
request.headers_mut().insert("Authorization", header_value);
}
let (mut ws_stream, _) = connect_async(request).await?;
let request_body = build_jsonrpc_request(method, NO_PARAMS)?;
ws_stream
.send(Message::text(request_body.to_string()))
.await?;
let (send_chan, recv_chan) = async_channel::unbounded::<Value>();
spawn(handle_stream(ws_stream, send_chan));
Ok(recv_chan)
}
}
/// JsonRpcResponse wraps the json rpc response.
/// We could have encountered success or error, this struct handles the error and result and convert
/// them into Result.
#[derive(Debug, Deserialize)]
struct JsonRpcResponse<T> {
id: u8,
jsonrpc: String,
result: Option<T>,
error: Option<Value>,
}
impl<T: DeserializeOwned> From<JsonRpcResponse<T>> for Result<T> {
fn from(j: JsonRpcResponse<T>) -> Self {
if j.error.is_some() {
return Err(anyhow!("json_rpc error: {:}", j.error.unwrap()));
}
if j.result.is_some() {
Ok(j.result.unwrap())
} else {
// The result is not found, but it is possible T could be the rust unit type: (), i.e. the
// caller is expecting Result<()>.
// To do this, we need to rely on serde to perform a conversion from NULL.
Ok(serde_json::from_value(serde_json::Value::Null)?)
}
}
}
// Processes a websocket stream by reading messages from the stream `ws_stream` and sending
// them to an output channel `chan`.
async fn handle_stream(
mut ws_stream: WebSocketStream<MaybeTlsStream<TcpStream>>,
chan: Sender<Value>,
) {
loop {
match ws_stream.next().await {
None => {
tracing::trace!("No message in websocket stream. The stream was closed.");
break;
}
Some(result) => match result {
Ok(msg) => {
println!("{}", msg);
tracing::trace!("Read message from websocket stream: {}", msg);
let value = serde_json::from_str(msg.to_text().unwrap()).unwrap();
chan.send(value).await.unwrap();
}
Err(err) => {
tracing::error!("Error reading message from websocket stream: {:?}", err);
break;
}
},
};
}
chan.close();
}
// A convenience function to build a JSON-RPC request.
fn build_jsonrpc_request(method: &str, params: Value) -> Result<Value> {
let has_params = if params.is_array() {
let array_params = params.as_array().unwrap();
!array_params.is_empty()
} else if params.is_object() {
let object_params = params.as_object().unwrap();
!object_params.is_empty()
} else if params.is_null() {
false
} else {
return Err(anyhow!("params is not an array nor an object"));
};
let request_value = if has_params {
json!({
"jsonrpc": DEFAULT_JSON_RPC_VERSION,
"id": DEFAULT_JSON_RPC_ID,
"method": method,
"params": params,
})
} else {
json!({
"jsonrpc": DEFAULT_JSON_RPC_VERSION,
"id": DEFAULT_JSON_RPC_ID,
"method": method,
})
};
Ok(request_value)
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/manager/subnet.rs | ipc/provider/src/manager/subnet.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use std::collections::{BTreeMap, HashMap};
use anyhow::Result;
use async_trait::async_trait;
use fvm_shared::clock::ChainEpoch;
use fvm_shared::{address::Address, econ::TokenAmount};
use ipc_api::checkpoint::{
BottomUpCheckpoint, BottomUpCheckpointBundle, QuorumReachedEvent, Signature,
};
use ipc_api::cross::IpcEnvelope;
use ipc_api::staking::{StakingChangeRequest, ValidatorInfo};
use ipc_api::subnet::{ConstructParams, PermissionMode, SupplySource};
use ipc_api::subnet_id::SubnetID;
use ipc_api::validator::Validator;
use crate::lotus::message::ipc::SubnetInfo;
/// Trait to interact with a subnet and handle its lifecycle.
#[async_trait]
pub trait SubnetManager: Send + Sync + TopDownFinalityQuery + BottomUpCheckpointRelayer {
/// Deploys a new subnet actor on the `parent` subnet and with the
/// configuration passed in `ConstructParams`.
/// The result of the function is the ID address for the subnet actor from which the final
/// subet ID can be inferred.
async fn create_subnet(&self, from: Address, params: ConstructParams) -> Result<Address>;
/// Performs the call to join a subnet from a wallet address and staking an amount
/// of collateral. This function, as well as all of the ones on this trait, can infer
/// the specific subnet and actors on which to perform the relevant calls from the
/// SubnetID given as an argument.
async fn join_subnet(
&self,
subnet: SubnetID,
from: Address,
collateral: TokenAmount,
metadata: Vec<u8>,
) -> Result<ChainEpoch>;
/// Adds some initial balance to an address before a child subnet bootstraps to make
/// it available in the subnet at genesis.
async fn pre_fund(&self, subnet: SubnetID, from: Address, balance: TokenAmount) -> Result<()>;
/// Releases initial funds from an address for a subnet that has not yet been bootstrapped
async fn pre_release(&self, subnet: SubnetID, from: Address, amount: TokenAmount)
-> Result<()>;
/// Allows validators that have already joined the subnet to stake more collateral
/// and increase their power in the subnet.
async fn stake(&self, subnet: SubnetID, from: Address, collateral: TokenAmount) -> Result<()>;
/// Allows validators that have already joined the subnet to unstake collateral
/// and reduce their power in the subnet.
async fn unstake(&self, subnet: SubnetID, from: Address, collateral: TokenAmount)
-> Result<()>;
/// Sends a request to leave a subnet from a wallet address.
async fn leave_subnet(&self, subnet: SubnetID, from: Address) -> Result<()>;
/// Sends a signal to kill a subnet
async fn kill_subnet(&self, subnet: SubnetID, from: Address) -> Result<()>;
/// Lists all the registered children in a gateway.
async fn list_child_subnets(
&self,
gateway_addr: Address,
) -> Result<HashMap<SubnetID, SubnetInfo>>;
/// Claims any collateral that may be available to claim by validators that
/// have left the subnet.
async fn claim_collateral(&self, subnet: SubnetID, from: Address) -> Result<()>;
/// Fund injects new funds from an account of the parent chain to a subnet.
/// Returns the epoch that the fund is executed in the parent.
async fn fund(
&self,
subnet: SubnetID,
gateway_addr: Address,
from: Address,
to: Address,
amount: TokenAmount,
) -> Result<ChainEpoch>;
/// Sends funds to a specified subnet receiver using ERC20 tokens.
/// This function locks the amount of ERC20 tokens into custody and then mints the supply in the specified subnet.
/// It checks if the subnet's supply strategy is ERC20 and if not, the operation is reverted.
/// It allows for free injection of funds into a subnet and is protected against reentrancy.
///
/// # Arguments
///
/// * `subnetId` - The ID of the subnet where the funds will be sent to.
/// * `from` - The funding address.
/// * `to` - The funded address.
/// * `amount` - The amount of ERC20 tokens to be sent.
async fn fund_with_token(
&self,
subnet: SubnetID,
from: Address,
to: Address,
amount: TokenAmount,
) -> Result<ChainEpoch>;
/// Grants an allowance to the `from` address to withdraw up to `amount` of tokens from the contract at `token_address`.
/// This function sets up an approval, allowing the `from` address to later transfer or utilize the tokens from the specified ERC20 token contract.
/// The primary use case is to enable subsequent contract interactions that require an upfront allowance,
/// such as depositing tokens into a contract that requires an allowance check.
///
/// The operation ensures that the caller has the necessary authority and token balance before setting the allowance.
/// It is crucial for enabling controlled access to the token funds without transferring the ownership.
/// Note that calling this function multiple times can overwrite the existing allowance with the new value.
///
/// # Arguments
///
/// * `from` - The address granting the approval.
/// * `token_address`- The contract address of the ERC20 token for which the approval is being granted.
/// * `amount` - The maximum amount of tokens `from` is allowing to be used.
///
/// # Returns
///
/// * `Result<()>` - An empty result indicating success or an error on failure, encapsulating any issues encountered during the approval process.
async fn approve_token(
&self,
subnet: SubnetID,
from: Address,
amount: TokenAmount,
) -> Result<ChainEpoch>;
/// Release creates a new check message to release funds in parent chain
/// Returns the epoch that the released is executed in the child.
async fn release(
&self,
gateway_addr: Address,
from: Address,
to: Address,
amount: TokenAmount,
) -> Result<ChainEpoch>;
/// Propagate a cross-net message forward. For `postbox_msg_key`, we are using bytes because different
/// runtime have different representations. For FVM, it should be `CID` as bytes. For EVM, it is
/// `bytes32`.
async fn propagate(
&self,
subnet: SubnetID,
gateway_addr: Address,
from: Address,
postbox_msg_key: Vec<u8>,
) -> Result<()>;
/// Send value between two addresses in a subnet
async fn send_value(&self, from: Address, to: Address, amount: TokenAmount) -> Result<()>;
/// Get the balance of an address
async fn wallet_balance(&self, address: &Address) -> Result<TokenAmount>;
/// Get chainID for the network.
/// Returning as a `String` because the maximum value for an EVM
/// networks is a `U256` that wouldn't fit in an integer type.
async fn get_chain_id(&self) -> Result<String>;
/// Get commit sha for deployed contracts
async fn get_commit_sha(&self) -> Result<[u8; 32]>;
/// Gets the subnet supply source
async fn get_subnet_supply_source(
&self,
subnet: &SubnetID,
) -> Result<ipc_actors_abis::subnet_actor_getter_facet::SupplySource>;
/// Gets the genesis information required to bootstrap a child subnet
async fn get_genesis_info(&self, subnet: &SubnetID) -> Result<SubnetGenesisInfo>;
/// Advertises the endpoint of a bootstrap node for the subnet.
async fn add_bootstrap(
&self,
subnet: &SubnetID,
from: &Address,
endpoint: String,
) -> Result<()>;
/// Lists the bootstrap nodes of a subnet
async fn list_bootstrap_nodes(&self, subnet: &SubnetID) -> Result<Vec<String>>;
/// Get the validator information
async fn get_validator_info(
&self,
subnet: &SubnetID,
validator: &Address,
) -> Result<ValidatorInfo>;
async fn set_federated_power(
&self,
from: &Address,
subnet: &SubnetID,
validators: &[Address],
public_keys: &[Vec<u8>],
federated_power: &[u128],
) -> Result<ChainEpoch>;
}
#[derive(Debug)]
pub struct SubnetGenesisInfo {
pub bottom_up_checkpoint_period: u64,
pub majority_percentage: u8,
pub active_validators_limit: u16,
pub min_collateral: TokenAmount,
pub genesis_epoch: ChainEpoch,
pub validators: Vec<Validator>,
pub genesis_balances: BTreeMap<Address, TokenAmount>,
pub permission_mode: PermissionMode,
pub supply_source: SupplySource,
}
/// The generic payload that returns the block hash of the data returning block with the actual
/// data payload.
#[derive(Debug)]
pub struct TopDownQueryPayload<T> {
pub value: T,
pub block_hash: Vec<u8>,
}
#[derive(Default, Debug)]
pub struct GetBlockHashResult {
pub parent_block_hash: Vec<u8>,
pub block_hash: Vec<u8>,
}
/// Trait to interact with a subnet to query the necessary information for top down checkpoint.
#[async_trait]
pub trait TopDownFinalityQuery: Send + Sync {
/// Returns the genesis epoch that the subnet is created in parent network
async fn genesis_epoch(&self, subnet_id: &SubnetID) -> Result<ChainEpoch>;
/// Returns the chain head height
async fn chain_head_height(&self) -> Result<ChainEpoch>;
/// Returns the list of top down messages
async fn get_top_down_msgs(
&self,
subnet_id: &SubnetID,
epoch: ChainEpoch,
) -> Result<TopDownQueryPayload<Vec<IpcEnvelope>>>;
/// Get the block hash
async fn get_block_hash(&self, height: ChainEpoch) -> Result<GetBlockHashResult>;
/// Get the validator change set from start to end block.
async fn get_validator_changeset(
&self,
subnet_id: &SubnetID,
epoch: ChainEpoch,
) -> Result<TopDownQueryPayload<Vec<StakingChangeRequest>>>;
/// Returns the latest parent finality committed in a child subnet
async fn latest_parent_finality(&self) -> Result<ChainEpoch>;
}
/// The bottom up checkpoint manager that handles the bottom up relaying from child subnet to the parent
/// subnet.
#[async_trait]
pub trait BottomUpCheckpointRelayer: Send + Sync {
/// Submit a checkpoint for execution.
/// It triggers the commitment of the checkpoint and the execution of related cross-net messages.
/// Returns the epoch that the execution is successful
async fn submit_checkpoint(
&self,
submitter: &Address,
checkpoint: BottomUpCheckpoint,
signatures: Vec<Signature>,
signatories: Vec<Address>,
) -> Result<ChainEpoch>;
/// The last confirmed/submitted checkpoint height.
async fn last_bottom_up_checkpoint_height(&self, subnet_id: &SubnetID) -> Result<ChainEpoch>;
/// Get the checkpoint period, i.e the number of blocks to submit bottom up checkpoints.
async fn checkpoint_period(&self, subnet_id: &SubnetID) -> Result<ChainEpoch>;
/// Get the checkpoint bundle at a specific height. If it does not exist, it will through error.
async fn checkpoint_bundle_at(
&self,
height: ChainEpoch,
) -> Result<Option<BottomUpCheckpointBundle>>;
/// Queries the signature quorum reached events at target height.
async fn quorum_reached_events(&self, height: ChainEpoch) -> Result<Vec<QuorumReachedEvent>>;
/// Get the current epoch in the current subnet
async fn current_epoch(&self) -> Result<ChainEpoch>;
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/manager/mod.rs | ipc/provider/src/manager/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
pub use crate::lotus::message::ipc::SubnetInfo;
pub use evm::{EthManager, EthSubnetManager};
pub use subnet::{
BottomUpCheckpointRelayer, GetBlockHashResult, SubnetGenesisInfo, SubnetManager,
TopDownFinalityQuery, TopDownQueryPayload,
};
pub mod evm;
mod subnet;
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/manager/evm/manager.rs | ipc/provider/src/manager/evm/manager.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use std::borrow::Borrow;
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use ethers_contract::{ContractError, EthLogDecode, LogMeta};
use ipc_actors_abis::{
checkpointing_facet, gateway_getter_facet, gateway_manager_facet, gateway_messenger_facet,
lib_gateway, lib_quorum, lib_staking_change_log, register_subnet_facet,
subnet_actor_checkpointing_facet, subnet_actor_getter_facet, subnet_actor_manager_facet,
subnet_actor_reward_facet,
};
use ipc_api::evm::{fil_to_eth_amount, payload_to_evm_address, subnet_id_to_evm_addresses};
use ipc_api::validator::from_contract_validators;
use reqwest::header::HeaderValue;
use reqwest::Client;
use std::net::{IpAddr, SocketAddr};
use ipc_api::subnet::{PermissionMode, SupplyKind, SupplySource};
use ipc_api::{eth_to_fil_amount, ethers_address_to_fil_address};
use crate::config::subnet::SubnetConfig;
use crate::config::Subnet;
use crate::lotus::message::ipc::SubnetInfo;
use crate::manager::subnet::{
BottomUpCheckpointRelayer, GetBlockHashResult, SubnetGenesisInfo, TopDownFinalityQuery,
TopDownQueryPayload,
};
use crate::manager::{EthManager, SubnetManager};
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use ethers::abi::Tokenizable;
use ethers::contract::abigen;
use ethers::prelude::k256::ecdsa::SigningKey;
use ethers::prelude::{Signer, SignerMiddleware};
use ethers::providers::{Authorization, Http, Middleware, Provider};
use ethers::signers::{LocalWallet, Wallet};
use ethers::types::{BlockId, Eip1559TransactionRequest, ValueOrArray, I256, U256};
use fvm_shared::clock::ChainEpoch;
use fvm_shared::{address::Address, econ::TokenAmount};
use ipc_api::checkpoint::{
BottomUpCheckpoint, BottomUpCheckpointBundle, QuorumReachedEvent, Signature,
};
use ipc_api::cross::IpcEnvelope;
use ipc_api::staking::{StakingChangeRequest, ValidatorInfo, ValidatorStakingInfo};
use ipc_api::subnet::ConstructParams;
use ipc_api::subnet_id::SubnetID;
use ipc_wallet::{EthKeyAddress, EvmKeyStore, PersistentKeyStore};
use num_traits::ToPrimitive;
use std::result;
pub type DefaultSignerMiddleware = SignerMiddleware<Provider<Http>, Wallet<SigningKey>>;
/// Default polling time used by the Ethers provider to check for pending
/// transactions and events. Default is 7, and for our child subnets we
/// can reduce it to the block time (or potentially less)
const ETH_PROVIDER_POLLING_TIME: Duration = Duration::from_secs(1);
/// Maximum number of retries to fetch a transaction receipt.
/// The number of retries should ensure that for the block time
/// of the network the number of retires considering the polling
/// time above waits enough tie to get the transaction receipt.
/// We currently support a low polling time and high number of
/// retries so these numbers accommodate fast subnets with slow
/// roots (like Calibration and mainnet).
const TRANSACTION_RECEIPT_RETRIES: usize = 200;
/// The majority vote percentage for checkpoint submission when creating a subnet.
const SUBNET_MAJORITY_PERCENTAGE: u8 = 67;
pub struct EthSubnetManager {
keystore: Option<Arc<RwLock<PersistentKeyStore<EthKeyAddress>>>>,
ipc_contract_info: IPCContractInfo,
}
/// Keep track of the on chain information for the subnet manager
struct IPCContractInfo {
gateway_addr: ethers::types::Address,
registry_addr: ethers::types::Address,
chain_id: u64,
provider: Provider<Http>,
}
//TODO receive clarity on this implementation
abigen!(
IERC20,
r#"[
function approve(address spender, uint256 amount) external returns (bool)
event Transfer(address indexed from, address indexed to, uint256 value)
event Approval(address indexed owner, address indexed spender, uint256 value)
]"#,
);
#[async_trait]
impl TopDownFinalityQuery for EthSubnetManager {
async fn genesis_epoch(&self, subnet_id: &SubnetID) -> Result<ChainEpoch> {
let address = contract_address_from_subnet(subnet_id)?;
tracing::info!("querying genesis epoch in evm subnet contract: {address:}");
let evm_subnet_id = gateway_getter_facet::SubnetID::try_from(subnet_id)?;
let contract = gateway_getter_facet::GatewayGetterFacet::new(
self.ipc_contract_info.gateway_addr,
Arc::new(self.ipc_contract_info.provider.clone()),
);
let (exists, subnet) = contract.get_subnet(evm_subnet_id).call().await?;
if !exists {
return Err(anyhow!("subnet: {} does not exists", subnet_id));
}
Ok(subnet.genesis_epoch.as_u64() as ChainEpoch)
}
async fn chain_head_height(&self) -> Result<ChainEpoch> {
let block = self
.ipc_contract_info
.provider
.get_block_number()
.await
.context("cannot get evm block number")?;
Ok(block.as_u64() as ChainEpoch)
}
async fn get_top_down_msgs(
&self,
subnet_id: &SubnetID,
epoch: ChainEpoch,
) -> Result<TopDownQueryPayload<Vec<IpcEnvelope>>> {
let gateway_contract = gateway_manager_facet::GatewayManagerFacet::new(
self.ipc_contract_info.gateway_addr,
Arc::new(self.ipc_contract_info.provider.clone()),
);
let topic1 = contract_address_from_subnet(subnet_id)?;
tracing::debug!(
"getting top down messages for subnet: {:?} with topic 1: {}",
subnet_id,
topic1,
);
let ev = gateway_contract
.event::<lib_gateway::NewTopDownMessageFilter>()
.from_block(epoch as u64)
.to_block(epoch as u64)
.topic1(topic1)
.address(ValueOrArray::Value(gateway_contract.address()));
let mut messages = vec![];
let mut hash = None;
for (event, meta) in query_with_meta(ev, gateway_contract.client()).await? {
if let Some(h) = hash {
if h != meta.block_hash {
return Err(anyhow!("block hash not equal"));
}
} else {
hash = Some(meta.block_hash);
}
messages.push(IpcEnvelope::try_from(event.message)?);
}
let block_hash = if let Some(h) = hash {
h.0.to_vec()
} else {
self.get_block_hash(epoch).await?.block_hash
};
Ok(TopDownQueryPayload {
value: messages,
block_hash,
})
}
async fn get_block_hash(&self, height: ChainEpoch) -> Result<GetBlockHashResult> {
let block = self
.ipc_contract_info
.provider
.get_block(height as u64)
.await?
.ok_or_else(|| anyhow!("height does not exist"))?;
Ok(GetBlockHashResult {
parent_block_hash: block.parent_hash.to_fixed_bytes().to_vec(),
block_hash: block
.hash
.ok_or_else(|| anyhow!("block hash is empty"))?
.to_fixed_bytes()
.to_vec(),
})
}
async fn get_validator_changeset(
&self,
subnet_id: &SubnetID,
epoch: ChainEpoch,
) -> Result<TopDownQueryPayload<Vec<StakingChangeRequest>>> {
let address = contract_address_from_subnet(subnet_id)?;
tracing::info!("querying validator changes in evm subnet contract: {address:}");
let contract = subnet_actor_manager_facet::SubnetActorManagerFacet::new(
address,
Arc::new(self.ipc_contract_info.provider.clone()),
);
let ev = contract
.event::<lib_staking_change_log::NewStakingChangeRequestFilter>()
.from_block(epoch as u64)
.to_block(epoch as u64)
.address(ValueOrArray::Value(contract.address()));
let mut changes = vec![];
let mut hash = None;
for (event, meta) in query_with_meta(ev, contract.client()).await? {
if let Some(h) = hash {
if h != meta.block_hash {
return Err(anyhow!("block hash not equal"));
}
} else {
hash = Some(meta.block_hash);
}
changes.push(StakingChangeRequest::try_from(event)?);
}
let block_hash = if let Some(h) = hash {
h.0.to_vec()
} else {
self.get_block_hash(epoch).await?.block_hash
};
Ok(TopDownQueryPayload {
value: changes,
block_hash,
})
}
async fn latest_parent_finality(&self) -> Result<ChainEpoch> {
tracing::info!("querying latest parent finality ");
let contract = gateway_getter_facet::GatewayGetterFacet::new(
self.ipc_contract_info.gateway_addr,
Arc::new(self.ipc_contract_info.provider.clone()),
);
let finality = contract.get_latest_parent_finality().call().await?;
Ok(finality.height.as_u64() as ChainEpoch)
}
}
#[async_trait]
impl SubnetManager for EthSubnetManager {
async fn create_subnet(&self, from: Address, params: ConstructParams) -> Result<Address> {
self.ensure_same_gateway(¶ms.ipc_gateway_addr)?;
let min_validator_stake = params
.min_validator_stake
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid min validator stake"))?;
tracing::debug!("calling create subnet for EVM manager");
let route = subnet_id_to_evm_addresses(¶ms.parent)?;
tracing::debug!("root SubnetID as Ethereum type: {route:?}");
let params = register_subnet_facet::ConstructorParams {
parent_id: register_subnet_facet::SubnetID {
root: params.parent.root_id(),
route,
},
ipc_gateway_addr: self.ipc_contract_info.gateway_addr,
consensus: params.consensus as u64 as u8,
min_activation_collateral: ethers::types::U256::from(min_validator_stake),
min_validators: params.min_validators,
bottom_up_check_period: params.bottomup_check_period as u64,
majority_percentage: SUBNET_MAJORITY_PERCENTAGE,
active_validators_limit: params.active_validators_limit,
power_scale: 3,
permission_mode: params.permission_mode as u8,
supply_source: register_subnet_facet::SupplySource::try_from(params.supply_source)?,
};
tracing::info!("creating subnet on evm with params: {params:?}");
let signer = self.get_signer(&from)?;
let signer = Arc::new(signer);
let registry_contract = register_subnet_facet::RegisterSubnetFacet::new(
self.ipc_contract_info.registry_addr,
signer.clone(),
);
let call = call_with_premium_estimation(signer, registry_contract.new_subnet_actor(params))
.await?;
// TODO: Edit call to get estimate premium
let pending_tx = call.send().await?;
// We need the retry to parse the deployment event. At the time of this writing, it's a bug
// in current FEVM that without the retries, events are not picked up.
// See https://github.com/filecoin-project/community/discussions/638 for more info and updates.
let receipt = pending_tx.retries(TRANSACTION_RECEIPT_RETRIES).await?;
match receipt {
Some(r) => {
for log in r.logs {
tracing::debug!("log: {log:?}");
match ethers_contract::parse_log::<register_subnet_facet::SubnetDeployedFilter>(
log,
) {
Ok(subnet_deploy) => {
let register_subnet_facet::SubnetDeployedFilter { subnet_addr } =
subnet_deploy;
tracing::debug!("subnet deployed at {subnet_addr:?}");
return ethers_address_to_fil_address(&subnet_addr);
}
Err(_) => {
tracing::debug!("no event for subnet actor published yet, continue");
continue;
}
}
}
Err(anyhow!("no logs receipt"))
}
None => Err(anyhow!("no receipt for event, txn not successful")),
}
}
async fn join_subnet(
&self,
subnet: SubnetID,
from: Address,
collateral: TokenAmount,
pub_key: Vec<u8>,
) -> Result<ChainEpoch> {
let collateral = collateral
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid min validator stake"))?;
let address = contract_address_from_subnet(&subnet)?;
tracing::info!(
"interacting with evm subnet contract: {address:} with collateral: {collateral:}"
);
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
let mut txn = contract.join(ethers::types::Bytes::from(pub_key));
txn.tx.set_value(collateral);
let txn = call_with_premium_estimation(signer, txn).await?;
// Use the pending state to get the nonce because there could have been a pre-fund. Best would be to use this for everything.
let txn = txn.block(BlockId::Number(ethers::types::BlockNumber::Pending));
let pending_tx = txn.send().await?;
let receipt = pending_tx.retries(TRANSACTION_RECEIPT_RETRIES).await?;
block_number_from_receipt(receipt)
}
async fn pre_fund(&self, subnet: SubnetID, from: Address, balance: TokenAmount) -> Result<()> {
let balance = balance
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid initial balance"))?;
let address = contract_address_from_subnet(&subnet)?;
tracing::info!("interacting with evm subnet contract: {address:} with balance: {balance:}");
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
let mut txn = contract.pre_fund();
txn.tx.set_value(balance);
let txn = call_with_premium_estimation(signer, txn).await?;
txn.send().await?;
Ok(())
}
async fn pre_release(
&self,
subnet: SubnetID,
from: Address,
amount: TokenAmount,
) -> Result<()> {
let address = contract_address_from_subnet(&subnet)?;
tracing::info!("pre-release funds from {subnet:} at contract: {address:}");
let amount = amount
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid pre-release amount"))?;
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
call_with_premium_estimation(signer, contract.pre_release(amount.into()))
.await?
.send()
.await?
.await?;
Ok(())
}
async fn stake(&self, subnet: SubnetID, from: Address, collateral: TokenAmount) -> Result<()> {
let collateral = collateral
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid collateral amount"))?;
let address = contract_address_from_subnet(&subnet)?;
tracing::info!(
"interacting with evm subnet contract: {address:} with collateral: {collateral:}"
);
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
let mut txn = contract.stake();
txn.tx.set_value(collateral);
let txn = call_with_premium_estimation(signer, txn).await?;
txn.send().await?.await?;
Ok(())
}
async fn unstake(
&self,
subnet: SubnetID,
from: Address,
collateral: TokenAmount,
) -> Result<()> {
let collateral = collateral
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid collateral amount"))?;
let address = contract_address_from_subnet(&subnet)?;
tracing::info!(
"interacting with evm subnet contract: {address:} with collateral: {collateral:}"
);
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
let txn = call_with_premium_estimation(signer, contract.unstake(collateral.into())).await?;
txn.send().await?.await?;
Ok(())
}
async fn leave_subnet(&self, subnet: SubnetID, from: Address) -> Result<()> {
let address = contract_address_from_subnet(&subnet)?;
tracing::info!("leaving evm subnet: {subnet:} at contract: {address:}");
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
call_with_premium_estimation(signer, contract.leave())
.await?
.send()
.await?
.await?;
Ok(())
}
async fn kill_subnet(&self, subnet: SubnetID, from: Address) -> Result<()> {
let address = contract_address_from_subnet(&subnet)?;
tracing::info!("kill evm subnet: {subnet:} at contract: {address:}");
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
call_with_premium_estimation(signer, contract.kill())
.await?
.send()
.await?
.await?;
Ok(())
}
async fn list_child_subnets(
&self,
gateway_addr: Address,
) -> Result<HashMap<SubnetID, SubnetInfo>> {
self.ensure_same_gateway(&gateway_addr)?;
let gateway_contract = gateway_getter_facet::GatewayGetterFacet::new(
self.ipc_contract_info.gateway_addr,
Arc::new(self.ipc_contract_info.provider.clone()),
);
let mut s = HashMap::new();
let evm_subnets = gateway_contract.list_subnets().call().await?;
tracing::debug!("raw subnet: {evm_subnets:?}");
for subnet in evm_subnets {
let info = SubnetInfo::try_from(subnet)?;
s.insert(info.id.clone(), info);
}
Ok(s)
}
async fn claim_collateral(&self, subnet: SubnetID, from: Address) -> Result<()> {
let address = contract_address_from_subnet(&subnet)?;
tracing::info!("claim collateral evm subnet: {subnet:} at contract: {address:}");
let signer = Arc::new(self.get_signer(&from)?);
let contract =
subnet_actor_reward_facet::SubnetActorRewardFacet::new(address, signer.clone());
call_with_premium_estimation(signer, contract.claim())
.await?
.send()
.await?
.await?;
Ok(())
}
async fn fund(
&self,
subnet: SubnetID,
gateway_addr: Address,
from: Address,
to: Address,
amount: TokenAmount,
) -> Result<ChainEpoch> {
self.ensure_same_gateway(&gateway_addr)?;
let value = amount
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid value to fund"))?;
tracing::info!("fund with evm gateway contract: {gateway_addr:} with value: {value:}, original: {amount:?}");
let evm_subnet_id = gateway_manager_facet::SubnetID::try_from(&subnet)?;
tracing::debug!("evm subnet id to fund: {evm_subnet_id:?}");
let signer = Arc::new(self.get_signer(&from)?);
let gateway_contract = gateway_manager_facet::GatewayManagerFacet::new(
self.ipc_contract_info.gateway_addr,
signer.clone(),
);
let mut txn = gateway_contract.fund(
evm_subnet_id,
gateway_manager_facet::FvmAddress::try_from(to)?,
);
txn.tx.set_value(value);
let txn = call_with_premium_estimation(signer, txn).await?;
let pending_tx = txn.send().await?;
let receipt = pending_tx.retries(TRANSACTION_RECEIPT_RETRIES).await?;
block_number_from_receipt(receipt)
}
/// Approves the `from` address to use up to `amount` tokens from `token_address`.
async fn approve_token(
&self,
subnet: SubnetID,
from: Address,
amount: TokenAmount,
) -> Result<ChainEpoch> {
log::debug!("approve token, subnet: {subnet}, amount: {amount}, from: {from}");
let value = fil_amount_to_eth_amount(&amount)?;
let signer = Arc::new(self.get_signer(&from)?);
let subnet_supply_source = self.get_subnet_supply_source(&subnet).await?;
if subnet_supply_source.kind != SupplyKind::ERC20 as u8 {
return Err(anyhow!("Invalid operation: Expected the subnet's supply source to be ERC20, but found a different kind."));
}
let token_contract = IERC20::new(subnet_supply_source.token_address, signer.clone());
let txn = token_contract.approve(self.ipc_contract_info.gateway_addr, value);
let txn = call_with_premium_estimation(signer, txn).await?;
let pending_tx = txn.send().await?;
let receipt = pending_tx.retries(TRANSACTION_RECEIPT_RETRIES).await?;
block_number_from_receipt(receipt)
}
async fn fund_with_token(
&self,
subnet: SubnetID,
from: Address,
to: Address,
amount: TokenAmount,
) -> Result<ChainEpoch> {
tracing::debug!(
"fund with token, subnet: {subnet}, amount: {amount}, from: {from}, to: {to}"
);
let value = fil_amount_to_eth_amount(&amount)?;
let evm_subnet_id = gateway_manager_facet::SubnetID::try_from(&subnet)?;
let signer = Arc::new(self.get_signer(&from)?);
let gateway_contract = gateway_manager_facet::GatewayManagerFacet::new(
self.ipc_contract_info.gateway_addr,
signer.clone(),
);
let txn = gateway_contract.fund_with_token(
evm_subnet_id,
gateway_manager_facet::FvmAddress::try_from(to)?,
value,
);
let txn = call_with_premium_estimation(signer, txn).await?;
let pending_tx = txn.send().await?;
let receipt = pending_tx.retries(TRANSACTION_RECEIPT_RETRIES).await?;
block_number_from_receipt(receipt)
}
async fn release(
&self,
gateway_addr: Address,
from: Address,
to: Address,
amount: TokenAmount,
) -> Result<ChainEpoch> {
self.ensure_same_gateway(&gateway_addr)?;
let value = amount
.atto()
.to_u128()
.ok_or_else(|| anyhow!("invalid value to fund"))?;
tracing::info!("release with evm gateway contract: {gateway_addr:} with value: {value:}");
let signer = Arc::new(self.get_signer(&from)?);
let gateway_contract = gateway_manager_facet::GatewayManagerFacet::new(
self.ipc_contract_info.gateway_addr,
signer.clone(),
);
let mut txn = gateway_contract.release(gateway_manager_facet::FvmAddress::try_from(to)?);
txn.tx.set_value(value);
let txn = call_with_premium_estimation(signer, txn).await?;
let pending_tx = txn.send().await?;
let receipt = pending_tx.retries(TRANSACTION_RECEIPT_RETRIES).await?;
block_number_from_receipt(receipt)
}
/// Propagate the postbox message key. The key should be `bytes32`.
async fn propagate(
&self,
_subnet: SubnetID,
gateway_addr: Address,
from: Address,
postbox_msg_key: Vec<u8>,
) -> Result<()> {
if postbox_msg_key.len() != 32 {
return Err(anyhow!(
"invalid message cid length, expect 32 but found {}",
postbox_msg_key.len()
));
}
self.ensure_same_gateway(&gateway_addr)?;
tracing::info!("propagate postbox evm gateway contract: {gateway_addr:} with message key: {postbox_msg_key:?}");
let signer = Arc::new(self.get_signer(&from)?);
let gateway_contract = gateway_messenger_facet::GatewayMessengerFacet::new(
self.ipc_contract_info.gateway_addr,
signer.clone(),
);
let mut key = [0u8; 32];
key.copy_from_slice(&postbox_msg_key);
call_with_premium_estimation(signer, gateway_contract.propagate(key))
.await?
.send()
.await?;
Ok(())
}
/// Send value between two addresses in a subnet
async fn send_value(&self, from: Address, to: Address, amount: TokenAmount) -> Result<()> {
let signer = Arc::new(self.get_signer(&from)?);
let (fee, fee_cap) = premium_estimation(signer.clone()).await?;
let tx = Eip1559TransactionRequest::new()
.to(payload_to_evm_address(to.payload())?)
.value(fil_to_eth_amount(&amount)?)
.max_priority_fee_per_gas(fee)
.max_fee_per_gas(fee_cap);
let tx_pending = signer.send_transaction(tx, None).await?;
tracing::info!(
"sending FIL from {from:} to {to:} in tx {:?}",
tx_pending.tx_hash()
);
tx_pending.await?;
Ok(())
}
async fn wallet_balance(&self, address: &Address) -> Result<TokenAmount> {
let balance = self
.ipc_contract_info
.provider
.clone()
.get_balance(payload_to_evm_address(address.payload())?, None)
.await?;
Ok(TokenAmount::from_atto(balance.as_u128()))
}
async fn get_chain_id(&self) -> Result<String> {
Ok(self
.ipc_contract_info
.provider
.get_chainid()
.await?
.to_string())
}
async fn get_commit_sha(&self) -> Result<[u8; 32]> {
let gateway_contract = gateway_getter_facet::GatewayGetterFacet::new(
self.ipc_contract_info.gateway_addr,
Arc::new(self.ipc_contract_info.provider.clone()),
);
tracing::debug!(
"gateway_contract address : {:?}",
self.ipc_contract_info.gateway_addr
);
tracing::debug!(
"gateway_contract_getter_facet address : {:?}",
gateway_contract.address()
);
let commit_sha = gateway_contract
.get_commit_sha()
.call()
.await
.map_err(|e| anyhow!("cannot get commit sha due to: {e:}"))?;
Ok(commit_sha)
}
async fn get_subnet_supply_source(
&self,
subnet: &SubnetID,
) -> Result<ipc_actors_abis::subnet_actor_getter_facet::SupplySource> {
let address = contract_address_from_subnet(subnet)?;
let contract = subnet_actor_getter_facet::SubnetActorGetterFacet::new(
address,
Arc::new(self.ipc_contract_info.provider.clone()),
);
Ok(contract.supply_source().call().await?)
}
async fn get_genesis_info(&self, subnet: &SubnetID) -> Result<SubnetGenesisInfo> {
let address = contract_address_from_subnet(subnet)?;
let contract = subnet_actor_getter_facet::SubnetActorGetterFacet::new(
address,
Arc::new(self.ipc_contract_info.provider.clone()),
);
let genesis_balances = contract.genesis_balances().await?;
let bottom_up_checkpoint_period = contract.bottom_up_check_period().call().await?.as_u64();
Ok(SubnetGenesisInfo {
// Active validators limit set for the child subnet.
active_validators_limit: contract.active_validators_limit().call().await?,
// Bottom-up checkpoint period set in the subnet actor.
bottom_up_checkpoint_period,
// Genesis epoch when the subnet was bootstrapped in the parent.
genesis_epoch: self.genesis_epoch(subnet).await?,
// Majority percentage of
majority_percentage: contract.majority_percentage().call().await?,
// Minimum collateral required for subnets to register into the subnet
min_collateral: eth_to_fil_amount(&contract.min_activation_collateral().call().await?)?,
// Custom message fee that the child subnet wants to set for cross-net messages
validators: from_contract_validators(contract.genesis_validators().call().await?)?,
genesis_balances: into_genesis_balance_map(genesis_balances.0, genesis_balances.1)?,
// TODO: fixme https://github.com/consensus-shipyard/ipc-monorepo/issues/496
permission_mode: PermissionMode::Collateral,
supply_source: SupplySource {
kind: SupplyKind::Native,
token_address: None,
},
})
}
async fn add_bootstrap(
&self,
subnet: &SubnetID,
from: &Address,
endpoint: String,
) -> Result<()> {
let address = contract_address_from_subnet(subnet)?;
if is_valid_bootstrap_addr(&endpoint).is_none() {
return Err(anyhow!("wrong format for bootstrap endpoint"));
}
let signer = Arc::new(self.get_signer(from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
call_with_premium_estimation(signer, contract.add_bootstrap_node(endpoint))
.await?
.send()
.await?
.await?;
Ok(())
}
async fn list_bootstrap_nodes(&self, subnet: &SubnetID) -> Result<Vec<String>> {
let address = contract_address_from_subnet(subnet)?;
let contract = subnet_actor_getter_facet::SubnetActorGetterFacet::new(
address,
Arc::new(self.ipc_contract_info.provider.clone()),
);
Ok(contract.get_bootstrap_nodes().call().await?)
}
async fn get_validator_info(
&self,
subnet: &SubnetID,
validator: &Address,
) -> Result<ValidatorInfo> {
let address = contract_address_from_subnet(subnet)?;
let contract = subnet_actor_getter_facet::SubnetActorGetterFacet::new(
address,
Arc::new(self.ipc_contract_info.provider.clone()),
);
let validator = payload_to_evm_address(validator.payload())?;
let validator_info = contract.get_validator(validator).call().await?;
let is_active = contract.is_active_validator(validator).call().await?;
let is_waiting = contract.is_waiting_validator(validator).call().await?;
Ok(ValidatorInfo {
staking: ValidatorStakingInfo::try_from(validator_info)?,
is_active,
is_waiting,
})
}
async fn set_federated_power(
&self,
from: &Address,
subnet: &SubnetID,
validators: &[Address],
public_keys: &[Vec<u8>],
federated_power: &[u128],
) -> Result<ChainEpoch> {
let address = contract_address_from_subnet(subnet)?;
tracing::info!("interacting with evm subnet contract: {address:}");
let signer = Arc::new(self.get_signer(from)?);
let contract =
subnet_actor_manager_facet::SubnetActorManagerFacet::new(address, signer.clone());
let addresses: Vec<ethers::core::types::Address> = validators
.iter()
.map(|validator_address| payload_to_evm_address(validator_address.payload()).unwrap())
.collect();
tracing::debug!("converted addresses: {:?}", addresses);
let pubkeys: Vec<ethers::core::types::Bytes> = public_keys
.iter()
.map(|key| ethers::core::types::Bytes::from(key.clone()))
.collect();
tracing::debug!("converted pubkeys: {:?}", pubkeys);
let power_u256: Vec<ethers::core::types::U256> = federated_power
.iter()
.map(|power| ethers::core::types::U256::from(*power))
.collect();
tracing::debug!("converted power: {:?}", power_u256);
tracing::debug!("from address: {:?}", from);
let call = contract.set_federated_power(addresses, pubkeys, power_u256);
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | true |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/manager/evm/mod.rs | ipc/provider/src/manager/evm/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
mod manager;
use async_trait::async_trait;
use fvm_shared::clock::ChainEpoch;
use ipc_api::subnet_id::SubnetID;
use super::subnet::SubnetManager;
pub use manager::EthSubnetManager;
use ipc_actors_abis::subnet_actor_checkpointing_facet;
#[async_trait]
pub trait EthManager: SubnetManager {
/// The current epoch/block number of the blockchain that the manager connects to.
async fn current_epoch(&self) -> anyhow::Result<ChainEpoch>;
/// Get all the top down messages till a certain epoch
async fn bottom_up_checkpoint(
&self,
epoch: ChainEpoch,
) -> anyhow::Result<subnet_actor_checkpointing_facet::BottomUpCheckpoint>;
/// Get the latest applied top down nonce
async fn get_applied_top_down_nonce(&self, subnet_id: &SubnetID) -> anyhow::Result<u64>;
/// Get the subnet contract bottom up checkpoint period
async fn subnet_bottom_up_checkpoint_period(
&self,
subnet_id: &SubnetID,
) -> anyhow::Result<ChainEpoch>;
/// Get the previous checkpoint hash from the gateway
async fn prev_bottom_up_checkpoint_hash(
&self,
subnet_id: &SubnetID,
epoch: ChainEpoch,
) -> anyhow::Result<[u8; 32]>;
/// The minimal number of validators required for the subnet
async fn min_validators(&self, subnet_id: &SubnetID) -> anyhow::Result<u64>;
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/config/subnet.rs | ipc/provider/src/config/subnet.rs | use std::time::Duration;
// Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use fvm_shared::address::Address;
use ipc_api::subnet_id::SubnetID;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DurationSeconds};
use url::Url;
use crate::config::deserialize::{
deserialize_address_from_str, deserialize_eth_address_from_str, deserialize_subnet_id,
};
use crate::config::serialize::{
serialize_address_to_str, serialize_eth_address_to_str, serialize_subnet_id_to_str,
};
/// Represents a subnet declaration in the config.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct Subnet {
#[serde(deserialize_with = "deserialize_subnet_id")]
#[serde(serialize_with = "serialize_subnet_id_to_str")]
pub id: SubnetID,
pub config: SubnetConfig,
}
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
#[serde(tag = "network_type")]
pub enum SubnetConfig {
#[serde(rename = "fevm")]
Fevm(EVMSubnet),
}
/// A helper enum to differentiate the different network types
#[derive(PartialEq, Eq)]
pub enum NetworkType {
Fevm,
}
impl Subnet {
pub fn network_type(&self) -> NetworkType {
match &self.config {
SubnetConfig::Fevm(_) => NetworkType::Fevm,
}
}
pub fn auth_token(&self) -> Option<String> {
match &self.config {
SubnetConfig::Fevm(s) => s.auth_token.clone(),
}
}
pub fn rpc_http(&self) -> &Url {
match &self.config {
SubnetConfig::Fevm(s) => &s.provider_http,
}
}
pub fn rpc_timeout(&self) -> Option<Duration> {
match &self.config {
SubnetConfig::Fevm(s) => s.provider_timeout,
}
}
pub fn gateway_addr(&self) -> Address {
match &self.config {
SubnetConfig::Fevm(s) => s.gateway_addr,
}
}
}
/// The FVM subnet config parameters
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct FVMSubnet {
#[serde(deserialize_with = "deserialize_address_from_str")]
#[serde(serialize_with = "serialize_address_to_str")]
pub gateway_addr: Address,
pub jsonrpc_api_http: Url,
pub auth_token: Option<String>,
}
/// The EVM subnet config parameters
#[serde_as]
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct EVMSubnet {
pub provider_http: Url,
#[serde_as(as = "Option<DurationSeconds<u64>>")]
pub provider_timeout: Option<Duration>,
pub auth_token: Option<String>,
#[serde(deserialize_with = "deserialize_eth_address_from_str")]
#[serde(serialize_with = "serialize_eth_address_to_str")]
pub registry_addr: Address,
#[serde(deserialize_with = "deserialize_eth_address_from_str")]
#[serde(serialize_with = "serialize_eth_address_to_str")]
pub gateway_addr: Address,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/config/tests.rs | ipc/provider/src/config/tests.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use std::str::FromStr;
use fvm_shared::address::Address;
use indoc::formatdoc;
use ipc_api::subnet_id::SubnetID;
use ipc_types::EthAddress;
use url::Url;
use crate::config::Config;
// Arguments for the config's fields
const REPO_PATH: &str = "~/.ipc";
const CHILD_ID: &str = "/r123/f0100";
const CHILD_AUTH_TOKEN: &str = "CHILD_AUTH_TOKEN";
const PROVIDER_HTTP: &str = "http://127.0.0.1:3030/rpc/v1";
const ETH_ADDRESS: &str = "0x6be1ccf648c74800380d0520d797a170c808b624";
#[test]
fn check_keystore_config() {
let config = read_config();
assert_eq!(
config.keystore_path,
Some(REPO_PATH.to_string()),
"invalid provider keystore path"
);
}
#[test]
fn check_subnets_config() {
let config = read_config().subnets;
let child_id = SubnetID::from_str(CHILD_ID).unwrap();
let child = &config[&child_id];
assert_eq!(child.id, child_id);
assert_eq!(
child.gateway_addr(),
Address::from(EthAddress::from_str(ETH_ADDRESS).unwrap())
);
assert_eq!(*child.rpc_http(), Url::from_str(PROVIDER_HTTP).unwrap(),);
assert_eq!(child.auth_token().as_ref().unwrap(), CHILD_AUTH_TOKEN);
}
fn config_str() -> String {
formatdoc!(
r#"
keystore_path = "{REPO_PATH}"
[[subnets]]
id = "{CHILD_ID}"
[subnets.config]
network_type = "fevm"
auth_token = "{CHILD_AUTH_TOKEN}"
provider_http = "{PROVIDER_HTTP}"
registry_addr = "{ETH_ADDRESS}"
gateway_addr = "{ETH_ADDRESS}"
"#
)
}
fn read_config() -> Config {
Config::from_toml_str(config_str().as_str()).unwrap()
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/config/deserialize.rs | ipc/provider/src/config/deserialize.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Deserialization utils for config mod.
use crate::config::Subnet;
use fvm_shared::address::Address;
use ipc_api::subnet_id::SubnetID;
use ipc_types::EthAddress;
use serde::de::Error;
use serde::{Deserialize, Deserializer};
use std::collections::HashMap;
use std::fmt::Formatter;
use std::str::FromStr;
/// A serde deserialization method to deserialize a hashmap of subnets with subnet id as key and
/// Subnet struct as value from a vec of subnets
pub(crate) fn deserialize_subnets_from_vec<'de, D>(
deserializer: D,
) -> anyhow::Result<HashMap<SubnetID, Subnet>, D::Error>
where
D: Deserializer<'de>,
{
let subnets = <Vec<Subnet>>::deserialize(deserializer)?;
let mut hashmap = HashMap::new();
for subnet in subnets {
hashmap.insert(subnet.id.clone(), subnet);
}
Ok(hashmap)
}
/// A serde deserialization method to deserialize an address from i64
pub(crate) fn deserialize_address_from_str<'de, D>(
deserializer: D,
) -> anyhow::Result<Address, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Address;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("an string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Address::from_str(v).map_err(E::custom)
}
}
deserializer.deserialize_str(Visitor)
}
/// A serde deserialization method to deserialize an eth address from string, i.e. "0x...."
pub fn deserialize_eth_address_from_str<'de, D>(
deserializer: D,
) -> anyhow::Result<Address, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Address;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
eth_addr_str_to_address(v).map_err(E::custom)
}
}
deserializer.deserialize_str(Visitor)
}
/// A serde deserialization method to deserialize a subnet path string into a [`SubnetID`].
pub(crate) fn deserialize_subnet_id<'de, D>(deserializer: D) -> anyhow::Result<SubnetID, D::Error>
where
D: Deserializer<'de>,
{
struct SubnetIDVisitor;
impl<'de> serde::de::Visitor<'de> for SubnetIDVisitor {
type Value = SubnetID;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: Error,
{
SubnetID::from_str(v).map_err(E::custom)
}
}
deserializer.deserialize_str(SubnetIDVisitor)
}
fn eth_addr_str_to_address(s: &str) -> anyhow::Result<Address> {
let addr = EthAddress::from_str(s)?;
Ok(Address::from(addr))
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/config/serialize.rs | ipc/provider/src/config/serialize.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Serialization utils for config mod.
use crate::config::Subnet;
use anyhow::anyhow;
use fvm_shared::address::{Address, Payload};
use ipc_api::subnet_id::SubnetID;
use ipc_types::EthAddress;
use serde::ser::{Error, SerializeSeq};
use serde::Serializer;
use std::collections::HashMap;
/// A serde serialization method to serialize a hashmap of subnets with subnet id as key and
/// Subnet struct as value to a vec of subnets
pub fn serialize_subnets_to_str<S>(
subnets: &HashMap<SubnetID, Subnet>,
s: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let values = subnets.values().collect::<Vec<_>>();
let mut seq = s.serialize_seq(Some(values.len()))?;
for element in values {
seq.serialize_element(element)?;
}
seq.end()
}
pub fn serialize_subnet_id_to_str<S>(id: &SubnetID, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(&id.to_string())
}
pub fn serialize_address_to_str<S>(addr: &Address, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(&addr.to_string())
}
pub fn serialize_eth_address_to_str<S>(addr: &Address, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let addr = address_to_eth_address(addr).map_err(S::Error::custom)?;
s.serialize_str(&format!("0x{:?}", addr))
}
fn address_to_eth_address(addr: &Address) -> anyhow::Result<EthAddress> {
match addr.payload() {
Payload::Delegated(inner) => {
let mut bytes = [0; 20];
bytes.copy_from_slice(&inner.subaddress()[0..20]);
Ok(EthAddress(bytes))
}
Payload::ID(id) => Ok(EthAddress::from_id(*id)),
_ => Err(anyhow!("not eth address")),
}
}
#[cfg(test)]
mod tests {
use crate::config::subnet::{EVMSubnet, SubnetConfig};
use crate::config::{Config, Subnet};
use fvm_shared::address::Address;
use ipc_api::subnet_id::SubnetID;
use ipc_types::EthAddress;
use std::str::FromStr;
const STR: &str = r#"
keystore_path = "~/.ipc"
[[subnets]]
id = "/r1234"
[subnets.config]
network_type = "fevm"
provider_http = "http://127.0.0.1:3030/rpc/v1"
registry_addr = "0x6be1ccf648c74800380d0520d797a170c808b624"
gateway_addr = "0x6be1ccf648c74800380d0520d797a170c808b624"
private_key = "0x6BE1Ccf648c74800380d0520D797a170c808b624"
"#;
const EMPTY_KEYSTORE: &str = r#"
[[subnets]]
id = "/r1234"
[subnets.config]
network_type = "fevm"
provider_http = "http://127.0.0.1:3030/rpc/v1"
registry_addr = "0x6be1ccf648c74800380d0520d797a170c808b624"
gateway_addr = "0x6be1ccf648c74800380d0520d797a170c808b624"
private_key = "0x6BE1Ccf648c74800380d0520D797a170c808b624"
accounts = ["0x6be1ccf648c74800380d0520d797a170c808b624", "0x6be1ccf648c74800380d0520d797a170c808b624"]
"#;
#[test]
fn test_serialization2() {
let config = Config::from_toml_str(STR).unwrap();
let r = toml::to_string(&config).unwrap();
let from_str = Config::from_toml_str(&r).unwrap();
assert_eq!(from_str, config);
}
#[test]
fn test_empty_keystore() {
let config = Config::from_toml_str(EMPTY_KEYSTORE).unwrap();
let r = toml::to_string(&config).unwrap();
let from_str = Config::from_toml_str(&r).unwrap();
assert_eq!(from_str, config);
}
#[test]
fn test_serialization() {
let mut config = Config {
keystore_path: Some(String::from("~/.ipc")),
subnets: Default::default(),
};
let eth_addr1 = EthAddress::from_str("0x6BE1Ccf648c74800380d0520D797a170c808b624").unwrap();
let subnet2 = Subnet {
id: SubnetID::new_root(1234),
config: SubnetConfig::Fevm(EVMSubnet {
gateway_addr: Address::from(eth_addr1),
provider_http: "http://127.0.0.1:3030/rpc/v1".parse().unwrap(),
provider_timeout: None,
auth_token: None,
registry_addr: Address::from(eth_addr1),
}),
};
config.add_subnet(subnet2);
assert!(toml::to_string(&config).is_ok());
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/provider/src/config/mod.rs | ipc/provider/src/config/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Provides a simple way of reading configuration files.
//!
//! Reads a TOML config file for the IPC Agent and deserializes it in a type-safe way into a
//! [`Config`] struct.
pub mod deserialize;
pub mod subnet;
pub mod serialize;
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use anyhow::{Context, Result};
use deserialize::deserialize_subnets_from_vec;
use ipc_api::subnet_id::SubnetID;
use serde::{Deserialize, Serialize};
use serialize::serialize_subnets_to_str;
pub use subnet::Subnet;
pub const JSON_RPC_VERSION: &str = "2.0";
/// DefaulDEFAULT_CHAIN_IDSUBNET_e
pub const DEFAULT_CONFIG_TEMPLATE: &str = r#"
keystore_path = "~/.ipc"
# Filecoin Calibration
[[subnets]]
id = "/r314159"
[subnets.config]
network_type = "fevm"
provider_http = "https://api.calibration.node.glif.io/rpc/v1"
gateway_addr = "0x1AEe8A878a22280fc2753b3C63571C8F895D2FE3"
registry_addr = "0x0b4e239FF21b40120cDa817fba77bD1B366c1bcD"
# Subnet template - uncomment and adjust before using
# [[subnets]]
# id = "/r314159/<SUBNET_ID>"
# [subnets.config]
# network_type = "fevm"
# provider_http = "https://<RPC_ADDR>/"
# gateway_addr = "0x77aa40b105843728088c0132e43fc44348881da8"
# registry_addr = "0x74539671a1d2f1c8f200826baba665179f53a1b7"
"#;
/// The top-level struct representing the config. Calls to [`Config::from_file`] deserialize into
/// this struct.
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
pub struct Config {
/// Directory of the keystore that wants to be made available by the provider.
pub keystore_path: Option<String>,
#[serde(deserialize_with = "deserialize_subnets_from_vec", default)]
#[serde(serialize_with = "serialize_subnets_to_str")]
pub subnets: HashMap<SubnetID, Subnet>,
}
impl Config {
/// Returns an empty config to be populated further
pub fn new() -> Self {
Config {
keystore_path: None,
subnets: Default::default(),
}
}
/// Reads a TOML configuration in the `s` string and returns a [`Config`] struct.
pub fn from_toml_str(s: &str) -> Result<Self> {
let config = toml::from_str(s)?;
Ok(config)
}
/// Reads a TOML configuration file specified in the `path` and returns a [`Config`] struct.
pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
let contents = fs::read_to_string(&path).with_context(|| {
format!(
"failed to read config from {}",
path.as_ref().to_string_lossy()
)
})?;
let config: Config =
Config::from_toml_str(contents.as_str()).context("failed to parse config TOML")?;
Ok(config)
}
/// Reads a TOML configuration file specified in the `path` and returns a [`Config`] struct.
pub async fn from_file_async(path: impl AsRef<Path>) -> Result<Self> {
let contents = tokio::fs::read_to_string(path).await?;
Config::from_toml_str(contents.as_str())
}
pub async fn write_to_file_async(&self, path: impl AsRef<Path>) -> Result<()> {
let content = toml::to_string(self)?;
tokio::fs::write(path, content.into_bytes()).await?;
Ok(())
}
pub fn add_subnet(&mut self, subnet: Subnet) {
self.subnets.insert(subnet.id.clone(), subnet);
}
pub fn remove_subnet(&mut self, subnet_id: &SubnetID) {
self.subnets.remove(subnet_id);
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/lib.rs | ipc/cli/src/lib.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use anyhow::Result;
use async_trait::async_trait;
use clap::Args;
use fvm_shared::address::Network;
use num_traits::cast::FromPrimitive;
mod commands;
pub use commands::*;
use ipc_provider::config::Config;
/// The trait that represents the abstraction of a command line handler. To implement a new command
/// line operation, implement this trait and register it.
///
/// Note that this trait does not support a stateful implementation as we assume CLI commands are all
/// constructed from scratch.
#[async_trait]
pub trait CommandLineHandler {
/// Abstraction for command line operations arguments.
///
/// NOTE that this parameter is used to generate the command line arguments.
/// Currently we are directly integrating with `clap` crate. In the future we can use our own
/// implementation to abstract away external crates. But this should be good for now.
type Arguments: std::fmt::Debug + Args;
/// Handles the request with the provided arguments. Dev should handle the content to print and how
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()>;
}
/// The global arguments that will be shared by all cli commands.
#[derive(Debug, Args, Clone, Default)]
pub struct GlobalArguments {
#[arg(
long,
help = "The toml config file path for IPC Agent, default to ${HOME}/.ipc/config.toml",
env = "IPC_CLI_CONFIG_PATH"
)]
config_path: Option<String>,
/// Set the FVM Address Network. It's value affects whether `f` (main) or `t` (test) prefixed addresses are accepted.
#[arg(long = "network", default_value = "testnet", env = "IPC_NETWORK", value_parser = parse_network)]
_network: Network,
/// Legacy env var for network
#[arg(long = "__network", hide = true, env = "NETWORK", value_parser = parse_network)]
__network: Option<Network>,
}
impl GlobalArguments {
pub fn config_path(&self) -> String {
self.config_path
.clone()
.unwrap_or_else(ipc_provider::default_config_path)
}
pub fn config(&self) -> Result<Config> {
let config_path = self.config_path();
Config::from_file(config_path)
}
pub fn network(&self) -> Network {
self.__network.unwrap_or(self._network)
}
}
/// Parse the FVM network and set the global value.
fn parse_network(s: &str) -> Result<Network, String> {
match s.to_lowercase().as_str() {
"main" | "mainnet" | "f" => Ok(Network::Mainnet),
"test" | "testnet" | "t" => Ok(Network::Testnet),
n => {
let n: u8 = n
.parse()
.map_err(|e| format!("expected 0 or 1 for network: {e}"))?;
let n = Network::from_u8(n).ok_or_else(|| format!("unexpected network: {s}"))?;
Ok(n)
}
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/main.rs | ipc/cli/src/main.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")))
.init();
if let Err(e) = ipc_cli::cli().await {
log::error!("main process failed: {e:#}");
std::process::exit(1);
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/mod.rs | ipc/cli/src/commands/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! This mod contains the different command line implementations.
mod checkpoint;
mod config;
mod crossmsg;
// mod daemon;
mod subnet;
mod util;
mod wallet;
use crate::commands::checkpoint::CheckpointCommandsArgs;
use crate::commands::crossmsg::CrossMsgsCommandsArgs;
use crate::commands::util::UtilCommandsArgs;
use crate::GlobalArguments;
use anyhow::{anyhow, Context, Result};
use clap::{Command, CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Generator, Shell};
use fvm_shared::econ::TokenAmount;
use ipc_api::ethers_address_to_fil_address;
use fvm_shared::address::set_current_network;
use ipc_api::subnet_id::SubnetID;
use ipc_provider::config::{Config, Subnet};
use std::fmt::Debug;
use std::io;
use std::path::Path;
use std::str::FromStr;
use crate::commands::config::ConfigCommandsArgs;
use crate::commands::wallet::WalletCommandsArgs;
use subnet::SubnetCommandsArgs;
/// We only support up to 9 decimal digits for transaction
const FIL_AMOUNT_NANO_DIGITS: u32 = 9;
/// The collection of all subcommands to be called, see clap's documentation for usage. Internal
/// to the current mode. Register a new command accordingly.
#[derive(Debug, Subcommand)]
enum Commands {
// Daemon(LaunchDaemonArgs),
Config(ConfigCommandsArgs),
Subnet(SubnetCommandsArgs),
Wallet(WalletCommandsArgs),
CrossMsg(CrossMsgsCommandsArgs),
Checkpoint(CheckpointCommandsArgs),
Util(UtilCommandsArgs),
}
#[derive(Debug, Parser)]
#[command(
name = "ipc-agent",
about = "The IPC agent command line tool",
version = "v0.0.1"
)]
#[command(propagate_version = true, arg_required_else_help = true)]
struct IPCAgentCliCommands {
// If provided, outputs the completion file for given shell
#[arg(long = "cli-autocomplete-gen", value_enum)]
generator: Option<Shell>,
#[clap(flatten)]
global_params: GlobalArguments,
#[command(subcommand)]
command: Option<Commands>,
}
/// A version of options that does partial matching on the arguments, with its only interest
/// being the capture of global parameters that need to take effect first, before we parse [Options],
/// because their value affects how others arse parsed.
///
/// This one doesn't handle `--help` or `help` so that it is passed on to the next parser,
/// where the full set of commands and arguments can be printed properly.
#[derive(Parser, Debug)]
#[command(version, disable_help_flag = true)]
struct GlobalOptions {
#[command(flatten)]
global_params: GlobalArguments,
/// Capture all the normal commands, basically to ingore them.
#[arg(allow_hyphen_values = true, trailing_var_arg = true)]
pub cmd: Vec<String>,
}
/// The `cli` method exposed to handle all the cli commands, ideally from main.
///
/// # Examples
/// Sample usage:
/// ```ignore
/// # to start the daemon with
/// ipc-client daemon ./config/template.toml
/// ```
///
/// To register a new command, add the command to
/// ```ignore
/// pub async fn cli() {
///
/// // ... other code
///
/// let r = match &args.command {
/// // ... other existing commands
/// Commands::NewCommand => NewCommand::handle(n).await,
/// };
///
/// // ... other code
/// ```
/// Also add this type to Command enum.
/// ```ignore
/// enum Commands {
/// NewCommand(NewCommandArgs),
/// }
/// ```
pub async fn cli() -> anyhow::Result<()> {
let global = GlobalOptions::parse();
set_current_network(global.global_params.network());
// parse the arguments
let args = IPCAgentCliCommands::parse();
if let Some(generator) = args.generator {
let mut cmd = IPCAgentCliCommands::command();
print_completions(generator, &mut cmd);
Ok(())
} else {
let global = &args.global_params;
if let Some(c) = &args.command {
let r = match &c {
// Commands::Daemon(args) => LaunchDaemon::handle(global, args).await,
Commands::Config(args) => args.handle(global).await,
Commands::Subnet(args) => args.handle(global).await,
Commands::CrossMsg(args) => args.handle(global).await,
Commands::Wallet(args) => args.handle(global).await,
Commands::Checkpoint(args) => args.handle(global).await,
Commands::Util(args) => args.handle(global).await,
};
r.with_context(|| format!("error processing command {:?}", args.command))
} else {
Ok(())
}
}
}
fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
pub(crate) fn get_ipc_provider(global: &GlobalArguments) -> Result<ipc_provider::IpcProvider> {
ipc_provider::IpcProvider::new_from_config(global.config_path())
}
pub(crate) fn f64_to_token_amount(f: f64) -> anyhow::Result<TokenAmount> {
// no rounding, just the integer part
let nano = f64::trunc(f * (10u64.pow(FIL_AMOUNT_NANO_DIGITS) as f64));
Ok(TokenAmount::from_nano(nano as u128))
}
/// Receives a f/eth-address as an input and returns the corresponding
/// filecoin or delegated address, respectively
pub(crate) fn require_fil_addr_from_str(s: &str) -> anyhow::Result<fvm_shared::address::Address> {
let addr = match fvm_shared::address::Address::from_str(s) {
Err(_) => {
// see if it is an eth address
let addr = ethers::types::Address::from_str(s)?;
ethers_address_to_fil_address(&addr)?
}
Ok(addr) => addr,
};
Ok(addr)
}
/// Get the subnet configuration from the config path
pub(crate) fn get_subnet_config(
config_path: impl AsRef<Path>,
subnet: &SubnetID,
) -> Result<Subnet> {
let config = Config::from_file(&config_path)?;
Ok(config
.subnets
.get(subnet)
.ok_or_else(|| anyhow!("{subnet} is not configured"))?
.clone())
}
#[cfg(test)]
mod tests {
use crate::f64_to_token_amount;
use fvm_shared::econ::TokenAmount;
#[test]
fn test_amount() {
let amount = f64_to_token_amount(1000000.1f64).unwrap();
assert_eq!(amount, TokenAmount::from_nano(1000000100000000u128));
}
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/daemon.rs | ipc/cli/src/commands/daemon.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! The Daemon command line handler that prints the info about IPC Agent.
use std::fmt::Debug;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use async_trait::async_trait;
use clap::Args;
use ipc_wallet::Wallet;
use tokio_graceful_shutdown::{IntoSubsystem, Toplevel};
use crate::checkpoint::CheckpointSubsystem;
use crate::config::ReloadableConfig;
use crate::server::jsonrpc::JsonRPCServer;
use crate::server::{new_evm_keystore_from_config, new_fvm_wallet_from_config};
use crate::{CommandLineHandler, GlobalArguments};
/// The number of seconds to wait for a subsystem to start before returning an error.
const SUBSYSTEM_WAIT_TIME_SECS: Duration = Duration::from_secs(10);
/// The command to start the ipc agent json rpc server in the foreground.
pub(crate) struct LaunchDaemon;
#[async_trait]
impl CommandLineHandler for LaunchDaemon {
type Arguments = LaunchDaemonArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!(
"launching json rpc server with args: {:?} and global params: {:?}",
arguments,
global
);
let reloadable_config = Arc::new(ReloadableConfig::new(global.config_path())?);
let fvm_wallet = Arc::new(RwLock::new(Wallet::new(new_fvm_wallet_from_config(
reloadable_config.clone(),
)?)));
let evm_keystore = Arc::new(RwLock::new(new_evm_keystore_from_config(
reloadable_config.clone(),
)?));
// Start subsystems.
let checkpointing = CheckpointSubsystem::new(
reloadable_config.clone(),
fvm_wallet.clone(),
evm_keystore.clone(),
);
let server = JsonRPCServer::new(
reloadable_config.clone(),
fvm_wallet.clone(),
evm_keystore.clone(),
);
Toplevel::new()
.start("Checkpoint subsystem", checkpointing.into_subsystem())
.start("JSON-RPC server subsystem", server.into_subsystem())
.catch_signals()
.handle_shutdown_requests(SUBSYSTEM_WAIT_TIME_SECS)
.await?;
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Launch the ipc agent daemon process")]
pub(crate) struct LaunchDaemonArgs {}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/util/mod.rs | ipc/cli/src/commands/util/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use crate::{CommandLineHandler, GlobalArguments};
use clap::{Args, Subcommand};
use self::f4::{EthToF4Addr, EthToF4AddrArgs};
mod f4;
#[derive(Debug, Args)]
#[command(name = "util", about = "util commands")]
#[command(args_conflicts_with_subcommands = true)]
pub(crate) struct UtilCommandsArgs {
#[command(subcommand)]
command: Commands,
}
impl UtilCommandsArgs {
pub async fn handle(&self, global: &GlobalArguments) -> anyhow::Result<()> {
match &self.command {
Commands::EthToF4Addr(args) => EthToF4Addr::handle(global, args).await,
}
}
}
#[derive(Debug, Subcommand)]
pub(crate) enum Commands {
EthToF4Addr(EthToF4AddrArgs),
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/util/f4.rs | ipc/cli/src/commands/util/f4.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! F4 address util
use async_trait::async_trait;
use clap::Args;
use fvm_shared::address::Address;
use ipc_types::EthAddress;
use std::fmt::Debug;
use std::str::FromStr;
use crate::{CommandLineHandler, GlobalArguments};
pub(crate) struct EthToF4Addr;
#[async_trait]
impl CommandLineHandler for EthToF4Addr {
type Arguments = EthToF4AddrArgs;
async fn handle(_global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
let eth_addr = EthAddress::from_str(&arguments.addr)?;
log::info!("f4 address: {:}", Address::from(eth_addr));
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Get F4 for an Ethereum address")]
pub(crate) struct EthToF4AddrArgs {
#[arg(long, help = "Ethereum address to get the underlying f4 addr from")]
pub addr: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/crossmsg/topdown_cross.rs | ipc/cli/src/commands/crossmsg/topdown_cross.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! List top down cross messages
use std::fmt::Debug;
use std::str::FromStr;
use async_trait::async_trait;
use clap::Args;
use fvm_shared::clock::ChainEpoch;
use ipc_api::subnet_id::SubnetID;
use crate::commands::get_ipc_provider;
use crate::{CommandLineHandler, GlobalArguments};
/// The command to list top down cross messages in a subnet
pub(crate) struct ListTopdownMsgs;
#[async_trait]
impl CommandLineHandler for ListTopdownMsgs {
type Arguments = ListTopdownMsgsArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("list topdown messages with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
for h in arguments.from..=arguments.to {
let result = provider.get_top_down_msgs(&subnet, h).await?;
println!(
"block height: {}, block hash: {}, number of messages: {}",
h,
hex::encode(result.block_hash),
result.value.len()
);
for msg in result.value {
println!(
"from: {}, to: {}, message: {}, nonce: {} ",
msg.from.to_string()?,
msg.to.to_string()?,
hex::encode(msg.message),
msg.nonce
);
}
}
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "List topdown cross messages for a specific epoch")]
pub(crate) struct ListTopdownMsgsArgs {
#[arg(long, help = "The subnet id of the topdown subnet")]
pub subnet: String,
#[arg(long, help = "Include topdown messages starting from this epoch")]
pub from: ChainEpoch,
#[arg(long, help = "Include topdown messages to this epoch")]
pub to: ChainEpoch,
}
pub(crate) struct LatestParentFinality;
#[async_trait]
impl CommandLineHandler for LatestParentFinality {
type Arguments = LatestParentFinalityArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("latest parent finality: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
println!("{}", provider.latest_parent_finality(&subnet).await?);
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Latest height of parent finality committed in child subnet")]
pub(crate) struct LatestParentFinalityArgs {
#[arg(long, help = "The subnet id to check parent finality")]
pub subnet: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/crossmsg/mod.rs | ipc/cli/src/commands/crossmsg/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use self::fund::{FundWithToken, FundWithTokenArgs, PreFund, PreFundArgs};
use self::release::{PreRelease, PreReleaseArgs};
use self::topdown_cross::{
LatestParentFinality, LatestParentFinalityArgs, ListTopdownMsgs, ListTopdownMsgsArgs,
};
use crate::commands::crossmsg::fund::Fund;
use crate::commands::crossmsg::propagate::Propagate;
use crate::commands::crossmsg::release::Release;
use crate::{CommandLineHandler, GlobalArguments};
use fund::FundArgs;
use propagate::PropagateArgs;
use release::ReleaseArgs;
use clap::{Args, Subcommand};
pub mod fund;
pub mod propagate;
pub mod release;
mod topdown_cross;
#[derive(Debug, Args)]
#[command(name = "crossmsg", about = "cross network messages related commands")]
#[command(args_conflicts_with_subcommands = true)]
pub(crate) struct CrossMsgsCommandsArgs {
#[command(subcommand)]
command: Commands,
}
impl CrossMsgsCommandsArgs {
pub async fn handle(&self, global: &GlobalArguments) -> anyhow::Result<()> {
match &self.command {
Commands::Fund(args) => Fund::handle(global, args).await,
Commands::FundWithToken(args) => FundWithToken::handle(global, args).await,
Commands::PreFund(args) => PreFund::handle(global, args).await,
Commands::Release(args) => Release::handle(global, args).await,
Commands::PreRelease(args) => PreRelease::handle(global, args).await,
Commands::Propagate(args) => Propagate::handle(global, args).await,
Commands::ListTopdownMsgs(args) => ListTopdownMsgs::handle(global, args).await,
Commands::ParentFinality(args) => LatestParentFinality::handle(global, args).await,
}
}
}
#[derive(Debug, Subcommand)]
pub(crate) enum Commands {
Fund(FundArgs),
FundWithToken(FundWithTokenArgs),
PreFund(PreFundArgs),
Release(ReleaseArgs),
PreRelease(PreReleaseArgs),
Propagate(PropagateArgs),
ListTopdownMsgs(ListTopdownMsgsArgs),
ParentFinality(LatestParentFinalityArgs),
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/crossmsg/release.rs | ipc/cli/src/commands/crossmsg/release.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Release cli command handler.
use async_trait::async_trait;
use clap::Args;
use ipc_api::subnet_id::SubnetID;
use std::{fmt::Debug, str::FromStr};
use crate::{
f64_to_token_amount, get_ipc_provider, require_fil_addr_from_str, CommandLineHandler,
GlobalArguments,
};
/// The command to release funds from a child to a parent
pub(crate) struct Release;
#[async_trait]
impl CommandLineHandler for Release {
type Arguments = ReleaseArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("release operation with args: {:?}", arguments);
let mut provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let from = match &arguments.from {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
let to = match &arguments.to {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
let gateway_addr = match &arguments.gateway_address {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
println!(
"release performed in epoch: {:?}",
provider
.release(
subnet,
gateway_addr,
from,
to,
f64_to_token_amount(arguments.amount)?,
)
.await?,
);
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Release operation in the gateway actor")]
pub(crate) struct ReleaseArgs {
#[arg(long, help = "The gateway address of the subnet")]
pub gateway_address: Option<String>,
#[arg(long, help = "The address that releases funds")]
pub from: Option<String>,
#[arg(
long,
help = "The address to release funds to (if not set, amount sent to from address)"
)]
pub to: Option<String>,
#[arg(long, help = "The subnet to release funds from")]
pub subnet: String,
#[arg(help = "The amount to release in FIL, in whole FIL")]
pub amount: f64,
}
pub struct PreRelease;
#[async_trait]
impl CommandLineHandler for PreRelease {
type Arguments = PreReleaseArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("pre-release subnet with args: {:?}", arguments);
let mut provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let from = match &arguments.from {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
provider
.pre_release(subnet.clone(), from, f64_to_token_amount(arguments.amount)?)
.await?;
log::info!("address pre-release successfully");
Ok(())
}
}
#[derive(Debug, Args)]
#[command(
name = "pre-release",
about = "Release some funds from the genesis balance of the child subnet"
)]
pub struct PreReleaseArgs {
#[arg(long, help = "The address funded in the subnet")]
pub from: Option<String>,
#[arg(long, help = "The subnet to release balance from")]
pub subnet: String,
#[arg(help = "Amount to release from the genesis balance of a child subnet")]
pub amount: f64,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/crossmsg/fund.rs | ipc/cli/src/commands/crossmsg/fund.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Fund cli command handler.
use async_trait::async_trait;
use clap::Args;
use fvm_shared::bigint::BigInt;
use fvm_shared::econ::TokenAmount;
use ipc_api::subnet_id::SubnetID;
use num_traits::Num;
use std::{fmt::Debug, str::FromStr};
use crate::{
f64_to_token_amount, get_ipc_provider, require_fil_addr_from_str, CommandLineHandler,
GlobalArguments,
};
/// The command to send funds to a subnet from parent
pub(crate) struct Fund;
#[async_trait]
impl CommandLineHandler for Fund {
type Arguments = FundArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("fund operation with args: {:?}", arguments);
let mut provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let from = match &arguments.from {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
let to = match &arguments.to {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
let gateway_addr = match &arguments.gateway_address {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
println!(
"fund performed in epoch: {:?}",
provider
.fund(
subnet,
gateway_addr,
from,
to,
f64_to_token_amount(arguments.amount)?,
)
.await?,
);
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Send funds from a parent to a child subnet")]
pub(crate) struct FundArgs {
#[arg(long, help = "The gateway address of the subnet")]
pub gateway_address: Option<String>,
#[arg(long, help = "The address to send funds from")]
pub from: Option<String>,
#[arg(
long,
help = "The address to send funds to (if not set, amount sent to from address)"
)]
pub to: Option<String>,
#[arg(long, help = "The subnet to fund")]
pub subnet: String,
#[arg(help = "The amount to fund in FIL, in whole FIL")]
pub amount: f64,
}
pub struct PreFund;
#[async_trait]
impl CommandLineHandler for PreFund {
type Arguments = PreFundArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("pre-fund subnet with args: {:?}", arguments);
let mut provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let from = match &arguments.from {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
provider
.pre_fund(
subnet.clone(),
from,
f64_to_token_amount(arguments.initial_balance)?,
)
.await?;
log::info!("address pre-funded successfully");
Ok(())
}
}
#[derive(Debug, Args)]
#[command(
name = "pre-fund",
about = "Add some funds in genesis to an address in a child-subnet"
)]
pub struct PreFundArgs {
#[arg(long, help = "The address funded in the subnet")]
pub from: Option<String>,
#[arg(long, help = "The subnet to add balance to")]
pub subnet: String,
#[arg(help = "Add an initial balance for the address in genesis in the subnet")]
pub initial_balance: f64,
}
/// The command to send ERC20 tokens to a subnet from parent
pub(crate) struct FundWithToken;
#[async_trait]
impl CommandLineHandler for FundWithToken {
type Arguments = FundWithTokenArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("fund with token operation with args: {:?}", arguments);
let mut provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let from = match &arguments.from {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
let to = match &arguments.to {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
let amount = BigInt::from_str_radix(arguments.amount.as_str(), 10)
.map_err(|e| anyhow::anyhow!("not a token amount: {e}"))
.map(TokenAmount::from_atto)?;
if arguments.approve {
println!(
"approve token performed in epoch: {:?}",
provider
.approve_token(subnet.clone(), from, amount.clone())
.await?,
);
}
println!(
"fund with token performed in epoch: {:?}",
provider.fund_with_token(subnet, from, to, amount).await?,
);
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Send erc20 tokens from a parent to a child subnet")]
pub(crate) struct FundWithTokenArgs {
#[arg(long, help = "The address to send funds from")]
pub from: Option<String>,
#[arg(
long,
help = "The address to send funds to (if not set, amount sent to from address)"
)]
pub to: Option<String>,
#[arg(long, help = "The subnet to fund")]
pub subnet: String,
#[arg(help = "The amount to fund in erc20, in the token's precision unit")]
pub amount: String,
#[arg(long, help = "Approve gateway before funding")]
pub approve: bool,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/crossmsg/propagate.rs | ipc/cli/src/commands/crossmsg/propagate.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Propagate cli command handler.
use async_trait::async_trait;
use clap::Args;
use std::fmt::Debug;
use crate::{CommandLineHandler, GlobalArguments};
/// The command to propagate a message in the postbox.
pub(crate) struct Propagate;
#[async_trait]
impl CommandLineHandler for Propagate {
type Arguments = PropagateArgs;
async fn handle(_global: &GlobalArguments, _arguments: &Self::Arguments) -> anyhow::Result<()> {
todo!()
}
}
#[derive(Debug, Args)]
#[command(about = "Propagate operation in the gateway actor")]
pub(crate) struct PropagateArgs {
#[arg(long, help = "The JSON RPC server url for ipc agent")]
pub ipc_agent_url: Option<String>,
#[arg(long, help = "The address that pays for the propagation gas")]
pub from: Option<String>,
#[arg(long, help = "The subnet of the message to propagate")]
pub subnet: String,
#[arg(help = "The message cid to propagate")]
pub postbox_msg_key: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/list.rs | ipc/cli/src/commands/wallet/list.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Wallet list cli handler
use async_trait::async_trait;
use clap::Args;
use ipc_wallet::{EthKeyAddress, EvmKeyStore, WalletType};
use std::fmt::Debug;
use std::str::FromStr;
use crate::{get_ipc_provider, CommandLineHandler, GlobalArguments};
pub(crate) struct WalletList;
#[async_trait]
impl CommandLineHandler for WalletList {
type Arguments = WalletListArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
match wallet_type {
WalletType::Evm => {
let wallet = provider.evm_wallet()?;
let addresses = wallet.read().unwrap().list()?;
for address in addresses.iter() {
if *address == EthKeyAddress::default() {
continue;
}
print!("Address: {}", address);
let key_info = wallet.read().unwrap().get(address)?.unwrap();
let sk = libsecp256k1::SecretKey::parse_slice(key_info.private_key())?;
let pub_key =
hex::encode(libsecp256k1::PublicKey::from_secret_key(&sk).serialize())
.to_string();
println!("\tPubKey: {}", pub_key);
}
Ok(())
}
WalletType::Fvm => {
let wallet = provider.fvm_wallet()?;
let addresses = wallet.read().unwrap().list_addrs()?;
for address in addresses.iter() {
print!("Address: {}", address);
let key_info = wallet.write().unwrap().export(address)?;
let sk = libsecp256k1::SecretKey::parse_slice(key_info.private_key())?;
let pub_key =
hex::encode(libsecp256k1::PublicKey::from_secret_key(&sk).serialize())
.to_string();
print!("\tPubKey: {}", pub_key);
println!("\tKeyType: {:?}", key_info.key_type());
}
Ok(())
}
}
}
}
#[derive(Debug, Args)]
#[command(about = "List addresses and pubkeys in the wallet")]
pub(crate) struct WalletListArgs {
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/default.rs | ipc/cli/src/commands/wallet/default.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Wallet remove cli handler
use async_trait::async_trait;
use clap::Args;
use ipc_wallet::{EvmKeyStore, WalletType};
use std::fmt::Debug;
use std::str::FromStr;
use crate::{get_ipc_provider, CommandLineHandler, GlobalArguments};
pub(crate) struct WalletSetDefault;
#[async_trait]
impl CommandLineHandler for WalletSetDefault {
type Arguments = WalletSetDefaultArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("remove wallet with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
match wallet_type {
WalletType::Evm => {
let wallet = provider.evm_wallet()?;
let addr = ipc_wallet::EthKeyAddress::from_str(&arguments.address)?;
wallet.write().unwrap().set_default(&addr)?;
}
WalletType::Fvm => {
let wallet = provider.fvm_wallet()?;
let addr = fvm_shared::address::Address::from_str(&arguments.address)?;
wallet.write().unwrap().set_default(addr)?;
}
}
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Set default wallet")]
pub(crate) struct WalletSetDefaultArgs {
#[arg(long, help = "Address of the key to default")]
pub address: String,
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
}
pub(crate) struct WalletGetDefault;
#[async_trait]
impl CommandLineHandler for WalletGetDefault {
type Arguments = WalletGetDefaultArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("remove wallet with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
match wallet_type {
WalletType::Evm => {
let wallet = provider.evm_wallet()?;
let mut wallet = wallet.write().unwrap();
match wallet.get_default()? {
None => println!("No default account set"),
Some(addr) => println!("{:?}", addr.to_string()),
}
}
WalletType::Fvm => {
let wallet = provider.fvm_wallet()?;
println!("{:?}", wallet.write().unwrap().get_default()?);
}
}
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Set default wallet")]
pub(crate) struct WalletGetDefaultArgs {
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/balances.rs | ipc/cli/src/commands/wallet/balances.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Wallet balances cli handler
use async_trait::async_trait;
use clap::Args;
use futures_util::future::join_all;
use fvm_shared::{address::Address, econ::TokenAmount};
use ipc_api::ethers_address_to_fil_address;
use ipc_api::subnet_id::SubnetID;
use ipc_wallet::{EthKeyAddress, EvmKeyStore, WalletType};
use std::{fmt::Debug, str::FromStr};
use crate::{get_ipc_provider, CommandLineHandler, GlobalArguments};
pub(crate) struct WalletBalances;
#[async_trait]
impl CommandLineHandler for WalletBalances {
type Arguments = WalletBalancesArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("list wallets with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let mut errors = Vec::new();
match wallet_type {
WalletType::Evm => {
let wallet = provider.evm_wallet()?;
let addresses = wallet.read().unwrap().list()?;
let r = addresses
.iter()
.map(|addr| {
let provider = provider.clone();
let subnet = subnet.clone();
async move {
provider
.wallet_balance(
&subnet,
ðers_address_to_fil_address(&(addr.clone()).into())?,
)
.await
.map(|balance| (balance, addr))
}
})
.collect::<Vec<_>>();
let v: Vec<anyhow::Result<(TokenAmount, &EthKeyAddress)>> = join_all(r).await;
for r in v.into_iter() {
match r {
Ok(i) => {
let (balance, addr) = i;
if addr.to_string() != "default-key" {
println!("{} - Balance: {}", addr, balance);
}
}
Err(e) => {
errors.push(e);
}
}
}
if !errors.is_empty() {
let error = errors
.into_iter()
.fold(anyhow::anyhow!("Error fetching balances"), |acc, err| {
acc.context(err)
});
return Err(error);
}
}
WalletType::Fvm => {
let wallet = provider.fvm_wallet()?;
let addresses = wallet.read().unwrap().list_addrs()?;
let r = addresses
.iter()
.map(|addr| {
let provider = provider.clone();
let subnet = subnet.clone();
async move {
provider
.wallet_balance(&subnet, addr)
.await
.map(|balance| (balance, addr))
}
})
.collect::<Vec<_>>();
let r = join_all(r)
.await
.into_iter()
.collect::<anyhow::Result<Vec<(TokenAmount, &Address)>>>()?;
for (balance, addr) in r {
println!("{:?} - Balance: {}", addr, balance);
}
}
};
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "List balance of wallets in a subnet")]
pub(crate) struct WalletBalancesArgs {
#[arg(long, help = "The subnet to list wallets from")]
pub subnet: String,
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/mod.rs | ipc/cli/src/commands/wallet/mod.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
use crate::{CommandLineHandler, GlobalArguments};
use crate::commands::wallet::balances::{WalletBalances, WalletBalancesArgs};
use crate::commands::wallet::new::{WalletNew, WalletNewArgs};
use clap::{Args, Subcommand};
use self::default::{
WalletGetDefault, WalletGetDefaultArgs, WalletSetDefault, WalletSetDefaultArgs,
};
use self::export::{WalletExport, WalletExportArgs, WalletPublicKey, WalletPublicKeyArgs};
use self::import::{WalletImport, WalletImportArgs};
use self::list::{WalletList, WalletListArgs};
use self::remove::{WalletRemove, WalletRemoveArgs};
mod balances;
mod default;
mod export;
mod import;
mod list;
mod new;
mod remove;
#[derive(Debug, Args)]
#[command(name = "wallet", about = "wallet related commands")]
#[command(args_conflicts_with_subcommands = true)]
pub(crate) struct WalletCommandsArgs {
#[command(subcommand)]
command: Commands,
}
impl WalletCommandsArgs {
pub async fn handle(&self, global: &GlobalArguments) -> anyhow::Result<()> {
match &self.command {
Commands::New(args) => WalletNew::handle(global, args).await,
Commands::Balances(args) => WalletBalances::handle(global, args).await,
Commands::Import(args) => WalletImport::handle(global, args).await,
Commands::Export(args) => WalletExport::handle(global, args).await,
Commands::Remove(args) => WalletRemove::handle(global, args).await,
Commands::SetDefault(args) => WalletSetDefault::handle(global, args).await,
Commands::GetDefault(args) => WalletGetDefault::handle(global, args).await,
Commands::PubKey(args) => WalletPublicKey::handle(global, args).await,
Commands::List(args) => WalletList::handle(global, args).await,
}
}
}
#[derive(Debug, Subcommand)]
pub(crate) enum Commands {
New(WalletNewArgs),
Balances(WalletBalancesArgs),
Import(WalletImportArgs),
Export(WalletExportArgs),
Remove(WalletRemoveArgs),
SetDefault(WalletSetDefaultArgs),
GetDefault(WalletGetDefaultArgs),
PubKey(WalletPublicKeyArgs),
List(WalletListArgs),
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/export.rs | ipc/cli/src/commands/wallet/export.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Wallet export cli handler
use anyhow::anyhow;
use async_trait::async_trait;
use base64::{prelude::BASE64_STANDARD, Engine};
use clap::Args;
use fvm_shared::address::Address;
use ipc_provider::{lotus::message::wallet::WalletKeyType, IpcProvider, LotusJsonKeyType};
use ipc_wallet::{EvmKeyStore, PersistentKeyInfo, WalletType};
use std::fmt::Debug;
use std::fs::Permissions;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::str::FromStr;
use crate::{get_ipc_provider, CommandLineHandler, GlobalArguments};
pub(crate) struct WalletExport;
impl WalletExport {
fn export_evm(provider: &IpcProvider, arguments: &WalletExportArgs) -> anyhow::Result<String> {
let keystore = provider.evm_wallet()?;
let address = ethers::types::Address::from_str(&arguments.address)?;
let key_info = keystore
.read()
.unwrap()
.get(&address.into())?
.ok_or_else(|| anyhow!("key does not exists"))?;
if arguments.hex {
return Ok(hex::encode(key_info.private_key()));
}
if arguments.fendermint {
return Ok(BASE64_STANDARD.encode(key_info.private_key()));
}
let info = PersistentKeyInfo::new(
format!("{:?}", address),
hex::encode(key_info.private_key()),
);
Ok(serde_json::to_string(&info)?)
}
fn export_fvm(provider: &IpcProvider, arguments: &WalletExportArgs) -> anyhow::Result<String> {
let wallet = provider.fvm_wallet()?;
let addr = Address::from_str(&arguments.address)?;
let key_info = wallet.write().unwrap().export(&addr)?;
if arguments.hex {
return Ok(hex::encode(key_info.private_key()));
}
if arguments.fendermint {
return Ok(BASE64_STANDARD.encode(key_info.private_key()));
}
Ok(serde_json::to_string(&LotusJsonKeyType {
r#type: WalletKeyType::try_from(*key_info.key_type())?.to_string(),
private_key: BASE64_STANDARD.encode(key_info.private_key()),
})?)
}
}
#[async_trait]
impl CommandLineHandler for WalletExport {
type Arguments = WalletExportArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("export wallet with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
let v = match wallet_type {
WalletType::Evm => WalletExport::export_evm(&provider, arguments),
WalletType::Fvm => WalletExport::export_fvm(&provider, arguments),
}?;
match &arguments.output {
Some(p) => {
let mut file = std::fs::File::create(p)?;
file.set_permissions(Permissions::from_mode(0o600))?;
file.write_all(v.as_bytes())?;
println!(
"exported new wallet with address {:?} in file {:?}",
arguments.address, p
);
}
None => {
println!("{}", v);
}
}
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Export the key from a wallet address in JSON format")]
pub(crate) struct WalletExportArgs {
#[arg(long, help = "Address of the key to export")]
pub address: String,
#[arg(
long,
help = "Optional parameter that outputs the address key into the file specified"
)]
pub output: Option<String>,
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
#[arg(
long,
help = "Exports the secret key encoded in base64 as Fendermint expects"
)]
pub fendermint: bool,
#[arg(long, help = "Export the hex encoded secret key")]
pub hex: bool,
}
pub(crate) struct WalletPublicKey;
impl WalletPublicKey {
fn pubkey_evm(
provider: &IpcProvider,
arguments: &WalletPublicKeyArgs,
) -> anyhow::Result<String> {
let keystore = provider.evm_wallet()?;
let address = ethers::types::Address::from_str(&arguments.address)?;
let key_info = keystore
.read()
.unwrap()
.get(&address.into())?
.ok_or_else(|| anyhow!("key does not exists"))?;
let sk = libsecp256k1::SecretKey::parse_slice(key_info.private_key())?;
Ok(hex::encode(libsecp256k1::PublicKey::from_secret_key(&sk).serialize()).to_string())
}
fn pubkey_fvm(
provider: &IpcProvider,
arguments: &WalletPublicKeyArgs,
) -> anyhow::Result<String> {
let wallet = provider.fvm_wallet()?;
let addr = Address::from_str(&arguments.address)?;
let key_info = wallet.write().unwrap().export(&addr)?;
let sk = libsecp256k1::SecretKey::parse_slice(key_info.private_key())?;
Ok(hex::encode(libsecp256k1::PublicKey::from_secret_key(&sk).serialize()).to_string())
}
}
#[async_trait]
impl CommandLineHandler for WalletPublicKey {
type Arguments = WalletPublicKeyArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("export wallet with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
let v = match wallet_type {
WalletType::Evm => WalletPublicKey::pubkey_evm(&provider, arguments),
WalletType::Fvm => WalletPublicKey::pubkey_fvm(&provider, arguments),
}?;
println!("{v}");
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Return public key from a wallet address")]
pub(crate) struct WalletPublicKeyArgs {
#[arg(long, help = "Address of the key to export")]
pub address: String,
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/import.rs | ipc/cli/src/commands/wallet/import.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Wallet import cli handler
use anyhow::bail;
use async_trait::async_trait;
use clap::{ArgGroup, Args};
use ipc_wallet::WalletType;
use std::fmt::Debug;
use std::str::FromStr;
use crate::{get_ipc_provider, CommandLineHandler, GlobalArguments};
pub(crate) struct WalletImport;
#[async_trait]
impl CommandLineHandler for WalletImport {
type Arguments = WalletImportArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("import wallet with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
if let Some(key) = &arguments.private_key {
if !matches!(wallet_type, WalletType::Evm) {
bail!("--private-key only supported by --wallet-type=evm");
}
println!(
"{:?}",
provider.import_evm_key_from_privkey(key)?.to_string()
);
Ok(())
} else {
// Get keyinfo from file or stdin
let keyinfo = if arguments.path.is_some() {
std::fs::read_to_string(arguments.path.as_ref().unwrap())?
} else {
// FIXME: Accept keyinfo from stdin
bail!("stdin not supported yet")
};
match wallet_type {
WalletType::Fvm => println!("{:?}", provider.import_fvm_key(&keyinfo)?),
WalletType::Evm => {
let key = provider
.import_evm_key_from_privkey(&keyinfo)
.or_else(|_| provider.import_evm_key_from_json(&keyinfo))?;
println!("{:?}", key.to_string())
}
};
Ok(())
}
}
}
#[derive(Debug, Args)]
#[command(about = "Import a key into the agent's wallet")]
#[clap(group(ArgGroup::new("key_source")
.required(true)
.multiple(false)
.args(&["path", "private_key"]),
))]
pub(crate) struct WalletImportArgs {
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
#[arg(
long,
group = "key_source",
help = "Path of key info file for the key to import"
)]
pub path: Option<String>,
#[arg(
long,
group = "key_source",
help = "The evm private key to import if path is not specified"
)]
pub private_key: Option<String>,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/remove.rs | ipc/cli/src/commands/wallet/remove.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Wallet remove cli handler
use async_trait::async_trait;
use clap::Args;
use ipc_wallet::{EvmKeyStore, WalletType};
use std::fmt::Debug;
use std::str::FromStr;
use crate::{get_ipc_provider, CommandLineHandler, GlobalArguments};
pub(crate) struct WalletRemove;
#[async_trait]
impl CommandLineHandler for WalletRemove {
type Arguments = WalletRemoveArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("remove wallet with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
match wallet_type {
WalletType::Evm => {
let wallet = provider.evm_wallet()?;
let addr = ipc_wallet::EthKeyAddress::from_str(&arguments.address)?;
wallet.write().unwrap().remove(&addr)?;
}
WalletType::Fvm => {
let wallet = provider.fvm_wallet()?;
let addr = fvm_shared::address::Address::from_str(&arguments.address)?;
wallet.write().unwrap().remove(&addr)?;
}
}
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Remove wallet from keystore")]
pub(crate) struct WalletRemoveArgs {
#[arg(long, help = "Address of the key to remove")]
pub address: String,
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/wallet/new.rs | ipc/cli/src/commands/wallet/new.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Wallet new cli handler
use async_trait::async_trait;
use clap::Args;
use ipc_provider::lotus::message::wallet::WalletKeyType;
use ipc_wallet::WalletType;
use std::fmt::Debug;
use std::str::FromStr;
use crate::{get_ipc_provider, CommandLineHandler, GlobalArguments};
pub(crate) struct WalletNew;
#[async_trait]
impl CommandLineHandler for WalletNew {
type Arguments = WalletNewArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("create new wallet with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let wallet_type = WalletType::from_str(&arguments.wallet_type)?;
match wallet_type {
WalletType::Evm => {
println!("{:?}", provider.new_evm_key()?.to_string());
}
WalletType::Fvm => {
let tp = WalletKeyType::from_str(
&arguments
.key_type
.clone()
.expect("fvm key type not specified"),
)?;
println!("{:?}", provider.new_fvm_key(tp)?)
}
};
Ok(())
}
}
#[derive(Debug, Args)]
#[command(about = "Create new wallet in subnet")]
pub(crate) struct WalletNewArgs {
#[arg(
long,
help = "The fvm key type of the wallet (secp256k1, bls, secp256k1-ledger), only for fvm wallet type"
)]
pub key_type: Option<String>,
#[arg(long, help = "The type of the wallet, i.e. fvm, evm")]
pub wallet_type: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/subnet/list_subnets.rs | ipc/cli/src/commands/subnet/list_subnets.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! List subnets cli command
use async_trait::async_trait;
use clap::Args;
use ipc_api::subnet_id::SubnetID;
use std::fmt::Debug;
use std::str::FromStr;
use crate::{get_ipc_provider, require_fil_addr_from_str, CommandLineHandler, GlobalArguments};
/// The command to create a new subnet actor.
pub(crate) struct ListSubnets;
#[async_trait]
impl CommandLineHandler for ListSubnets {
type Arguments = ListSubnetsArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("list subnets with args: {:?}", arguments);
let provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.parent)?;
let gateway_addr = match &arguments.gateway_address {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
let ls = provider.list_child_subnets(gateway_addr, &subnet).await?;
for (_, s) in ls.iter() {
println!(
"{} - collateral: {} FIL, circ.supply: {} FIL, genesis: {}",
s.id, s.stake, s.circ_supply, s.genesis_epoch
);
}
Ok(())
}
}
#[derive(Debug, Args)]
#[command(
name = "list",
about = "List all child subnets registered in the gateway (i.e. that have provided enough collateral)"
)]
pub(crate) struct ListSubnetsArgs {
#[arg(long, help = "The gateway address to query subnets")]
pub gateway_address: Option<String>,
#[arg(long, help = "The network id to query child subnets")]
pub parent: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/subnet/kill.rs | ipc/cli/src/commands/subnet/kill.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! Kill a subnet cli command handler.
use async_trait::async_trait;
use clap::Args;
use ipc_api::subnet_id::SubnetID;
use std::{fmt::Debug, str::FromStr};
use crate::{get_ipc_provider, require_fil_addr_from_str, CommandLineHandler, GlobalArguments};
/// The command to kill an existing subnet.
pub struct KillSubnet;
#[async_trait]
impl CommandLineHandler for KillSubnet {
type Arguments = KillSubnetArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("kill subnet with args: {:?}", arguments);
let mut provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let from = match &arguments.from {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
provider.kill_subnet(subnet, from).await
}
}
#[derive(Debug, Args)]
#[command(name = "kill", about = "Kill an existing subnet")]
pub struct KillSubnetArgs {
#[arg(long, help = "The address that kills the subnet")]
pub from: Option<String>,
#[arg(long, help = "The subnet to kill")]
pub subnet: String,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
ChainSafe/Delorean-Protocol | https://github.com/ChainSafe/Delorean-Protocol/blob/7f0f8b8a48f44486434bae881ba85785f6f7cf64/ipc/cli/src/commands/subnet/send_value.rs | ipc/cli/src/commands/subnet/send_value.rs | // Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: MIT
//! SendValue cli handler
use async_trait::async_trait;
use clap::Args;
use ipc_api::subnet_id::SubnetID;
use std::{fmt::Debug, str::FromStr};
use crate::{
f64_to_token_amount, get_ipc_provider, require_fil_addr_from_str, CommandLineHandler,
GlobalArguments,
};
pub(crate) struct SendValue;
#[async_trait]
impl CommandLineHandler for SendValue {
type Arguments = SendValueArgs;
async fn handle(global: &GlobalArguments, arguments: &Self::Arguments) -> anyhow::Result<()> {
log::debug!("send value in subnet with args: {:?}", arguments);
let mut provider = get_ipc_provider(global)?;
let subnet = SubnetID::from_str(&arguments.subnet)?;
let from = match &arguments.from {
Some(address) => Some(require_fil_addr_from_str(address)?),
None => None,
};
provider
.send_value(
&subnet,
from,
require_fil_addr_from_str(&arguments.to)?,
f64_to_token_amount(arguments.amount)?,
)
.await
}
}
#[derive(Debug, Args)]
#[command(about = "Send value to an address within a subnet")]
pub(crate) struct SendValueArgs {
#[arg(long, help = "The address to send value from")]
pub from: Option<String>,
#[arg(long, help = "The address to send value to")]
pub to: String,
#[arg(long, help = "The subnet of the addresses")]
pub subnet: String,
#[arg(help = "The amount to send (in whole FIL units)")]
pub amount: f64,
}
| rust | Apache-2.0 | 7f0f8b8a48f44486434bae881ba85785f6f7cf64 | 2026-01-04T20:23:10.651123Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.