From 4276678c0fb3d1d3d6f985135f65039ce2f91e63 Mon Sep 17 00:00:00 2001 From: Kasper Ziemianek Date: Thu, 1 Feb 2024 14:07:30 +0100 Subject: [PATCH 1/2] fix on taplo 0.8.1 release (#2458) --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7785e11e78..ed0f342620 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -153,7 +153,7 @@ jobs: - name: Install pre-built taplo run: | mkdir -p $HOME/.local/bin - wget -q https://github.com/tamasfe/taplo/releases/latest/download/taplo-linux-x86_64.gz + wget -q https://github.com/tamasfe/taplo/releases/download/0.8.1/taplo-linux-x86_64.gz gzip -d taplo-linux-x86_64.gz cp taplo-linux-x86_64 $HOME/.local/bin/taplo chmod a+x $HOME/.local/bin/taplo From 81e8402cce68dc9d214e831d3d9e3c91153925d4 Mon Sep 17 00:00:00 2001 From: Kasper Ziemianek Date: Thu, 1 Feb 2024 14:53:58 +0100 Subject: [PATCH 2/2] Ethereum and Bitcoin key repository (#2454) * init eth and btc wallet * fmt --------- Co-authored-by: Kai <7630809+Kailai-Wang@users.noreply.github.com> --- bitacross-worker/Cargo.lock | 1 + .../core-primitives/sgx/crypto/Cargo.toml | 1 + .../core-primitives/sgx/crypto/src/lib.rs | 1 + .../sgx/crypto/src/secp256k1.rs | 168 ++++++++++++++++++ bitacross-worker/enclave-runtime/Cargo.lock | 1 + bitacross-worker/enclave-runtime/Makefile | 4 +- .../src/initialization/global_components.rs | 18 +- .../enclave-runtime/src/initialization/mod.rs | 16 +- 8 files changed, 206 insertions(+), 4 deletions(-) create mode 100644 bitacross-worker/core-primitives/sgx/crypto/src/secp256k1.rs diff --git a/bitacross-worker/Cargo.lock b/bitacross-worker/Cargo.lock index a0631f3ce6..6d07382944 100644 --- a/bitacross-worker/Cargo.lock +++ b/bitacross-worker/Cargo.lock @@ -5253,6 +5253,7 @@ dependencies = [ "derive_more", "itp-sgx-io", "itp-sgx-temp-dir", + "libsecp256k1", "log 0.4.20", "ofb", "parity-scale-codec", diff --git a/bitacross-worker/core-primitives/sgx/crypto/Cargo.toml b/bitacross-worker/core-primitives/sgx/crypto/Cargo.toml index fd8a971e49..c7f4f35360 100644 --- a/bitacross-worker/core-primitives/sgx/crypto/Cargo.toml +++ b/bitacross-worker/core-primitives/sgx/crypto/Cargo.toml @@ -9,6 +9,7 @@ edition = "2021" aes = { version = "0.6.0" } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } derive_more = { version = "0.99.5" } +libsecp256k1 = { version = "0.7.1", default-features = false } log = { version = "0.4", default-features = false } ofb = { version = "0.4.0" } serde_json = { version = "1.0", default-features = false, features = ["alloc"], optional = true } diff --git a/bitacross-worker/core-primitives/sgx/crypto/src/lib.rs b/bitacross-worker/core-primitives/sgx/crypto/src/lib.rs index 832239c027..b530e16788 100644 --- a/bitacross-worker/core-primitives/sgx/crypto/src/lib.rs +++ b/bitacross-worker/core-primitives/sgx/crypto/src/lib.rs @@ -38,6 +38,7 @@ pub mod ed25519_derivation; pub mod error; pub mod key_repository; pub mod rsa3072; +pub mod secp256k1; pub mod traits; pub use self::{aes::*, ed25519::*, rsa3072::*}; diff --git a/bitacross-worker/core-primitives/sgx/crypto/src/secp256k1.rs b/bitacross-worker/core-primitives/sgx/crypto/src/secp256k1.rs new file mode 100644 index 0000000000..e31d6f0c26 --- /dev/null +++ b/bitacross-worker/core-primitives/sgx/crypto/src/secp256k1.rs @@ -0,0 +1,168 @@ +// Copyright 2020-2024 Trust Computing GmbH. +// This file is part of Litentry. +// +// Litentry is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Litentry is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Litentry. If not, see . +#[cfg(feature = "sgx")] +pub use sgx::*; + +pub use libsecp256k1; + +use libsecp256k1::{PublicKey, SecretKey}; + +/// File name of the sealed seed file. +pub const SEALED_SIGNER_SEED_FILE: &str = "secp256k1_key_sealed.bin"; + +#[derive(Clone, PartialEq)] +pub struct Pair { + pub public: PublicKey, + pub secret: SecretKey, +} + +#[cfg(feature = "sgx")] +pub mod sgx { + use super::SEALED_SIGNER_SEED_FILE; + use crate::{ + error::{Error, Result}, + key_repository::KeyRepository, + secp256k1::Pair, + std::string::ToString, + }; + use itp_sgx_io::{seal, unseal, SealedIO}; + use libsecp256k1::{PublicKey, SecretKey}; + use log::*; + use sgx_rand::{Rng, StdRng}; + use std::{path::PathBuf, string::String}; + + /// Creates a repository for an secp256k1 keypair and initializes + /// a fresh private key if it doesn't exist at `path`. + pub fn create_secp256k1_repository( + path: PathBuf, + key_file_prefix: &str, + ) -> Result> { + let seal = Seal::new(path, key_file_prefix.to_string()); + Ok(KeyRepository::new(seal.init()?, seal.into())) + } + + #[derive(Clone, Debug)] + pub struct Seal { + base_path: PathBuf, + key_file_prefix: String, + } + + impl Seal { + pub fn new(base_path: PathBuf, key_file_prefix: String) -> Self { + Self { base_path, key_file_prefix } + } + + pub fn path(&self) -> PathBuf { + self.base_path + .join(self.key_file_prefix.clone() + "_" + SEALED_SIGNER_SEED_FILE) + } + } + + impl Seal { + fn unseal_pair(&self) -> Result { + self.unseal() + } + + fn exists(&self) -> bool { + self.path().exists() + } + + fn init(&self) -> Result { + if !self.exists() { + info!("Keyfile not found, creating new! {}", self.path().display()); + let mut seed = [0u8; 32]; + let mut rand = StdRng::new()?; + rand.fill_bytes(&mut seed); + seal(&seed, self.path())?; + } + self.unseal_pair() + } + } + + impl SealedIO for Seal { + type Error = Error; + type Unsealed = Pair; + + fn unseal(&self) -> Result { + let raw = unseal(self.path())?; + + let secret = SecretKey::parse_slice(&raw) + .map_err(|e| Error::Other(format!("{:?}", e).into()))?; + let public = PublicKey::from_secret_key(&secret); + + Ok(Pair { public, secret }) + } + + fn seal(&self, unsealed: &Self::Unsealed) -> Result<()> { + let raw = unsealed.secret.serialize(); + seal(&raw, self.path()).map_err(|e| e.into()) + } + } +} + +#[cfg(feature = "test")] +pub mod sgx_tests { + use super::sgx::*; + use crate::{key_repository::AccessKey, secp256k1::Pair, std::string::ToString, ToPubkey}; + use itp_sgx_temp_dir::TempDir; + use std::path::{Path, PathBuf}; + + #[test] + pub fn creating_repository_with_same_path_and_prefix_results_in_same_key() { + let key_file_prefix = "test"; + fn get_key_from_repo(path: PathBuf, prefix: &str) -> Pair { + create_secp256k1_repository(path, prefix).unwrap().retrieve_key().unwrap() + } + let temp_dir = TempDir::with_prefix( + "creating_repository_with_same_path_and_prefix_results_in_same_key", + ) + .unwrap(); + let temp_path = temp_dir.path().to_path_buf(); + assert_eq!( + get_key_from_repo(temp_path.clone(), key_file_prefix), + get_key_from_repo(temp_path.clone(), key_file_prefix) + ); + } + + #[test] + pub fn seal_init_should_create_new_key_if_not_present() { + //given + let temp_dir = + TempDir::with_prefix("seal_init_should_create_new_key_if_not_present").unwrap(); + let seal = Seal::new(temp_dir.path().to_path_buf(), "test".to_string()); + assert!(!seal.exists()); + + //when + seal.init().unwrap(); + + //then + assert!(seal.exists()); + } + + #[test] + pub fn seal_init_should_not_change_key_if_exists() { + //given + let temp_dir = TempDir::with_prefix("seal_init_should_not_change_key_if_exists").unwrap(); + let seal = Seal::new(temp_dir.path().to_path_buf(), "test".to_string()); + let pair = seal.init().unwrap(); + + //when + let new_pair = seal.init().unwrap(); + + //then + assert!(pair, new_pair); + } +} diff --git a/bitacross-worker/enclave-runtime/Cargo.lock b/bitacross-worker/enclave-runtime/Cargo.lock index 5506e3e89e..ae5936ad0b 100644 --- a/bitacross-worker/enclave-runtime/Cargo.lock +++ b/bitacross-worker/enclave-runtime/Cargo.lock @@ -2279,6 +2279,7 @@ dependencies = [ "derive_more", "itp-sgx-io", "itp-sgx-temp-dir", + "libsecp256k1", "log", "ofb", "parity-scale-codec", diff --git a/bitacross-worker/enclave-runtime/Makefile b/bitacross-worker/enclave-runtime/Makefile index b4dc322eed..bf3aa55dee 100644 --- a/bitacross-worker/enclave-runtime/Makefile +++ b/bitacross-worker/enclave-runtime/Makefile @@ -27,8 +27,8 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ######## Worker Feature Settings ######## -# Set sidechain as default feature mode -WORKER_MODE ?= sidechain +# Set offchain-worker as default feature mode +WORKER_MODE ?= offchain-worker Rust_Enclave_Name := libenclave.a Rust_Enclave_Files := $(wildcard src/*.rs) $(wildcard ../stf/src/*.rs) diff --git a/bitacross-worker/enclave-runtime/src/initialization/global_components.rs b/bitacross-worker/enclave-runtime/src/initialization/global_components.rs index 8f45ddcc7f..d0aa22e265 100644 --- a/bitacross-worker/enclave-runtime/src/initialization/global_components.rs +++ b/bitacross-worker/enclave-runtime/src/initialization/global_components.rs @@ -63,7 +63,11 @@ use itp_node_api::{ metadata::{provider::NodeMetadataRepository, NodeMetadata}, }; use itp_nonce_cache::NonceCache; -use itp_sgx_crypto::{key_repository::KeyRepository, Aes, AesSeal, Ed25519Seal, Rsa3072Seal}; +use itp_sgx_crypto::{ + key_repository::KeyRepository, + secp256k1::{Pair as Secp256k1Pair, Seal as Secp256k1Seal}, + Aes, AesSeal, Ed25519Seal, Rsa3072Seal, +}; use itp_stf_executor::{ enclave_signer::StfEnclaveSigner, executor::StfExecutor, getter_executor::GetterExecutor, state_getter::StfStateGetter, @@ -106,6 +110,8 @@ pub type EnclaveStf = Stf; pub type EnclaveShieldingKeyRepository = KeyRepository; pub type EnclaveSigningKeyRepository = KeyRepository; +pub type EnclaveBitcoinKeyRepository = KeyRepository; +pub type EnclaveEthereumKeyRepository = KeyRepository; pub type EnclaveStateFileIo = SgxStateFileIo; pub type EnclaveStateSnapshotRepository = StateSnapshotRepository; pub type EnclaveStateObserver = StateObserver; @@ -381,6 +387,16 @@ pub static GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT: ComponentContainer< EnclaveSigningKeyRepository, > = ComponentContainer::new("Signing key repository"); +/// Bitcoin key repository +pub static GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT: ComponentContainer< + EnclaveBitcoinKeyRepository, +> = ComponentContainer::new("Bitcoin key repository"); + +/// Ethereum key repository +pub static GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT: ComponentContainer< + EnclaveEthereumKeyRepository, +> = ComponentContainer::new("Ethereum key repository"); + /// Light client db seal for the Integritee parentchain pub static GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL: ComponentContainer< EnclaveLightClientSeal, diff --git a/bitacross-worker/enclave-runtime/src/initialization/mod.rs b/bitacross-worker/enclave-runtime/src/initialization/mod.rs index 1510341a61..f97b9e3679 100644 --- a/bitacross-worker/enclave-runtime/src/initialization/mod.rs +++ b/bitacross-worker/enclave-runtime/src/initialization/mod.rs @@ -27,7 +27,8 @@ use crate::{ EnclaveStateHandler, EnclaveStateInitializer, EnclaveStateObserver, EnclaveStateSnapshotRepository, EnclaveStfEnclaveSigner, EnclaveTopPool, EnclaveTopPoolAuthor, DIRECT_RPC_REQUEST_SINK_COMPONENT, - GLOBAL_ATTESTATION_HANDLER_COMPONENT, GLOBAL_DIRECT_RPC_BROADCASTER_COMPONENT, + GLOBAL_ATTESTATION_HANDLER_COMPONENT, GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT, + GLOBAL_DIRECT_RPC_BROADCASTER_COMPONENT, GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_OCALL_API_COMPONENT, GLOBAL_RPC_WS_HANDLER_COMPONENT, GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, GLOBAL_SIDECHAIN_BLOCK_COMPOSER_COMPONENT, GLOBAL_SIDECHAIN_BLOCK_SYNCER_COMPONENT, @@ -70,6 +71,7 @@ use itp_settings::files::{ }; use itp_sgx_crypto::{ get_aes_repository, get_ed25519_repository, get_rsa3072_repository, key_repository::AccessKey, + secp256k1::create_secp256k1_repository, }; use itp_stf_state_handler::{ file_io::StateDir, handle_state::HandleState, query_shard_state::QueryShardState, @@ -99,6 +101,18 @@ pub(crate) fn init_enclave( let signer = signing_key_repository.retrieve_key()?; info!("[Enclave initialized] Ed25519 prim raw : {:?}", signer.public().0); + let bitcoin_key_repository = + Arc::new(create_secp256k1_repository(base_dir.clone(), "bitcoin")?); + GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT.initialize(bitcoin_key_repository.clone()); + let bitcoin_key = bitcoin_key_repository.retrieve_key()?; + info!("[Enclave initialized] Bitcoin public key raw : {:?}", bitcoin_key.public.serialize()); + + let ethereum_key_repository = + Arc::new(create_secp256k1_repository(base_dir.clone(), "ethereum")?); + GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT.initialize(ethereum_key_repository.clone()); + let ethereum_key = ethereum_key_repository.retrieve_key()?; + info!("[Enclave initialized] Ethereum public key raw : {:?}", ethereum_key.public.serialize()); + let shielding_key_repository = Arc::new(get_rsa3072_repository(base_dir.clone())?); GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.initialize(shielding_key_repository.clone());