Skip to content

Commit

Permalink
authorize signing tasks (#2483)
Browse files Browse the repository at this point in the history
  • Loading branch information
kziemianek committed Feb 14, 2024
1 parent ce56ef0 commit 9bc0e7e
Show file tree
Hide file tree
Showing 15 changed files with 235 additions and 43 deletions.
6 changes: 5 additions & 1 deletion bitacross-worker/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 14 additions & 6 deletions bitacross-worker/bitacross/core/bc-relayer-registry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ pub trait RelayerRegistryUpdater {
fn init(&self) -> RegistryResult<()>;
fn update(&self, account: Identity) -> RegistryResult<()>;
fn remove(&self, account: Identity) -> RegistryResult<()>;
}

pub trait RelayerRegistryLookup {
fn contains_key(&self, account: Identity) -> bool;
}

Expand All @@ -121,7 +124,9 @@ impl RelayerRegistryUpdater for RelayerRegistry {
}

#[cfg(feature = "std")]
fn update(&self, _account: Identity) -> RegistryResult<()> {
fn update(&self, account: Identity) -> RegistryResult<()> {
let mut registry = self.registry.write().unwrap();
registry.insert(account, ());
Ok(())
}

Expand All @@ -130,11 +135,6 @@ impl RelayerRegistryUpdater for RelayerRegistry {
Ok(())
}

#[cfg(feature = "std")]
fn contains_key(&self, _account: Identity) -> bool {
true
}

// if `RELAYER_REGISTRY_FILE` exists, unseal and init from it
// otherwise create a new instance and seal to static file
#[cfg(feature = "sgx")]
Expand Down Expand Up @@ -184,6 +184,14 @@ impl RelayerRegistryUpdater for RelayerRegistry {
}
Ok(())
}
}

impl RelayerRegistryLookup for RelayerRegistry {
#[cfg(feature = "std")]
fn contains_key(&self, account: Identity) -> bool {
let registry = self.registry.read().unwrap();
registry.contains_key(&account)
}

#[cfg(feature = "sgx")]
fn contains_key(&self, account: Identity) -> bool {
Expand Down
5 changes: 3 additions & 2 deletions bitacross-worker/bitacross/core/bc-task-receiver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ itp-types = { path = "../../../core-primitives/types", default-features = false
itp-utils = { path = "../../../core-primitives/utils", default-features = false }

# litentry primities
bc-relayer-registry = { path = "../bc-relayer-registry", default-features = false }
lc-direct-call = { path = "../../../litentry/core/direct-call", default-features = false }
litentry-macros = { path = "../../../../primitives/core/macros", default-features = false }
litentry-primitives = { path = "../../../litentry/primitives", default-features = false }

bc-task-sender = { path = "../bc-task-sender", default-features = false }
Expand All @@ -56,6 +56,7 @@ sgx = [
"hex-sgx",
"sgx_tstd",
"bc-task-sender/sgx",
"bc-relayer-registry/sgx",
"lc-direct-call/sgx",
"litentry-primitives/sgx",
"ita-stf/sgx",
Expand All @@ -75,6 +76,7 @@ std = [
"threadpool",
"log/std",
"bc-task-sender/std",
"bc-relayer-registry/std",
"lc-direct-call/std",
"litentry-primitives/std",
"ita-sgx-runtime/std",
Expand All @@ -95,5 +97,4 @@ std = [
"thiserror",
]
production = [
"litentry-macros/production",
]
50 changes: 30 additions & 20 deletions bitacross-worker/bitacross/core/bc-task-receiver/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![cfg_attr(not(feature = "std"), no_std)]

extern crate core;
#[cfg(all(not(feature = "std"), feature = "sgx"))]
extern crate sgx_tstd as std;

Expand All @@ -17,6 +18,7 @@ compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the sam

#[cfg(all(not(feature = "std"), feature = "sgx"))]
pub use crate::sgx_reexport_prelude::*;
use core::ops::Deref;

use bc_task_sender::init_bit_across_task_sender_storage;
use codec::{Decode, Encode};
Expand All @@ -39,9 +41,10 @@ use itp_sgx_externalities::SgxExternalitiesTrait;
use itp_stf_executor::traits::StfEnclaveSigning;
use itp_stf_state_handler::handle_state::HandleState;

use bc_relayer_registry::RelayerRegistryLookup;
use ita_stf::TrustedCallSigned;
use itp_sgx_crypto::{ecdsa::Pair as EcdsaPair, schnorr::Pair as SchnorrPair};
use litentry_macros::if_production_or;
use lc_direct_call::handler::{sign_bitcoin, sign_ethereum};
use litentry_primitives::DecryptableRequest;

#[derive(Debug, thiserror::Error, Clone)]
Expand All @@ -60,6 +63,7 @@ pub struct BitAcrossTaskContext<
S: StfEnclaveSigning<TrustedCallSigned>,
H: HandleState,
O: EnclaveOnChainOCallApi,
RRL: RelayerRegistryLookup,
> where
SKR: AccessKey,
EKR: AccessKey<KeyType = EcdsaPair>,
Expand All @@ -72,6 +76,7 @@ pub struct BitAcrossTaskContext<
pub enclave_signer: Arc<S>,
pub state_handler: Arc<H>,
pub ocall_api: Arc<O>,
pub relayer_registry_lookup: Arc<RRL>,
}

impl<
Expand All @@ -81,7 +86,8 @@ impl<
S: StfEnclaveSigning<TrustedCallSigned>,
H: HandleState,
O: EnclaveOnChainOCallApi,
> BitAcrossTaskContext<SKR, EKR, BKR, S, H, O>
RRL: RelayerRegistryLookup,
> BitAcrossTaskContext<SKR, EKR, BKR, S, H, O, RRL>
where
SKR: AccessKey,
EKR: AccessKey<KeyType = EcdsaPair>,
Expand All @@ -96,6 +102,7 @@ where
enclave_signer: Arc<S>,
state_handler: Arc<H>,
ocall_api: Arc<O>,
relayer_registry_lookup: Arc<RRL>,
) -> Self {
Self {
shielding_key,
Expand All @@ -104,12 +111,13 @@ where
enclave_signer,
state_handler,
ocall_api,
relayer_registry_lookup,
}
}
}

pub fn run_bit_across_handler_runner<SKR, EKR, BKR, S, H, O>(
context: Arc<BitAcrossTaskContext<SKR, EKR, BKR, S, H, O>>,
pub fn run_bit_across_handler_runner<SKR, EKR, BKR, S, H, O, RRL>(
context: Arc<BitAcrossTaskContext<SKR, EKR, BKR, S, H, O, RRL>>,
) where
SKR: AccessKey + Send + Sync + 'static,
EKR: AccessKey<KeyType = EcdsaPair> + Send + Sync + 'static,
Expand All @@ -119,6 +127,7 @@ pub fn run_bit_across_handler_runner<SKR, EKR, BKR, S, H, O>(
H: HandleState + Send + Sync + 'static,
H::StateT: SgxExternalitiesTrait,
O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static,
RRL: RelayerRegistryLookup + Send + Sync + 'static,
{
let bit_across_task_receiver = init_bit_across_task_sender_storage();
let n_workers = 2;
Expand All @@ -137,9 +146,9 @@ pub fn run_bit_across_handler_runner<SKR, EKR, BKR, S, H, O>(
warn!("bit_across_task_receiver loop terminated");
}

pub fn handle_request<SKR, EKR, BKR, S, H, O>(
pub fn handle_request<SKR, EKR, BKR, S, H, O, RRL>(
request: &mut AesRequest,
context: Arc<BitAcrossTaskContext<SKR, EKR, BKR, S, H, O>>,
context: Arc<BitAcrossTaskContext<SKR, EKR, BKR, S, H, O, RRL>>,
) -> Result<Vec<u8>, String>
where
SKR: AccessKey,
Expand All @@ -149,6 +158,7 @@ where
S: StfEnclaveSigning<TrustedCallSigned> + Send + Sync + 'static,
H: HandleState + Send + Sync + 'static,
O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static,
RRL: RelayerRegistryLookup + 'static,
{
let enclave_shielding_key = context
.shielding_key
Expand All @@ -166,19 +176,19 @@ where
};
ensure!(dc.verify_signature(&mrenclave, &request.shard), "Failed to verify sig".to_string());
match dc.call {
DirectCall::SignBitcoin(_, aes_key, payload) => {
if_production_or!(unimplemented!(), {
let key = context.bitcoin_key_repository.retrieve_key().unwrap();
let signature = key.sign(&payload).unwrap();
Ok(aes_encrypt_default(&aes_key, &signature).encode())
})
},
DirectCall::SignEthereum(_, aes_key, payload) => {
if_production_or!(unimplemented!(), {
let key = context.ethereum_key_repository.retrieve_key().unwrap();
let signature = key.sign(&payload).unwrap();
Ok(aes_encrypt_default(&aes_key, &signature).encode())
})
},
DirectCall::SignBitcoin(signer, aes_key, payload) => sign_bitcoin::handle(
signer,
payload,
context.relayer_registry_lookup.deref(),
context.bitcoin_key_repository.deref(),
)
.map(|r| aes_encrypt_default(&aes_key, &r).encode()),
DirectCall::SignEthereum(signer, aes_key, payload) => sign_ethereum::handle(
signer,
payload,
context.relayer_registry_lookup.deref(),
context.ethereum_key_repository.deref(),
)
.map(|r| aes_encrypt_default(&aes_key, &r).encode()),
}
}
6 changes: 5 additions & 1 deletion bitacross-worker/cli/src/trusted_command_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,11 @@ pub(crate) fn get_pair_from_str(
) -> sr25519_core::Pair {
info!("getting pair for {}", account);
match &account[..2] {
"//" => sr25519_core::Pair::from_string(account, None).unwrap(),
"//" => {
let pair = sr25519_core::Pair::from_string(account, None).unwrap();
info!("public_key: {:?}", &pair.public().to_hex());
pair
},
_ => {
info!("fetching from keystore at {}", &TRUSTED_KEYSTORE_PATH);
// open store without password protection
Expand Down
11 changes: 7 additions & 4 deletions bitacross-worker/core-primitives/sgx/crypto/src/ecdsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub use sgx::*;

use crate::error::{Error, Result};
use k256::{
ecdsa::{signature::Signer, Signature, SigningKey},
ecdsa::{signature::Signer, Signature, SigningKey, VerifyingKey},
elliptic_curve::group::GroupEncoding,
PublicKey,
};
Expand All @@ -34,6 +34,11 @@ pub struct Pair {
}

impl Pair {
pub fn new(private: SigningKey) -> Self {
let public = PublicKey::from(VerifyingKey::from(&private));
Self { private, public }
}

pub fn public_bytes(&self) -> Vec<u8> {
self.public.as_affine().to_bytes().as_slice().to_vec()
}
Expand Down Expand Up @@ -117,9 +122,7 @@ pub mod sgx {
let raw = unseal(self.path())?;
let secret = SigningKey::from_slice(&raw)
.map_err(|e| Error::Other(format!("{:?}", e).into()))?;

let public = PublicKey::from(VerifyingKey::from(&secret));
Ok(Pair { public, private: secret })
Ok(Pair::new(secret))
}

fn seal(&self, unsealed: &Self::Unsealed) -> Result<()> {
Expand Down
8 changes: 4 additions & 4 deletions bitacross-worker/core-primitives/sgx/crypto/src/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ use sgx_crypto_helper::rsa3072::Rsa3072KeyPair;
#[derive(Default)]
pub struct KeyRepositoryMock<KeyType>
where
KeyType: Clone + Default,
KeyType: Clone,
{
key: RwLock<KeyType>,
}

impl<KeyType> KeyRepositoryMock<KeyType>
where
KeyType: Clone + Default,
KeyType: Clone,
{
pub fn new(key: KeyType) -> Self {
KeyRepositoryMock { key: RwLock::new(key) }
Expand All @@ -48,7 +48,7 @@ where

impl<KeyType> AccessKey for KeyRepositoryMock<KeyType>
where
KeyType: Clone + Default,
KeyType: Clone,
{
type KeyType = KeyType;

Expand All @@ -59,7 +59,7 @@ where

impl<KeyType> MutateKey<KeyType> for KeyRepositoryMock<KeyType>
where
KeyType: Clone + Default,
KeyType: Clone,
{
fn update_key(&self, key: KeyType) -> Result<()> {
let mut lock = self.key.write().unwrap();
Expand Down
10 changes: 7 additions & 3 deletions bitacross-worker/core-primitives/sgx/crypto/src/schnorr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ pub struct Pair {
}

impl Pair {
pub fn new(private: SigningKey) -> Self {
let public = PublicKey::from(private.verifying_key());
Self { private, public }
}

pub fn public_bytes(&self) -> Vec<u8> {
self.public.as_affine().to_bytes().as_slice().to_vec()
}
Expand All @@ -55,7 +60,7 @@ pub mod sgx {
std::string::ToString,
};
use itp_sgx_io::{seal, unseal, SealedIO};
use k256::{schnorr::SigningKey, PublicKey};
use k256::schnorr::SigningKey;
use log::*;
use sgx_rand::{Rng, StdRng};
use std::{path::PathBuf, string::String};
Expand Down Expand Up @@ -116,8 +121,7 @@ pub mod sgx {
let raw = unseal(self.path())?;
let secret = SigningKey::from_bytes(&raw)
.map_err(|e| Error::Other(format!("{:?}", e).into()))?;
let public = PublicKey::from(secret.verifying_key().clone());
Ok(Pair { public, private: secret })
Ok(Pair::new(secret))
}

fn seal(&self, unsealed: &Self::Unsealed) -> Result<()> {
Expand Down
4 changes: 3 additions & 1 deletion bitacross-worker/enclave-runtime/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9bc0e7e

Please sign in to comment.