Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
Prev Previous commit
Next Next commit
make itp-utils purely no-std
  • Loading branch information
clangenb committed Nov 2, 2023
commit 66a23b78d53442399f03094e3f39d145801dbeb7
9 changes: 4 additions & 5 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3048,6 +3048,7 @@ dependencies = [
"derive_more",
"frame-support",
"frame-system",
"hex",
"integritee-node-runtime",
"ita-sgx-runtime",
"itp-hashing",
Expand Down Expand Up @@ -3732,6 +3733,7 @@ dependencies = [
name = "itp-stf-primitives"
version = "0.9.0"
dependencies = [
"itp-sgx-runtime-primitives",
"parity-scale-codec",
"sp-core",
"sp-runtime",
Expand Down Expand Up @@ -3905,6 +3907,7 @@ dependencies = [
"frame-system",
"integritee-node-runtime",
"itp-sgx-runtime-primitives",
"itp-utils",
"pallet-balances",
"parity-scale-codec",
"primitive-types",
Expand All @@ -3913,20 +3916,16 @@ dependencies = [
"sp-core",
"sp-runtime",
"sp-std",
"substrate-api-client",
"teerex-primitives",
]

[[package]]
name = "itp-utils"
version = "0.9.0"
dependencies = [
"frame-support",
"hex",
"parity-scale-codec",
"sgx_tstd",
"sp-core",
"thiserror 1.0.40",
"thiserror 1.0.9",
]

[[package]]
Expand Down
2 changes: 0 additions & 2 deletions app-libs/stf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ evm_std = ["evm", "ita-sgx-runtime/evm_std"]
sgx = [
"sgx_tstd",
"itp-sgx-externalities/sgx",
"itp-utils/sgx",
"sp-io/sgx",
"itp-node-api/sgx",
"itp-node-api-metadata-provider/sgx",
Expand All @@ -70,7 +69,6 @@ std = [
"itp-stf-interface/std",
"itp-storage/std",
"itp-types/std",
"itp-utils/std",
"itp-node-api/std",
"itp-node-api-metadata/std",
"itp-node-api-metadata-provider/std",
Expand Down
2 changes: 0 additions & 2 deletions core-primitives/top-pool-author/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ std = [
"itp-stf-state-handler/std",
"itp-top-pool/std",
"itp-types/std",
"itp-utils/std",
"jsonrpc-core",
"log/std",
"thiserror",
Expand All @@ -67,7 +66,6 @@ sgx = [
"itp-sgx-crypto/sgx",
"itp-stf-state-handler/sgx",
"itp-top-pool/sgx",
"itp-utils/sgx",
"thiserror_sgx",
]
test = ["itp-test/sgx", "itp-top-pool/mocks"]
Expand Down
19 changes: 0 additions & 19 deletions core-primitives/utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,9 @@ edition = "2021"
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }

# substrate
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" }
sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" }

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

# sgx enabled external libraries
thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linux/thiserror-sgx", tag = "sgx_1.1.3", optional = true }
# std compatible external libraries (make sure these versions match with the sgx-enabled ones above)
thiserror = { version = "1.0", optional = true }

[features]
default = ["std"]
std = [
"codec/std",
"frame-support/std",
"hex/std",
"sp-core/std",
"thiserror",
]
sgx = [
"sgx_tstd",
"thiserror_sgx",
]
21 changes: 9 additions & 12 deletions core-primitives/utils/src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,29 @@

//! Buffer utility functions.

use frame_support::ensure;
use std::vec::Vec;

#[cfg(all(not(feature = "std"), feature = "sgx"))]
use crate::sgx_reexport_prelude::thiserror;
use alloc::vec::Vec;

/// Fills a given buffer with data and the left over buffer space with white spaces.
pub fn write_slice_and_whitespace_pad(
writable: &mut [u8],
data: Vec<u8>,
) -> Result<(), BufferError> {
ensure!(
data.len() <= writable.len(),
BufferError::InsufficientBufferSize(writable.len(), data.len())
);
if data.len() > writable.len() {
return Err(BufferError::InsufficientBufferSize {
actual: writable.len(),
required: data.len(),
})
}
let (left, right) = writable.split_at_mut(data.len());
left.clone_from_slice(&data);
// fill the right side with whitespace
right.iter_mut().for_each(|x| *x = 0x20);
Ok(())
}

#[derive(Debug, thiserror::Error)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum BufferError {
#[error("Insufficient buffer size. Actual: {0}, required: {1}")]
InsufficientBufferSize(usize, usize),
InsufficientBufferSize { actual: usize, required: usize },
}

#[cfg(test)]
Expand Down
12 changes: 3 additions & 9 deletions core-primitives/utils/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,13 @@

*/

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

use std::boxed::Box;
use alloc::string::String;

pub type Result<T> = core::result::Result<T, Error>;

#[derive(Debug, thiserror::Error)]
#[derive(Debug)]
pub enum Error {
#[error("Could not decode from hex data: {0}")]
Hex(hex::FromHexError),
#[error("Parity Scale Codec: {0}")]
Codec(codec::Error),
#[error(transparent)]
Other(#[from] Box<dyn std::error::Error + Sync + Send + 'static>),
Other(String),
}
4 changes: 3 additions & 1 deletion core-primitives/utils/src/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@

//! Hex encoding utility functions.

// Todo: merge with hex_display

use crate::error::{Error, Result};
use alloc::{string::String, vec::Vec};
use codec::{Decode, Encode};
use std::{string::String, vec::Vec};

/// Trait to encode a given value to a hex string, prefixed with "0x".
pub trait ToHexPrefixed {
Expand Down
96 changes: 96 additions & 0 deletions core-primitives/utils/src/hex_display.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Wrapper type for byte collections that outputs hex.
//!
//! Copied from sp-core and made purely no-std.

/// Simple wrapper to display hex representation of bytes.
pub struct HexDisplay<'a>(&'a [u8]);

impl<'a> HexDisplay<'a> {
/// Create new instance that will display `d` as a hex string when displayed.
pub fn from<R: AsBytesRef>(d: &'a R) -> Self {
HexDisplay(d.as_bytes_ref())
}
}

impl<'a> core::fmt::Display for HexDisplay<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
if self.0.len() < 1027 {
for byte in self.0 {
f.write_fmt(format_args!("{:02x}", byte))?;
}
} else {
for byte in &self.0[0..512] {
f.write_fmt(format_args!("{:02x}", byte))?;
}
f.write_str("...")?;
for byte in &self.0[self.0.len() - 512..] {
f.write_fmt(format_args!("{:02x}", byte))?;
}
}
Ok(())
}
}

impl<'a> core::fmt::Debug for HexDisplay<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
for byte in self.0 {
f.write_fmt(format_args!("{:02x}", byte))?;
}
Ok(())
}
}

/// Simple trait to transform various types to `&[u8]`
pub trait AsBytesRef {
/// Transform `self` into `&[u8]`.
fn as_bytes_ref(&self) -> &[u8];
}

impl AsBytesRef for &[u8] {
fn as_bytes_ref(&self) -> &[u8] {
self
}
}

impl AsBytesRef for [u8] {
fn as_bytes_ref(&self) -> &[u8] {
self
}
}

impl AsBytesRef for alloc::vec::Vec<u8> {
fn as_bytes_ref(&self) -> &[u8] {
self
}
}

macro_rules! impl_non_endians {
( $( $t:ty ),* ) => { $(
impl AsBytesRef for $t {
fn as_bytes_ref(&self) -> &[u8] { &self[..] }
}
)* }
}

impl_non_endians!(
[u8; 1], [u8; 2], [u8; 3], [u8; 4], [u8; 5], [u8; 6], [u8; 7], [u8; 8], [u8; 10], [u8; 12],
[u8; 14], [u8; 16], [u8; 20], [u8; 24], [u8; 28], [u8; 32], [u8; 40], [u8; 48], [u8; 56],
[u8; 64], [u8; 65], [u8; 80], [u8; 96], [u8; 112], [u8; 128]
);
16 changes: 3 additions & 13 deletions core-primitives/utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,18 @@

//! General utility functions.

#![cfg_attr(not(feature = "std"), no_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;

// re-export module to properly feature gate sgx and regular std environment
#[cfg(all(not(feature = "std"), feature = "sgx"))]
pub mod sgx_reexport_prelude {
pub use thiserror_sgx as thiserror;
}
extern crate alloc;

pub mod buffer;
pub mod error;
pub mod hex;
pub mod hex_display;
pub mod stringify;

// Public re-exports.
pub use self::{
buffer::write_slice_and_whitespace_pad,
hex::{FromHexPrefixed, ToHexPrefixed},
};
pub use error::Error;
9 changes: 4 additions & 5 deletions core-primitives/utils/src/stringify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@
//! Utility methods to stringify certain types that don't have a working
//! `Debug` implementation on `sgx`.

use crate::hex_display::{AsBytesRef, HexDisplay};
use alloc::{format, string::String};
use codec::Encode;
use sp_core::{crypto::Public, hexdisplay::HexDisplay};
use std::{format, string::String};

/// Convert a sp_core public type to string.
pub fn public_to_string<T: Public>(t: &T) -> String {
let crypto_pair = t.as_ref();
format!("{}", HexDisplay::from(&crypto_pair))
pub fn public_to_string<T: AsBytesRef>(t: &T) -> String {
format!("{}", HexDisplay::from(t))
}

pub fn account_id_to_string<AccountId: Encode>(account: &AccountId) -> String {
Expand Down
2 changes: 0 additions & 2 deletions core/direct-rpc-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ std = [
"sp-runtime/std",
# integritee dependencies
"itp-types/std",
"itp-utils/std",
# local
"itc-tls-websocket-server/std",
"itp-rpc/std",
Expand All @@ -50,7 +49,6 @@ std = [
sgx = [
"itc-tls-websocket-server/sgx",
"itp-rpc/sgx",
"itp-utils/sgx",
"jsonrpc-core_sgx",
"sgx_tstd",
"sgx_types",
Expand Down
1 change: 0 additions & 1 deletion core/parentchain/indirect-calls-executor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ std = [
"itp-api-client-types/std",
"itp-types/std",
"itp-sgx-runtime-primitives/std",
"itp-utils/std",
"log/std",
#substrate
"binary-merkle-tree/std",
Expand Down
2 changes: 1 addition & 1 deletion enclave-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ itp-time-utils = { path = "../core-primitives/time-utils", default-features = fa
itp-top-pool = { path = "../core-primitives/top-pool", default-features = false, features = ["sgx"] }
itp-top-pool-author = { path = "../core-primitives/top-pool-author", default-features = false, features = ["sgx"] }
itp-types = { path = "../core-primitives/types", default-features = false }
itp-utils = { path = "../core-primitives/utils", default-features = false, features = ["sgx"] }
itp-utils = { path = "../core-primitives/utils", default-features = false }
its-block-verification = { path = "../sidechain/block-verification", default-features = false }
its-primitives = { path = "../sidechain/primitives", default-features = false }
its-sidechain = { path = "../sidechain/sidechain-crate", default-features = false, features = ["sgx"] }
Expand Down
2 changes: 0 additions & 2 deletions sidechain/block-verification/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ std = [
"thiserror",
# local
"itp-types/std",
"itp-utils/std",
"its-primitives/std",
# substrate
"frame-support/std",
Expand All @@ -43,7 +42,6 @@ std = [
"sp-runtime/std",
]
sgx = [
"itp-utils/sgx",
"sgx_tstd",
"thiserror-sgx",
]
Expand Down
2 changes: 0 additions & 2 deletions sidechain/consensus/aura/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ std = [
"itp-stf-state-handler/std",
"itp-time-utils/std",
"itp-types/std",
"itp-utils/std",
"its-block-composer/std",
"its-block-verification/std",
"its-consensus-common/std",
Expand All @@ -90,7 +89,6 @@ sgx = [
"itp-stf-executor/sgx",
"itp-stf-state-handler/sgx",
"itp-time-utils/sgx",
"itp-utils/sgx",
"its-block-composer/sgx",
"its-consensus-common/sgx",
"its-consensus-slots/sgx",
Expand Down
Loading