Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
99afeb2
[itc-light-client] light-client db is now a generic parameter to faci…
clangenb Apr 24, 2023
317045b
[itc-light-client] fix import paths
clangenb Apr 24, 2023
89bed89
[itc-light-client] add no-genesis error, which was lost in rebase
clangenb Apr 26, 2023
d319b8c
[itc-light-client] `LightClientSeal` does no longer refer to a static…
clangenb Apr 26, 2023
cdd09b1
[itc-light-client] remove obsolete fixme
clangenb Apr 26, 2023
93b9473
[itc-light-client] better naming for generic type parameter
clangenb Apr 26, 2023
98318f5
Cargo.lock
clangenb Apr 26, 2023
f5b25fc
[itc-parentchain-light-client] fix test compilation
clangenb Apr 26, 2023
8857420
[itc-parentchain-light-client] fix `cargo test -p itc-parentchain-lig…
clangenb May 6, 2023
524e809
add sgx compatible temp-dir implementation
clangenb May 6, 2023
5fac89e
[itc-parentchain-light-client] the path is now a `Path` instead of a …
clangenb May 6, 2023
d0164a2
[itp-sgx-tempdir] add process-id like behaviour
clangenb May 6, 2023
12d01f6
[itc-parentchain-light-client] fix: enable std feature in sgx-temp-dir.
clangenb May 6, 2023
b18b4c5
more accurate docs.
clangenb May 6, 2023
4ad3269
typos
clangenb May 6, 2023
e9ab9d8
add doc
clangenb May 6, 2023
12ba016
fix clippy
clangenb May 6, 2023
07df91a
taplo fmt
clangenb May 6, 2023
d53bbe3
add debug logs for CI
clangenb May 6, 2023
74554e0
[itp-test] better re-exports
clangenb May 6, 2023
b60cdef
[itc-parentchain-test] better re-exports
clangenb May 6, 2023
940b4ce
[itc-parentchain-light-client] add seal test
clangenb May 6, 2023
828b562
[itc-parentchain-light-client] fix seal test
clangenb May 6, 2023
90856b4
[itc-parentchain-light-client] better naming
clangenb May 6, 2023
ca5771e
add todo for more light-client tests
clangenb May 6, 2023
4d2f3dd
Revert "add debug logs for CI"
clangenb May 6, 2023
9a16378
taplo fmt
clangenb May 6, 2023
a7eac03
Merge branch 'master' into cl/configurable-light-client-db
clangenb May 8, 2023
c03b5c4
[itc-parentchain-light-client] use `PathBuf` instead of `Box<Path>`
clangenb May 9, 2023
f87991a
add temp-dir deprecation note
clangenb May 9, 2023
fe23875
Merge branch 'master' into cl/configurable-light-client-db
clangenb May 10, 2023
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
17 changes: 16 additions & 1 deletion Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3090,8 +3090,8 @@ dependencies = [
"hash-db",
"itc-parentchain-test",
"itp-ocall-api",
"itp-settings",
"itp-sgx-io",
"itp-sgx-temp-dir",
"itp-storage",
"itp-test",
"itp-types",
Expand Down Expand Up @@ -3544,6 +3544,15 @@ dependencies = [
"sp-runtime",
]

[[package]]
name = "itp-sgx-temp-dir"
version = "0.1.0"
dependencies = [
"lazy_static",
"safe-lock",
"sgx_tstd",
]

[[package]]
name = "itp-stf-executor"
version = "0.9.0"
Expand Down Expand Up @@ -6626,6 +6635,12 @@ version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041"

[[package]]
name = "safe-lock"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "077d73db7973cccf63eb4aff1e5a34dc2459baa867512088269ea5f2f4253c90"

[[package]]
name = "safe-mix"
version = "1.0.1"
Expand Down
20 changes: 20 additions & 0 deletions core-primitives/sgx/temp-dir/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "itp-sgx-temp-dir"
version = "0.1.0"
edition = "2021"

[dependencies]
lazy_static = { version = "1.1.0", features = ["spin_no_std"] }

# sgx deps
sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }

[dev-dependencies.safe-lock]
version = "^0.1"

[features]
default = ["std"]
std = []
sgx = [
"sgx_tstd",
]
192 changes: 192 additions & 0 deletions core-primitives/sgx/temp-dir/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
//! # temp-dir
//!
//! Copied from the original tempdir crate with tiny adjustments for SGX-compatibility.
//!
//! Note: The temp-dir is deprecated and there might be uncovered security aspects. If we want to
//! use this in production, we should run some checks.

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(all(feature = "std", feature = "sgx"))]
compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time");

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

use core::sync::atomic::{AtomicU32, Ordering};
use std::{
borrow::ToOwned,
collections::hash_map::RandomState,
format,
hash::{BuildHasher, Hasher},
path::{Path, PathBuf},
string::String,
};

/// Serve some low-security random ID to prevent temp-dir clashes across multiple processes.
fn rand_id() -> String {
// u64 always has more than 4 bytes so this never panics.
format!("{:x}", RandomState::new().build_hasher().finish())[..4].to_owned()
}

lazy_static::lazy_static! {
/// A unique identifier, which is instanciated upon process start, but it is
/// not the process id itself.
///
/// This is a workaround for `sgx_tstd` lib not exposing the `process::id()`.
pub static ref PROCESS_UNIQUE_ID: String = rand_id();
}

static COUNTER: AtomicU32 = AtomicU32::new(0);

/// The path of an existing writable directory in a system temporary directory.
///
/// Drop the struct to delete the directory and everything under it.
/// Deletes symbolic links and does not follow them.
///
/// Ignores any error while deleting.
/// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
///
/// # Example
/// ```rust
/// use itp_sgx_temp_dir::TempDir;
/// let d = TempDir::new().unwrap();
/// // Prints "/tmp/t1a9b-0".
/// println!("{:?}", d.path());
/// let f = d.child("file1");
/// // Prints "/tmp/t1a9b-0/file1".
/// println!("{:?}", f);
/// std::fs::write(&f, b"abc").unwrap();
/// assert_eq!(
/// "abc",
/// std::fs::read_to_string(&f).unwrap(),
/// );
/// // Prints "/tmp/t1a9b-1".
/// println!("{:?}", TempDir::new().unwrap().path());
/// ```
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
pub struct TempDir {
path_buf: Option<PathBuf>,
panic_on_delete_err: bool,
}
impl TempDir {
fn remove_dir(path: &Path) -> Result<(), std::io::Error> {
match std::fs::remove_dir_all(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(std::io::Error::new(
e.kind(),
format!("error removing directory and contents {:?}: {}", path, e),
)),
}
}

/// Create a new empty directory in a system temporary directory.
///
/// Drop the struct to delete the directory and everything under it.
/// Deletes symbolic links and does not follow them.
///
/// Ignores any error while deleting.
/// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
///
/// # Errors
/// Returns `Err` when it fails to create the directory.
///
/// # Example
/// ```rust
/// // Prints "/tmp/t1a9b-0".
/// println!("{:?}", itp_sgx_temp_dir::TempDir::new().unwrap().path());
/// ```
pub fn new() -> Result<Self, std::io::Error> {
// Prefix with 't' to avoid name collisions with `temp-file` crate.
Self::with_prefix("t")
}

/// Create a new empty directory in a system temporary directory.
/// Use `prefix` as the first part of the directory's name.
///
/// Drop the struct to delete the directory and everything under it.
/// Deletes symbolic links and does not follow them.
///
/// Ignores any error while deleting.
/// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
///
/// # Errors
/// Returns `Err` when it fails to create the directory.
///
/// # Example
/// ```rust
/// // Prints "/tmp/ok1a9b-0".
/// println!("{:?}", itp_sgx_temp_dir::TempDir::with_prefix("ok").unwrap().path());
/// ```
pub fn with_prefix(prefix: impl AsRef<str>) -> Result<Self, std::io::Error> {
let path_buf = std::env::temp_dir().join(format!(
"{}{}-{:x}",
prefix.as_ref(),
// std::process::id(), -> The original tempdir crate had this, but the sgx-std lib does not expose it.
*PROCESS_UNIQUE_ID,
COUNTER.fetch_add(1, Ordering::AcqRel),
));
std::fs::create_dir(&path_buf).map_err(|e| {
std::io::Error::new(
e.kind(),
format!("error creating directory {:?}: {}", &path_buf, e),
)
})?;
Ok(Self { path_buf: Some(path_buf), panic_on_delete_err: false })
}

/// Remove the directory on its contents now. Do nothing later on drop.
///
/// # Errors
/// Returns an error if the directory exists and we fail to remove it and its contents.
#[allow(clippy::missing_panics_doc)]
pub fn cleanup(mut self) -> Result<(), std::io::Error> {
Self::remove_dir(&self.path_buf.take().unwrap())
}

/// Make the struct panic on Drop if it hits an error while
/// removing the directory or its contents.
#[must_use]
pub fn panic_on_cleanup_error(mut self) -> Self {
Self { path_buf: self.path_buf.take(), panic_on_delete_err: true }
}

/// Do not delete the directory or its contents.
///
/// This is useful when debugging a test.
pub fn leak(mut self) {
self.path_buf.take();
}

/// The path to the directory.
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn path(&self) -> &Path {
self.path_buf.as_ref().unwrap()
}

/// The path to `name` under the directory.
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn child(&self, name: impl AsRef<str>) -> PathBuf {
let mut result = self.path_buf.as_ref().unwrap().clone();
result.push(name.as_ref());
result
}
}
impl Drop for TempDir {
fn drop(&mut self) {
if let Some(path) = self.path_buf.take() {
let result = Self::remove_dir(&path);
if self.panic_on_delete_err {
if let Err(e) = result {
panic!("{}", e);
}
}
}
}
}

#[cfg(test)]
mod test;
Loading