Skip to content
This repository was archived by the owner on Jun 21, 2020. It is now read-only.

Refactoring the KM #286

Open
wants to merge 30 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
f75230c
DEV: added error return on enigma-core main
AvishaiW Jan 28, 2020
25836b4
DEV: added thiserror crate and PrincipalConfig custom error
AvishaiW Jan 28, 2020
f8fd778
DEV: removed duplicate code in the principal manager
AvishaiW Jan 28, 2020
f4e913c
STY: removed unused code
AvishaiW Jan 28, 2020
8c34227
DEV: custom errors for report manager
AvishaiW Jan 28, 2020
ea884b0
BUG: added extern crate for failure
AvishaiW Jan 28, 2020
d675ea4
BUG: fixed a error mapping in main
AvishaiW Jan 29, 2020
09eaff7
STY: removed unused code
AvishaiW Jan 30, 2020
5a2a1f6
DEV: changed threading to crossbeam
AvishaiW Jan 30, 2020
fcf1dfd
MAINT: refactoring the KM-1
AvishaiW Feb 2, 2020
1f1608c
MAINT:removed warnings
AvishaiW Feb 2, 2020
d7d12a3
MAINT: changed gas_limit to a const
AvishaiW Feb 2, 2020
528a1f0
MAINT: removed stringWrapper and done many changes in the http server
AvishaiW Feb 3, 2020
f10b1c2
MAINT: removed unnecessary configurations
AvishaiW Feb 3, 2020
c67786b
MAINT: removed pub definitions from signed epoch struct
AvishaiW Feb 3, 2020
d2b4c5e
MAINT: doc fixes and renaming
AvishaiW Feb 3, 2020
856bac4
MAINT: renaming files and directories
AvishaiW Feb 4, 2020
d190d4b
BUG: fixed ContractAddress renaming
AvishaiW Feb 4, 2020
dd519e6
MAINT: added better error handling to the KM
AvishaiW Feb 6, 2020
774dbc4
Update enigma-core/app/src/main.rs
AvishaiW Feb 6, 2020
f1ef95b
Update enigma-core/app/src/main.rs
AvishaiW Feb 6, 2020
91704a7
MAINT: removed all warnings
AvishaiW Feb 6, 2020
c8af94c
Merge remote-tracking branch 'origin/km_errors' into km_errors
AvishaiW Feb 6, 2020
701209b
MAINT: changes according to review
AvishaiW Feb 6, 2020
25dac49
BLD: removed unused crate from KM
AvishaiW Feb 6, 2020
afff021
Merge branch 'develop' into km_errors
AvishaiW Feb 6, 2020
3e2be21
MAINT: Changes according to review of #286
AvishaiW Feb 6, 2020
497b0ac
BUG: fixing changes done in the previous commit
AvishaiW Feb 6, 2020
a684703
MAINT: changed name and message in a verifier error
AvishaiW Feb 6, 2020
587c56b
MAINT: more changes according to the review
AvishaiW Feb 6, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions enigma-core/app/src/networking/ipc_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ pub(self) mod handling {
#[logfn(TRACE)]
pub fn get_tips(db: &DB, input: &[String]) -> ResponseResult {
let mut tips_results = Vec::with_capacity(input.len());
let addresses : Result<Vec<Hash256>, Error> = input.iter().
map(|data| Hash256::from_hex(&data)).collect::<Result<Vec<Hash256>,Error>>()?;
let addresses = input.iter()
.map(|data| Hash256::from_hex(&data)).collect::<Result<Vec<Hash256>,Error>>()?;
let tips = db.get_tips::<DeltaKey>(&addresses)?;
for (key, data) in tips {
let delta = IpcDelta::from_delta_key(key, &data)?;
Expand Down
2 changes: 1 addition & 1 deletion enigma-principal/app/src/controller/boot_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub fn start(eid: sgx_enclave_id_t) -> Result<(), ControllerError> {
Ok(())
}

//#[logfn(INFO)]
#[logfn(INFO)]
fn run(reset_epoch: bool, controller: KMController) -> Result<(), ControllerError> {
controller.verify_identity_or_register()?;
if reset_epoch {
Expand Down
54 changes: 26 additions & 28 deletions enigma-principal/app/src/controller/km_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ impl KMController {
}

/// Find confirmed `EpochState` by block number
/// # Arguments
///
/// # Arguments
/// * `block_number` - A block number in the desired epoch
pub fn find_epoch(&self, block_number: U256) -> Result<SignedEpoch, ControllerError> {
self.epoch_verifier.get_confirmed_by_block_number(block_number).map_err(ControllerError::VerifierError)
Expand All @@ -55,39 +55,36 @@ impl KMController {

#[logfn(DEBUG)]
fn parse_worker_parameterized(&self, receipt: &TransactionReceipt) -> Result<Log, ControllerError> {
if receipt.logs.is_empty() {
// todo: change the web3error to a proper custom error
Err(Web3Error {
message: format!("A connection error occurred with the Smart Contract- workerParams did not return a log response" ),
})?
}
let log = receipt.logs[0].clone();
let log = receipt.logs.get(0).ok_or(Web3Error {
message: format!("A connection error occurred with the Smart Contract- workerParams did not return a log response" ),
})?.clone();
let raw_log = RawLog { topics: log.topics, data: log.data.0 };
let event = WorkersParameterizedEvent::new();
let result = match event.0.parse_log(raw_log) {
Ok(result) => result,
Err(err) => Err(Web3Error {
let result = match event.0.parse_log(raw_log).map_err(|err|
Web3Error {
message: format!("Unable to parse {} event: {:?}", WORKER_PARAMETERIZED_EVENT, err),
})?,
};
})?;
debug!("Parsed the {} event: {:?}", WORKER_PARAMETERIZED_EVENT, result);
Ok(result)
}

#[logfn(DEBUG)]
fn verify_worker_params(&self) -> Result<(), ControllerError> {
for signed_epoch in self.epoch_verifier.get_all_confirmed().
map_err(ControllerError::VerifierError)?.iter() {
// if the epoch is confirmed by the Enigma Contract
if let Some(_) = &signed_epoch.confirmed_state {
// Get the km_block_number which indicates where to take the list of active workers from
let km_block_number = signed_epoch.get_km_block_num();
let (workers, stakes) = self.contract.get_active_workers(km_block_number).map_err(ControllerError::Other)?;
let worker_params = InputWorkerParams { km_block_number, workers, stakes };
set_or_verify_worker_params(self.eid, &worker_params, Some(signed_epoch.clone())).
map_err(ControllerError::EnclaveError)?;
for signed_epoch in self.epoch_verifier
.get_all_confirmed()
.map_err(ControllerError::VerifierError)?
.iter()
{
// if the epoch is confirmed by the Enigma Contract
if signed_epoch.confirmed_state.is_some() {
// Get the km_block_number which indicates where to take the list of active workers from
let km_block_number = signed_epoch.get_km_block_num();
let (workers, stakes) = self.contract.get_active_workers(km_block_number).map_err(ControllerError::Other)?;
let worker_params = InputWorkerParams { km_block_number, workers, stakes };
set_or_verify_worker_params(self.eid, &worker_params, Some(signed_epoch.clone())).
map_err(ControllerError::EnclaveError)?;
}
}
}
Ok(())
}

Expand Down Expand Up @@ -182,8 +179,9 @@ impl KMController {
self.epoch_verifier.append_unconfirmed(epoch.clone()).map_err(ControllerError::VerifierError)?;

debug!("Waiting for setWorkerParams({:?}, {:?}, {:?})", km_block_number, epoch.get_seed(), epoch.get_sig());
let receipt = self.contract.set_workers_params(km_block_number, epoch.get_seed(), epoch.get_sig(), *GAS_LIMIT, confirmations).
map_err(ControllerError::Other)?;
let receipt = self.contract
.set_workers_params(km_block_number, epoch.get_seed(), epoch.get_sig(), *GAS_LIMIT, confirmations)
.map_err(ControllerError::Other)?;
debug!("Got the receipt: {:?}", receipt);

let log = self.parse_worker_parameterized(&receipt)?;
Expand Down Expand Up @@ -211,8 +209,8 @@ impl KMController {
/// * `worker_params` - The `InputWorkerParams` used to run the worker selection algorithm
#[logfn(DEBUG)]
pub fn confirm_epoch(&self, epoch_state: &mut SignedEpoch, ether_block_number: U256, worker_params: InputWorkerParams) -> Result<(), ControllerError> {
let sc_addresses = self.contract.get_all_secret_contract_addresses().
map_err(ControllerError::Other)?;
let sc_addresses = self.contract.get_all_secret_contract_addresses()
.map_err(ControllerError::Other)?;

debug!("The secret contract addresses: {:?}",
sc_addresses.iter().map(|item| {item.to_hex()}).collect::<Vec<String>>());
Expand Down
81 changes: 31 additions & 50 deletions enigma-principal/app/src/controller/km_http_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ impl KMHttpServer {
let sig = request.get_sig()?;
let worker = KeyPair::recover(&image, sig).or( Err(HTTPServerError::KeyRecoveryErr))?.address();
trace!("Searching contract addresses for recovered worker: {:?}", worker.to_vec());
Ok(epoch_state.get_contract_addresses(&worker.into())?)
epoch_state.get_contract_addresses(&worker.into()).into()
}

#[logfn(DEBUG)]
Expand All @@ -93,59 +93,48 @@ impl KMHttpServer {
let addrs = match request.addresses.clone() {
Some(addrs) => addrs,
None => {
let msg = PrincipalMessage::from_message(&request.get_data()).
or( Err(ControllerError::HTTPServerError(HTTPServerError::InvalidMessage)))?;
let msg = PrincipalMessage::from_message(&request.get_data())
.or( Err(ControllerError::HTTPServerError(HTTPServerError::InvalidMessage)))?;
Self::find_epoch_contract_addresses(&request, &msg, &signed_epoch)?
},
};
let response =
get_enc_state_keys(self.controller.eid, request, signed_epoch.get_nonce(), &addrs).
map_err(ControllerError::EnclaveError)?;
let response_data = serde_json::to_value(&response).
or( Err(ControllerError::HTTPServerError(HTTPServerError::InvalidMessage)))?;
get_enc_state_keys(self.controller.eid, request, signed_epoch.get_nonce(), &addrs)
.map_err(ControllerError::EnclaveError)?;
let response_data = serde_json::to_value(&response)
.or( Err(ControllerError::HTTPServerError(HTTPServerError::InvalidMessage)))?;
Ok(response_data)
}

fn handle_error(internal_err: ControllerError) -> ServerError {
match internal_err {
ControllerError::EnclaveError(e) => {
error!("{:?}", e);
match e {
EnclaveError::Failure {err: e, status: _} => {
match &e {
EnclaveReturn::WorkerAuthError => {
ServerError {
code: ErrorCode::ServerError(JSON_RPC_ERROR_WORKER_NOT_AUTHORIZED),
message: format!("Worker not authorized to request the keys: {:?}.", e),
data: None,
}
},
_ => {
ServerError {
code: ErrorCode::InternalError,
message: format!("Internal error in enclave: {:?}", e),
data: None,
}
},
}
},
_ => {
ServerError {
code: ErrorCode::InternalError,
message: format!("Internal error: {:?}", e),
data: None,
}
},
ControllerError::EnclaveError(
EnclaveError::EnclaveFailErr {
err: e @ EnclaveReturn::WorkerAuthError,
..
}

) => ServerError {
code: ErrorCode::ServerError(JSON_RPC_ERROR_WORKER_NOT_AUTHORIZED),
message: format!("Worker not authorized to request the keys: {:?}.", e),
data: None,
},
_ => {
ServerError {
code: ErrorCode::InternalError,
message: format!("Internal error: {:?}", internal_err),
data: None,
}
ControllerError::EnclaveError(
EnclaveError::EnclaveFailErr { err: e @ _, .. }
) => ServerError {
code: ErrorCode::InternalError,
message: format!("Internal error in enclave: {:?}", e),
data: None,
},
ControllerError::EnclaveError(e @ _) => ServerError {
code: ErrorCode::InternalError,
message: format!("Internal error: {:?}", e),
data: None,
},
_ => ServerError {
code: ErrorCode::InternalError,
message: format!("Internal error: {:?}", internal_err),
data: None,
}
}
}

Expand Down Expand Up @@ -219,14 +208,6 @@ mod test {
const REF_WORKER: [u8; 20] = [161, 186, 144, 238, 40, 242, 102, 161, 178, 93, 177, 83, 107, 128, 189, 132, 112, 8, 163, 252];
const REF_CONTRACT_ADDR: [u8; 32] = [253, 20, 84, 186, 169, 51, 74, 146, 65, 95, 59, 133, 9, 25, 170, 193, 33, 159, 199, 204, 122, 116, 189, 122, 37, 132, 117, 188, 103, 120, 103, 137];

#[test]
fn test_foo() -> failure::Fallible<()> {
let foo: StateKeyRequest = serde_json::from_str("{\"data\": \"1234fF\", \"sig\": \"5678\"}").map_err(|e| {println!("{:?}", e); e})?;
println!("{:?}, {:?}", foo.sig, foo.data);

Ok(())
}

#[test]
pub fn test_jsonrpc_get_state_keys() {
let enclave = init_enclave_wrapper().unwrap();
Expand Down