This is an automated email from the ASF dual-hosted git repository.
yuanz pushed a commit to branch main
in repository
https://gitbox.apache.org/repos/asf/incubator-teaclave-trustzone-sdk.git
The following commit(s) were added to refs/heads/main by this push:
new e67293c crates: reorg for secure_db and related examples
e67293c is described below
commit e67293c0d2f8168f47586be2e5b1a4231c8bd8e9
Author: Yuan Zhuang <[email protected]>
AuthorDate: Wed Apr 30 07:30:22 2025 +0000
crates: reorg for secure_db and related examples
Reorganize basic modules to promote reuse and improve the
development experience for TAs.
* the secure_db module has been moved into the crates directory.
* adjusted secure_db_abstraction and eth_wallet examples to use
the secure_db crate.
Signed-off-by: Yuan Zhuang <[email protected]>
Acked-by: Zehui Chen <[email protected]>
---
.../ta => crates/secure_db}/Cargo.toml | 27 ++----
.../secure_db => crates/secure_db/src}/backend.rs | 12 +--
.../secure_db => crates/secure_db/src}/client.rs | 11 ++-
.../src/secure_db => crates/secure_db/src}/db.rs | 4 +-
.../mod.rs => crates/secure_db/src/lib.rs | 0
.../secure_db => crates/secure_db/src}/storable.rs | 6 +-
examples/secure_db_abstraction-rs/ta/Cargo.toml | 3 +-
examples/secure_db_abstraction-rs/ta/src/main.rs | 4 +-
projects/web3/eth_wallet/ta/Cargo.toml | 1 +
projects/web3/eth_wallet/ta/build.rs | 2 +-
projects/web3/eth_wallet/ta/src/main.rs | 29 +++---
projects/web3/eth_wallet/ta/src/secure_storage.rs | 106 ---------------------
projects/web3/eth_wallet/ta/src/wallet.rs | 9 ++
13 files changed, 51 insertions(+), 163 deletions(-)
diff --git a/examples/secure_db_abstraction-rs/ta/Cargo.toml
b/crates/secure_db/Cargo.toml
similarity index 57%
copy from examples/secure_db_abstraction-rs/ta/Cargo.toml
copy to crates/secure_db/Cargo.toml
index 40e2e9d..8396620 100644
--- a/examples/secure_db_abstraction-rs/ta/Cargo.toml
+++ b/crates/secure_db/Cargo.toml
@@ -16,27 +16,14 @@
# under the License.
[package]
-name = "ta"
+name = "secure_db"
version = "0.1.0"
-authors = ["Teaclave Contributors <[email protected]>"]
-license = "Apache-2.0"
-repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
-description = "An example of Rust OP-TEE TrustZone SDK."
-edition = "2018"
+edition = "2021"
[dependencies]
-proto = { path = "../proto" }
-optee-utee-sys = { path = "../../../optee-utee/optee-utee-sys" }
-optee-utee = { path = "../../../optee-utee" }
-bincode = "1.3.3"
-anyhow = "1.0"
-serde = { version = "1.0", features = ["derive"] }
-
-[build-dependencies]
-proto = { path = "../proto" }
-optee-utee-build = { path = "../../../optee-utee-build" }
+optee-utee-sys = { path = "../../optee-utee/optee-utee-sys" }
+optee-utee = { path = "../../optee-utee" }
-[profile.release]
-panic = "abort"
-lto = true
-opt-level = 1
+bincode = "1.3.3"
+anyhow = "1.0"
+serde = { version = "1.0", features = ["derive"] }
\ No newline at end of file
diff --git a/examples/secure_db_abstraction-rs/ta/src/secure_db/backend.rs
b/crates/secure_db/src/backend.rs
similarity index 91%
rename from examples/secure_db_abstraction-rs/ta/src/secure_db/backend.rs
rename to crates/secure_db/src/backend.rs
index ab40dcd..4cf9271 100644
--- a/examples/secure_db_abstraction-rs/ta/src/secure_db/backend.rs
+++ b/crates/secure_db/src/backend.rs
@@ -45,9 +45,7 @@ pub fn load_from_secure_storage(obj_id: &[u8]) ->
Result<Option<Vec<u8>>> {
DataFlag::ACCESS_READ | DataFlag::SHARE_READ,
) {
Err(e) => match e.kind() {
- optee_utee::ErrorKind::ItemNotFound => {
- return Ok(None);
- }
+ optee_utee::ErrorKind::ItemNotFound => Ok(None),
_ => {
bail!("[-] {:?}: failed to open object: {:?}", &obj_id, e);
}
@@ -55,14 +53,14 @@ pub fn load_from_secure_storage(obj_id: &[u8]) ->
Result<Option<Vec<u8>>> {
Ok(object) => {
let obj_info = object.info()?;
- let mut buf = vec![0u8; obj_info.data_size() as usize];
+ let mut buf = vec![0u8; obj_info.data_size()];
let read_bytes = object.read(&mut buf)?;
if read_bytes != obj_info.data_size() as u32 {
bail!("[-] {:?}: failed to read data", &obj_id);
}
- return Ok(Some(buf));
+ Ok(Some(buf))
}
}
}
@@ -70,7 +68,7 @@ pub fn load_from_secure_storage(obj_id: &[u8]) ->
Result<Option<Vec<u8>>> {
pub fn delete_from_secure_storage(obj_id: &[u8]) -> Result<()> {
match PersistentObject::open(
ObjectStorageConstants::Private,
- &obj_id,
+ obj_id,
DataFlag::ACCESS_READ | DataFlag::ACCESS_WRITE_META,
) {
Err(e) => {
@@ -80,7 +78,7 @@ pub fn delete_from_secure_storage(obj_id: &[u8]) ->
Result<()> {
Ok(mut object) => {
object.close_and_delete()?;
std::mem::forget(object);
- return Ok(());
+ Ok(())
}
}
}
diff --git a/examples/secure_db_abstraction-rs/ta/src/secure_db/client.rs
b/crates/secure_db/src/client.rs
similarity index 93%
rename from examples/secure_db_abstraction-rs/ta/src/secure_db/client.rs
rename to crates/secure_db/src/client.rs
index d6d649e..2ef489e 100644
--- a/examples/secure_db_abstraction-rs/ta/src/secure_db/client.rs
+++ b/crates/secure_db/src/client.rs
@@ -15,10 +15,11 @@
// specific language governing permissions and limitations
// under the License.
-use crate::secure_db::SecureStorageDb;
+use crate::SecureStorageDb;
use crate::Storable;
use anyhow::{anyhow, Result};
use std::{
+ string::ToString,
collections::HashMap,
convert::TryFrom,
hash::Hash,
@@ -42,9 +43,9 @@ impl SecureStorageClient {
pub fn get<V>(&self, key: &V::Key) -> Result<V>
where
V: Storable + serde::de::DeserializeOwned,
- V::Key: Into<String> + Clone,
+ V::Key: ToString,
{
- let key: String = key.clone().into();
+ let key = key.to_string();
let storage_key = V::concat_key(&key);
let value = self
.db
@@ -70,9 +71,9 @@ impl SecureStorageClient {
pub fn delete_entry<V>(&self, key: &V::Key) -> Result<()>
where
V: Storable,
- V::Key: Into<String> + Clone,
+ V::Key: ToString,
{
- let key: String = key.clone().into();
+ let key = key.to_string();
let storage_key = V::concat_key(&key);
self.db
.write()
diff --git a/examples/secure_db_abstraction-rs/ta/src/secure_db/db.rs
b/crates/secure_db/src/db.rs
similarity index 97%
rename from examples/secure_db_abstraction-rs/ta/src/secure_db/db.rs
rename to crates/secure_db/src/db.rs
index 580601a..eb34d03 100644
--- a/examples/secure_db_abstraction-rs/ta/src/secure_db/db.rs
+++ b/crates/secure_db/src/db.rs
@@ -15,9 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use crate::secure_db::{
- delete_from_secure_storage, load_from_secure_storage,
save_in_secure_storage,
-};
+use crate::{delete_from_secure_storage, load_from_secure_storage,
save_in_secure_storage};
use anyhow::{bail, ensure, Result};
use std::collections::{HashMap, HashSet};
diff --git a/examples/secure_db_abstraction-rs/ta/src/secure_db/mod.rs
b/crates/secure_db/src/lib.rs
similarity index 100%
rename from examples/secure_db_abstraction-rs/ta/src/secure_db/mod.rs
rename to crates/secure_db/src/lib.rs
diff --git a/examples/secure_db_abstraction-rs/ta/src/secure_db/storable.rs
b/crates/secure_db/src/storable.rs
similarity index 89%
rename from examples/secure_db_abstraction-rs/ta/src/secure_db/storable.rs
rename to crates/secure_db/src/storable.rs
index afe063b..07acac2 100644
--- a/examples/secure_db_abstraction-rs/ta/src/secure_db/storable.rs
+++ b/crates/secure_db/src/storable.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use std::{convert::TryFrom, hash::Hash};
+use std::hash::Hash;
// For each key-value data, the storage key is "$TABLE_NAME#$KEY"
// For example, if we store the Data whose type is Structure named
@@ -25,7 +25,7 @@ use std::{convert::TryFrom, hash::Hash};
const CONCAT: &str = "#";
pub trait Storable {
- type Key: Into<String> + Clone + TryFrom<String> + Eq + Hash; //
Associated type `Key`
+ type Key: ToString + Eq + Hash; // Associated type `Key`
fn unique_id(&self) -> Self::Key;
@@ -42,7 +42,7 @@ pub trait Storable {
"{}{}{}",
Self::table_name(),
CONCAT,
- Into::<String>::into(self.unique_id())
+ self.unique_id().to_string()
)
}
diff --git a/examples/secure_db_abstraction-rs/ta/Cargo.toml
b/examples/secure_db_abstraction-rs/ta/Cargo.toml
index 40e2e9d..c6c2970 100644
--- a/examples/secure_db_abstraction-rs/ta/Cargo.toml
+++ b/examples/secure_db_abstraction-rs/ta/Cargo.toml
@@ -28,7 +28,8 @@ edition = "2018"
proto = { path = "../proto" }
optee-utee-sys = { path = "../../../optee-utee/optee-utee-sys" }
optee-utee = { path = "../../../optee-utee" }
-bincode = "1.3.3"
+secure_db = { path = "../../../crates/secure_db" }
+
anyhow = "1.0"
serde = { version = "1.0", features = ["derive"] }
diff --git a/examples/secure_db_abstraction-rs/ta/src/main.rs
b/examples/secure_db_abstraction-rs/ta/src/main.rs
index adc61bf..8d620f5 100644
--- a/examples/secure_db_abstraction-rs/ta/src/main.rs
+++ b/examples/secure_db_abstraction-rs/ta/src/main.rs
@@ -17,8 +17,6 @@
#![no_main]
-mod secure_db;
-
extern crate alloc;
use alloc::vec;
@@ -80,7 +78,7 @@ pub struct ExampleData {
// Any structure that implements Storable can be stored in the secure db.
// Any Key type can be used as unique id as long as it implements
-// TryFrom<String> + Into<String> + Clone
+// TryFrom<String> + ToString
impl Storable for ExampleData {
type Key = String;
diff --git a/projects/web3/eth_wallet/ta/Cargo.toml
b/projects/web3/eth_wallet/ta/Cargo.toml
index 6d50631..02e5b19 100644
--- a/projects/web3/eth_wallet/ta/Cargo.toml
+++ b/projects/web3/eth_wallet/ta/Cargo.toml
@@ -29,6 +29,7 @@ libc = { path = "../../../../rust/libc" }
proto = { path = "../proto" }
optee-utee-sys = { path = "../../../../optee-utee/optee-utee-sys" }
optee-utee = { path = "../../../../optee-utee" }
+secure_db = { path = "../../../../crates/secure_db" }
anyhow = "1.0"
uuid = { version = "1.8", default-features = false }
diff --git a/projects/web3/eth_wallet/ta/build.rs
b/projects/web3/eth_wallet/ta/build.rs
index 2352649..7a32a4a 100644
--- a/projects/web3/eth_wallet/ta/build.rs
+++ b/projects/web3/eth_wallet/ta/build.rs
@@ -15,8 +15,8 @@
// specific language governing permissions and limitations
// under the License.
-use proto;
use optee_utee_build::{Error, RustEdition, TaConfig};
+use proto;
fn main() -> Result<(), Error> {
let ta_config = TaConfig::new_default_with_cargo_env(proto::UUID)?
diff --git a/projects/web3/eth_wallet/ta/src/main.rs
b/projects/web3/eth_wallet/ta/src/main.rs
index 5f72179..c61142a 100644
--- a/projects/web3/eth_wallet/ta/src/main.rs
+++ b/projects/web3/eth_wallet/ta/src/main.rs
@@ -18,23 +18,21 @@
#![no_main]
mod hash;
-mod secure_storage;
mod wallet;
-use crate::secure_storage::{
- delete_from_secure_storage, load_from_secure_storage,
save_in_secure_storage,
-};
use optee_utee::{
ta_close_session, ta_create, ta_destroy, ta_invoke_command,
ta_open_session, trace_println,
};
use optee_utee::{Error, ErrorKind, Parameters};
use proto::Command;
+use secure_db::SecureStorageClient;
use anyhow::{anyhow, bail, Result};
-use std::convert::TryInto;
use std::io::Write;
use wallet::Wallet;
+const DB_NAME: &str = "eth_wallet_db";
+
#[ta_create]
fn create() -> optee_utee::Result<()> {
trace_println!("[+] TA create");
@@ -73,8 +71,8 @@ fn create_wallet(_input: &proto::CreateWalletInput) ->
Result<proto::CreateWalle
let mnemonic = wallet.get_mnemonic()?;
dbg_println!("[+] Wallet ID: {:?}", wallet_id);
- let secure_object: Vec<u8> = wallet.try_into()?;
- save_in_secure_storage(wallet_id.as_bytes(), &secure_object)?;
+ let db_client = SecureStorageClient::open(DB_NAME)?;
+ db_client.put(&wallet)?;
dbg_println!("[+] Wallet saved in secure storage");
Ok(proto::CreateWalletOutput {
@@ -86,18 +84,20 @@ fn create_wallet(_input: &proto::CreateWalletInput) ->
Result<proto::CreateWalle
fn remove_wallet(input: &proto::RemoveWalletInput) ->
Result<proto::RemoveWalletOutput> {
dbg_println!("[+] Removing wallet: {:?}", input.wallet_id);
- delete_from_secure_storage(input.wallet_id.as_bytes())?;
+ let db_client = SecureStorageClient::open(DB_NAME)?;
+ db_client.delete_entry::<Wallet>(&input.wallet_id)?;
dbg_println!("[+] Wallet removed");
Ok(proto::RemoveWalletOutput {})
}
fn derive_address(input: &proto::DeriveAddressInput) ->
Result<proto::DeriveAddressOutput> {
- let secure_object = load_from_secure_storage(input.wallet_id.as_bytes())
+ let db_client = SecureStorageClient::open(DB_NAME)?;
+ let wallet = db_client
+ .get::<Wallet>(&input.wallet_id)
.map_err(|e| anyhow!("[+] Deriving address: error: wallet not found:
{:?}", e))?;
- dbg_println!("[+] Deriving address: secure object loaded");
+ dbg_println!("[+] Deriving address: wallet loaded");
- let wallet: Wallet = secure_object.try_into()?;
let (address, public_key) = wallet.derive_address(&input.hd_path)?;
dbg_println!("[+] Deriving address: address: {:?}", address);
dbg_println!("[+] Deriving address: public key: {:?}", public_key);
@@ -109,11 +109,12 @@ fn derive_address(input: &proto::DeriveAddressInput) ->
Result<proto::DeriveAddr
}
fn sign_transaction(input: &proto::SignTransactionInput) ->
Result<proto::SignTransactionOutput> {
- let secure_object = load_from_secure_storage(input.wallet_id.as_bytes())
+ let db_client = SecureStorageClient::open(DB_NAME)?;
+ let wallet = db_client
+ .get::<Wallet>(&input.wallet_id)
.map_err(|e| anyhow!("[+] Sign transaction: error: wallet not found:
{:?}", e))?;
- dbg_println!("[+] Sign transaction: secure object loaded");
+ dbg_println!("[+] Sign transaction: wallet loaded");
- let wallet: Wallet = secure_object.try_into()?;
let signature = wallet.sign_transaction(&input.hd_path,
&input.transaction)?;
dbg_println!("[+] Sign transaction: signature: {:?}", signature);
diff --git a/projects/web3/eth_wallet/ta/src/secure_storage.rs
b/projects/web3/eth_wallet/ta/src/secure_storage.rs
deleted file mode 100644
index 808adb7..0000000
--- a/projects/web3/eth_wallet/ta/src/secure_storage.rs
+++ /dev/null
@@ -1,106 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you 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.
-
-use anyhow::{bail, Result};
-use optee_utee::{DataFlag, ObjectStorageConstants, PersistentObject};
-
-pub fn save_in_secure_storage(obj_id: &[u8], data: &[u8]) -> Result<()> {
- let obj_data_flag = DataFlag::ACCESS_READ
- | DataFlag::ACCESS_WRITE
- | DataFlag::ACCESS_WRITE_META
- | DataFlag::OVERWRITE;
-
- let mut init_data: [u8; 0] = [0; 0];
- match PersistentObject::create(
- ObjectStorageConstants::Private,
- obj_id,
- obj_data_flag,
- None,
- &mut init_data,
- ) {
- Err(e) => {
- bail!("[-] {:?}: failed to create object: {:?}", &obj_id, e);
- }
-
- Ok(mut object) => match object.write(&data) {
- Ok(()) => {
- return Ok(());
- }
- Err(e_write) => {
- object.close_and_delete()?;
- std::mem::forget(object);
- bail!(
- "[-] {:?}: failed to write data to object: {:?}",
- &obj_id,
- e_write
- );
- }
- },
- }
-}
-
-pub fn load_from_secure_storage(obj_id: &[u8]) -> Result<Vec<u8>> {
- let mut buf = vec![0; 5000];
-
- match PersistentObject::open(
- ObjectStorageConstants::Private,
- obj_id,
- DataFlag::ACCESS_READ | DataFlag::SHARE_READ,
- ) {
- Err(e) => bail!("[-] {:?}: failed to open object: {:?}", &obj_id, e),
-
- Ok(object) => {
- let obj_info = object.info()?;
-
- if obj_info.data_size() > buf.len() {
- bail!("[-] {:?}: data size is too large", &obj_id);
- }
- let read_bytes = match object.read(&mut buf) {
- Ok(read_bytes) => read_bytes,
- Err(e) => {
- bail!("[-] {:?}: failed to read data: {:?}", &obj_id, e);
- }
- };
-
- if read_bytes != obj_info.data_size() as u32 {
- bail!("[-] {:?}: failed to read data", &obj_id);
- }
-
- buf.truncate(read_bytes as usize);
- }
- }
-
- Ok(buf)
-}
-
-pub fn delete_from_secure_storage(obj_id: &[u8]) -> Result<()> {
- match PersistentObject::open(
- ObjectStorageConstants::Private,
- &mut obj_id.to_vec(),
- DataFlag::ACCESS_READ | DataFlag::ACCESS_WRITE_META,
- ) {
- Err(e) => {
- bail!("[-] {:?}: failed to open object: {:?}", &obj_id, e);
- }
-
- Ok(mut object) => {
- object.close_and_delete()?;
- std::mem::forget(object);
- return Ok(());
- }
- }
-}
diff --git a/projects/web3/eth_wallet/ta/src/wallet.rs
b/projects/web3/eth_wallet/ta/src/wallet.rs
index 4072061..895a5a9 100644
--- a/projects/web3/eth_wallet/ta/src/wallet.rs
+++ b/projects/web3/eth_wallet/ta/src/wallet.rs
@@ -25,6 +25,7 @@ use crate::hash::keccak_hash_to_bytes;
use ethereum_tx_sign::Transaction;
use optee_utee::Random;
use proto::EthTransaction;
+use secure_db::Storable;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Wallet {
@@ -32,6 +33,14 @@ pub struct Wallet {
entropy: Vec<u8>,
}
+impl Storable for Wallet {
+ type Key = Uuid;
+
+ fn unique_id(&self) -> Self::Key {
+ self.id
+ }
+}
+
impl Wallet {
pub fn new() -> Result<Self> {
let mut entropy = vec![0u8; 32];
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]