Skip to content

Commit

Permalink
Decoding events are working
Browse files Browse the repository at this point in the history
  • Loading branch information
ryardley committed Sep 30, 2024
1 parent e66ab85 commit e7aa7ef
Show file tree
Hide file tree
Showing 10 changed files with 174 additions and 119 deletions.
58 changes: 47 additions & 11 deletions packages/ciphernode/core/src/evm_enclave.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ use crate::{
EnclaveEvent, EventBus,
};
use actix::Addr;
use alloy::{primitives::Address, sol, sol_types::SolValue};
use alloy::{
hex,
primitives::{Address, Bytes},
sol,
sol_types::SolValue,
};
use anyhow::{Context, Result};

sol! {
struct EncodedE3ProgramParams {
bytes params;
address input_validator;
}

#[derive(Debug)]
struct E3 {
uint256 seed;
Expand Down Expand Up @@ -50,9 +50,12 @@ impl TryFrom<&E3Requested> for events::E3Requested {
type Error = anyhow::Error;
fn try_from(value: &E3Requested) -> Result<Self, Self::Error> {
let program_params = value.e3.e3ProgramParams.to_vec();
let decoded = EncodedE3ProgramParams::abi_decode(&program_params, true)?;
println!("received: {}", hex::encode(&program_params));

let decoded =
decode_e3_params(&program_params).context("Failed to ABI decode program_params")?;
Ok(events::E3Requested {
params: decoded.params.into(),
params: decoded.0.into(),
threshold_m: value.e3.threshold[0] as usize,
seed: value.e3.seed.into(),
e3_id: value.e3Id.to_string().into(),
Expand All @@ -71,9 +74,7 @@ impl From<CiphertextOutputPublished> for events::CiphertextOutputPublished {

impl ContractEvent for E3Requested {
fn process(&self, bus: Addr<EventBus>) -> Result<()> {
let data: events::E3Requested = self
.try_into()
.context("Could not parse E3Requested event")?;
let data: events::E3Requested = self.try_into()?;

bus.do_send(EnclaveEvent::from(data));
Ok(())
Expand Down Expand Up @@ -108,3 +109,38 @@ pub async fn connect_evm_enclave(bus: Addr<EventBus>, rpc_url: &str, contract_ad

println!("Evm is listening to {}", contract_address);
}

pub fn decode_e3_params(bytes: &[u8]) -> Result<(Vec<u8>, String)> {
let decoded: (Bytes, Address) = SolValue::abi_decode_params(bytes, true)?;
Ok((decoded.0.into(), decoded.1.to_string()))
}

pub fn encode_e3_params(params: &[u8], input_validator: Address) -> Vec<u8> {
(params, input_validator).abi_encode_params()
}

#[cfg(test)]
mod tests {
use crate::encode_bfv_params;

use super::{decode_e3_params, encode_e3_params};
use alloy::{hex, primitives::address};
use anyhow::*;
use fhe::bfv::BfvParameters;
use fhe_traits::Deserialize;

#[test]
fn test_evm_decode() -> Result<()> {
let params_encoded = encode_bfv_params(vec![0x3FFFFFFF000001], 2048, 1032193);

let add = address!("8A791620dd6260079BF849Dc5567aDC3F2FdC318");
let encoded = hex::encode(&encode_e3_params(&params_encoded, add));
assert_eq!(encoded, "00000000000000000000000000000000000000000000000000000000000000400000000000000000000000008a791620dd6260079bf849dc5567adc3f2fdc31800000000000000000000000000000000000000000000000000000000000000130880101208818080f8ffffff1f1881803f200a00000000000000000000000000");
let input: Vec<u8> = hex::decode(&encoded)?;
let (de_params, de_address) = decode_e3_params(&input)?;
let params_assemble = BfvParameters::try_deserialize(&de_params)?;
assert_eq!(params_assemble.degree(), 2048);
assert_eq!(de_address, "0x8A791620dd6260079BF849Dc5567aDC3F2FdC318");
Ok(())
}
}
12 changes: 10 additions & 2 deletions packages/ciphernode/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub use data::*;
pub use e3_request::*;
pub use eventbus::*;
pub use events::*;
pub use evm_enclave::{decode_e3_params, encode_e3_params};
pub use fhe::*;
pub use keyshare::*;
pub use logger::*;
Expand Down Expand Up @@ -78,7 +79,12 @@ mod tests {
use tokio::{sync::mpsc::channel, time::sleep};

// Simulating a local node
async fn setup_local_ciphernode(bus: Addr<EventBus>, rng:SharedRng, logging: bool, addr: &str) {
async fn setup_local_ciphernode(
bus: Addr<EventBus>,
rng: SharedRng,
logging: bool,
addr: &str,
) {
// create data actor for saving data
let data = Data::new(logging).start(); // TODO: Use a sled backed Data Actor

Expand Down Expand Up @@ -136,7 +142,9 @@ mod tests {
&[0x3FFFFFFF000001],
2048,
1032193,
Arc::new(std::sync::Mutex::new(ChaCha20Rng::from_seed(seed.clone().into()))),
Arc::new(std::sync::Mutex::new(ChaCha20Rng::from_seed(
seed.clone().into(),
))),
);

let regevt_1 = EnclaveEvent::from(CiphernodeAdded {
Expand Down
3 changes: 3 additions & 0 deletions packages/ciphernode/core/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ impl Handler<EnclaveEvent> for SimpleLogger {
},
EnclaveEvent::E3Requested { data,.. } => {
println!("[{}]: E3Requested(e3_id: {}, threshold_m: {} , seed: {:?})", self.name, data.e3_id, data.threshold_m, data.seed);
},
EnclaveEvent::EnclaveError { data, .. } => {
println!("[{}]: EnclaveError('{}')", self.name, data.message);
}
_ => println!("[{}]: {}", self.name, msg),
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use alloy::{hex::FromHex, primitives::{address, Address}};
use clap::{command, Parser};
use enclave_core::encode_bfv_params;
use enclave_core::{encode_bfv_params, encode_e3_params};
use std::{error::Error, num::ParseIntError, process};

fn parse_hex(arg: &str) -> Result<u64, ParseIntError> {
Expand All @@ -21,6 +22,9 @@ struct Args {

#[arg(short, long = "no-crp", help = "Skip the CRP generation")]
no_crp: bool,

#[arg(short, long = "input-validator", help = "The input validator address")]
input_validator: String
}

fn main() -> Result<(), Box<dyn Error>> {
Expand All @@ -32,8 +36,8 @@ fn main() -> Result<(), Box<dyn Error>> {
}

let encoded = encode_bfv_params(args.moduli, args.degree, args.plaintext_modulus);

for byte in encoded {
let abi_encoded = encode_e3_params(&encoded,Address::from_hex(args.input_validator)?);
for byte in abi_encoded {
print!("{:02x}", byte);
}

Expand Down
3 changes: 2 additions & 1 deletion packages/evm/contracts/test/MockE3Program.sol
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ contract MockE3Program is IE3Program {
computeProviderParams.length == 32,
invalidParams(e3ProgramParams, computeProviderParams)
);
(,inputValidator) = abi.decode(
(, IInputValidator _inputValidator) = abi.decode(
e3ProgramParams,
(bytes, IInputValidator)
);

inputValidator = _inputValidator;
encryptionSchemeId = 0x0000000000000000000000000000000000000000000000000000000000000001;
}

Expand Down
Loading

0 comments on commit e7aa7ef

Please sign in to comment.