You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@teaclave.apache.org by yu...@apache.org on 2025/09/25 07:05:10 UTC
(teaclave) branch experimental-web3 created (now c212c339)
This is an automated email from the ASF dual-hosted git repository.
yuanz pushed a change to branch experimental-web3
in repository https://gitbox.apache.org/repos/asf/teaclave.git
at c212c339 experimental-web3: add wallet-gateway
This branch includes the following new commits:
new c212c339 experimental-web3: add wallet-gateway
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org
(teaclave) 01/01: experimental-web3: add wallet-gateway
Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
yuanz pushed a commit to branch experimental-web3
in repository https://gitbox.apache.org/repos/asf/teaclave.git
commit c212c33971ba6518816cf617c247c5192450d2f5
Author: Yuan Zhuang <yu...@apache.org>
AuthorDate: Thu Sep 25 07:03:51 2025 +0000
experimental-web3: add wallet-gateway
---
vm/wallet-gateway/Cargo.toml | 29 +
vm/wallet-gateway/abi/erc20_abi.json | 1 +
vm/wallet-gateway/api-server/Cargo.toml | 53 +
vm/wallet-gateway/api-server/Dockerfile | 39 +
vm/wallet-gateway/api-server/src/main.rs | 1010 +++++++++++++++++
vm/wallet-gateway/authority-server/Cargo.toml | 59 +
vm/wallet-gateway/authority-server/Dockerfile | 39 +
.../authority-server/src/auth_data.rs | 37 +
vm/wallet-gateway/authority-server/src/config.rs | 62 ++
.../authority-server/src/console_user.rs | 107 ++
.../authority-server/src/console_wallet_info.rs | 53 +
vm/wallet-gateway/authority-server/src/error.rs | 49 +
.../authority-server/src/file_utils.rs | 72 ++
vm/wallet-gateway/authority-server/src/main.rs | 1114 +++++++++++++++++++
.../authority-server/src/state_manager.rs | 544 ++++++++++
.../authority-server/src/tee_status_for_client.rs | 45 +
vm/wallet-gateway/authority/Cargo.toml | 42 +
vm/wallet-gateway/authority/src/device_registry.rs | 520 +++++++++
vm/wallet-gateway/authority/src/lib.rs | 22 +
vm/wallet-gateway/authority/src/user_registry.rs | 140 +++
vm/wallet-gateway/certs/scripts/generate_certs.sh | 53 +
vm/wallet-gateway/certs/scripts/install_certs.sh | 54 +
vm/wallet-gateway/config/Cargo.toml | 33 +
.../config/runtime_config_example.toml | 70 ++
vm/wallet-gateway/config/src/lib.rs | 28 +
vm/wallet-gateway/config/src/runtime.rs | 125 +++
vm/wallet-gateway/credential-manager/Cargo.toml | 35 +
vm/wallet-gateway/credential-manager/src/lib.rs | 198 ++++
vm/wallet-gateway/db-manager/Cargo.toml | 39 +
.../db-manager/src/db_compatible_client.rs | 99 ++
vm/wallet-gateway/db-manager/src/lib.rs | 23 +
.../db-manager/src/local_service_client.rs | 172 +++
vm/wallet-gateway/db-manager/src/storage_client.rs | 93 ++
vm/wallet-gateway/db-service/Cargo.toml | 34 +
vm/wallet-gateway/db-service/Dockerfile | 39 +
vm/wallet-gateway/db-service/src/main.rs | 202 ++++
vm/wallet-gateway/env.list | 23 +
vm/wallet-gateway/net/Cargo.toml | 41 +
vm/wallet-gateway/net/src/endpoints/asset_price.rs | 89 ++
vm/wallet-gateway/net/src/endpoints/btc_rpc.rs | 150 +++
vm/wallet-gateway/net/src/endpoints/eth_payment.rs | 162 +++
vm/wallet-gateway/net/src/endpoints/eth_rpc.rs | 297 +++++
vm/wallet-gateway/net/src/endpoints/mail.rs | 76 ++
vm/wallet-gateway/net/src/endpoints/mod.rs | 23 +
.../net/src/endpoints/params/erc20.rs | 32 +
vm/wallet-gateway/net/src/endpoints/params/gas.rs | 85 ++
.../net/src/endpoints/params/infura.rs | 99 ++
vm/wallet-gateway/net/src/endpoints/params/mod.rs | 27 +
.../net/src/endpoints/params/payment.rs | 88 ++
vm/wallet-gateway/net/src/endpoints/params/utxo.rs | 34 +
vm/wallet-gateway/net/src/lib.rs | 25 +
vm/wallet-gateway/notification/Cargo.toml | 39 +
vm/wallet-gateway/notification/src/email_event.rs | 53 +
vm/wallet-gateway/notification/src/email_task.rs | 33 +
.../notification/src/email_template.rs | 260 +++++
vm/wallet-gateway/notification/src/lib.rs | 20 +
vm/wallet-gateway/share/attestation/Cargo.toml | 36 +
vm/wallet-gateway/share/attestation/src/cert.rs | 485 +++++++++
vm/wallet-gateway/share/attestation/src/date.rs | 315 ++++++
vm/wallet-gateway/share/attestation/src/lib.rs | 24 +
.../share/attestation/src/report_verifier.rs | 217 ++++
vm/wallet-gateway/share/attestation/src/sign.rs | 211 ++++
vm/wallet-gateway/share/attestation/src/utils.rs | 140 +++
vm/wallet-gateway/share/attestation/src/verify.rs | 109 ++
vm/wallet-gateway/share/basic_utils/Cargo.toml | 28 +
vm/wallet-gateway/share/basic_utils/src/hash.rs | 38 +
vm/wallet-gateway/share/basic_utils/src/lib.rs | 26 +
vm/wallet-gateway/share/basic_utils/src/random.rs | 36 +
vm/wallet-gateway/share/basic_utils/src/time.rs | 32 +
vm/wallet-gateway/share/crypto/Cargo.toml | 28 +
vm/wallet-gateway/share/crypto/src/aead.rs | 201 ++++
vm/wallet-gateway/share/crypto/src/ecdsa.rs | 103 ++
vm/wallet-gateway/share/crypto/src/lib.rs | 21 +
vm/wallet-gateway/share/proto/Cargo.toml | 35 +
vm/wallet-gateway/share/proto/src/device.rs | 107 ++
vm/wallet-gateway/share/proto/src/lib.rs | 88 ++
vm/wallet-gateway/share/proto/src/transaction.rs | 94 ++
vm/wallet-gateway/share/proto/src/wallet.rs | 56 +
vm/wallet-gateway/share/types/Cargo.toml | 51 +
.../share/types/src/external/account/btc.rs | 167 +++
.../share/types/src/external/account/eth.rs | 44 +
.../share/types/src/external/account/mod.rs | 102 ++
.../share/types/src/external/approval_chain.rs | 330 ++++++
.../types/src/external/approval_chain_basic.rs | 97 ++
.../share/types/src/external/asset_type.rs | 425 ++++++++
.../share/types/src/external/erc20.rs | 67 ++
.../share/types/src/external/external_address.rs | 142 +++
vm/wallet-gateway/share/types/src/external/mod.rs | 53 +
.../share/types/src/external/numeric.rs | 120 +++
.../share/types/src/external/operators_basic.rs | 60 ++
.../share/types/src/external/transfer.rs | 220 ++++
vm/wallet-gateway/share/types/src/external/tx.rs | 56 +
vm/wallet-gateway/share/types/src/external/user.rs | 56 +
.../share/types/src/external/viewers_basic.rs | 52 +
vm/wallet-gateway/share/types/src/lib.rs | 31 +
vm/wallet-gateway/share/types/src/serde_util.rs | 145 +++
vm/wallet-gateway/share/types/src/share/account.rs | 161 +++
.../share/types/src/share/address/btc.rs | 139 +++
.../share/types/src/share/address/eth.rs | 41 +
.../share/types/src/share/address/mod.rs | 19 +
.../share/types/src/share/approval_operations.rs | 32 +
.../share/types/src/share/basic_types.rs | 101 ++
vm/wallet-gateway/share/types/src/share/ck_hash.rs | 42 +
vm/wallet-gateway/share/types/src/share/device.rs | 68 ++
vm/wallet-gateway/share/types/src/share/mod.rs | 71 ++
vm/wallet-gateway/share/types/src/share/network.rs | 233 ++++
.../share/types/src/share/ta_approval_chain.rs | 192 ++++
.../types/src/share/ta_approval_chain_basic.rs | 76 ++
.../share/types/src/share/ta_operators_basic.rs | 52 +
.../share/types/src/share/ta_user_info.rs | 64 ++
.../share/types/src/share/tee_config.rs | 63 ++
.../share/types/src/share/tee_status.rs | 70 ++
vm/wallet-gateway/share/types/src/share/tx/btc.rs | 111 ++
vm/wallet-gateway/share/types/src/share/tx/eth.rs | 79 ++
vm/wallet-gateway/share/types/src/share/tx/mod.rs | 87 ++
.../share/types/src/share/tx/multichain.rs | 51 +
vm/wallet-gateway/share/types/src/share/user.rs | 128 +++
vm/wallet-gateway/share/types/src/share/wallet.rs | 84 ++
vm/wallet-gateway/share/types/src/share/xpub.rs | 93 ++
vm/wallet-gateway/share/types/src/storable.rs | 50 +
vm/wallet-gateway/share/types/src/trust/mod.rs | 38 +
.../share/types/src/trust/tee_device_info.rs | 37 +
.../share/types/src/trust/tee_wallet.rs | 196 ++++
vm/wallet-gateway/share/types/src/trust/tx/btc.rs | 146 +++
vm/wallet-gateway/share/types/src/trust/tx/mod.rs | 19 +
.../share/types/src/trust/tx/tee_tx.rs | 113 ++
.../share/types/src/trust/wallet_secret.rs | 75 ++
.../share/types/src/trust/xpriv/btc.rs | 158 +++
.../share/types/src/trust/xpriv/eth.rs | 44 +
.../share/types/src/trust/xpriv/master.rs | 177 +++
.../share/types/src/trust/xpriv/mod.rs | 20 +
vm/wallet-gateway/storable/Cargo.toml | 37 +
.../storable/src/account_to_wallet.rs | 59 +
vm/wallet-gateway/storable/src/address_book.rs | 98 ++
vm/wallet-gateway/storable/src/balance.rs | 88 ++
vm/wallet-gateway/storable/src/committed_config.rs | 47 +
vm/wallet-gateway/storable/src/console/mod.rs | 19 +
vm/wallet-gateway/storable/src/console/wallet.rs | 182 ++++
vm/wallet-gateway/storable/src/credential.rs | 101 ++
vm/wallet-gateway/storable/src/currency.rs | 49 +
vm/wallet-gateway/storable/src/delegation.rs | 84 ++
vm/wallet-gateway/storable/src/device_info.rs | 192 ++++
vm/wallet-gateway/storable/src/fee.rs | 43 +
vm/wallet-gateway/storable/src/gas_price.rs | 183 ++++
vm/wallet-gateway/storable/src/legacy_tx.rs | 158 +++
vm/wallet-gateway/storable/src/lib.rs | 70 ++
vm/wallet-gateway/storable/src/nickname.rs | 118 ++
vm/wallet-gateway/storable/src/pending_tx.rs | 74 ++
vm/wallet-gateway/storable/src/received_payment.rs | 91 ++
vm/wallet-gateway/storable/src/subscription.rs | 55 +
vm/wallet-gateway/storable/src/synced_wallet.rs | 110 ++
vm/wallet-gateway/storable/src/tee_status.rs | 51 +
vm/wallet-gateway/storable/src/tx_history.rs | 118 ++
vm/wallet-gateway/storable/src/user_info.rs | 278 +++++
vm/wallet-gateway/storable/src/utxo_record.rs | 90 ++
vm/wallet-gateway/task-exec/Cargo.toml | 43 +
vm/wallet-gateway/task-exec/src/lib.rs | 68 ++
vm/wallet-gateway/task-runner-normal/Cargo.toml | 40 +
vm/wallet-gateway/task-runner-normal/Dockerfile | 39 +
vm/wallet-gateway/task-runner-normal/src/main.rs | 197 ++++
.../task-runner-normal/src/task/asset_price.rs | 59 +
.../task-runner-normal/src/task/balance.rs | 220 ++++
.../task-runner-normal/src/task/email_notify.rs | 494 +++++++++
.../task-runner-normal/src/task/gas_price.rs | 144 +++
.../task-runner-normal/src/task/mod.rs | 30 +
.../src/task/received_payment.rs | 463 ++++++++
.../task-runner-normal/src/task/sync_utxos.rs | 72 ++
vm/wallet-gateway/task-runner-tee/Cargo.toml | 42 +
vm/wallet-gateway/task-runner-tee/Dockerfile | 39 +
vm/wallet-gateway/task-runner-tee/src/main.rs | 153 +++
vm/wallet-gateway/task-runner-tee/src/task/mod.rs | 24 +
.../task-runner-tee/src/task/sync_tee_status.rs | 77 ++
.../task-runner-tee/src/task/sync_wallets.rs | 204 ++++
.../task-runner-tee/src/task/tx_delegation.rs | 287 +++++
vm/wallet-gateway/tls-client-processing/Cargo.toml | 38 +
vm/wallet-gateway/tls-client-processing/src/lib.rs | 222 ++++
vm/wallet-gateway/types-client/Cargo.toml | 31 +
.../types-client/src/additional_info.rs | 38 +
.../types-client/src/approval_chain.rs | 87 ++
vm/wallet-gateway/types-client/src/balance.rs | 45 +
vm/wallet-gateway/types-client/src/fee.rs | 42 +
vm/wallet-gateway/types-client/src/lib.rs | 34 +
.../types-client/src/received_payment.rs | 85 ++
vm/wallet-gateway/types-client/src/transfer.rs | 193 ++++
vm/wallet-gateway/types-client/src/tx.rs | 187 ++++
vm/wallet-gateway/types-client/src/wallet.rs | 135 +++
vm/wallet-gateway/utils/Cargo.toml | 33 +
vm/wallet-gateway/utils/src/lib.rs | 18 +
vm/wallet-gateway/utils/src/logger.rs | 40 +
vm/wallet-gateway/webapi/Cargo.toml | 69 ++
vm/wallet-gateway/webapi/src/auth_data.rs | 37 +
vm/wallet-gateway/webapi/src/coin_selection.rs | 239 ++++
vm/wallet-gateway/webapi/src/config.rs | 127 +++
vm/wallet-gateway/webapi/src/error.rs | 49 +
vm/wallet-gateway/webapi/src/lib.rs | 29 +
vm/wallet-gateway/webapi/src/state_manager.rs | 1138 ++++++++++++++++++++
vm/wallet-gateway/webapi/src/tx_transfer.rs | 373 +++++++
197 files changed, 23147 insertions(+)
diff --git a/vm/wallet-gateway/Cargo.toml b/vm/wallet-gateway/Cargo.toml
new file mode 100644
index 00000000..e253861f
--- /dev/null
+++ b/vm/wallet-gateway/Cargo.toml
@@ -0,0 +1,29 @@
+# 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.
+
+[workspace]
+members = [
+ "api-server",
+ "authority-server",
+ "db-service",
+ "task-runner-normal",
+ "task-runner-tee",
+]
+workspace.resolver = "2"
+
+[profile.release]
+lto = true
diff --git a/vm/wallet-gateway/abi/erc20_abi.json b/vm/wallet-gateway/abi/erc20_abi.json
new file mode 100644
index 00000000..6f8bda21
--- /dev/null
+++ b/vm/wallet-gateway/abi/erc20_abi.json
@@ -0,0 +1 @@
+[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable [...]
diff --git a/vm/wallet-gateway/api-server/Cargo.toml b/vm/wallet-gateway/api-server/Cargo.toml
new file mode 100644
index 00000000..1a2f41c5
--- /dev/null
+++ b/vm/wallet-gateway/api-server/Cargo.toml
@@ -0,0 +1,53 @@
+# 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.
+
+[package]
+name = "api-server"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+actix-web = { version = "4.3" }
+actix-web-lab = "0.19"
+actix-files = "0.6"
+actix-cors = "0.6"
+tokio-rustls = "=0.24.0"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+env_logger = "0.10"
+log = "0.4"
+rustls = { version = "0.21", features = ["dangerous_configuration"]}
+rustls-pemfile = "1"
+anyhow = "1.0"
+thiserror = "1.0"
+uuid = { version = "=1.3.0", features = ["serde", "v4"] }
+hex = { version = "0.4", features = ["serde"] }
+serde-hex = "0.1.0"
+serde_derive = "1.0"
+reqwest = { version = "0.11.18", features = ["json"] }
+bincode = "1.3.3"
+url = { version = "2.1.1", features = ["serde"] }
+oauth2 = "4.4"
+
+webapi = { path = "../webapi" }
+client-info = { path = "../types-client" }
+tls-client-processing = { path = "../tls-client-processing" }
+proto = { path = "../share/proto" }
+ck_config = { path = "../config" }
+types = { path = "../share/types" }
+storable = { path = "../storable" }
+utils = { path = "../utils" }
diff --git a/vm/wallet-gateway/api-server/Dockerfile b/vm/wallet-gateway/api-server/Dockerfile
new file mode 100644
index 00000000..71ae3628
--- /dev/null
+++ b/vm/wallet-gateway/api-server/Dockerfile
@@ -0,0 +1,39 @@
+# 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.
+
+# Pull the Rust Docker image
+FROM rust:1.82 as builder
+
+# Install Clang
+RUN apt-get update && apt-get install -y \
+ clang
+
+# Create a new empty shell project
+WORKDIR /wallet-gateway
+COPY . .
+
+# Build the project
+RUN cargo install --path ./api-server
+
+# Start a new, final image
+FROM rust:1.82-slim
+
+# Copy over the binary from the builder phase
+COPY --from=builder /usr/local/cargo/bin/api-server /usr/local/bin/api-server
+
+# Run the binary
+CMD ["api-server"]
diff --git a/vm/wallet-gateway/api-server/src/main.rs b/vm/wallet-gateway/api-server/src/main.rs
new file mode 100644
index 00000000..a35ce1e2
--- /dev/null
+++ b/vm/wallet-gateway/api-server/src/main.rs
@@ -0,0 +1,1010 @@
+// 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 actix_web::{
+ http::header::ContentType, middleware, post, web, App, HttpRequest, HttpResponse, HttpServer,
+ Result,
+};
+use anyhow::anyhow;
+use client_info::{
+ AdditionalInfoForClient, ApprovalStageInfo, ClientTxTransfer, FeeEstimationRequest,
+ FeeEstimationResponse, HistoryTxInfo, PendingTxInfo, TxHistoryReceivedPayment,
+ WalletInfoForClient,
+};
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::path::Path;
+use std::sync::Arc;
+use storable::address_book::{AddressBookEntry, AddressName};
+use storable::delegation::DelegationInfo;
+use storable::nickname::{NicknameKey, NicknameValue};
+use storable::pending_tx::PendingTx;
+use storable::user_info::User;
+use types::external::ClientExternalAddress;
+use types::share::{TransactionID, WalletID};
+use utils::logger::setup_logger;
+
+use webapi::*;
+
+/// simple handle
+async fn index(_req: HttpRequest) -> HttpResponse {
+ HttpResponse::Ok().content_type(ContentType::html()).body(
+ "<!DOCTYPE html><html><body>\
+ <p>Welcome to your TLS-secured homepage!</p>\
+ </body></html>",
+ )
+}
+
+fn shared_read_ref(req: &HttpRequest) -> Result<&SharedStateManager> {
+ let shared_state = req
+ .app_data::<web::Data<Arc<SharedStateManager>>>()
+ .ok_or_else(|| {
+ log::error!("shared_read_ref error: {:?}", anyhow!("no shared state"));
+ actix_web::error::ErrorInternalServerError("no shared state")
+ })?;
+ Ok(shared_state.get_ref())
+}
+
+macro_rules! authenticate {
+ ($st :expr, $auth_data :expr) => {
+ match $st.authenticate($auth_data).await {
+ Ok(operator) => operator,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ }
+ };
+}
+
+// to avoid code duplication
+macro_rules! get_additional_info {
+ ($st :expr, $transfer_info :expr) => {
+ match $st.get_additional_info($transfer_info).await {
+ Ok((from_info, to_info)) => (from_info, to_info),
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ }
+ };
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxCreateRequest {
+ auth_data: AuthData,
+ tx_transfer: ClientTxTransfer,
+ address_name: AddressBookEntry,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxCreateResponse {
+ tx_id: TransactionID,
+}
+
+impl TxCreateResponse {
+ fn new(tx_id: TransactionID) -> Self {
+ Self { tx_id }
+ }
+}
+
+#[post("/tx/create")]
+async fn tx_create(
+ request: web::Json<TxCreateRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxCreateResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let operator = authenticate!(st, &request.auth_data);
+
+ let tx_id = match st
+ .create_tx(operator, request.tx_transfer.clone(), &request.address_name)
+ .await
+ {
+ Ok(tx_id) => tx_id,
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ let response = TxCreateResponse::new(tx_id);
+ Ok(web::Json(WebApiResult::Ok(response)))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxApproveRequest {
+ auth_data: AuthData,
+ tx_id: TransactionID,
+ approval_chain: Vec<ApprovalStageInfo>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxApproveResponse {
+ tx_id: TransactionID,
+}
+
+impl TxApproveResponse {
+ fn new(tx_id: TransactionID) -> Self {
+ Self { tx_id }
+ }
+}
+
+#[post("/tx/approve")]
+async fn tx_approve(
+ request: web::Json<TxApproveRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxApproveResponse>>> {
+ let request = request.into_inner();
+ let st = shared_read_ref(&req)?;
+ let approver = authenticate!(st, &request.auth_data);
+
+ let tx_id = match st
+ .approve_tx(&approver, &request.tx_id, request.approval_chain)
+ .await
+ {
+ Ok(tx) => tx,
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::info!(
+ "tx_approve: approver {:?} tx_id {:?}",
+ approver,
+ request.tx_id
+ );
+
+ let pending_tx_response = TxApproveResponse::new(tx_id);
+
+ Ok(web::Json(WebApiResult::Ok(pending_tx_response)))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxRejectRequest {
+ auth_data: AuthData,
+ tx_id: TransactionID,
+ approval_chain: Vec<ApprovalStageInfo>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxRejectResponse {
+ tx_id: TransactionID,
+}
+
+impl TxRejectResponse {
+ fn new(tx_id: TransactionID) -> Self {
+ Self { tx_id }
+ }
+}
+
+#[post("/tx/reject")]
+async fn tx_reject(
+ request: web::Json<TxRejectRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxRejectResponse>>> {
+ let request = request.into_inner();
+ let st = shared_read_ref(&req)?;
+ let approver = authenticate!(st, &request.auth_data);
+
+ let tx_id = match st
+ .reject_tx(&approver, &request.tx_id, request.approval_chain)
+ .await
+ {
+ Ok(tx) => tx,
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+
+ log::info!(
+ "tx_reject: approver {:?} tx_id {:?}",
+ approver,
+ request.tx_id
+ );
+
+ Ok(web::Json(WebApiResult::Ok(TxRejectResponse::new(tx_id))))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxRecallRequest {
+ auth_data: AuthData,
+ tx_id: TransactionID,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxRecallResponse {
+ tx_id: TransactionID,
+}
+
+impl TxRecallResponse {
+ fn new(tx_id: TransactionID) -> Self {
+ Self { tx_id }
+ }
+}
+
+#[post("/tx/recall")]
+async fn tx_recall(
+ request: web::Json<TxRecallRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxRecallResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let operator = authenticate!(st, &request.auth_data);
+
+ log::info!(
+ "tx_recall: operator {:?} tx_id {:?}",
+ operator,
+ request.tx_id
+ );
+ let tx_id = match st.recall_tx(&operator, &request.tx_id).await {
+ Ok(tx_id) => tx_id,
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+
+ Ok(web::Json(WebApiResult::Ok(TxRecallResponse::new(tx_id))))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[serde(tag = "pendingTxStatus")]
+enum PendingTxResponse {
+ PendingForApproval(PendingTxInfo),
+ ReadyForSigning(PendingTxInfo),
+ DelegationStarted(PendingTxInfo),
+ DelegationExpired(PendingTxInfo),
+ RejectedByApprover(PendingTxInfo),
+}
+impl PendingTxResponse {
+ pub fn new(
+ pending_tx: PendingTx,
+ from_info: AdditionalInfoForClient,
+ to_info: AdditionalInfoForClient,
+ ) -> Self {
+ match pending_tx {
+ PendingTx::PendingForApproval(tx) => {
+ PendingTxResponse::PendingForApproval(PendingTxInfo::new(tx, from_info, to_info))
+ }
+ PendingTx::ReadyForSigning(tx) => {
+ PendingTxResponse::ReadyForSigning(PendingTxInfo::new(tx, from_info, to_info))
+ }
+ PendingTx::DelegationStarted(tx) => {
+ PendingTxResponse::DelegationStarted(PendingTxInfo::new(tx, from_info, to_info))
+ }
+ PendingTx::DelegationExpired(tx) => {
+ PendingTxResponse::DelegationExpired(PendingTxInfo::new(tx, from_info, to_info))
+ }
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxListPendingRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxListPendingResponse {
+ txs: Vec<PendingTxResponse>,
+}
+
+impl TxListPendingResponse {
+ fn new(txs: Vec<PendingTxResponse>) -> Self {
+ Self { txs }
+ }
+}
+
+#[post("/tx/list/pending")]
+async fn tx_list_pending(
+ request: web::Json<TxListPendingRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxListPendingResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ let mut txs = match st.list_pending_tx_for_user(&user).await {
+ Ok(txs) => txs,
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ txs.sort_by_key(|p| std::cmp::Reverse(p.tx().get_created_at()));
+
+ let mut items = Vec::new();
+ for pending_tx in txs {
+ let (from_info, to_info) = get_additional_info!(st, pending_tx.tx().transfer_info());
+ items.push(PendingTxResponse::new(pending_tx, from_info, to_info));
+ }
+
+ let response = TxListPendingResponse::new(items);
+ Ok(web::Json(WebApiResult::Ok(response)))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxListIdRequest {
+ auth_data: AuthData,
+ tx_id: TransactionID,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[serde(tag = "status")]
+enum TxListIdResponse {
+ Pending(PendingTxResponse),
+ History(HistoryTxInfo),
+}
+
+#[post("/tx/list/id")]
+async fn tx_list_id(
+ request: web::Json<TxListIdRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxListIdResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ match st
+ .get_pending_tx_for_user(user.get_email(), &request.tx_id)
+ .await
+ {
+ Ok(tx) => {
+ let (from_info, to_info) = get_additional_info!(st, tx.tx().transfer_info());
+ let pending_tx_response = PendingTxResponse::new(tx, from_info, to_info);
+
+ Ok(web::Json(WebApiResult::Ok(TxListIdResponse::Pending(
+ pending_tx_response,
+ ))))
+ }
+ Err(e) => {
+ log::info!(
+ "get_pending_tx_for_user error: {:?}, trying to load from history db",
+ e
+ );
+ match st.get_signed_tx_for_user(&user, &request.tx_id).await {
+ Ok(tx) => {
+ let explorer_base_url = tx
+ .tx
+ .transfer_info
+ .amount
+ .asset_type()
+ .as_ck_network(st.network_config().network_type)
+ .explorer_base_url();
+ let (from_info, to_info) = get_additional_info!(st, tx.tx.transfer_info());
+ let response = TxListIdResponse::History(
+ HistoryTxInfo::new(tx, explorer_base_url, from_info, to_info).map_err(
+ |e| {
+ log::error!("Failed to create HistoryTxInfo: {}", e);
+ actix_web::error::ErrorInternalServerError(e)
+ },
+ )?,
+ );
+ Ok(web::Json(WebApiResult::Ok(response)))
+ }
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxListHistoryRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxListHistoryResponse {
+ txs: Vec<HistoryTxInfo>,
+}
+
+impl TxListHistoryResponse {
+ fn new(txs: Vec<HistoryTxInfo>) -> Self {
+ Self { txs }
+ }
+}
+
+#[post("/tx/list/history")]
+async fn tx_list_history(
+ request: web::Json<TxListHistoryRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxListHistoryResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ let mut history_vec = match st.list_signed_tx_for_user(&user).await {
+ Ok(history_vec) => history_vec,
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+
+ // sort the HistoryTx by created_at
+ history_vec.sort_by_key(|p| std::cmp::Reverse(p.tx().get_created_at()));
+
+ let mut items = Vec::new();
+ for tx_history in history_vec {
+ let explorer_base_url = tx_history
+ .tx
+ .transfer_info()
+ .amount
+ .asset_type()
+ .as_ck_network(st.network_config().network_type)
+ .explorer_base_url();
+ let (from_info, to_info) = get_additional_info!(st, tx_history.tx.transfer_info());
+ items.push(
+ HistoryTxInfo::new(tx_history, explorer_base_url, from_info, to_info).map_err(|e| {
+ log::error!("Failed to create HistoryTxInfo: {}", e);
+ actix_web::error::ErrorInternalServerError(e)
+ })?,
+ );
+ }
+ let response = TxListHistoryResponse::new(items);
+ Ok(web::Json(WebApiResult::Ok(response)))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxHistoryReceivedRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxHistoryReceivedResponse {
+ txs: Vec<TxHistoryReceivedPayment>,
+}
+impl TxHistoryReceivedResponse {
+ fn new(txs: Vec<TxHistoryReceivedPayment>) -> Self {
+ Self { txs }
+ }
+}
+
+#[post("/tx/list/history/received")]
+async fn tx_list_history_received(
+ request: web::Json<TxHistoryReceivedRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<TxHistoryReceivedResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ let received_payments = match st.gather_user_history_tx(&user).await {
+ Ok(received_payments) => received_payments,
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+
+ Ok(web::Json(WebApiResult::Ok(TxHistoryReceivedResponse::new(
+ received_payments,
+ ))))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletListRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletListResponse {
+ wallets: Vec<WalletInfoForClient>,
+}
+
+impl WalletListResponse {
+ fn new(wallets: Vec<WalletInfoForClient>) -> Self {
+ Self { wallets }
+ }
+}
+
+#[post("/wallet/list")]
+async fn wallet_list(
+ request: web::Json<WalletListRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletListResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ match st.gather_user_wallets_info(&user).await {
+ Ok(wallets_info) => {
+ let response = WalletListResponse::new(wallets_info);
+ Ok(web::Json(WebApiResult::Ok(response)))
+ }
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserSetNicknameRequest {
+ auth_data: AuthData,
+ key: NicknameKey,
+ nickname: Option<NicknameValue>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserSetNicknameResponse {}
+
+#[post("/user/nickname/set")]
+async fn user_set_nickname(
+ request: web::Json<UserSetNicknameRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<UserSetNicknameResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ let request = request.into_inner();
+ match request.nickname {
+ Some(nickname) => {
+ st.set_nickname(&user, request.key, nickname)
+ .await
+ .map_err(|e| {
+ log::error!("set_nickname error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
+ })?;
+ }
+ None => {
+ st.remove_nickname(&user, &request.key).await.map_err(|e| {
+ log::error!("remove_nickname error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
+ })?;
+ }
+ }
+
+ Ok(web::Json(WebApiResult::Ok(UserSetNicknameResponse {})))
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserListNicknameRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserListNicknameResponse {
+ nicknames: HashMap<NicknameKey, NicknameValue>,
+}
+
+#[post("/user/nickname/list")]
+async fn user_list_nickname(
+ request: web::Json<UserListNicknameRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<UserListNicknameResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ match st.get_all_nickname_for_user(&user).await {
+ Ok(nicknames) => {
+ let response = UserListNicknameResponse { nicknames };
+ Ok(web::Json(WebApiResult::Ok(response)))
+ }
+ Err(e) => {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletSubscribeRequest {
+ auth_data: AuthData,
+ wallet_id: WalletID,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletSubscribeResponse {}
+
+#[post("/wallet/subscribe")]
+async fn wallet_subscribe(
+ request: web::Json<WalletSubscribeRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletSubscribeResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ match st.subscribe(&user, &request.wallet_id).await {
+ Ok(_) => {
+ log::info!(
+ "subscribed account {:?} for user {:?}",
+ &request.wallet_id,
+ &user.get_email()
+ );
+ Ok(web::Json(WebApiResult::Ok(WalletSubscribeResponse {})))
+ }
+ Err(e) => {
+ log::error!("subscribe error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletUnsubscribeRequest {
+ auth_data: AuthData,
+ wallet_id: WalletID,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletUnsubscribeResponse {}
+
+#[post("/wallet/unsubscribe")]
+async fn wallet_unsubscribe(
+ request: web::Json<WalletUnsubscribeRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletUnsubscribeResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ match st.unsubscribe(&user, &request.wallet_id).await {
+ Ok(_) => {
+ log::info!(
+ "unsubscribed account {:?} for user {:?}",
+ &request.wallet_id,
+ &user.get_email()
+ );
+ Ok(web::Json(WebApiResult::Ok(WalletUnsubscribeResponse {})))
+ }
+ Err(e) => {
+ log::error!("unsubscribe error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletSubscribeAllRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletSubscribeAllResponse {}
+
+#[post("/wallet/subscribe/all")]
+async fn wallet_subscribe_all(
+ request: web::Json<WalletSubscribeAllRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletSubscribeAllResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ match st.subscribe_all_associated_wallets(&user).await {
+ Ok(_) => {
+ log::info!(
+ "subscribed all accounts for user {:?}",
+ &user.get_info().get_email()
+ );
+ Ok(web::Json(WebApiResult::Ok(WalletSubscribeAllResponse {})))
+ }
+ Err(e) => {
+ log::error!("subscribe_all error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletUnsubscribeAllRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletUnsubscribeAllResponse {}
+
+#[post("/wallet/unsubscribe/all")]
+async fn wallet_unsubscribe_all(
+ request: web::Json<WalletUnsubscribeAllRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletUnsubscribeAllResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = authenticate!(st, &request.auth_data);
+
+ match st.unsubscribe_all(&user).await {
+ Ok(_) => {
+ log::info!(
+ "unsubscribed all accounts for user {:?}",
+ &user.get_info().get_email()
+ );
+ Ok(web::Json(WebApiResult::Ok(WalletUnsubscribeAllResponse {})))
+ }
+ Err(e) => {
+ log::error!("unsubscribe_all error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxSignRequest {
+ auth_data: AuthData,
+ tx_id: TransactionID,
+ delegation_info: Option<DelegationInfo>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxFeeEstimateRequest {
+ auth_data: AuthData,
+ tx_info_for_gas: FeeEstimationRequest,
+}
+
+#[post("/tx/fee/estimate")]
+async fn tx_fee_estimate(
+ request: web::Json<TxFeeEstimateRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<FeeEstimationResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let _user: User = authenticate!(st, &request.auth_data);
+ let request = request.into_inner();
+
+ match st.estimate_tx_fee(request.tx_info_for_gas).await {
+ Ok(fee) => Ok(web::Json(WebApiResult::Ok(fee))),
+ Err(e) => {
+ log::error!("estimate_gas error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AddressBookAddRequest {
+ auth_data: AuthData,
+ address: ClientExternalAddress,
+ name: AddressName,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AddressBookAddResponse {
+ entry: AddressBookEntry,
+}
+
+#[post("/address-book/add")]
+async fn address_book_add(
+ request: web::Json<AddressBookAddRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<AddressBookAddResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = match st.authenticate(&request.auth_data).await {
+ Ok(user) => user,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+
+ match st
+ .add_address_book_entry(&user, &request.address, &request.name)
+ .await
+ {
+ Ok(entry) => Ok(web::Json(WebApiResult::Ok(AddressBookAddResponse {
+ entry,
+ }))),
+ Err(e) => {
+ log::error!("add_address_book_entry error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AddressBookUpdateRequest {
+ auth_data: AuthData,
+ existing_entry: AddressBookEntry,
+ new_name: Option<AddressName>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AddressBookUpdateResponse {}
+
+#[post("/address-book/update")]
+async fn address_book_update(
+ request: web::Json<AddressBookUpdateRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<AddressBookUpdateResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = match st.authenticate(&request.auth_data).await {
+ Ok(user) => user,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ match request.new_name {
+ Some(ref name) => {
+ // update name
+ match st
+ .update_address_book_entry(&user, &request.existing_entry, name)
+ .await
+ {
+ Ok(_) => Ok(web::Json(WebApiResult::Ok(AddressBookUpdateResponse {}))),
+ Err(e) => {
+ log::error!("update_address_book_entry error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+ }
+ None => {
+ // clear name
+ match st
+ .remove_address_book_entry(&user, &request.existing_entry)
+ .await
+ {
+ Ok(_) => Ok(web::Json(WebApiResult::Ok(AddressBookUpdateResponse {}))),
+ Err(e) => {
+ log::error!("remove_address_book_entry error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AddressBookListRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AddressBookListResponse {
+ entries: Vec<AddressBookEntry>,
+}
+
+#[post("/address-book/list")]
+async fn address_book_list(
+ request: web::Json<AddressBookListRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<AddressBookListResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let user: User = match st.authenticate(&request.auth_data).await {
+ Ok(user) => user,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+
+ match st.list_address_book_entries(&user).await {
+ Ok(entries) => Ok(web::Json(WebApiResult::Ok(AddressBookListResponse {
+ entries,
+ }))),
+ Err(e) => {
+ log::error!("list_address_book_entries error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+ use actix_cors::Cors;
+
+ // setup global config
+ let root_path = std::env::var("CK_ROOT_PATH").map_err(|e| {
+ log::error!("CK_ROOT_PATH error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e)
+ })?;
+ let webapi_config = WebapiConfig::new(
+ Path::new(&root_path),
+ Path::new("config/runtime_config.toml"),
+ )
+ .map_err(|e| {
+ log::error!("WebapiConfig::new() error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e)
+ })?;
+
+ // setup logger
+ setup_logger(&webapi_config.shared_state_config().log_path, "api-server")
+ .expect("Failed to initialize logger");
+
+ // shared state manager
+ let st = Arc::new(
+ SharedStateManager::new(webapi_config.shared_state_config())
+ .await
+ .map_err(|e| {
+ log::error!("SharedStateManager::new() error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e)
+ })?,
+ );
+
+ let app_state = web::Data::new(st.clone());
+
+ // start server
+ let http_server_config = webapi_config.http_server_config();
+ let ip = http_server_config.ip();
+ let port = http_server_config.port();
+ log::info!("starting HTTPS server at https://{}:{}", ip, port);
+
+ HttpServer::new(move || {
+ let cors = Cors::permissive();
+
+ App::new()
+ // enable logger
+ .wrap(middleware::Logger::default())
+ .wrap(cors)
+ .app_data(web::JsonConfig::default().limit(4096)) // <- limit size of the payload (global configuration)
+ .app_data(web::Data::clone(&app_state))
+ .service(web::resource("/index.html").to(index))
+ .service(wallet_list)
+ .service(wallet_subscribe)
+ .service(wallet_unsubscribe)
+ .service(wallet_subscribe_all)
+ .service(wallet_unsubscribe_all)
+ .service(user_set_nickname)
+ .service(user_list_nickname)
+ .service(tx_fee_estimate)
+ .service(tx_create)
+ .service(tx_approve)
+ .service(tx_reject)
+ .service(tx_recall)
+ .service(tx_list_pending)
+ .service(tx_list_id)
+ .service(tx_list_history)
+ .service(tx_list_history_received)
+ .service(address_book_add)
+ .service(address_book_list)
+ .service(address_book_update)
+ })
+ .bind((ip, port))?
+ .run()
+ .await
+}
diff --git a/vm/wallet-gateway/authority-server/Cargo.toml b/vm/wallet-gateway/authority-server/Cargo.toml
new file mode 100644
index 00000000..973df2c6
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/Cargo.toml
@@ -0,0 +1,59 @@
+# 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.
+
+[package]
+name = "authority-server"
+version = "0.1.0"
+edition = "2021"
+
+[features]
+default = []
+
+[dependencies]
+actix-web = { version = "4.3" }
+actix-web-lab = "0.19"
+actix-files = "0.6"
+actix-cors = "0.6"
+tokio-rustls = "=0.24.0"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+serde-hex = "0.1.0"
+serde_derive = "1.0"
+serde_with = "3.8"
+env_logger = "0.10"
+log = "0.4"
+#rustls = { version = "0.21", features = ["dangerous_configuration"]}
+#rustls-pemfile = "1"
+anyhow = "1.0"
+thiserror = "1.0"
+uuid = { version = "=1.3.0", features = ["serde", "v4"] }
+hex = { version = "0.4", features = ["serde"] }
+bincode = "1.3.3"
+url = { version = "2.1.1", features = ["serde"] }
+oauth2 = "4.4"
+base64 = "0.21"
+tokio = { version = "1.0", features = ["full"] }
+
+types = { path = "../share/types" }
+proto = { path = "../share/proto" }
+utils = { path = "../utils" }
+storable = { path = "../storable" }
+authority = { path = "../authority" }
+ck_config = { path = "../config" }
+tls-client-processing = { path = "../tls-client-processing" }
+db-manager = { path = "../db-manager" }
+credential-manager = { path = "../credential-manager" }
diff --git a/vm/wallet-gateway/authority-server/Dockerfile b/vm/wallet-gateway/authority-server/Dockerfile
new file mode 100644
index 00000000..5a28123f
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/Dockerfile
@@ -0,0 +1,39 @@
+# 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.
+
+# Pull the Rust Docker image
+FROM rust:1.82 as builder
+
+# Install Clang
+RUN apt-get update && apt-get install -y \
+ clang
+
+# Create a new empty shell project
+WORKDIR /wallet-gateway
+COPY . .
+
+# Build the project
+RUN cargo install --path ./authority-server
+
+# Start a new, final image
+FROM rust:1.82-slim
+
+# Copy over the binary from the builder phase
+COPY --from=builder /usr/local/cargo/bin/authority-server /usr/local/bin/authority-server
+
+# Run the binary
+CMD ["authority-server"]
diff --git a/vm/wallet-gateway/authority-server/src/auth_data.rs b/vm/wallet-gateway/authority-server/src/auth_data.rs
new file mode 100644
index 00000000..92e9577b
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/auth_data.rs
@@ -0,0 +1,37 @@
+// 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::Result;
+use serde::{Deserialize, Serialize};
+use types::external::Email;
+
+// a demo AuthData struct, please implement the real one for production
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AuthData {
+ access_token: String,
+ email: String,
+ id_token: String,
+}
+
+impl AuthData {
+ // important: for dev, we skip verifying token, for production please implement the verification
+ pub async fn get_authorized_email(&self, _auth_url: &url::Url) -> Result<Email> {
+ log::warn!("skip verifying token for dev");
+ self.email.clone().try_into()
+ }
+}
diff --git a/vm/wallet-gateway/authority-server/src/config.rs b/vm/wallet-gateway/authority-server/src/config.rs
new file mode 100644
index 00000000..0203f4b4
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/config.rs
@@ -0,0 +1,62 @@
+// 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 ck_config::RuntimeConfig;
+use std::{
+ net::IpAddr,
+ path::{Path, PathBuf},
+};
+use url::Url;
+
+pub struct AuthorityConfig {
+ pub cert_path: PathBuf, // certs: ca.cert, ca.der, ca.key
+ pub export_base_path: PathBuf, // export: device.cert, signed files
+ pub export_base_url: Url, // exported files for download
+ pub log_path: PathBuf, // log: log file
+ pub auth_service_url: Url,
+ pub db_server_url: Url,
+ pub ip: IpAddr,
+ pub port: u16,
+}
+impl AuthorityConfig {
+ pub fn new(root_path: &Path, config_file_path: &Path) -> Self {
+ let runtime_config = RuntimeConfig::from_toml(root_path.join(config_file_path))
+ .expect("failed to read runtime config");
+
+ Self {
+ cert_path: root_path.join(runtime_config.storage.certs_path),
+ export_base_path: root_path.join(runtime_config.storage.export_path),
+ export_base_url: runtime_config.storage.export_base_url,
+ log_path: root_path.join(runtime_config.storage.log_path),
+ auth_service_url: runtime_config.user_auth_info.auth_service_url,
+ db_server_url: runtime_config
+ .internal_endpoints
+ .db_service
+ .advertised_address,
+ ip: runtime_config
+ .internal_endpoints
+ .authority_server
+ .listen_address
+ .ip(),
+ port: runtime_config
+ .internal_endpoints
+ .authority_server
+ .listen_address
+ .port(),
+ }
+ }
+}
diff --git a/vm/wallet-gateway/authority-server/src/console_user.rs b/vm/wallet-gateway/authority-server/src/console_user.rs
new file mode 100644
index 00000000..5228c630
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/console_user.rs
@@ -0,0 +1,107 @@
+// 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, ensure, Result};
+use serde::{Deserialize, Serialize};
+use std::convert::TryFrom;
+use types::external::Email;
+
+const ADMIN_EMAIL: [&str; 1] = ["admin@ck.com"];
+
+#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq)]
+pub enum ConsoleUserRole {
+ Admin,
+ DeviceOperator,
+}
+
+#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq)]
+pub enum ConsoleUser {
+ Admin(Admin),
+ DeviceOperator(DeviceOperator),
+}
+impl ConsoleUser {
+ pub fn _get_info(&self) -> &ConsoleUserInfo {
+ match self {
+ ConsoleUser::Admin(admin) => &admin.0,
+ ConsoleUser::DeviceOperator(device_operator) => &device_operator.0,
+ }
+ }
+ pub fn get_role(&self) -> ConsoleUserRole {
+ match self {
+ ConsoleUser::Admin(_) => ConsoleUserRole::Admin,
+ ConsoleUser::DeviceOperator(_) => ConsoleUserRole::DeviceOperator,
+ }
+ }
+}
+impl TryFrom<ConsoleUserInfo> for ConsoleUser {
+ type Error = anyhow::Error;
+
+ fn try_from(user_info: ConsoleUserInfo) -> Result<Self> {
+ if user_info.is_admin() {
+ Ok(ConsoleUser::Admin(Admin(user_info)))
+ } else if user_info.is_device_operator() {
+ Ok(ConsoleUser::DeviceOperator(DeviceOperator(user_info)))
+ } else {
+ bail!("unknown role")
+ }
+ }
+}
+
+#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq)]
+pub struct ConsoleUserInfo {
+ pub email: Email,
+}
+impl ConsoleUserInfo {
+ pub fn new(email: Email) -> Self {
+ Self { email }
+ }
+ pub fn is_admin(&self) -> bool {
+ if ADMIN_EMAIL.contains(&self.email.0.as_str()) {
+ return true;
+ }
+ false
+ }
+ pub fn is_device_operator(&self) -> bool {
+ false
+ }
+}
+
+#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq)]
+pub struct Admin(pub ConsoleUserInfo);
+
+#[derive(Serialize, Deserialize, Debug, Hash, Eq, PartialEq)]
+pub struct DeviceOperator(pub ConsoleUserInfo);
+
+impl TryFrom<ConsoleUserInfo> for Admin {
+ type Error = anyhow::Error;
+
+ fn try_from(user_info: ConsoleUserInfo) -> Result<Self> {
+ ensure!(user_info.is_admin(), "not admin");
+ let admin = Admin(user_info);
+ Ok(admin)
+ }
+}
+
+impl TryFrom<ConsoleUserInfo> for DeviceOperator {
+ type Error = anyhow::Error;
+
+ fn try_from(user_info: ConsoleUserInfo) -> Result<Self> {
+ ensure!(user_info.is_device_operator(), "not device operator");
+ let device_operator = DeviceOperator(user_info);
+ Ok(device_operator)
+ }
+}
diff --git a/vm/wallet-gateway/authority-server/src/console_wallet_info.rs b/vm/wallet-gateway/authority-server/src/console_wallet_info.rs
new file mode 100644
index 00000000..983d6823
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/console_wallet_info.rs
@@ -0,0 +1,53 @@
+// 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 std::collections::HashSet;
+
+use serde::{Deserialize, Serialize};
+use storable::console::ConsoleWalletInfo;
+use types::external::{ApprovalChainBasic, OperatorsBasic, ViewersBasic};
+use types::share::{AccountId, DeviceID, WalletID};
+
+#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsoleWalletInfoForClient {
+ pub wallet_id: WalletID,
+ pub wallet_name: String,
+ pub account_address: Option<AccountId>,
+ pub created_by_device: DeviceID,
+ pub backed_up_by_devices: HashSet<DeviceID>,
+ pub approval_chain_basic: ApprovalChainBasic,
+ pub authorized_operators: OperatorsBasic,
+ pub viewers: ViewersBasic,
+ pub update_time: u64,
+}
+
+impl ConsoleWalletInfoForClient {
+ pub fn new(wallet_info_basic: ConsoleWalletInfo, account_address: Option<AccountId>) -> Self {
+ Self {
+ wallet_id: wallet_info_basic.wallet_id,
+ wallet_name: wallet_info_basic.wallet_name,
+ account_address,
+ created_by_device: wallet_info_basic.created_by_device,
+ backed_up_by_devices: wallet_info_basic.backed_up_by_devices,
+ approval_chain_basic: wallet_info_basic.approval_chain_basic,
+ authorized_operators: wallet_info_basic.authorized_operators,
+ viewers: wallet_info_basic.viewers,
+ update_time: wallet_info_basic.update_time,
+ }
+ }
+}
diff --git a/vm/wallet-gateway/authority-server/src/error.rs b/vm/wallet-gateway/authority-server/src/error.rs
new file mode 100644
index 00000000..199f4109
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/error.rs
@@ -0,0 +1,49 @@
+// 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 serde::{Deserialize, Serialize};
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[serde(tag = "result")]
+pub enum WebApiResult<R>
+where
+ R: Serialize,
+{
+ Ok(R),
+ Error(WebApiError),
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[serde(tag = "errorType")]
+pub enum WebApiError {
+ Unauthorized(ErrorMessage),
+ NotFound(ErrorMessage),
+ InternalError(ErrorMessage),
+ InvalidOperation(ErrorMessage),
+ UnknownError(ErrorMessage),
+}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ErrorMessage {
+ pub message: String,
+}
+impl ErrorMessage {
+ pub fn new(message: String) -> Self {
+ ErrorMessage { message }
+ }
+}
diff --git a/vm/wallet-gateway/authority-server/src/file_utils.rs b/vm/wallet-gateway/authority-server/src/file_utils.rs
new file mode 100644
index 00000000..c32f3273
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/file_utils.rs
@@ -0,0 +1,72 @@
+// 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::Result;
+use std::path::Path;
+use std::time::SystemTime;
+use url::Url;
+
+pub enum ExportedFileType {
+ Cert,
+ WalletInfo,
+ SignedBackupList,
+}
+impl ExportedFileType {
+ fn as_str(&self) -> &str {
+ match self {
+ Self::Cert => "cert",
+ Self::WalletInfo => "wallet_info",
+ Self::SignedBackupList => "signed_backup_list",
+ }
+ }
+}
+
+pub fn export_file(
+ export_base_path: &Path,
+ export_base_url: &Url,
+ id: impl Into<String>,
+ file_type: &ExportedFileType,
+ content: &[u8],
+ // if the file (serialized struct) has original timestamp, use it as filename
+ // otherwise use current timestamp
+ timestamp: Option<u64>,
+) -> Result<Url> {
+ let tms = match timestamp {
+ Some(t) => t,
+ None => SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)?
+ .as_secs(),
+ };
+ let file_name_prefix = format!("{}.{}.", Into::<String>::into(id), file_type.as_str(),);
+ // file name: $ID.$TYPE.$TIMESTAMP
+ let file_name_with_timestamp = format!("{}{}", file_name_prefix, tms);
+ std::fs::write(export_base_path.join(&file_name_with_timestamp), content)?;
+ // create symbolic link named as "$ID.$TYPE.latest"
+ let latest_file_name = format!("{}latest", file_name_prefix);
+ // remove symlink if it existd
+ if std::path::Path::new(&export_base_path.join(&latest_file_name)).exists() {
+ std::fs::remove_file(export_base_path.join(&latest_file_name))?;
+ }
+ std::os::unix::fs::symlink(
+ &file_name_with_timestamp,
+ export_base_path.join(&latest_file_name),
+ )?;
+ log::info!("symbolic link created: {}", latest_file_name);
+
+ let url = export_base_url.join(&latest_file_name)?;
+ Ok(url)
+}
diff --git a/vm/wallet-gateway/authority-server/src/main.rs b/vm/wallet-gateway/authority-server/src/main.rs
new file mode 100644
index 00000000..5a7a613a
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/main.rs
@@ -0,0 +1,1114 @@
+// 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 actix_web::{
+ http::header::ContentType, middleware, post, web, App, HttpRequest, HttpResponse, HttpServer,
+ Result,
+};
+use anyhow::anyhow;
+use console_user::ConsoleUserRole;
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use std::convert::TryInto;
+use std::path::Path;
+use std::sync::Arc;
+use url::Url;
+
+use storable::console::{CreateConsoleWalletInfo, UpdateConsoleWalletInfo};
+use storable::device_info::{BackupDeviceInfoBasic, DeviceInfoBasic};
+use storable::user_info::UserInfo;
+use types::external::Email;
+use types::share::{DeviceID, Role, UserID, WalletID};
+use utils::logger::setup_logger;
+
+mod error;
+use crate::error::{ErrorMessage, WebApiError, WebApiResult};
+mod state_manager;
+use crate::state_manager::SharedStateManager;
+mod auth_data;
+use crate::auth_data::AuthData;
+mod console_user;
+use crate::console_user::{Admin, ConsoleUser, ConsoleUserInfo};
+mod console_wallet_info;
+use crate::console_wallet_info::ConsoleWalletInfoForClient;
+mod config;
+mod file_utils;
+use crate::config::AuthorityConfig;
+mod tee_status_for_client;
+use crate::tee_status_for_client::TeeStatusForClient;
+
+/// simple handle
+async fn index(_req: HttpRequest) -> HttpResponse {
+ HttpResponse::Ok().content_type(ContentType::html()).body(
+ "<!DOCTYPE html><html><body>\
+ <p>Welcome to your TLS-secured homepage!</p>\
+ </body></html>",
+ )
+}
+
+fn shared_read_ref(req: &HttpRequest) -> Result<&SharedStateManager> {
+ let shared_state = req
+ .app_data::<web::Data<Arc<SharedStateManager>>>()
+ .ok_or_else(|| {
+ log::error!("shared_read_ref error: {:?}", anyhow!("no shared state"));
+ actix_web::error::ErrorInternalServerError("no shared state")
+ })?;
+ Ok(shared_state.get_ref())
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsoleUserRoleRequest {
+ auth_data: AuthData, // the user logged in
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsoleUserRoleResponse {
+ console_roles: HashSet<ConsoleUserRole>,
+}
+
+#[post("/console-user/role")]
+async fn console_user_role(
+ request: web::Json<ConsoleUserRoleRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<ConsoleUserRoleResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let console_roles: HashSet<ConsoleUserRole> = match st.authenticate(&request.auth_data).await {
+ Ok(email) => {
+ log::debug!("console_user_role: login as {:?}", email);
+ match TryInto::<ConsoleUser>::try_into(ConsoleUserInfo::new(email)) {
+ Ok(console_user) => HashSet::from_iter(vec![console_user.get_role()]),
+ Err(e) => {
+ log::warn!("user is not console user: {:?}", e);
+ HashSet::new()
+ }
+ }
+ }
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ let response = ConsoleUserRoleResponse { console_roles };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+}
+
+// user registry input
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
+pub struct UserBasicInfo {
+ pub name: String,
+ pub email: Email,
+ pub roles: HashSet<Role>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserRegisterRequest {
+ auth_data: AuthData,
+ #[serde(flatten)]
+ user_basic_info: UserBasicInfo,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserRegisterResponse {
+ #[serde(flatten)]
+ user_info: UserInfo,
+}
+
+#[post("/app-user/register")]
+async fn user_register(
+ request: web::Json<UserRegisterRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<UserRegisterResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("user_register: login as {:?}", admin);
+
+ match st.register_user(&request.user_basic_info).await {
+ Ok(info) => {
+ let response = UserRegisterResponse { user_info: info };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("user_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserRoleAppendRequest {
+ auth_data: AuthData, // the user logged in
+ email: Email, // the user to be modified
+ roles: HashSet<Role>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserRoleAppendResponse {
+ #[serde(flatten)]
+ user_info: UserInfo,
+}
+
+#[post("/app-user/role/append")]
+async fn user_role_append(
+ request: web::Json<UserRoleAppendRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<UserRoleAppendResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("user_role_append: login as {:?}", admin);
+ match st.append_role(&request.email, &request.roles).await {
+ Ok(info) => {
+ let response = UserRoleAppendResponse { user_info: info };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("user_role_append error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserInfoGetRequest {
+ auth_data: AuthData,
+ email: Email,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserInfoGetResponse {
+ #[serde(flatten)]
+ user_info: UserInfo,
+}
+
+#[post("/app-user/info/get")]
+async fn user_info_get(
+ request: web::Json<UserInfoGetRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<UserInfoGetResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("user_info_get: login as {:?}", admin);
+ match st.get_user_info(&request.email).await {
+ Ok(info) => {
+ let response = UserInfoGetResponse { user_info: info };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("user_info_get error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserInfoGetAllRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserInfoGetAllResponse {
+ user_list: Vec<UserInfo>,
+}
+
+#[post("/app-user/info/get-all")]
+async fn user_info_get_all(
+ request: web::Json<UserInfoGetAllRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<UserInfoGetAllResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("user_info_get_all: login as {:?}", admin);
+ match st.get_all_user_info().await {
+ Ok(user_list) => {
+ let response = UserInfoGetAllResponse { user_list };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("user_info_get_all error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserInfoGetByIdRequest {
+ auth_data: AuthData,
+ id: UserID,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UserInfoGetByIdResponse {
+ #[serde(flatten)]
+ user_info: UserInfo,
+}
+
+#[post("/app-user/info/get-by-id")]
+async fn user_info_get_by_id(
+ request: web::Json<UserInfoGetByIdRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<UserInfoGetByIdResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("user_info_get_by_id: login as {:?}", admin);
+ match st.get_user_info_by_id(&request.id).await {
+ Ok(info) => {
+ let response = UserInfoGetByIdResponse { user_info: info };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("user_info_get_by_id error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceRegisterRequest {
+ auth_data: AuthData,
+ device_pubkeys: String, // base64
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceRegisterResponse {
+ #[serde(flatten)]
+ device_info: DeviceInfoBasic,
+}
+#[post("/device/register")]
+async fn device_register(
+ request: web::Json<DeviceRegisterRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceRegisterResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("device_register: login as {:?}", admin);
+ // register the device on behalf of the logged-in user
+ // cannot register device for other users
+ match st
+ .register_device(&admin.0.email, &request.device_pubkeys)
+ .await
+ {
+ Ok(device_info) => {
+ let response = DeviceRegisterResponse { device_info };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceCertExportRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceCertExportResponse {
+ download_link: Url,
+}
+
+#[post("/device/cert/export")]
+async fn device_cert_export(
+ request: web::Json<DeviceCertExportRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceCertExportResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("device_cert_export: login as {:?}", admin);
+ // admin or device owner can export the device cert
+ match st.export_device_cert(&request.device_id).await {
+ Ok(download_link) => {
+ let response = DeviceCertExportResponse { download_link };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_cert_export error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceCertRefreshRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceCertRefreshResponse {
+ download_link: Url,
+}
+
+#[post("/device/cert/refresh")]
+async fn device_cert_refresh(
+ request: web::Json<DeviceCertRefreshRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceCertRefreshResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("device_cert_refresh: login as {:?}", admin);
+
+ // admin or device owner can export the device cert
+ match st.refresh_device_cert(&request.device_id).await {
+ Ok(download_link) => {
+ let response = DeviceCertRefreshResponse { download_link };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_cert_refresh error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceAuthorizeRequest {
+ auth_data: AuthData,
+ from_device_id: DeviceID,
+ backup_info: BackupDeviceInfoBasic,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceAuthorizeResponse {
+ download_link: Url,
+}
+
+#[post("/device/authorize")]
+async fn device_authorize(
+ request: web::Json<DeviceAuthorizeRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceAuthorizeResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("device_authorize: login as {:?}", admin);
+ // logged-in user should be the device owner or admin
+ match st
+ .authorize_backup_device(&request.from_device_id, &request.backup_info)
+ .await
+ {
+ Ok(download_link) => {
+ let response = DeviceAuthorizeResponse { download_link };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_authorize error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceInfoGetRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceInfoGetResponse {
+ #[serde(flatten)]
+ device_info: DeviceInfoBasic,
+}
+
+#[post("/device/info/get")]
+async fn device_info_get(
+ request: web::Json<DeviceInfoGetRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceInfoGetResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("device_info_get: login as {:?}", admin);
+ match st.get_device_info(&request.device_id).await {
+ Ok(info) => {
+ let response = DeviceInfoGetResponse { device_info: info };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_info_get error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceStatusRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[serde(transparent)]
+struct DeviceStatusResponse {
+ tee_status: TeeStatusForClient,
+}
+
+#[post("/device/status")]
+async fn device_status(
+ request: web::Json<DeviceStatusRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceStatusResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("device_status: login as {:?}", admin);
+ match st.get_tee_status(&request.device_id).await {
+ Ok(Some(tee_status)) => {
+ let response = DeviceStatusResponse {
+ tee_status: tee_status.into(),
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Ok(None) => {
+ let response = DeviceStatusResponse {
+ tee_status: TeeStatusForClient::Offline,
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_status error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceGetAllRequest {
+ auth_data: AuthData,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceGetAllResponse {
+ device_list: Vec<DeviceID>,
+}
+
+#[post("/device/get-all")]
+async fn device_get_all(
+ request: web::Json<DeviceGetAllRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceGetAllResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("device_current_online: login as {:?}", admin);
+ match st.get_current_online_device().await {
+ Ok(device_id) => {
+ let response = DeviceGetAllResponse {
+ device_list: vec![device_id],
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_current_online error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceSyncRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DeviceSyncResponse {
+ message: String,
+}
+
+#[post("/device/sync")]
+async fn device_sync(
+ request: web::Json<DeviceSyncRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<DeviceSyncResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::info!(
+ "device_sync: operated by {:?} for device {:?}",
+ admin,
+ request.device_id
+ );
+ match st.sync_config(&request.device_id).await {
+ Ok(_) => {
+ let response = DeviceSyncResponse {
+ message: "Config updated, please wait for device to sync".to_string(),
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("device_sync error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletRegisterRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+ wallet_info_list: Vec<CreateConsoleWalletInfo>,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletRegisterResponse {
+ wallet_info_list: Vec<ConsoleWalletInfoForClient>,
+}
+
+#[post("/wallet/register")]
+async fn wallet_register(
+ request: web::Json<WalletRegisterRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletRegisterResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("wallet_register: login as {:?}", admin);
+ // check all wallet_name length
+ for wallet_info in &request.wallet_info_list {
+ if wallet_info.wallet_name.len() > 20 {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(format!(
+ "wallet_name length should be less than 20, got {}",
+ wallet_info.wallet_name.len()
+ )));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ }
+ match st
+ .register_wallets(&request.device_id, &request.wallet_info_list)
+ .await
+ {
+ Ok(wallet_info_list) => {
+ let mut console_wallet_info_list = Vec::new();
+ for wallet_info in wallet_info_list {
+ let account = match st.get_wallet_address(&wallet_info.wallet_id).await {
+ Ok(account) => account,
+ Err(e) => {
+ log::error!("wallet_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ console_wallet_info_list
+ .push(ConsoleWalletInfoForClient::new(wallet_info, account));
+ }
+ let response = WalletRegisterResponse {
+ wallet_info_list: console_wallet_info_list,
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("wallet_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoUpdateRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+ wallet_info_list: Vec<UpdateConsoleWalletInfo>,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoUpdateResponse {
+ wallet_info_list: Vec<ConsoleWalletInfoForClient>,
+}
+
+#[post("/wallet/info/update")]
+async fn wallet_info_update(
+ request: web::Json<WalletInfoUpdateRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletInfoUpdateResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("wallet_info_update: login as {:?}", admin);
+ // check all wallet_name length
+ for wallet_info in &request.wallet_info_list {
+ if wallet_info.wallet_name.len() > 20 {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(format!(
+ "wallet_name length should be less than 20, got {}",
+ wallet_info.wallet_name.len()
+ )));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ }
+ match st
+ .update_wallet_info(&request.device_id, &request.wallet_info_list)
+ .await
+ {
+ Ok(wallet_info_list) => {
+ let mut console_wallet_info_list = Vec::new();
+ for wallet_info in wallet_info_list {
+ let account = match st.get_wallet_address(&wallet_info.wallet_id).await {
+ Ok(account) => account,
+ Err(e) => {
+ log::error!("wallet_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ console_wallet_info_list
+ .push(ConsoleWalletInfoForClient::new(wallet_info, account));
+ }
+ let response = WalletInfoUpdateResponse {
+ wallet_info_list: console_wallet_info_list,
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("wallet_info_update error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoGetRequest {
+ auth_data: AuthData,
+ wallet_id: WalletID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoGetResponse {
+ wallet_info: ConsoleWalletInfoForClient,
+}
+
+#[post("/wallet/info/get")]
+async fn wallet_info_get(
+ request: web::Json<WalletInfoGetRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletInfoGetResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("wallet_info_get: login as {:?}", admin);
+ match st.get_wallet_info(&request.wallet_id).await {
+ Ok(wallet_info) => {
+ let account = match st.get_wallet_address(&wallet_info.wallet_id).await {
+ Ok(account) => account,
+ Err(e) => {
+ log::error!("wallet_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ let console_wallet_info = ConsoleWalletInfoForClient::new(wallet_info, account);
+ let response = WalletInfoGetResponse {
+ wallet_info: console_wallet_info,
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("wallet_info_get error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoGetByDeviceRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoGetByDeviceResponse {
+ wallet_info_list: Vec<ConsoleWalletInfoForClient>,
+}
+
+#[post("/wallet/info/get-by-device")]
+async fn wallet_info_get_all(
+ request: web::Json<WalletInfoGetByDeviceRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletInfoGetByDeviceResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("wallet_info_get_all: login as {:?}", admin);
+ match st.get_all_wallet_info(&request.device_id).await {
+ Ok(wallet_info_list) => {
+ let mut console_wallet_info_list = Vec::new();
+ for wallet_info in wallet_info_list {
+ let account = match st.get_wallet_address(&wallet_info.wallet_id).await {
+ Ok(account) => account,
+ Err(e) => {
+ log::error!("wallet_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ console_wallet_info_list
+ .push(ConsoleWalletInfoForClient::new(wallet_info, account));
+ }
+ let response = WalletInfoGetByDeviceResponse {
+ wallet_info_list: console_wallet_info_list,
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("wallet_info_get_all error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletCreateWithIdRequest {
+ auth_data: AuthData,
+ device_id: DeviceID,
+ wallet_info_list: Vec<UpdateConsoleWalletInfo>,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletCreateWithIdResponse {
+ wallet_info_list: Vec<ConsoleWalletInfoForClient>,
+}
+
+#[post("/wallet/create/with-id")]
+async fn wallet_create_with_id(
+ request: web::Json<WalletCreateWithIdRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletCreateWithIdResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("wallet_create_with_id: login as {:?}", admin);
+ // check all wallet_name length
+ for wallet_info in &request.wallet_info_list {
+ if wallet_info.wallet_name.len() > 20 {
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(format!(
+ "wallet_name length should be less than 20, got {}",
+ wallet_info.wallet_name.len()
+ )));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ }
+ match st
+ .wallet_create_with_id(&request.device_id, &request.wallet_info_list)
+ .await
+ {
+ Ok(wallet_info_list) => {
+ let mut console_wallet_info_list = Vec::new();
+ for wallet_info in wallet_info_list {
+ let account = match st.get_wallet_address(&wallet_info.wallet_id).await {
+ Ok(account) => account,
+ Err(e) => {
+ log::error!("wallet_register error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ console_wallet_info_list
+ .push(ConsoleWalletInfoForClient::new(wallet_info, account));
+ }
+ let response = WalletCreateWithIdResponse {
+ wallet_info_list: console_wallet_info_list,
+ };
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("wallet_info_update error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoRevertRequest {
+ auth_data: AuthData,
+ wallet_id: WalletID,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WalletInfoRevertResponse {}
+
+#[post("/wallet/info/revert")]
+async fn wallet_info_revert(
+ request: web::Json<WalletInfoRevertRequest>,
+ req: HttpRequest,
+) -> Result<web::Json<WebApiResult<WalletInfoRevertResponse>>> {
+ let st = shared_read_ref(&req)?;
+ let admin: Admin = match st.authenticate_console_user(&request.auth_data).await {
+ Ok(admin) => admin,
+ Err(e) => {
+ let error = WebApiError::Unauthorized(ErrorMessage::new(e.to_string()));
+ return Ok(web::Json(WebApiResult::Error(error)));
+ }
+ };
+ log::debug!("wallet_info_revert: login as {:?}", admin);
+
+ match st.revert_wallet_info(&request.wallet_id).await {
+ Ok(_) => {
+ let response = WalletInfoRevertResponse {};
+ let result = WebApiResult::Ok(response);
+ Ok(web::Json(result))
+ }
+ Err(e) => {
+ log::error!("wallet_info_revert error: {:?}", e);
+ let error = WebApiError::InvalidOperation(ErrorMessage::new(e.to_string()));
+ Ok(web::Json(WebApiResult::Error(error)))
+ }
+ }
+}
+
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+ use actix_cors::Cors;
+
+ // setup global config
+ let root_path = std::env::var("CK_ROOT_PATH").map_err(|e| {
+ log::error!("CK_ROOT_PATH error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e)
+ })?;
+ let authority_config = AuthorityConfig::new(
+ Path::new(&root_path),
+ Path::new("config/runtime_config.toml"),
+ );
+
+ setup_logger(&authority_config.log_path, "authority-server")
+ .expect("Failed to initialize logger");
+
+ let ip = authority_config.ip;
+ let port = authority_config.port;
+ // shared state manager
+ let st = Arc::new(
+ SharedStateManager::new(Arc::new(authority_config))
+ .await
+ .map_err(|e| {
+ log::error!("SharedStateManager::new() error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e)
+ })?,
+ );
+ let app_state = web::Data::new(st.clone());
+
+ // start server
+ log::info!("starting HTTP server at http://{}:{}", ip, port);
+ HttpServer::new(move || {
+ let cors = Cors::permissive();
+
+ App::new()
+ // enable logger
+ .wrap(middleware::Logger::default())
+ .wrap(cors)
+ .app_data(web::JsonConfig::default().limit(4096)) // <- limit size of the payload (global configuration)
+ .app_data(web::Data::clone(&app_state))
+ .service(web::resource("/index.html").to(index))
+ .service(console_user_role)
+ .service(user_register)
+ .service(user_role_append)
+ .service(user_info_get)
+ .service(user_info_get_by_id)
+ .service(user_info_get_all)
+ .service(device_register)
+ .service(device_cert_export)
+ .service(device_cert_refresh)
+ .service(device_authorize)
+ .service(device_info_get)
+ .service(device_get_all)
+ .service(device_status)
+ .service(device_sync)
+ .service(wallet_register)
+ .service(wallet_create_with_id)
+ .service(wallet_info_get)
+ .service(wallet_info_get_all)
+ .service(wallet_info_update)
+ .service(wallet_info_revert)
+ })
+ .bind((ip, port))?
+ .run()
+ .await
+}
diff --git a/vm/wallet-gateway/authority-server/src/state_manager.rs b/vm/wallet-gateway/authority-server/src/state_manager.rs
new file mode 100644
index 00000000..ec5841ac
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/state_manager.rs
@@ -0,0 +1,544 @@
+// 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::{anyhow, bail, ensure, Result};
+use base64::{engine::general_purpose, Engine as _};
+use std::collections::HashSet;
+use std::sync::Arc;
+use std::time::SystemTime;
+use storable::committed_config::CommittedConfig;
+use storable::synced_wallet::SyncedWalletInfo;
+use storable::tee_status::OnlineDevice;
+use tokio::sync::RwLock;
+use url::Url;
+
+use credential_manager::CredentialManager;
+use storable::console::{ConsoleWalletInfo, CreateConsoleWalletInfo, UpdateConsoleWalletInfo};
+use storable::device_info::{BackupDeviceInfoBasic, DeviceInfoBasic};
+use storable::user_info::{User, UserInfo};
+
+use authority::{DeviceRegistry, UserRegistry};
+use db_manager::{DBCompatibleClient, LocalServiceClient, StorageClient};
+use proto::InitBoardOutput;
+use types::external::Email;
+use types::share::{AccountId, DeviceID, Role, TeeOnlineStatus, UserID, WalletID};
+
+use crate::auth_data::AuthData;
+use crate::config::AuthorityConfig;
+use crate::console_user::ConsoleUserInfo;
+use crate::file_utils::{export_file, ExportedFileType};
+use crate::UserBasicInfo;
+
+pub struct SharedStateManager {
+ config: Arc<AuthorityConfig>,
+ user_registry: Arc<RwLock<UserRegistry>>,
+ device_registry: Arc<RwLock<DeviceRegistry>>,
+ credential_manager: Arc<CredentialManager>,
+ db_client: Arc<StorageClient>,
+}
+
+impl SharedStateManager {
+ pub async fn new(config: Arc<AuthorityConfig>) -> Result<Self> {
+ let db_client = Arc::new(StorageClient::new(Box::new(
+ LocalServiceClient::init(config.db_server_url.as_str(), None).await?,
+ )));
+ let user_registry = Arc::new(RwLock::new(UserRegistry::init(db_client.clone()).await?));
+ let device_registry = Arc::new(RwLock::new(DeviceRegistry::init(db_client.clone()).await?));
+ let credential_manager = Arc::new(
+ CredentialManager::init(
+ db_client.clone(),
+ config.cert_path.to_str().unwrap_or_default(),
+ )
+ .await?,
+ );
+ Ok(Self {
+ config,
+ user_registry,
+ device_registry,
+ credential_manager,
+ db_client,
+ })
+ }
+
+ // /user/register
+ pub async fn register_user(&self, user_basic_info: &UserBasicInfo) -> Result<UserInfo> {
+ self.user_registry
+ .write()
+ .await
+ .add_user(
+ &self.credential_manager,
+ &user_basic_info.name,
+ &user_basic_info.email,
+ &user_basic_info.roles,
+ )
+ .await
+ }
+ // /user/role/append
+ pub async fn append_role(&self, user_email: &Email, roles: &HashSet<Role>) -> Result<UserInfo> {
+ self.user_registry
+ .write()
+ .await
+ .append_role(user_email, roles)
+ .await
+ }
+ // /user/info/get
+ pub async fn get_user_info(&self, user_email: &Email) -> Result<UserInfo> {
+ self.user_registry.read().await.get_info(user_email).await
+ }
+ // /user/info/get-all
+ pub async fn get_all_user_info(&self) -> Result<Vec<UserInfo>> {
+ self.user_registry.read().await.get_all_info().await
+ }
+
+ // /user/info/get_by_id
+ pub async fn get_user_info_by_id(&self, user_id: &UserID) -> Result<UserInfo> {
+ self.user_registry
+ .read()
+ .await
+ .get_user_info_by_id(user_id)
+ .await
+ }
+
+ // /device/register
+ pub async fn register_device(
+ &self,
+ user_email: &Email,
+ device_pubkeys: &str,
+ ) -> Result<DeviceInfoBasic> {
+ // base64 decode
+ let decoded_pubkeys = general_purpose::STANDARD.decode(device_pubkeys)?;
+ // deserialize
+ let device_pubkeys: InitBoardOutput = bincode::deserialize(&decoded_pubkeys)?;
+ log::debug!("device_pubkeys: {:?}", device_pubkeys);
+ self.device_registry
+ .write()
+ .await
+ .register_device(
+ &self.credential_manager,
+ user_email,
+ device_pubkeys.signing_pubkey,
+ device_pubkeys.backup_pubkey,
+ )
+ .await
+ }
+
+ // admin or associated device owner can operate on the device
+ pub async fn _user_can_operate_on_device(&self, user: &User, device_id: &DeviceID) -> bool {
+ if user.get_info().is_admin() {
+ return true;
+ }
+ self.device_registry
+ .read()
+ .await
+ .device_exist_for_user(user.get_info().get_email(), device_id)
+ .await
+ }
+
+ // /device/cert/export
+ pub async fn export_device_cert(&self, device_id: &DeviceID) -> Result<Url> {
+ let device_cert = self
+ .device_registry
+ .read()
+ .await
+ .export_device_cert(device_id)
+ .await?;
+ let id: String = device_id.clone().into();
+ let url = export_file(
+ &self.config.export_base_path,
+ &self.config.export_base_url,
+ id,
+ &ExportedFileType::Cert,
+ &device_cert,
+ None,
+ )?;
+ log::info!("exported device cert: {}", url);
+ Ok(url)
+ }
+ // /device/cert/refresh
+ pub async fn refresh_device_cert(&self, device_id: &DeviceID) -> Result<Url> {
+ let device_cert = self
+ .device_registry
+ .write()
+ .await
+ .refresh_device_cert(&self.credential_manager, device_id)
+ .await?;
+ let id: String = device_id.clone().into();
+ let url = export_file(
+ &self.config.export_base_path,
+ &self.config.export_base_url,
+ id,
+ &ExportedFileType::Cert,
+ &device_cert,
+ None,
+ )?;
+ log::info!("refreshed device cert: {}", url);
+ Ok(url)
+ }
+ // /device/authorize
+ pub async fn authorize_backup_device(
+ &self,
+ from_device: &DeviceID,
+ backup_info: &BackupDeviceInfoBasic,
+ ) -> Result<Url> {
+ let (serialized_input, timestamp) = self
+ .device_registry
+ .read()
+ .await
+ .export_backup_device_list(&self.credential_manager, from_device, backup_info)
+ .await?;
+ let from_device_id: String = from_device.clone().into();
+ let url = export_file(
+ &self.config.export_base_path,
+ &self.config.export_base_url,
+ from_device_id,
+ &ExportedFileType::SignedBackupList,
+ &serialized_input,
+ Some(timestamp),
+ )?;
+ log::info!("authorized backup device: {}", url);
+ Ok(url)
+ }
+ // /device/info/get
+ pub async fn get_device_info(&self, device_id: &DeviceID) -> Result<DeviceInfoBasic> {
+ match self
+ .device_registry
+ .read()
+ .await
+ .get_device_info(device_id)
+ .await?
+ {
+ Some(info) => Ok(info),
+ None => bail!("Device not found"),
+ }
+ }
+ // /device/current-online
+ pub async fn get_current_online_device(&self) -> Result<DeviceID> {
+ match self
+ .db_client
+ .get::<_, OnlineDevice>(&"OnlineDevice".to_string())
+ .await?
+ {
+ Some(info) => Ok(info.device_id()),
+ None => bail!("No online device found"),
+ }
+ }
+
+ pub async fn get_wallet_address(&self, wallet_id: &WalletID) -> Result<Option<AccountId>> {
+ // get account address from db
+ let synced_wallet_info = match self.db_client.get::<_, SyncedWalletInfo>(wallet_id).await? {
+ Some(info) => info,
+ None => {
+ log::warn!("Wallet not found in db: {:?}", wallet_id);
+ return Ok(None);
+ }
+ };
+
+ Ok(synced_wallet_info
+ .accounts
+ .into_iter()
+ .next()
+ .map(|mca| mca.id().clone()))
+ }
+
+ // /wallet/register
+ pub async fn register_wallets(
+ &self,
+ device_id: &DeviceID,
+ create_wallet_info_list: &Vec<CreateConsoleWalletInfo>,
+ ) -> Result<Vec<ConsoleWalletInfo>> {
+ let mut wallet_info_basic_vec = Vec::new();
+ for create_wallet_info_basic in create_wallet_info_list {
+ let wallet_info_basic = ConsoleWalletInfo::new(
+ device_id.clone(),
+ create_wallet_info_basic.wallet_name.clone(),
+ create_wallet_info_basic.approval_chain_basic.clone(),
+ create_wallet_info_basic.authorized_operators.clone(),
+ create_wallet_info_basic.viewers.clone(),
+ )?;
+ // ensure all user exist
+ for user_email in wallet_info_basic.distinct_participants() {
+ ensure!(
+ self.user_registry.read().await.user_exist(user_email).await,
+ "user not exist"
+ );
+ }
+ let registered_wallet_id = self
+ .device_registry
+ .write()
+ .await
+ .register_wallet(self.user_registry.clone(), device_id, &wallet_info_basic)
+ .await?;
+ log::info!(
+ "Register wallet successfully, wallet id: {:?}",
+ registered_wallet_id
+ );
+ wallet_info_basic_vec.push(wallet_info_basic);
+ }
+ Ok(wallet_info_basic_vec)
+ }
+
+ pub async fn wallet_create_with_id(
+ &self,
+ device_id: &DeviceID,
+ create_wallet_info_list: &Vec<UpdateConsoleWalletInfo>,
+ ) -> Result<Vec<ConsoleWalletInfo>> {
+ let update_time = SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+ let mut wallet_info_basic_vec = Vec::new();
+ for create_wallet_info_basic in create_wallet_info_list {
+ let wallet_info_basic = ConsoleWalletInfo {
+ wallet_id: create_wallet_info_basic.wallet_id.clone(),
+ wallet_name: create_wallet_info_basic.wallet_name.clone(),
+ created_by_device: device_id.clone(),
+ approval_chain_basic: create_wallet_info_basic.approval_chain_basic.clone(),
+ authorized_operators: create_wallet_info_basic.authorized_operators.clone(),
+ viewers: create_wallet_info_basic.viewers.clone(),
+ backed_up_by_devices: HashSet::new(),
+ update_time,
+ };
+
+ // ensure all user exist
+ for user_email in wallet_info_basic.distinct_participants() {
+ ensure!(
+ self.user_registry.read().await.user_exist(user_email).await,
+ "user not exist"
+ );
+ }
+ let registered_wallet_id = self
+ .device_registry
+ .write()
+ .await
+ .register_wallet(self.user_registry.clone(), device_id, &wallet_info_basic)
+ .await?;
+ log::info!(
+ "Register wallet successfully, wallet id: {:?}",
+ registered_wallet_id
+ );
+ wallet_info_basic_vec.push(wallet_info_basic);
+ }
+ Ok(wallet_info_basic_vec)
+ }
+
+ // /wallet/info/update
+ pub async fn update_wallet_info(
+ &self,
+ device_id: &DeviceID,
+ update_wallet_info_list: &Vec<UpdateConsoleWalletInfo>,
+ ) -> Result<Vec<ConsoleWalletInfo>> {
+ let mut updated_wallet_list = Vec::new();
+
+ let device_info: DeviceInfoBasic = match self
+ .device_registry
+ .read()
+ .await
+ .get_device_info(device_id)
+ .await?
+ {
+ Some(info) => info,
+ None => bail!("Device not found"),
+ };
+ let device_owned_wallets = device_info.created_wallets;
+
+ for update_wallet_info_basic in update_wallet_info_list {
+ // load wallet info
+ let mut wallet_info_basic = match self
+ .device_registry
+ .read()
+ .await
+ .get_wallet_info(&update_wallet_info_basic.wallet_id)
+ .await?
+ {
+ Some(info) => info,
+ None => bail!("Wallet not found"),
+ };
+ // check correlation between device and wallet
+ ensure!(
+ &wallet_info_basic.created_by_device == device_id,
+ "DeviceRegistry::update_wallet_info(): wallet not owned by device"
+ );
+ ensure!(
+ device_owned_wallets.contains(wallet_info_basic.id()),
+ "DeviceRegistry::update_wallet_info(): wallet not owned by device"
+ );
+ // updated wallet info
+ wallet_info_basic.update_info(
+ &update_wallet_info_basic.wallet_name,
+ &update_wallet_info_basic.approval_chain_basic,
+ &update_wallet_info_basic.authorized_operators,
+ &update_wallet_info_basic.viewers,
+ );
+
+ // ensure all user of wallet info exist
+ for user_email in wallet_info_basic.distinct_participants() {
+ ensure!(
+ self.user_registry.read().await.user_exist(user_email).await,
+ "user: {:?} not exist",
+ &user_email
+ );
+ }
+ // save updated wallet info
+ self.device_registry
+ .read()
+ .await
+ .save_wallet_info(&wallet_info_basic)
+ .await?;
+ updated_wallet_list.push(wallet_info_basic);
+ }
+ Ok(updated_wallet_list)
+ }
+ // /wallet/info/get
+ pub async fn get_wallet_info(&self, wallet_id: &WalletID) -> Result<ConsoleWalletInfo> {
+ match self
+ .device_registry
+ .read()
+ .await
+ .get_wallet_info(wallet_id)
+ .await?
+ {
+ Some(info) => Ok(info),
+ None => bail!("Wallet not found"),
+ }
+ }
+ // /wallet/info/get-all
+ pub async fn get_all_wallet_info(
+ &self,
+ device_id: &DeviceID,
+ ) -> Result<Vec<ConsoleWalletInfo>> {
+ let mut wallet_info_basic_vec = Vec::new();
+ // get wallet id
+ let wallet_id_vec = self
+ .device_registry
+ .read()
+ .await
+ .get_wallet_id_associated_with_device(device_id)
+ .await?;
+ // get wallet info
+ for wallet_id in wallet_id_vec {
+ let wallet_info_basic = match self
+ .device_registry
+ .read()
+ .await
+ .get_wallet_info(&wallet_id)
+ .await?
+ {
+ Some(info) => info,
+ None => bail!("Wallet not found"),
+ };
+ wallet_info_basic_vec.push(wallet_info_basic);
+ }
+ Ok(wallet_info_basic_vec)
+ }
+ pub async fn revert_wallet_info(&self, wallet_id: &WalletID) -> Result<()> {
+ let mut console_wallet_info = self
+ .db_client
+ .get::<_, ConsoleWalletInfo>(wallet_id)
+ .await?
+ .ok_or(anyhow!("console_wallet_info not found for {:?}", wallet_id))?;
+ if let Some(synced_wallet_info) =
+ self.db_client.get::<_, SyncedWalletInfo>(wallet_id).await?
+ {
+ console_wallet_info.revert_info(&synced_wallet_info);
+ self.db_client.put(&console_wallet_info).await
+ } else {
+ ensure!(
+ self.get_wallet_address(wallet_id).await?.is_none(),
+ "console_wallet_info has been created in TEE before, but not synced successfully last time"
+ );
+ log::warn!(
+ "synced_wallet_info not found for {:?}, remove the pending wallet",
+ wallet_id
+ );
+ self.device_registry
+ .write()
+ .await
+ .remove_wallet(wallet_id)
+ .await
+ }
+ }
+
+ pub async fn authenticate_console_user<U: TryFrom<ConsoleUserInfo>>(
+ &self,
+ auth_data: &AuthData,
+ ) -> Result<U> {
+ let email = auth_data
+ .get_authorized_email(&self.config.auth_service_url)
+ .await?;
+ ConsoleUserInfo::new(email)
+ .try_into()
+ .map_err(|_| anyhow!("User is not console user"))
+ }
+
+ pub async fn authenticate(&self, auth_data: &AuthData) -> Result<Email> {
+ auth_data
+ .get_authorized_email(&self.config.auth_service_url)
+ .await
+ }
+
+ // /device/status
+ pub async fn get_tee_status(&self, device_id: &DeviceID) -> Result<Option<TeeOnlineStatus>> {
+ let online_device = self
+ .db_client
+ .get::<_, OnlineDevice>(&"OnlineDevice".to_string())
+ .await?;
+ match online_device {
+ Some(info) => {
+ if &info.device_id() == device_id {
+ Ok(Some(info.status().clone()))
+ } else {
+ Ok(None)
+ }
+ }
+ None => Ok(None),
+ }
+ }
+
+ // /device/sync
+ // sync_config will generate a CommittedConfig and store it in db
+ pub async fn sync_config(&self, device_id: &DeviceID) -> Result<()> {
+ let (signed_config, timestamp) = self
+ .device_registry
+ .read()
+ .await
+ .export_wallet_info(
+ &self.credential_manager,
+ self.user_registry.clone(),
+ device_id,
+ )
+ .await?;
+ // export to file for backup
+ let _url = export_file(
+ &self.config.export_base_path,
+ &self.config.export_base_url,
+ device_id.clone(),
+ &ExportedFileType::WalletInfo,
+ &bincode::serialize(&signed_config)?,
+ Some(timestamp),
+ )?;
+ log::info!(
+ "sync_config(): wallet info exported to file with config version {}",
+ timestamp
+ );
+ let committed_config = CommittedConfig {
+ device_id: device_id.clone(),
+ signed_config,
+ timestamp,
+ };
+ self.db_client.put(&committed_config).await
+ }
+}
diff --git a/vm/wallet-gateway/authority-server/src/tee_status_for_client.rs b/vm/wallet-gateway/authority-server/src/tee_status_for_client.rs
new file mode 100644
index 00000000..094e9795
--- /dev/null
+++ b/vm/wallet-gateway/authority-server/src/tee_status_for_client.rs
@@ -0,0 +1,45 @@
+// 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 serde::{Deserialize, Serialize};
+use types::share::{ServiceInfo, TeeOnlineStatus};
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+#[serde(tag = "teeStatus")]
+pub enum TeeStatusForClient {
+ ServiceRunning(ServiceInfo),
+ WaitingForSync,
+ ServicePaused,
+ Offline, // If tee cannot be reached, return this status to user
+}
+
+impl Default for TeeStatusForClient {
+ fn default() -> Self {
+ Self::Offline
+ }
+}
+
+impl From<TeeOnlineStatus> for TeeStatusForClient {
+ fn from(tee_online_status: TeeOnlineStatus) -> Self {
+ match tee_online_status {
+ TeeOnlineStatus::ServiceRunning(service_info) => Self::ServiceRunning(service_info),
+ TeeOnlineStatus::WaitingForSync => Self::WaitingForSync,
+ TeeOnlineStatus::ServicePaused => Self::ServicePaused,
+ }
+ }
+}
diff --git a/vm/wallet-gateway/authority/Cargo.toml b/vm/wallet-gateway/authority/Cargo.toml
new file mode 100644
index 00000000..e20dfdfd
--- /dev/null
+++ b/vm/wallet-gateway/authority/Cargo.toml
@@ -0,0 +1,42 @@
+# 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.
+
+[package]
+name = "authority"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+serde = "1.0"
+serde_json = "1.0"
+serde_with = "3.8"
+hex = { version = "0.4", features = ["serde"] }
+anyhow = "1.0"
+bincode = "1.3.3"
+sha3 = "0.10.6"
+uuid = { version = "1.3.0", features = ["v4"]}
+log = "0.4"
+lazy_static = "1.4.0"
+tokio = { version = "1.0", features = ["full"] }
+
+ck_config = { path = "../config" }
+types = { path = "../share/types" }
+tls-client-processing = { path = "../tls-client-processing" }
+proto = { path = "../share/proto" }
+db-manager = { path = "../db-manager" }
+credential-manager = { path = "../credential-manager" }
+storable = { path = "../storable" }
\ No newline at end of file
diff --git a/vm/wallet-gateway/authority/src/device_registry.rs b/vm/wallet-gateway/authority/src/device_registry.rs
new file mode 100644
index 00000000..6beb4885
--- /dev/null
+++ b/vm/wallet-gateway/authority/src/device_registry.rs
@@ -0,0 +1,520 @@
+// 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 crate::user_registry::UserRegistry;
+use credential_manager::CredentialManager;
+use storable::console::{ConsoleWalletInfo, WalletAccountInfo, MAX_WALLET_NUM_PER_DEVICE};
+
+use db_manager::StorageClient;
+use storable::device_info::{BackupDeviceInfoBasic, DeviceIndex, DeviceInfo, DeviceInfoBasic};
+use types::external::Email;
+use types::share::{
+ AccountId, CkHasher, CkPublicKey, DeviceID, Role, TaUserInfo, TaWalletInfo, TeeConfig, WalletID,
+};
+
+use anyhow::{anyhow, bail, ensure, Result};
+use std::collections::HashSet;
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+
+pub struct DeviceRegistry {
+ db_client: Arc<StorageClient>,
+}
+impl DeviceRegistry {
+ pub async fn init(db_client: Arc<StorageClient>) -> Result<Self> {
+ Ok(Self { db_client })
+ }
+
+ // device_index.db operations
+ async fn update_device_index(&mut self, device_index: &DeviceIndex) -> Result<()> {
+ // update db
+ self.db_client.put(device_index).await?;
+ Ok(())
+ }
+ pub async fn get_device_index_for_user(&self, email: &Email) -> Result<Option<DeviceIndex>> {
+ self.db_client.get(email).await
+ }
+ pub async fn device_exist_for_user(&self, email: &Email, device_id: &DeviceID) -> bool {
+ match self.get_device_index_for_user(email).await {
+ Ok(Some(device_index)) => device_index.device_list().contains(device_id),
+ _ => false,
+ }
+ }
+ pub async fn device_owner(&self, device_id: &DeviceID) -> Result<Email> {
+ for (email, device_index) in self.db_client.list_entries::<Email, DeviceIndex>().await? {
+ if device_index.device_list().contains(device_id) {
+ return Ok(email);
+ }
+ }
+ bail!(
+ "DeviceRegistry::device_owner(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+
+ // command RegisterDevice
+ pub async fn register_device(
+ &mut self,
+ credential_manager: &CredentialManager,
+ email: &Email,
+ signing_pubkey: CkPublicKey,
+ backup_pubkey: CkPublicKey,
+ ) -> Result<DeviceInfoBasic> {
+ log::debug!("register_device(): pubkey: {:?}", &signing_pubkey);
+ let device_id = DeviceID::from(signing_pubkey.clone());
+ log::info!("register device {:?} for user {:?}", &device_id, &email);
+ match self.device_owner(&device_id).await {
+ Ok(owner) => {
+ bail!(
+ "DeviceRegistry::register_device(): device {:?} already exists for user {:?}",
+ &device_id,
+ &owner
+ );
+ }
+ Err(_) => {
+ log::debug!(
+ "DeviceRegistry::register_device(): device {:?} does not exist in db",
+ &device_id
+ );
+ }
+ };
+ let device_tee_cert = credential_manager.generate_tee_cert(&signing_pubkey)?;
+ let device_info = DeviceInfo::new(
+ email.clone(),
+ device_id.clone(),
+ signing_pubkey,
+ backup_pubkey,
+ device_tee_cert,
+ HashSet::new(),
+ HashSet::new(),
+ );
+ // update device index
+ let new_device_list = match self.get_device_index_for_user(email).await? {
+ Some(device_index) => {
+ let mut device_list = device_index.device_list().clone();
+ device_list.insert(device_id);
+ device_list
+ }
+ None => {
+ let mut device_list = HashSet::new();
+ device_list.insert(device_id);
+ device_list
+ }
+ };
+ self.update_device_index(&DeviceIndex::new(email.clone(), new_device_list))
+ .await?;
+
+ // update device info db
+ self.db_client.put(&device_info).await?;
+ Ok(device_info.into())
+ }
+
+ // command ExportDeviceCert
+ pub async fn export_device_cert(&self, device_id: &DeviceID) -> Result<Vec<u8>> {
+ let device_info: DeviceInfo = match self.db_client.get(device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::export_device_cert(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+ };
+ Ok(device_info.cert().clone())
+ }
+
+ // command RefreshDeviceCert
+ pub async fn refresh_device_cert(
+ &mut self,
+ credential_manager: &CredentialManager,
+ device_id: &DeviceID,
+ ) -> Result<Vec<u8>> {
+ let mut device_info: DeviceInfo = match self.db_client.get(device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::refresh_device_cert(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+ };
+ let device_tee_cert = credential_manager.generate_tee_cert(device_info.signing_pubkey())?;
+ device_info.set_cert(device_tee_cert);
+ self.db_client.put(&device_info).await?;
+
+ Ok(device_info.cert().clone())
+ }
+
+ // command AuthorizeBackupDevice
+ pub async fn export_backup_device_list(
+ &self,
+ credential_manager: &CredentialManager,
+ from_device_id: &DeviceID,
+ backup_device_info_basic: &BackupDeviceInfoBasic,
+ ) -> Result<(Vec<u8>, u64)> {
+ let from_device_info: DeviceInfo = match self.db_client.get(from_device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::export_backup_device_list(): device {:?} not exist in db",
+ &from_device_id
+ );
+ }
+ };
+ let mut to_device_info: DeviceInfo = match self
+ .db_client
+ .get(&backup_device_info_basic.device_id)
+ .await?
+ {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::export_backup_device_list(): device {:?} not exist in db",
+ &backup_device_info_basic.device_id
+ );
+ }
+ };
+
+ // if wallet_id_list is empty, backup all wallets of this device
+ let wallet_id_list = if backup_device_info_basic.wallet_id_list.is_empty() {
+ log::info!(
+ "DeviceRegistry::export_backup_device_list(): backup all wallets of device {:?}",
+ from_device_id
+ );
+ from_device_info.created_wallets().iter().cloned().collect()
+ } else {
+ log::info!(
+ "DeviceRegistry::export_backup_device_list(): backup wallets {:?} of device {:?}",
+ &backup_device_info_basic.wallet_id_list,
+ from_device_id
+ );
+ backup_device_info_basic.wallet_id_list.clone()
+ };
+
+ for wallet_id in &wallet_id_list {
+ let mut wallet_info: ConsoleWalletInfo = match self.db_client.get(wallet_id).await? {
+ Some(wallet_info) => wallet_info,
+ None => {
+ bail!(
+ "DeviceRegistry::export_backup_device_list(): wallet {:?} not exist in db",
+ &wallet_id
+ );
+ }
+ };
+ ensure!(
+ from_device_info.created_wallets().contains(wallet_id),
+ "DeviceRegistry::export_backup_device_list(): check device_info: wallet {:?} not owned by device {:?}",
+ wallet_id,
+ from_device_info.id(),
+ );
+ ensure!(
+ &wallet_info.created_by_device == from_device_id,
+ "DeviceRegistry::export_backup_device_list(): check wallet_info: wallet {:?} not owned by device {:?}",
+ wallet_id,
+ &from_device_id
+ );
+ ensure!(
+ to_device_info.existing_wallets_num() < MAX_WALLET_NUM_PER_DEVICE,
+ "DeviceRegistry::export_backup_device_list(): wallet num exceed max wallet num per device",
+ );
+
+ wallet_info.add_backup_device(to_device_info.id().clone());
+ self.db_client.put(&wallet_info).await?;
+
+ log::info!("DeviceRegistry::export_backup_device_list(): wallet_info: saved in db");
+ to_device_info.add_backup_wallet(wallet_id)?;
+ }
+ self.db_client.put(&to_device_info).await?;
+ log::info!("DeviceRegistry::export_backup_device_list(): to_device_info: saved in db");
+
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_err(|e| anyhow!("Failed to get timestamp: {}", e))?
+ .as_secs();
+
+ // Empty list means backup all wallets: the TEE will handle this case
+ let wallet_id_list_to_signed = if backup_device_info_basic.wallet_id_list.is_empty() {
+ HashSet::new()
+ } else {
+ to_device_info.backed_up_wallets().clone()
+ };
+ let input = credential_manager.sign_backup_device_list(
+ to_device_info.id().clone(),
+ to_device_info.backup_pubkey().clone(),
+ wallet_id_list_to_signed,
+ )?;
+
+ let serialized_backup_wallet_input = bincode::serialize(&input)?;
+
+ Ok((serialized_backup_wallet_input, timestamp))
+ }
+
+ // command RegisterWallet
+ pub async fn register_wallet(
+ &mut self,
+ user_registry: Arc<RwLock<UserRegistry>>,
+ device_id: &DeviceID,
+ wallet_info_basic: &ConsoleWalletInfo,
+ ) -> Result<WalletID> {
+ let mut device_info: DeviceInfo = match self.db_client.get(device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::register_wallet(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+ };
+ // check if the wallet id has been registered
+ match self
+ .db_client
+ .get::<_, ConsoleWalletInfo>(wallet_info_basic.id())
+ .await?
+ {
+ Some(wallet_info) => {
+ bail!(
+ "DeviceRegistry::register_wallet(): wallet {:?} already exists for device {:?}",
+ wallet_info.wallet_id,
+ wallet_info.created_by_device,
+ );
+ }
+ None => {
+ log::debug!(
+ "DeviceRegistry::register_wallet(): wallet {:?} does not exist in db",
+ wallet_info_basic.id()
+ );
+ }
+ };
+ // check user's role
+ for stage in wallet_info_basic.approval_chain_basic.iter() {
+ for approvers in stage.approvers.iter() {
+ let user_info = user_registry.read().await.get_info(approvers).await?;
+ if !user_info.get_roles().contains(&Role::Approver) {
+ bail!(
+ "DeviceRegistry::register_wallet(): user {:?} is not approver",
+ approvers
+ );
+ };
+ }
+ }
+ for tx_operator in wallet_info_basic.authorized_operators.clone() {
+ let user_info = user_registry.read().await.get_info(&tx_operator).await?;
+ if !user_info.get_roles().contains(&Role::TxOperator) {
+ bail!(
+ "DeviceRegistry::register_wallet(): user {:?} is not tx_operator",
+ tx_operator
+ );
+ };
+ }
+
+ // check max wallet num per device
+ ensure!(
+ device_info.existing_wallets_num() < MAX_WALLET_NUM_PER_DEVICE,
+ "DeviceRegistry::add_wallet_for_device(): max wallet num per device reached"
+ );
+
+ device_info.add_owned_wallet(wallet_info_basic)?;
+ self.db_client.put(wallet_info_basic).await?;
+ self.db_client.put(&device_info).await?;
+ log::info!(
+ "DeviceRegistry::add_wallet_for_device(): wallet_info and device_info saved in db"
+ );
+ Ok(wallet_info_basic.id().clone())
+ }
+
+ pub async fn remove_wallet(&mut self, wallet_id: &WalletID) -> Result<()> {
+ let device_id = match self
+ .db_client
+ .get::<_, ConsoleWalletInfo>(wallet_id)
+ .await?
+ {
+ Some(wallet_info) => wallet_info.created_by_device.clone(),
+ None => {
+ bail!(
+ "DeviceRegistry::remove_wallet(): wallet {:?} not exist in db",
+ &wallet_id
+ );
+ }
+ };
+ let mut device_info: DeviceInfo = match self.db_client.get(&device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::remove_wallet(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+ };
+ device_info.remove_owned_wallet(wallet_id)?;
+ self.db_client
+ .delete_entry::<WalletID, ConsoleWalletInfo>(wallet_id)
+ .await?;
+ self.db_client.put(&device_info).await?;
+ Ok(())
+ }
+
+ // command ExportWalletInfo
+ pub async fn export_wallet_info(
+ &self,
+ credential_manager: &CredentialManager,
+ user_registry: Arc<RwLock<UserRegistry>>,
+ device_id: &DeviceID,
+ ) -> Result<(TeeConfig, u64)> {
+ let device_info: DeviceInfo = match self.db_client.get(device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::export_wallet_info(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+ };
+ let wallet_id_list = device_info.wallet_id_list();
+ log::info!(
+ "DeviceRegistry::export_wallet_info(): wallet_id_list: {:?}",
+ wallet_id_list
+ );
+
+ // gather all wallets
+ // convert to wallets_info_ta
+ // gather all participants
+ // gather all user pubkeys to registry
+
+ let mut wallets = Vec::new();
+ for wallet_id in &wallet_id_list {
+ let wallet_info_basic: ConsoleWalletInfo = match self.db_client.get(wallet_id).await? {
+ Some(wallet_info) => wallet_info,
+ None => {
+ bail!(
+ "DeviceRegistry::export_wallet_info(): wallet {:?} not exist in db",
+ &wallet_id
+ );
+ }
+ };
+ wallets.push(wallet_info_basic);
+ }
+
+ let all_related_users: HashSet<&Email> = wallets
+ .iter()
+ .flat_map(|wallet| wallet.distinct_participants())
+ .collect();
+
+ let mut registry: Vec<TaUserInfo> = Vec::new();
+ for each_user in all_related_users {
+ let user_info = user_registry.read().await.get_info(each_user).await?;
+ let ta_user_info = TaUserInfo::new(
+ user_info.get_pub_key().hash()?,
+ each_user.clone().into(),
+ user_info.get_roles().clone(),
+ );
+ registry.push(ta_user_info);
+ }
+
+ let ta_wallets: Vec<TaWalletInfo> =
+ wallets.into_iter().map(|wallet| wallet.into()).collect();
+
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_err(|e| anyhow!("Failed to get timestamp: {}", e))?
+ .as_secs();
+
+ let input = credential_manager.sign_wallet_info(registry, ta_wallets, timestamp)?;
+ Ok((input, timestamp))
+ }
+
+ // command GetUserInfo
+ pub async fn get_device_info_for_user(&self, email: &Email) -> Result<Vec<DeviceInfoBasic>> {
+ let mut device_info_list: Vec<DeviceInfoBasic> = Vec::new();
+ let device_index = self.get_device_index_for_user(email).await?.ok_or(anyhow!(
+ "DeviceRegistry::get_device_info_for_user(): user {:?} not exist in db",
+ &email
+ ))?;
+ let device_id_list = device_index.device_list();
+ for device_id in device_id_list {
+ let device_info: DeviceInfo = match self.db_client.get(device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::get_device_info_for_user(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+ };
+ let device_info_for_user: DeviceInfoBasic = device_info.into();
+ device_info_list.push(device_info_for_user);
+ }
+ Ok(device_info_list)
+ }
+
+ // command GetWalletInfo
+ pub async fn get_wallet_info(&self, wallet_id: &WalletID) -> Result<Option<ConsoleWalletInfo>> {
+ self.db_client.get::<_, ConsoleWalletInfo>(wallet_id).await
+ }
+
+ // command UpdateWalletInfo
+ pub async fn save_wallet_info(&self, wallet_info_basic: &ConsoleWalletInfo) -> Result<()> {
+ self.db_client.put(wallet_info_basic).await
+ }
+
+ // command GetDeviceInfo
+ pub async fn get_device_info(&self, device_id: &DeviceID) -> Result<Option<DeviceInfoBasic>> {
+ match self.db_client.get::<_, DeviceInfo>(device_id).await? {
+ Some(device_info) => Ok(Some(device_info.into())),
+ None => Ok(None),
+ }
+ }
+
+ pub async fn get_wallet_id_associated_with_device(
+ &self,
+ device_id: &DeviceID,
+ ) -> Result<Vec<WalletID>> {
+ let mut wallet_id_list = Vec::new();
+ let device_info: DeviceInfo = match self.db_client.get(device_id).await? {
+ Some(device_info) => device_info,
+ None => {
+ bail!(
+ "DeviceRegistry::get_wallet_id_associated_with_device(): device {:?} not exist in db",
+ &device_id
+ );
+ }
+ };
+ wallet_id_list.extend(device_info.created_wallets().clone());
+ wallet_id_list.extend(device_info.backed_up_wallets().clone());
+ Ok(wallet_id_list)
+ }
+
+ pub async fn get_wallet_account(&self, wallet_id: &WalletID) -> Result<Option<AccountId>> {
+ match self
+ .db_client
+ .get::<WalletID, WalletAccountInfo>(wallet_id)
+ .await?
+ {
+ Some(wallet_account_info) => Ok(Some(wallet_account_info.account_address)),
+ None => Ok(None),
+ }
+ }
+
+ pub async fn save_wallet_account(
+ &self,
+ wallet_id: &WalletID,
+ account: &AccountId,
+ ) -> Result<()> {
+ let wallet_account_info = WalletAccountInfo::new(wallet_id.clone(), account.clone());
+ self.db_client.put(&wallet_account_info).await
+ }
+}
diff --git a/vm/wallet-gateway/authority/src/lib.rs b/vm/wallet-gateway/authority/src/lib.rs
new file mode 100644
index 00000000..48600848
--- /dev/null
+++ b/vm/wallet-gateway/authority/src/lib.rs
@@ -0,0 +1,22 @@
+// 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.
+
+pub mod device_registry;
+pub mod user_registry;
+
+pub use device_registry::DeviceRegistry;
+pub use user_registry::UserRegistry;
diff --git a/vm/wallet-gateway/authority/src/user_registry.rs b/vm/wallet-gateway/authority/src/user_registry.rs
new file mode 100644
index 00000000..4598b018
--- /dev/null
+++ b/vm/wallet-gateway/authority/src/user_registry.rs
@@ -0,0 +1,140 @@
+// 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::{anyhow, bail, Result};
+use credential_manager::CredentialManager;
+use db_manager::StorageClient;
+use std::collections::HashSet;
+use std::sync::Arc;
+use storable::user_info::{UidToEmail, UserInfo};
+use types::external::Email;
+use types::share::{CkPublicKey, Role, UserID};
+
+pub struct UserRegistry {
+ db_client: Arc<StorageClient>,
+}
+
+impl UserRegistry {
+ pub async fn init(db_client: Arc<StorageClient>) -> Result<Self> {
+ Ok(Self { db_client })
+ }
+
+ pub async fn get_user_public_key(&self, email: Email) -> Result<CkPublicKey> {
+ let user_info: UserInfo = self
+ .db_client
+ .get(&email)
+ .await?
+ .ok_or(anyhow!("user not found"))?;
+ Ok(user_info.get_pub_key().clone())
+ }
+ pub async fn get_roles(&self, email: &Email) -> Result<Vec<Role>> {
+ let user_info: UserInfo = self
+ .db_client
+ .get(email)
+ .await?
+ .ok_or(anyhow!("user not found"))?;
+ Ok(user_info.get_roles().0.clone())
+ }
+ pub async fn get_info(&self, email: &Email) -> Result<UserInfo> {
+ let user_info = self
+ .db_client
+ .get(email)
+ .await?
+ .ok_or(anyhow!("user not found"))?;
+ Ok(user_info)
+ }
+ pub async fn get_user_info_by_id(&self, id: &UserID) -> Result<UserInfo> {
+ for (_email, info) in self.db_client.list_entries::<Email, UserInfo>().await? {
+ if info.get_id() == id {
+ return Ok(info);
+ }
+ }
+ bail!("user not found")
+ }
+
+ pub async fn get<T: TryFrom<UserInfo>>(&self, email: &Email) -> Result<T> {
+ match self.db_client.get::<Email, UserInfo>(email).await? {
+ Some(info) => {
+ let role: T = info
+ .clone()
+ .try_into()
+ .map_err(|_| anyhow!("userinfo cannot be converted to role"))?;
+ Ok(role)
+ }
+ None => bail!("user not found"),
+ }
+ }
+
+ pub async fn get_all_info(&self) -> Result<Vec<UserInfo>> {
+ let mut user_infos = Vec::new();
+ for (_email, info) in self.db_client.list_entries::<Email, UserInfo>().await? {
+ user_infos.push(info);
+ }
+ Ok(user_infos)
+ }
+
+ pub async fn tx_operators(&self) -> Result<Vec<UserInfo>> {
+ let mut tx_operators = Vec::new();
+ for (_email, info) in self.db_client.list_entries::<Email, UserInfo>().await? {
+ if info.is_tx_operator() {
+ tx_operators.push(info);
+ }
+ }
+ Ok(tx_operators)
+ }
+
+ pub async fn user_exist(&self, email: &Email) -> bool {
+ self.get_info(email).await.is_ok()
+ }
+ pub async fn add_user(
+ &mut self,
+ credential_manager: &CredentialManager,
+ user_name: &str,
+ user_email: &Email,
+ user_roles: &HashSet<Role>,
+ ) -> Result<UserInfo> {
+ if self.user_exist(user_email).await {
+ bail!("user already exists")
+ }
+ let public_key = credential_manager
+ .generate_user_credential(user_email)
+ .await?;
+ // account registry db
+ let userinfo = UserInfo::new(
+ user_name,
+ user_email.clone(),
+ user_roles.clone(),
+ public_key,
+ )?;
+
+ self.db_client.put(&userinfo).await?;
+ let uid_to_email = UidToEmail::new(userinfo.get_id().clone(), user_email.clone());
+ self.db_client.put(&uid_to_email).await?;
+ Ok(userinfo)
+ }
+
+ pub async fn append_role(&mut self, email: &Email, roles: &HashSet<Role>) -> Result<UserInfo> {
+ let mut info = self.get_info(email).await?;
+ for role in roles.iter() {
+ info.append_role((*role).clone());
+ log::info!("append role {:?} to user {:?}", role, email);
+ }
+ log::debug!("updated user info {:?}", info);
+ self.db_client.put(&info).await?;
+ Ok(info.clone())
+ }
+}
diff --git a/vm/wallet-gateway/certs/scripts/generate_certs.sh b/vm/wallet-gateway/certs/scripts/generate_certs.sh
new file mode 100755
index 00000000..6c06655c
--- /dev/null
+++ b/vm/wallet-gateway/certs/scripts/generate_certs.sh
@@ -0,0 +1,53 @@
+#!/bin/bash
+
+# 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.
+
+set -e
+
+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
+TMP_DIR=$SCRIPT_DIR/tmp
+if [ -d $TMP_DIR ]; then
+ echo "Temporary directory already exists"
+ exit 0
+fi
+mkdir $TMP_DIR
+
+openssl ecparam -name secp384r1 -out $TMP_DIR/ca.pem
+openssl req -nodes \
+ -x509 \
+ -newkey ec:$TMP_DIR/ca.pem \
+ -keyout $TMP_DIR/ca.key \
+ -out $TMP_DIR/ca.cert \
+ -sha256 \
+ -batch \
+ -days 3650 \
+ -subj "/CN=CK ECDSA CA"
+openssl asn1parse -in $TMP_DIR/ca.cert -out $TMP_DIR/ca.der > /dev/null
+openssl ec -in $TMP_DIR/ca.key -pubout -outform DER -out $TMP_DIR/ca.pub.der
+PUBKEY=$(openssl pkey -pubin -inform DER -in $TMP_DIR/ca.pub.der -text -noout)
+UNCOMPRESSED=$(echo $PUBKEY | sed ':a;N;$!ba;s/\n//g' | sed -e 's/[[:space:]]//g' | grep -o -E '04(:[[:xdigit:]]+)+')
+echo $UNCOMPRESSED | xxd -r -p > $TMP_DIR/ca.pub
+echo "CA certificate (for authority) generated"
+
+openssl ecparam -genkey -name prime256v1 -noout -out $TMP_DIR/system.pem
+openssl pkcs8 -topk8 -inform PEM -in $TMP_DIR/system.pem -out $TMP_DIR/system.key -nocrypt
+openssl ec -in $TMP_DIR/system.pem -pubout -outform DER -out $TMP_DIR/system.pub.der
+PUBKEY=$(openssl pkey -pubin -inform DER -in $TMP_DIR/system.pub.der -text -noout)
+UNCOMPRESSED=$(echo $PUBKEY | sed ':a;N;$!ba;s/\n//g' | sed -e 's/[[:space:]]//g' | grep -o -E '04(:[[:xdigit:]]+)+')
+echo $UNCOMPRESSED | xxd -r -p > $TMP_DIR/system.pub
+echo "System key pair (for webapi) generated"
diff --git a/vm/wallet-gateway/certs/scripts/install_certs.sh b/vm/wallet-gateway/certs/scripts/install_certs.sh
new file mode 100755
index 00000000..1dc67ec1
--- /dev/null
+++ b/vm/wallet-gateway/certs/scripts/install_certs.sh
@@ -0,0 +1,54 @@
+# 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.
+
+#!/bin/bash
+
+set -e
+
+CK_CLIENT_DB_ROOT_PATH=$1
+CK_TEE_BUILD_PATH=$2
+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
+TMP=$SCRIPT_DIR/tmp
+
+# check if paths are set
+if [ -z "$CK_CLIENT_DB_ROOT_PATH" ] || [ -z "$CK_TEE_BUILD_PATH" ]; then
+ echo "Usage: install_certs.sh <ck-root-path> <ck-tee-build-path>"
+ exit 1
+fi
+if [ ! -d $TMP ]; then
+ echo "$TMP does not exist. Please run generate_certs.sh first."
+ exit 1
+fi
+
+# install certs into ck client storage
+CK_ROOT_CERTS_PATH=$CK_CLIENT_DB_ROOT_PATH/certs
+if [ ! -d $CK_ROOT_CERTS_PATH ]; then
+ mkdir $CK_ROOT_CERTS_PATH
+fi
+cp $TMP/ca.key $TMP/ca.cert $TMP/ca.der $CK_ROOT_CERTS_PATH
+cp $TMP/system.key $CK_ROOT_CERTS_PATH
+echo "CA certificate (for authority) and system key pair (for webapi) installed into $CK_ROOT_CERTS_PATH"
+
+# install pubkeys into tee part
+CK_RS_CERTS_PATH=$CK_TEE_BUILD_PATH/pubkeys
+if [ ! -d $CK_RS_CERTS_PATH ]; then
+ mkdir $CK_RS_CERTS_PATH
+fi
+cp $TMP/ca.cert $TMP/ca.pub $TMP/system.pub $CK_RS_CERTS_PATH
+echo "CA pubkey (for authority) and system pubkey (for webapi) installed into $CK_RS_CERTS_PATH"
+
+echo "Certs installed"
diff --git a/vm/wallet-gateway/config/Cargo.toml b/vm/wallet-gateway/config/Cargo.toml
new file mode 100644
index 00000000..343691cc
--- /dev/null
+++ b/vm/wallet-gateway/config/Cargo.toml
@@ -0,0 +1,33 @@
+# 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.
+
+[package]
+name = "ck_config"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+anyhow = { version = "1.0.26" }
+log = { version = "0.4.6"}
+serde = { version = "1.0.92", features = ["derive"] }
+toml = { version = "0.5.1" }
+url = { version = "2.1.1", features = ["serde"] }
+types = { path = "../share/types" }
+utils = { path = "../utils" }
+
+[dev-dependencies]
+rustls = "0.21"
\ No newline at end of file
diff --git a/vm/wallet-gateway/config/runtime_config_example.toml b/vm/wallet-gateway/config/runtime_config_example.toml
new file mode 100644
index 00000000..c3e27d92
--- /dev/null
+++ b/vm/wallet-gateway/config/runtime_config_example.toml
@@ -0,0 +1,70 @@
+# 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.
+
+[internal_endpoints]
+# ---- app servers configuration:
+api_server = { listen_address = "0.0.0.0:8441", advertised_address = "http://localhost:8441" }
+authority_server = { listen_address = "0.0.0.0:8442", advertised_address = "http://localhost:8442" }
+db_service = { listen_address = "0.0.0.0:8543", advertised_address = "http://localhost:8543" }
+
+# ----Â TEE service configuration:
+tee_wallet = { listen_address = "0.0.0.0:54432", advertised_address = "https://localhost:54432" }
+
+[blockchain_network]
+# ---- specific configuration:
+network_type = "Testnet"
+# network_type = "Mainnet"
+
+# ---- common configuration:
+currency_query_base_url = "https://api.coingecko.com/api/v3/simple/price"
+
+eth_default_gas_limit = "21000" # string of u128
+erc20_default_gas_limit = "80000" # string of u128
+gas_price_percentage_increase = 0.2
+
+delegation_attempt_intervals = 60
+
+# automatically sign tx after all staged are approved
+auto_sign = true
+
+[task]
+# task-runner execution intervals
+task_exec_intervals = 30
+
+# email service domain
+email_domain = "mail.this.is.example.com"
+
+[user_auth_info]
+auth_service_url = "https://www.this.is.example.com"
+
+[storage]
+# root_path = $CK_ROOT_PATH, please set it before starting server
+# the below items set subpath as $CK_ROOT_PATH/*
+# this config file path is hardcoded as: config = "config/runtime_config.toml"
+
+# CA cert, CA keys
+certs_path = "certs/"
+
+# db server base path
+db_path = "db/"
+
+# authority export files
+export_path = "export/"
+export_base_url = "https://www.this.is.example.com/export/"
+
+# logs
+log_path = "log/"
diff --git a/vm/wallet-gateway/config/src/lib.rs b/vm/wallet-gateway/config/src/lib.rs
new file mode 100644
index 00000000..fb764f23
--- /dev/null
+++ b/vm/wallet-gateway/config/src/lib.rs
@@ -0,0 +1,28 @@
+// 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 serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum ConfigSource {
+ Path(PathBuf),
+}
+
+mod runtime;
+pub use runtime::{BlockchainNetworkConfig, RuntimeConfig};
diff --git a/vm/wallet-gateway/config/src/runtime.rs b/vm/wallet-gateway/config/src/runtime.rs
new file mode 100644
index 00000000..07247f45
--- /dev/null
+++ b/vm/wallet-gateway/config/src/runtime.rs
@@ -0,0 +1,125 @@
+// 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::{Context, Result};
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::net;
+use std::path::Path;
+use std::path::PathBuf;
+use types::serde_util;
+use types::share::NetworkType;
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct RuntimeConfig {
+ pub internal_endpoints: InternalEndpointsConfig,
+ pub blockchain_network: BlockchainNetworkConfig,
+ pub task: TaskConfig,
+ pub user_auth_info: UserAuthInfoConfig,
+ pub storage: StorageConfig,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct InternalEndpointsConfig {
+ pub api_server: InternalEndpoint,
+ pub authority_server: InternalEndpoint,
+ pub db_service: InternalEndpoint,
+ pub tee_wallet: InternalEndpoint,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct InternalEndpoint {
+ pub listen_address: net::SocketAddr,
+ pub advertised_address: url::Url,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct BlockchainNetworkConfig {
+ // network type
+ pub network_type: NetworkType,
+ // common
+ pub currency_query_base_url: url::Url,
+ #[serde(with = "serde_util::u128_string")]
+ pub eth_default_gas_limit: u128,
+ #[serde(with = "serde_util::u128_string")]
+ pub erc20_default_gas_limit: u128,
+ pub gas_price_percentage_increase: f64,
+ pub delegation_attempt_intervals: u64,
+ pub auto_sign: bool,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct TaskConfig {
+ pub task_exec_intervals: u64,
+ pub email_domain: String,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct UserAuthInfoConfig {
+ pub auth_service_url: url::Url,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct StorageConfig {
+ pub certs_path: PathBuf,
+ pub db_path: PathBuf,
+ pub export_path: PathBuf,
+ pub export_base_url: url::Url,
+ pub log_path: PathBuf,
+}
+
+impl RuntimeConfig {
+ pub fn from_toml<T: AsRef<Path>>(path: T) -> Result<Self> {
+ let contents = fs::read_to_string(path.as_ref())
+ .context("Something went wrong when reading the runtime config file")?;
+ let config: RuntimeConfig =
+ toml::from_str(&contents).context("Cannot parse the runtime config file")?;
+
+ log::trace!(
+ "Loaded config from {}: {:?}",
+ path.as_ref().display(),
+ config
+ );
+ Ok(config)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_runtime_config() {
+ let config = RuntimeConfig::from_toml("runtime_config_example.toml").unwrap();
+ let addr = config.internal_endpoints.api_server.listen_address;
+ println!("webapi: ip: {:?}, port: {:?}", addr.ip(), addr.port());
+
+ let url = config.internal_endpoints.tee_wallet.advertised_address;
+ let host = url.host().unwrap();
+ let s = format!("{}", &host);
+ println!(
+ "tee_wallet: name: {:?}, port: {:?}, s= {:?}",
+ url.host(),
+ url.port(),
+ s
+ );
+ println!(
+ "server_name = {:?}",
+ rustls::client::ServerName::try_from(s.as_str()).unwrap()
+ );
+ }
+}
diff --git a/vm/wallet-gateway/credential-manager/Cargo.toml b/vm/wallet-gateway/credential-manager/Cargo.toml
new file mode 100644
index 00000000..c270a2d0
--- /dev/null
+++ b/vm/wallet-gateway/credential-manager/Cargo.toml
@@ -0,0 +1,35 @@
+# 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.
+
+[package]
+name = "credential-manager"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+types = { path = "../share/types" }
+tls-client-processing = { path = "../tls-client-processing" }
+db-manager = { path = "../db-manager" }
+storable = { path = "../storable" }
+proto = { path = "../share/proto" }
+crypto = { path = "../share/crypto" }
+attestation = { path = "../share/attestation" }
+
+serde = "1.0"
+anyhow = "1.0"
+log = "0.4"
+bincode = "1.3.3"
\ No newline at end of file
diff --git a/vm/wallet-gateway/credential-manager/src/lib.rs b/vm/wallet-gateway/credential-manager/src/lib.rs
new file mode 100644
index 00000000..ee1586d0
--- /dev/null
+++ b/vm/wallet-gateway/credential-manager/src/lib.rs
@@ -0,0 +1,198 @@
+// 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::{anyhow, Result};
+use attestation::utils::{
+ generate_end_cert, generate_inter_cert, generate_key_pair, load_pem_key,
+ load_pem_key_from_bytes,
+};
+use crypto::sign_bytes_p384;
+use db_manager::StorageClient;
+use proto::BackupWalletInput;
+use std::collections::HashSet;
+use std::sync::Arc;
+use storable::credential::{CaCredential, UserCredential};
+use tls_client_processing::Credential;
+use types::external::Email;
+use types::share::{
+ CkPrivateKey, CkPublicKey, CkSignature, DeviceID, TaUserInfo, TaWalletInfo, TeeConfig, WalletID,
+};
+
+const END_CERT_VAILD_SECONDS: i64 = 60 * 60 * 24 * 365; // 1 year
+const INTER_CERT_VAILD_SECONDS: i64 = 60 * 60 * 24 * 365; // 1 year
+
+pub struct CredentialManager {
+ db_client: Arc<StorageClient>,
+ ca_credential: CaCredential,
+ cert_path: String,
+}
+
+impl CredentialManager {
+ pub async fn init(db_client: Arc<StorageClient>, cert_path: &str) -> Result<Self> {
+ let ca_creds = if let Some(ca_credential) = Self::load_from_db(db_client.clone()).await? {
+ ca_credential
+ } else {
+ Self::load_from_file(cert_path)?
+ };
+
+ Ok(Self {
+ db_client,
+ ca_credential: ca_creds,
+ cert_path: cert_path.to_string(),
+ })
+ }
+
+ async fn load_from_db(db_client: Arc<StorageClient>) -> Result<Option<CaCredential>> {
+ let ca_creds = db_client.get(&"CaCredential".into()).await?;
+ Ok(ca_creds)
+ }
+
+ fn load_from_file(cert_path: &str) -> Result<CaCredential> {
+ let ca_cert = std::fs::read(cert_path.to_owned() + "/ca.cert").map_err(|e| {
+ anyhow!(
+ "CaCredential::load: failed to read ca.cert from {}: {}",
+ cert_path.to_owned() + "/ca.cert",
+ e
+ )
+ })?;
+ let ca_der = std::fs::read(cert_path.to_owned() + "/ca.der").map_err(|e| {
+ anyhow!(
+ "CaCredential::load: failed to read ca.der from {}: {}",
+ cert_path.to_owned() + "/ca.der",
+ e
+ )
+ })?;
+ let ca_key = std::fs::read(cert_path.to_owned() + "/ca.key").map_err(|e| {
+ anyhow!(
+ "CaCredential::load: failed to read ca.key from {}: {}",
+ cert_path.to_owned() + "/ca.key",
+ e
+ )
+ })?;
+ Ok(CaCredential::new(ca_cert, ca_der, ca_key))
+ }
+
+ fn ca_cert(&self) -> &Vec<u8> {
+ self.ca_credential.ca_cert()
+ }
+
+ fn ca_der(&self) -> &Vec<u8> {
+ self.ca_credential.ca_der()
+ }
+
+ pub async fn get_user_tls_credential(&self, email: &Email) -> Result<Credential> {
+ let credential: UserCredential = match self.db_client.get(email).await? {
+ Some(credential) => credential,
+ None => {
+ return Err(anyhow!(
+ "CredentialManager::get_user_tls_credential(): user {} not found",
+ email.0
+ ))
+ }
+ };
+ let client_der = credential.cert().clone();
+ let client_key: CkPrivateKey = credential.into();
+ Ok(Credential::new(
+ self.ca_cert().clone(),
+ client_der,
+ client_key.into(),
+ self.ca_der().clone(),
+ ))
+ }
+
+ pub fn get_system_tls_credential(&self) -> Result<Credential> {
+ let ca_cert = self.ca_cert().clone();
+ let ca_der = self.ca_der().clone();
+ let private_key = load_pem_key(&(self.cert_path.clone() + "/system.key")).map_err(|e| {
+ anyhow!(
+ "CredentialManager::get_system_tls_credential(): failed to load system.key: {}",
+ e
+ )
+ })?;
+ let cert = generate_end_cert(
+ self.ca_credential.ca_key(),
+ &private_key.0,
+ "system",
+ END_CERT_VAILD_SECONDS,
+ )?;
+ Ok(Credential::new(ca_cert, cert, private_key.0, ca_der))
+ }
+
+ pub async fn generate_user_credential(&self, email: &Email) -> Result<CkPublicKey> {
+ // generate key pair
+ let (public_key, private_key) = generate_key_pair()?;
+ // generate cert
+ let cert = generate_end_cert(
+ self.ca_credential.ca_key(),
+ &private_key,
+ &email.0,
+ END_CERT_VAILD_SECONDS,
+ )?;
+
+ let credential = UserCredential::new(
+ email.clone(),
+ CkPublicKey::new(public_key.as_slice()),
+ CkPrivateKey::new(private_key.as_slice()),
+ cert,
+ );
+ self.db_client.put(&credential).await?;
+ Ok(CkPublicKey::new(public_key.as_slice()))
+ }
+
+ pub fn generate_tee_cert(&self, device_public_key: &CkPublicKey) -> Result<Vec<u8>> {
+ // generate cert
+ let tee_cert = generate_inter_cert(
+ self.ca_credential.ca_key(),
+ device_public_key.0.as_slice(),
+ INTER_CERT_VAILD_SECONDS,
+ )?;
+ Ok(tee_cert)
+ }
+
+ pub fn sign_wallet_info(
+ &self,
+ user_registry: Vec<TaUserInfo>,
+ wallets: Vec<TaWalletInfo>,
+ config_version: u64,
+ ) -> Result<TeeConfig> {
+ let mut config = TeeConfig::new(user_registry, wallets, config_version);
+ let priv_key = load_pem_key_from_bytes(self.ca_credential.ca_key())?;
+ let sig = CkSignature::new(sign_bytes_p384(
+ priv_key.0.as_slice(),
+ &config.serialize()?,
+ )?);
+ config.set_signature(sig);
+ Ok(config)
+ }
+
+ pub fn sign_backup_device_list(
+ &self,
+ backup_to_device_id: DeviceID,
+ backup_to_device_pubkey: CkPublicKey,
+ target_wallets: HashSet<WalletID>,
+ ) -> Result<BackupWalletInput> {
+ let mut input = BackupWalletInput::new_unsigned(
+ backup_to_device_id,
+ backup_to_device_pubkey,
+ target_wallets,
+ );
+ let priv_key = load_pem_key_from_bytes(self.ca_credential.ca_key())?;
+ let sig = CkSignature::new(sign_bytes_p384(priv_key.0.as_slice(), &input.serialize()?)?);
+ input.set_signature(sig);
+ Ok(input)
+ }
+}
diff --git a/vm/wallet-gateway/db-manager/Cargo.toml b/vm/wallet-gateway/db-manager/Cargo.toml
new file mode 100644
index 00000000..26611c79
--- /dev/null
+++ b/vm/wallet-gateway/db-manager/Cargo.toml
@@ -0,0 +1,39 @@
+# 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.
+
+[package]
+name = "db-manager"
+version = "0.1.0"
+edition = "2021"
+
+[features]
+default = []
+rocks-db = [ "dep:rocksdb" ]
+
+[dependencies]
+anyhow = "1.0"
+rocksdb = { version = "0.21.0", optional = true }
+env_logger = "0.10"
+log = "0.4"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+serde_with = "3.8"
+async-trait = "0.1.74"
+tokio = { version = "1.0", features = ["full"] }
+reqwest = { version = "0.11.18", features = ["json", "multipart"] }
+
+storable = { path = "../storable" }
diff --git a/vm/wallet-gateway/db-manager/src/db_compatible_client.rs b/vm/wallet-gateway/db-manager/src/db_compatible_client.rs
new file mode 100644
index 00000000..97ffb2d9
--- /dev/null
+++ b/vm/wallet-gateway/db-manager/src/db_compatible_client.rs
@@ -0,0 +1,99 @@
+// 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::Result;
+use async_trait::async_trait;
+#[cfg(feature = "rocks-db")]
+use rocksdb::{DBWithThreadMode, IteratorMode, MultiThreaded};
+use std::collections::HashMap;
+
+pub trait DBCredentials {}
+
+#[async_trait]
+pub trait DBCompatibleClient: Send + Sync {
+ type T: DBCredentials;
+ async fn init(db_name: &str, credentials: Option<Self::T>) -> Result<Self>
+ where
+ Self: Sized;
+ async fn get_value(&self, key: &str) -> Result<Option<Vec<u8>>>;
+ async fn put_value(&self, key: &str, value: &[u8]) -> Result<()>;
+ async fn delete_entry(&self, key: &str) -> Result<()>;
+ async fn list_entries(&self) -> Result<HashMap<String, Vec<u8>>>;
+ async fn list_entries_with_prefix(&self, prefix: &str) -> Result<HashMap<String, Vec<u8>>>;
+}
+
+#[cfg(feature = "rocks-db")]
+pub struct RocksDBCredentials {}
+#[cfg(feature = "rocks-db")]
+impl DBCredentials for RocksDBCredentials {}
+#[cfg(feature = "rocks-db")]
+pub struct RocksDBClient {
+ db: DBWithThreadMode<MultiThreaded>,
+}
+#[async_trait]
+#[cfg(feature = "rocks-db")]
+impl DBCompatibleClient for RocksDBClient {
+ type T = RocksDBCredentials;
+ async fn init(db_name: &str, _credentials: Option<Self::T>) -> Result<Self> {
+ let db = DBWithThreadMode::<MultiThreaded>::open_default(db_name)?;
+ Ok(Self { db })
+ }
+
+ async fn get_value(&self, key: &str) -> Result<Option<Vec<u8>>> {
+ match self.db.get(key) {
+ Ok(Some(value)) => Ok(Some(value)),
+ Ok(None) => Ok(None),
+ Err(e) => {
+ bail!("rocksdb get error: {}", e);
+ }
+ }
+ }
+
+ async fn put_value(&self, key: &str, value: &[u8]) -> Result<()> {
+ self.db.put(key, value)?;
+ Ok(())
+ }
+
+ async fn delete_entry(&self, key: &str) -> Result<()> {
+ self.db.delete(key)?;
+ Ok(())
+ }
+
+ async fn list_entries(&self) -> Result<HashMap<String, Vec<u8>>> {
+ let mut map = HashMap::new();
+ let iter = self.db.iterator(IteratorMode::Start);
+ for item in iter {
+ let (key, value) = item?;
+ map.insert(String::from_utf8(key.to_vec())?, value.to_vec());
+ }
+ Ok(map)
+ }
+
+ async fn list_entries_with_prefix(&self, prefix: &str) -> Result<HashMap<String, Vec<u8>>> {
+ let mut map: HashMap<String, Vec<u8>> = HashMap::new();
+ let iter = self.db.iterator(IteratorMode::Start);
+ for item in iter {
+ let (key, value) = item?;
+
+ let key = String::from_utf8(key.to_vec())?;
+ if key.starts_with(prefix) {
+ map.insert(key, value.to_vec());
+ }
+ }
+ Ok(map)
+ }
+}
diff --git a/vm/wallet-gateway/db-manager/src/lib.rs b/vm/wallet-gateway/db-manager/src/lib.rs
new file mode 100644
index 00000000..5217a663
--- /dev/null
+++ b/vm/wallet-gateway/db-manager/src/lib.rs
@@ -0,0 +1,23 @@
+// 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.
+
+mod db_compatible_client;
+pub use db_compatible_client::*;
+mod storage_client;
+pub use storage_client::*;
+pub mod local_service_client;
+pub use local_service_client::{LocalServiceClient, LocalServiceCredentials};
diff --git a/vm/wallet-gateway/db-manager/src/local_service_client.rs b/vm/wallet-gateway/db-manager/src/local_service_client.rs
new file mode 100644
index 00000000..5a40e510
--- /dev/null
+++ b/vm/wallet-gateway/db-manager/src/local_service_client.rs
@@ -0,0 +1,172 @@
+// 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 crate::{DBCompatibleClient, DBCredentials};
+use anyhow::Result;
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+
+// unused, reserved for AWS tokens
+pub struct LocalServiceCredentials {}
+impl DBCredentials for LocalServiceCredentials {}
+
+pub struct LocalServiceClient {
+ address: String, // ip:port, http://localhost:8543
+ req_client: reqwest::Client,
+}
+#[async_trait]
+impl DBCompatibleClient for LocalServiceClient {
+ type T = LocalServiceCredentials;
+ async fn init(db_name: &str, _credentials: Option<Self::T>) -> Result<Self> {
+ Ok(Self {
+ address: db_name.to_string(),
+ req_client: reqwest::Client::new(),
+ })
+ }
+
+ async fn get_value(&self, key: &str) -> Result<Option<Vec<u8>>> {
+ let request = GetRequest {
+ key: key.as_bytes().to_vec(),
+ };
+ let response = self
+ .req_client
+ .post(format!("{}get", self.address))
+ .json(&request)
+ .send()
+ .await?
+ .json::<GetResponse>()
+ .await?;
+ Ok(response.value)
+ }
+
+ async fn put_value(&self, key: &str, value: &[u8]) -> Result<()> {
+ let request = PutRequest {
+ key: key.as_bytes().to_vec(),
+ value: value.to_vec(),
+ };
+ match self
+ .req_client
+ .post(format!("{}put", self.address))
+ .json(&request)
+ .send()
+ .await?
+ .json::<PutResponse>()
+ .await
+ {
+ Ok(_) => Ok(()),
+ Err(e) => {
+ log::error!("put_value(): error: {:?}", e);
+ Ok(())
+ }
+ }
+ }
+
+ async fn delete_entry(&self, key: &str) -> Result<()> {
+ let request = DeleteRequest {
+ key: key.as_bytes().to_vec(),
+ };
+ match self
+ .req_client
+ .post(format!("{}delete", self.address))
+ .json(&request)
+ .send()
+ .await?
+ .json::<DeleteResponse>()
+ .await
+ {
+ Ok(_response) => Ok(()),
+ Err(e) => {
+ log::error!("delete_entry(): error: {:?}", e);
+ Ok(())
+ }
+ }
+ }
+
+ async fn list_entries(&self) -> Result<HashMap<String, Vec<u8>>> {
+ let request = ListRequest {};
+ let response = self
+ .req_client
+ .post(format!("{}list", self.address))
+ .json(&request)
+ .send()
+ .await?
+ .json::<ListResponse>()
+ .await?;
+ Ok(response.map)
+ }
+
+ async fn list_entries_with_prefix(&self, prefix: &str) -> Result<HashMap<String, Vec<u8>>> {
+ let request = ListByPrefixRequest {
+ prefix: prefix.to_string(),
+ };
+ let response = self
+ .req_client
+ .post(format!("{}list_by_prefix", self.address))
+ .json(&request)
+ .send()
+ .await?
+ .json::<ListByPrefixResponse>()
+ .await?;
+ Ok(response.map)
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct GetRequest {
+ pub key: Vec<u8>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct GetResponse {
+ pub value: Option<Vec<u8>>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PutRequest {
+ pub key: Vec<u8>,
+ pub value: Vec<u8>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PutResponse {}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DeleteRequest {
+ pub key: Vec<u8>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DeleteResponse {}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ListRequest {}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ListResponse {
+ pub map: HashMap<String, Vec<u8>>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ListByPrefixRequest {
+ pub prefix: String,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ListByPrefixResponse {
+ pub map: HashMap<String, Vec<u8>>, // key -> value
+}
diff --git a/vm/wallet-gateway/db-manager/src/storage_client.rs b/vm/wallet-gateway/db-manager/src/storage_client.rs
new file mode 100644
index 00000000..4a7145cb
--- /dev/null
+++ b/vm/wallet-gateway/db-manager/src/storage_client.rs
@@ -0,0 +1,93 @@
+// 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.
+
+// abstraction layer for webapi & authority
+
+use crate::{db_compatible_client::DBCompatibleClient, LocalServiceCredentials};
+use anyhow::Result;
+use core::hash::Hash;
+use std::collections::HashMap;
+use std::sync::Arc;
+use storable::Storable;
+use tokio::sync::RwLock;
+
+pub struct StorageClient {
+ client: Box<dyn DBCompatibleClient<T = LocalServiceCredentials>>,
+ cache: Arc<RwLock<HashMap<String, Vec<u8>>>>,
+}
+impl StorageClient {
+ pub fn new(client: Box<dyn DBCompatibleClient<T = LocalServiceCredentials>>) -> Self {
+ Self {
+ client,
+ cache: Arc::new(RwLock::new(HashMap::new())),
+ }
+ }
+ pub async fn get<K, V>(&self, key: &K) -> Result<Option<V>>
+ where
+ K: TryFrom<String> + Into<String> + Clone,
+ V: Storable<K>,
+ {
+ let key: String = (*key).clone().into();
+ let storage_key = V::concat_key(&key);
+ log::debug!("get(): storage_key: {}", storage_key);
+
+ match self.client.get_value(&storage_key).await? {
+ Some(value) => Ok(Some(serde_json::from_slice(&value)?)),
+ None => Ok(None),
+ }
+ }
+ pub async fn put<K, V>(&self, value: &V) -> Result<()>
+ where
+ K: TryFrom<String> + Into<String> + Clone,
+ V: Storable<K>,
+ {
+ let key = value.storage_key();
+ log::debug!("put(): storage_key: {}", key);
+ let value = serde_json::to_vec(value)?;
+ self.client.put_value(&key, &value).await?;
+
+ Ok(())
+ }
+ pub async fn delete_entry<K, V>(&self, key: &K) -> Result<()>
+ where
+ K: TryFrom<String> + Into<String> + Clone,
+ V: Storable<K>,
+ {
+ let key: String = (*key).clone().into();
+ let storage_key = V::concat_key(&key);
+ self.client.delete_entry(&storage_key).await?;
+
+ Ok(())
+ }
+ pub async fn list_entries<K, V>(&self) -> Result<HashMap<K, V>>
+ where
+ K: TryFrom<String> + Into<String> + Clone + Eq + Hash,
+ V: Storable<K>,
+ {
+ let mut entries = HashMap::new();
+ log::debug!("list_entries: table_name: {}", V::table_name());
+ let map = self
+ .client
+ .list_entries_with_prefix(V::table_name())
+ .await?;
+ for (key, value) in map {
+ let value: V = serde_json::from_slice(&value)?;
+ entries.insert(value.unique_id().to_owned(), value);
+ }
+ Ok(entries)
+ }
+}
diff --git a/vm/wallet-gateway/db-service/Cargo.toml b/vm/wallet-gateway/db-service/Cargo.toml
new file mode 100644
index 00000000..3ecc13fd
--- /dev/null
+++ b/vm/wallet-gateway/db-service/Cargo.toml
@@ -0,0 +1,34 @@
+# 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.
+
+[package]
+name = "db-service"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+actix-web = { version = "4.3" }
+env_logger = "0.10"
+log = "0.4"
+anyhow = "1.0"
+thiserror = "1.0"
+serde = { version = "1.0", features = ["derive"] }
+serde_with = "3.8"
+rocksdb = "0.21.0"
+
+ck_config = { path = "../config" }
+db-manager = { path = "../db-manager" }
\ No newline at end of file
diff --git a/vm/wallet-gateway/db-service/Dockerfile b/vm/wallet-gateway/db-service/Dockerfile
new file mode 100644
index 00000000..362e5fe6
--- /dev/null
+++ b/vm/wallet-gateway/db-service/Dockerfile
@@ -0,0 +1,39 @@
+# 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.
+
+# Pull the Rust Docker image
+FROM rust:1.82 as builder
+
+# Install Clang
+RUN apt-get update && apt-get install -y \
+ clang
+
+# Create a new empty shell project
+WORKDIR /wallet-gateway
+COPY . .
+
+# Build the project
+RUN cargo install --path ./db-service
+
+# Start a new, final image
+FROM rust:1.82-slim
+
+# Copy over the binary from the builder phase
+COPY --from=builder /usr/local/cargo/bin/db-service /usr/local/bin/db-service
+
+# Run the binary
+CMD ["db-service"]
diff --git a/vm/wallet-gateway/db-service/src/main.rs b/vm/wallet-gateway/db-service/src/main.rs
new file mode 100644
index 00000000..a94a8961
--- /dev/null
+++ b/vm/wallet-gateway/db-service/src/main.rs
@@ -0,0 +1,202 @@
+// 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 actix_web::{middleware, web, App, HttpResponse, HttpServer, Responder};
+use anyhow::{anyhow, Result};
+use rocksdb::{DBWithThreadMode, IteratorMode, MultiThreaded};
+use std::{collections::HashMap, sync::Arc};
+
+use ck_config::RuntimeConfig;
+use db_manager::local_service_client::{
+ DeleteRequest, DeleteResponse, GetRequest, GetResponse, ListByPrefixRequest,
+ ListByPrefixResponse, ListRequest, ListResponse, PutRequest, PutResponse,
+};
+
+#[derive(Debug, Clone)]
+struct LocalStorageService {
+ db: Arc<DBWithThreadMode<MultiThreaded>>,
+ listening_address: String,
+}
+
+impl LocalStorageService {
+ pub fn init(db_path: std::path::PathBuf, ip: std::net::IpAddr, port: u16) -> Result<Self> {
+ let db = DBWithThreadMode::<MultiThreaded>::open_default(db_path)?;
+ let addr = format!("{}:{}", ip, port);
+ Ok(Self {
+ db: Arc::new(db),
+ listening_address: addr,
+ })
+ }
+
+ pub async fn start(&self) -> std::io::Result<()> {
+ let app_data = web::Data::new(self.clone());
+ HttpServer::new(move || {
+ App::new()
+ .wrap(middleware::Logger::default())
+ .app_data(app_data.clone())
+ .route("/get", web::post().to(handle_get))
+ .route("/put", web::post().to(handle_put))
+ .route("/delete", web::post().to(handle_delete))
+ .route("/list", web::post().to(handle_list))
+ .route("/list_by_prefix", web::post().to(handle_list_by_prefix))
+ })
+ .bind(&self.listening_address)?
+ .run()
+ .await
+ }
+
+ fn get(&self, request: GetRequest) -> Result<GetResponse> {
+ self.db
+ .get(request.key)
+ .map_err(|e| anyhow!("rocksdb get error: {}", e))
+ .map(|value| GetResponse { value })
+ }
+
+ fn put(&self, request: PutRequest) -> Result<PutResponse> {
+ self.db
+ .put(&request.key, &request.value)
+ .map_err(|e| anyhow!("rocksdb put error: {}", e))
+ .map(|_| PutResponse {})
+ }
+
+ fn delete(&self, request: DeleteRequest) -> Result<DeleteResponse> {
+ self.db
+ .delete(request.key)
+ .map_err(|e| anyhow!("rocksdb delete error: {}", e))
+ .map(|_| DeleteResponse {})
+ }
+
+ fn list(&self) -> Result<ListResponse> {
+ let mut map: HashMap<String, Vec<u8>> = HashMap::new();
+ let iter = self.db.iterator(IteratorMode::Start);
+ for item in iter {
+ let (key, value) = item?;
+ map.insert(String::from_utf8(key.to_vec())?, value.to_vec());
+ }
+ Ok(ListResponse { map })
+ }
+
+ fn list_by_prefix(&self, request: ListByPrefixRequest) -> Result<ListByPrefixResponse> {
+ let prefix = &request.prefix;
+
+ let mut map: HashMap<String, Vec<u8>> = HashMap::new();
+ let iter = self.db.iterator(IteratorMode::Start);
+ for item in iter {
+ let (key, value) = item?;
+
+ let key = String::from_utf8(key.to_vec())?;
+ if key.starts_with(prefix) {
+ map.insert(key, value.to_vec());
+ }
+ }
+ Ok(ListByPrefixResponse { map })
+ }
+}
+
+async fn handle_get(
+ data: web::Data<LocalStorageService>,
+ request: web::Json<GetRequest>,
+) -> impl Responder {
+ match data.get(request.into_inner()) {
+ Ok(response) => HttpResponse::Ok().json(response),
+ Err(e) => {
+ log::error!("handle_get error: {}", e);
+ HttpResponse::InternalServerError().finish()
+ }
+ }
+}
+
+async fn handle_put(
+ data: web::Data<LocalStorageService>,
+ request: web::Json<PutRequest>,
+) -> impl Responder {
+ match data.put(request.into_inner()) {
+ Ok(_) => HttpResponse::Ok().json(PutResponse {}),
+ Err(e) => {
+ log::error!("handle_put error: {}", e);
+ HttpResponse::InternalServerError().finish()
+ }
+ }
+}
+
+async fn handle_delete(
+ data: web::Data<LocalStorageService>,
+ request: web::Json<DeleteRequest>,
+) -> impl Responder {
+ match data.delete(request.into_inner()) {
+ Ok(_) => HttpResponse::Ok().json(DeleteResponse {}),
+ Err(e) => {
+ log::error!("handle_delete error: {}", e);
+ HttpResponse::InternalServerError().finish()
+ }
+ }
+}
+
+async fn handle_list(
+ data: web::Data<LocalStorageService>,
+ _request: web::Json<ListRequest>,
+) -> impl Responder {
+ match data.list() {
+ Ok(response) => HttpResponse::Ok().json(response),
+ Err(e) => {
+ log::error!("handle_list error: {}", e);
+ HttpResponse::InternalServerError().finish()
+ }
+ }
+}
+
+async fn handle_list_by_prefix(
+ data: web::Data<LocalStorageService>,
+ request: web::Json<ListByPrefixRequest>,
+) -> impl Responder {
+ match data.list_by_prefix(request.into_inner()) {
+ Ok(response) => HttpResponse::Ok().json(response),
+ Err(e) => {
+ log::error!("handle_list_by_prefix error: {}", e);
+ HttpResponse::InternalServerError().finish()
+ }
+ }
+}
+
+#[actix_web::main]
+async fn main() -> std::io::Result<()> {
+ env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
+ let root_path_str = std::env::var("CK_ROOT_PATH").map_err(|e| {
+ log::error!("CK_ROOT_PATH error: {:?}", e);
+ std::io::Error::new(std::io::ErrorKind::Other, e)
+ })?;
+ let root_path = std::path::Path::new(&root_path_str);
+ let config_file_path = std::path::Path::new("config/runtime_config.toml");
+ let runtime_config = RuntimeConfig::from_toml(root_path.join(config_file_path))
+ .expect("failed to read runtime config");
+
+ let ip = runtime_config
+ .internal_endpoints
+ .db_service
+ .listen_address
+ .ip();
+ let port = runtime_config
+ .internal_endpoints
+ .db_service
+ .listen_address
+ .port();
+ let db_path = root_path.join(runtime_config.storage.db_path);
+
+ let storage_service =
+ LocalStorageService::init(db_path, ip, port).expect("Failed to create storage service");
+ storage_service.start().await
+}
diff --git a/vm/wallet-gateway/env.list b/vm/wallet-gateway/env.list
new file mode 100644
index 00000000..2885c047
--- /dev/null
+++ b/vm/wallet-gateway/env.list
@@ -0,0 +1,23 @@
+# 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.
+
+CK_ROOT_PATH=/ck-root
+MAILGUN_AUTH_TOKEN="YOUR_TOKEN"
+INFURA_TOKEN="YOUR_TOKEN"
+ETHERSCAN_TOKEN="YOUR_TOKEN"
+BSCSCAN_TOKEN="YOUR_TOKEN"
+CURRENCY_QUERY_TOKEN="YOUR_TOKEN"
diff --git a/vm/wallet-gateway/net/Cargo.toml b/vm/wallet-gateway/net/Cargo.toml
new file mode 100644
index 00000000..76e2c6fb
--- /dev/null
+++ b/vm/wallet-gateway/net/Cargo.toml
@@ -0,0 +1,41 @@
+# 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.
+
+[package]
+name = "net"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+serde = "1.0"
+anyhow = "1.0"
+thiserror = "1.0"
+log = "0.4"
+serde_json = "1.0"
+url = { version = "2.1.1", features = ["serde"] }
+reqwest = { version = "0.11.18", features = ["json", "multipart"] }
+ethabi = "14.0.0"
+hex = { version = "0.4", features = ["serde"] }
+serde-hex = "0.1.0"
+enum-iterator = "1.4.1"
+async-trait = "0.1.74"
+tokio = { version = "1.0", features = ["macros"] }
+
+types = { path = "../share/types" }
+storable = { path = "../storable" }
+utils = { path = "../utils" }
+notification = { path = "../notification" }
diff --git a/vm/wallet-gateway/net/src/endpoints/asset_price.rs b/vm/wallet-gateway/net/src/endpoints/asset_price.rs
new file mode 100644
index 00000000..476abf87
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/asset_price.rs
@@ -0,0 +1,89 @@
+// 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::{anyhow, Result};
+use async_trait::async_trait;
+use types::external::AssetType;
+
+// Query currency price for all chain, ETH, ERC20, BTC, ..
+pub struct AssetPriceEndpoint {
+ client: reqwest::Client,
+ end_point: Box<dyn GetAssetPriceService>,
+}
+
+impl AssetPriceEndpoint {
+ pub fn new(url: url::Url, token: String) -> Self {
+ Self {
+ client: reqwest::Client::new(),
+ end_point: Box::new(CoinGeckoEndpoint::new(url, token)),
+ }
+ }
+
+ pub async fn get_asset_price(&self, asset_type: AssetType) -> Result<f64> {
+ self.end_point
+ .get_asset_price(self.client.clone(), asset_type)
+ .await
+ }
+}
+
+#[async_trait]
+pub trait GetAssetPriceService: Send + Sync {
+ fn new(url: url::Url, token: String) -> Self
+ where
+ Self: Sized;
+ async fn get_asset_price(&self, client: reqwest::Client, asset_type: AssetType) -> Result<f64>;
+}
+
+pub struct CoinGeckoEndpoint {
+ url: url::Url,
+ token: String,
+}
+
+#[async_trait]
+impl GetAssetPriceService for CoinGeckoEndpoint {
+ fn new(url: url::Url, token: String) -> Self {
+ Self { url, token }
+ }
+ async fn get_asset_price(&self, client: reqwest::Client, asset_type: AssetType) -> Result<f64> {
+ let asset = asset_type.config();
+ let currency_id = asset.currency_id();
+ let resp = client
+ .get(self.url.clone())
+ .query(&[
+ ("ids", currency_id.as_str()),
+ ("vs_currencies", "usd"),
+ ("x_cg_demo_api_key", &self.token),
+ ])
+ .send()
+ .await?;
+ let resp_json: serde_json::Value = resp.json().await?;
+ match resp_json[¤cy_id]["usd"].as_f64() {
+ Some(price) => {
+ log::info!("get usd_currency: {:?} for {:?}", price, asset_type);
+ Ok(price)
+ }
+ None => {
+ log::error!(
+ "Failed to get price for {:?}, response: {:?}",
+ asset_type,
+ resp_json
+ );
+ Err(anyhow!("Failed to get price for {:?}", asset_type))
+ }
+ }
+ }
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/btc_rpc.rs b/vm/wallet-gateway/net/src/endpoints/btc_rpc.rs
new file mode 100644
index 00000000..55b4aeaa
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/btc_rpc.rs
@@ -0,0 +1,150 @@
+// 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 std::collections::HashMap;
+
+use anyhow::{anyhow, bail, Result};
+use storable::utxo_record::{AddressUtxoRecords, UtxoRecord};
+use types::{
+ external::TxSubmissionResult,
+ share::{CkNetwork, CkSignature, ClientBtcAddress, NetworkType},
+};
+
+use crate::params::UtxoQueryResult;
+
+pub struct BtcRpcEndpoint {
+ url: url::Url,
+ client: reqwest::Client,
+ network: NetworkType,
+}
+
+impl BtcRpcEndpoint {
+ pub fn new(network: CkNetwork) -> Self {
+ matches!(network, CkNetwork::Btc(_));
+ Self {
+ url: network.rpc_api_url(),
+ client: reqwest::Client::new(),
+ network: network.network_type(),
+ }
+ }
+
+ pub async fn get_utxos_for_address(
+ &self,
+ address: &ClientBtcAddress,
+ ) -> Result<AddressUtxoRecords> {
+ let esplora_get_utxo_endpoint =
+ format!("{}/address/{}/utxo", self.url, address.address_str());
+ log::debug!("esplora_get_utxo_endpoint: {:?}", esplora_get_utxo_endpoint);
+ let response = self.client.get(esplora_get_utxo_endpoint).send().await;
+ match response {
+ Ok(res) => {
+ let mut address_utxo_records = AddressUtxoRecords::new(address.clone());
+ if res.status().is_success() {
+ let utxos: serde_json::Value = res.json().await?;
+ log::debug!("UTXOs: {:?}", utxos);
+ if utxos.is_array() {
+ for utxo in utxos.as_array().ok_or(anyhow!("Error parsing UTXOs"))? {
+ let result: UtxoQueryResult = match serde_json::from_value(utxo.clone())
+ {
+ Ok(result) => result,
+ Err(err) => {
+ log::error!("Error parsing UTXO: {:?}", err);
+ continue;
+ }
+ };
+ log::info!("UTXO - {:?}", result);
+
+ let utxo = UtxoRecord::new(
+ address.clone(),
+ &result.txid,
+ result.vout,
+ result.value,
+ result.status.block_height,
+ &result.status.block_hash,
+ result.status.block_time,
+ );
+ address_utxo_records.push(utxo);
+ }
+ } else {
+ log::info!("No UTXOs found for the address {:?}", address);
+ }
+ } else {
+ bail!("Error in response: {}", res.status());
+ }
+ Ok(address_utxo_records)
+ }
+ Err(err) => {
+ bail!("Error querying address information: {:?}", err);
+ }
+ }
+ }
+
+ pub async fn get_fee_rate(&self) -> Result<HashMap<u16, f64>> {
+ let esplora_get_fee_rate_endpoint = format!("{}/fee-estimates", self.url);
+ let response = self.client.get(esplora_get_fee_rate_endpoint).send().await;
+ match response {
+ Ok(res) => {
+ if res.status().is_success() {
+ let fee_rates: HashMap<String, f64> = res.json().await?;
+ log::debug!("Estimated fee rate: {:?}", fee_rates);
+ // Convert the keys to u16
+ let fee_rates: HashMap<u16, f64> = fee_rates
+ .iter()
+ .map(|(k, v)| (k.parse().unwrap_or_default(), *v))
+ .collect();
+ Ok(fee_rates)
+ } else {
+ log::error!("Error in response: {}", res.status());
+ Ok(HashMap::new())
+ }
+ }
+ Err(err) => {
+ bail!("Error querying fee rate: {:?}", err);
+ }
+ }
+ }
+
+ pub async fn broadcast_transaction(
+ &self,
+ serialized_tx: CkSignature,
+ ) -> Result<TxSubmissionResult> {
+ let esplora_broadcast_tx_endpoint = format!("{}/tx", self.url);
+ let tx_hex: String = serialized_tx.into();
+ let response = self
+ .client
+ .post(esplora_broadcast_tx_endpoint)
+ .body(tx_hex)
+ .send()
+ .await;
+ match response {
+ Ok(res) => {
+ if res.status().is_success() {
+ let res = res.text().await?;
+ log::info!("Transaction broadcasted successfully. Res: {:?}", res);
+ Ok(TxSubmissionResult::Accepted(res.into()))
+ } else {
+ let msg = res.text().await?;
+ log::error!("Error in response: {}", msg);
+ Ok(TxSubmissionResult::Rejected(msg.into()))
+ }
+ }
+ Err(err) => {
+ bail!("Error broadcasting transaction: {:?}", err);
+ }
+ }
+ }
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/eth_payment.rs b/vm/wallet-gateway/net/src/endpoints/eth_payment.rs
new file mode 100644
index 00000000..adce5e89
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/eth_payment.rs
@@ -0,0 +1,162 @@
+// 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, ensure, Result};
+use types::{
+ external::AssetType,
+ share::{CkNetwork, EthAddress, NetworkType},
+};
+
+use crate::endpoints::params::{construct_payment_params, PaymentQueryResult};
+
+// Query historical payment from etherscan
+// Etherscan is enough for our use case, if we need to use other
+// service as backend, we can define a trait like in AssetPriceEndpoint
+pub struct EthReceivedPaymentEndpoint {
+ url: url::Url,
+ token: String,
+ network_type: NetworkType,
+ client: reqwest::Client,
+}
+
+impl EthReceivedPaymentEndpoint {
+ pub fn new(network: CkNetwork, token: String) -> Self {
+ Self {
+ url: network.explorer_api_url(),
+ token,
+ network_type: network.network_type(),
+ client: reqwest::Client::new(),
+ }
+ }
+
+ // Get all new received payment of specific asset type, for one ETH address
+ pub async fn get_received_payment(
+ &self,
+ address: &EthAddress,
+ asset_type: AssetType,
+ query_start_block_number: u64,
+ is_eth_internal_tx: bool,
+ ) -> Result<Vec<PaymentQueryResult>> {
+ ensure!(
+ asset_type.is_evm_compatible(),
+ "Invalid asset type: {:?}",
+ asset_type
+ );
+
+ // sleep for a while to avoid hitting the rate limit
+ std::thread::sleep(std::time::Duration::from_secs(1));
+
+ let mut url = self.url.clone();
+ construct_payment_params(
+ &mut url,
+ &self.token,
+ address,
+ &asset_type,
+ &self.network_type,
+ query_start_block_number,
+ is_eth_internal_tx,
+ )?;
+ let resp = self
+ .client
+ .get(url)
+ .send()
+ .await?
+ .json::<serde_json::Value>()
+ .await?;
+ let result = match resp.get("result") {
+ Some(resp) => {
+ log::debug!("get_received_payment_list_from_etherscan: resp: {:?}", resp);
+ serde_json::from_value::<Vec<PaymentQueryResult>>(resp.clone())?
+ }
+ None => {
+ bail!("Failed to get result from etherscan, resp: {:?}", resp);
+ }
+ };
+ // filter out the result that is not to the address and is success (is Some("0") or None)
+ let result: Vec<PaymentQueryResult> = result
+ .into_iter()
+ .filter(|x| {
+ x.to == address.as_hex()
+ && (x.is_error.is_none() || x.is_error.as_deref() == Some("0"))
+ })
+ .collect();
+
+ // double check the txreceipt_status for each new tx
+ // for normal tx, we can get it from the previous query, but for internal tx and ERC20 tx we can't
+ // so check it here for all tx, return the confirmed tx
+ self.check_tx_receipt_status(&result).await
+ }
+
+ // Check the tx receipt status
+ async fn check_tx_receipt_status(
+ &self,
+ txs: &[PaymentQueryResult],
+ ) -> Result<Vec<PaymentQueryResult>> {
+ let mut confirmed_result = Vec::new();
+ for tx in txs {
+ // sleep for a while to avoid hitting the rate limit
+ std::thread::sleep(std::time::Duration::from_secs(1));
+
+ let tx_hash = tx.hash.clone();
+ let url = format!(
+ "{}?module=transaction&action=gettxreceiptstatus&txhash={}&apikey={}",
+ self.url.as_str(),
+ tx_hash,
+ self.token
+ );
+ let resp = match self
+ .client
+ .get(url)
+ .send()
+ .await?
+ .json::<serde_json::Value>()
+ .await
+ {
+ Ok(resp) => resp,
+ Err(e) => {
+ log::error!(
+ "Failed to get tx receipt status from etherscan, error: {:?}",
+ e
+ );
+ continue;
+ }
+ };
+ let status = match resp.get("result") {
+ Some(resp) => {
+ log::debug!("get_received_payment_list_from_etherscan: resp: {:?}", resp);
+ serde_json::from_value::<serde_json::Value>(resp.clone())?
+ }
+ None => {
+ log::error!("Failed to get result from etherscan, resp: {:?}", resp);
+ continue;
+ }
+ };
+ match status.get("status") {
+ Some(status) => {
+ if status.as_str().unwrap_or_default() == "1" {
+ log::info!("tx: {:?} is confirmed", tx_hash);
+ confirmed_result.push(tx.clone());
+ }
+ }
+ None => {
+ log::error!("Failed to get status from etherscan, resp: {:?}", status);
+ }
+ }
+ }
+ Ok(confirmed_result)
+ }
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/eth_rpc.rs b/vm/wallet-gateway/net/src/endpoints/eth_rpc.rs
new file mode 100644
index 00000000..e176af4b
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/eth_rpc.rs
@@ -0,0 +1,297 @@
+// 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 crate::params::infura::{parse_infura_json_rpc_response, InfuraRpcError, InfuraRpcRequest};
+use crate::params::{construct_gas_estimation_params, EthCallParams};
+use anyhow::{anyhow, bail, ensure, Result};
+use ethabi::Contract;
+use types::external::{AssetType, CkAmount, NetworkErrMsg, NetworkTxHash, TxSubmissionResult};
+use types::share::CkSignature;
+use types::share::{EthAddress, NetworkType};
+
+pub struct EthRpcEndpoint {
+ url: url::Url, // ethereum rpc url, e.g. infura
+ client: reqwest::Client,
+ contract_abi: Option<Contract>,
+ network: NetworkType,
+}
+
+impl EthRpcEndpoint {
+ pub fn new(url: url::Url, contract_abi: Option<Contract>, network: NetworkType) -> Self {
+ Self {
+ url,
+ client: reqwest::Client::new(),
+ contract_abi,
+ network,
+ }
+ }
+
+ async fn get_eth_balance(&self, address: &EthAddress) -> Result<u128> {
+ let get_balance_req = serde_json::to_value(InfuraRpcRequest::<String>::new(
+ "eth_getBalance".to_string(),
+ vec![address.to_string(), "latest".to_string()],
+ ))?;
+
+ log::debug!("Requesting balance from network: {:?}", get_balance_req);
+ let resp = self
+ .client
+ .post(self.url.clone())
+ .json(&get_balance_req)
+ .send()
+ .await?;
+
+ let balance_resp = match parse_infura_json_rpc_response(resp).await {
+ Ok(resp) => resp,
+ Err(err) => bail!(err),
+ };
+
+ let balance = u128::from_str_radix(
+ balance_resp
+ .result()
+ .strip_prefix("0x")
+ .ok_or_else(|| anyhow!("eth_getBalance strip error"))?,
+ 16,
+ )?;
+ Ok(balance)
+ }
+
+ pub async fn get_nonce(&self, address: &EthAddress) -> Result<u128> {
+ let get_nonce_req = serde_json::to_value(InfuraRpcRequest::<String>::new(
+ "eth_getTransactionCount".to_string(),
+ vec![address.to_string(), "pending".to_string()],
+ ))?;
+
+ log::debug!("Requesting nonce from network: {:?}", get_nonce_req);
+ let resp = self
+ .client
+ .post(self.url.clone())
+ .json(&get_nonce_req)
+ .send()
+ .await?;
+
+ let tx_count_resp = match parse_infura_json_rpc_response(resp).await {
+ Ok(resp) => resp,
+ Err(err) => bail!(err),
+ };
+
+ let tx_count = u128::from_str_radix(
+ tx_count_resp
+ .result()
+ .strip_prefix("0x")
+ .ok_or_else(|| anyhow!("eth_getTransactionCount strip error"))?,
+ 16,
+ )?;
+ Ok(tx_count)
+ }
+
+ pub async fn send_raw_transaction(&self, payload: CkSignature) -> Result<TxSubmissionResult> {
+ let raw_tx = format!("0x{}", hex::encode(payload.as_bytes()));
+ let send_raw_tx_req = serde_json::to_value(InfuraRpcRequest::<String>::new(
+ "eth_sendRawTransaction".to_string(),
+ vec![raw_tx],
+ ))?;
+ log::info!("send_raw_tx_req: {:?}", &send_raw_tx_req);
+ let resp = self
+ .client
+ .post(self.url.clone())
+ .json(&send_raw_tx_req)
+ .send()
+ .await?;
+
+ match parse_infura_json_rpc_response(resp).await {
+ Ok(resp) => {
+ let tx_hash = NetworkTxHash::from(resp.result());
+ Ok(TxSubmissionResult::Accepted(tx_hash))
+ }
+ Err(err) => {
+ let inner_error = err.downcast::<InfuraRpcError>()?;
+ match inner_error {
+ // It's implementation choice to decide whith error to shown to user
+ // others are treated as internal error, which will effect the Delegations
+ InfuraRpcError::RejectedByNetwork(msg) => {
+ Ok(TxSubmissionResult::Rejected(NetworkErrMsg::from(msg)))
+ }
+ _ => bail!(inner_error),
+ }
+ }
+ }
+ }
+
+ async fn get_erc20_balance(&self, address: &EthAddress, asset_type: AssetType) -> Result<u128> {
+ ensure!(
+ self.contract_abi.is_some(),
+ "contract_abi should not be none"
+ );
+ // we use unwrap here because we have checked the contract_abi is not None
+ let contract = &self.contract_abi.as_ref().unwrap();
+ let balance_of_function = contract.function("balanceOf")?;
+
+ let balance_call_encoded = balance_of_function.encode_input(&[ethabi::Token::Address(
+ ethabi::Address::from_slice(address.as_bytes()),
+ )])?;
+
+ let asset = asset_type.config();
+ let token_address = asset
+ .contract_address(&self.network)
+ .ok_or(anyhow!("contract_address is none"))?;
+ let eth_call_params = serde_json::to_value(EthCallParams {
+ to: token_address,
+ data: balance_call_encoded,
+ })?;
+
+ let get_balance_req = serde_json::to_value(InfuraRpcRequest::<serde_json::Value>::new(
+ "eth_call".to_string(),
+ vec![
+ eth_call_params,
+ serde_json::Value::String("latest".to_string()),
+ ],
+ ))?;
+ log::debug!("get_balance_req: {:?}", &get_balance_req);
+
+ // Send the request
+ let resp = self
+ .client
+ .post(self.url.clone())
+ .json(&get_balance_req)
+ .send()
+ .await?;
+
+ let balance_resp = match parse_infura_json_rpc_response(resp).await {
+ Ok(resp) => resp,
+ Err(err) => bail!(err),
+ };
+
+ // The balance will be a hex string; parse it into a u128
+ let raw_balance = balance_resp
+ .result()
+ .strip_prefix("0x")
+ .ok_or(anyhow!("result strip error, without the 0x prefix"))?
+ .to_owned();
+ let balance = u128::from_str_radix(&raw_balance, 16)?;
+ log::debug!("get_erc20_balance: {:?}", balance);
+
+ Ok(balance)
+ }
+
+ pub async fn get_address_balance_for_asset(
+ &self,
+ address: &EthAddress,
+ asset_type: AssetType,
+ ) -> Result<u128> {
+ if asset_type.is_evm_compatible() {
+ if asset_type.is_erc20_compatible() {
+ let balance = self.get_erc20_balance(address, asset_type).await?;
+ log::info!(
+ "address: {} {:?} balance: {:?}",
+ address,
+ asset_type,
+ balance
+ );
+ Ok(balance)
+ } else if asset_type.is_evm_native() {
+ let balance = self.get_eth_balance(address).await?;
+ log::info!(
+ "address: {} {:?} balance: {:?}",
+ address,
+ asset_type,
+ balance
+ );
+ Ok(balance)
+ } else {
+ bail!("Unsupported evm asset type: {:?}", asset_type);
+ }
+ } else {
+ bail!("Unsupported asset type: {:?}", asset_type);
+ }
+ }
+
+ pub async fn get_gas_price(&self) -> Result<u128> {
+ let get_price_req = serde_json::to_value(InfuraRpcRequest::<serde_json::Value>::new(
+ "eth_gasPrice".to_string(),
+ vec![],
+ ))?;
+ log::debug!("Requesting gas price from network: {:?}", get_price_req);
+ let resp = self
+ .client
+ .post(self.url.clone())
+ .json(&get_price_req)
+ .send()
+ .await?;
+ log::debug!("Response: {:?}", &resp);
+
+ let gas_price_resp = match parse_infura_json_rpc_response(resp).await {
+ Ok(resp) => resp,
+ Err(err) => bail!(err),
+ };
+ let gas_price = u128::from_str_radix(
+ gas_price_resp
+ .result()
+ .strip_prefix("0x")
+ .ok_or_else(|| anyhow!("eth_gasPrice strip error"))?,
+ 16,
+ )?;
+ Ok(gas_price)
+ }
+
+ pub async fn estimate_gas(
+ &self,
+ from: [u8; 20],
+ to: [u8; 20],
+ amount: CkAmount,
+ ) -> Result<u128> {
+ ensure!(
+ self.contract_abi.is_some(),
+ "contract_abi should not be none"
+ );
+ let params = construct_gas_estimation_params(
+ from,
+ to,
+ amount,
+ self.contract_abi.as_ref().unwrap(),
+ &self.network,
+ )?;
+
+ let gas_estimate_req = serde_json::to_value(InfuraRpcRequest::new(
+ "eth_estimateGas".to_string(),
+ vec![params],
+ ))?;
+
+ log::debug!(
+ "Requesting gas estimate from network: {:?}",
+ gas_estimate_req
+ );
+ let resp = self
+ .client
+ .post(self.url.clone())
+ .json(&gas_estimate_req)
+ .send()
+ .await?;
+
+ let gas_estimate_resp = match parse_infura_json_rpc_response(resp).await {
+ Ok(resp) => resp,
+ Err(err) => bail!(err),
+ };
+ let gas_estimate = u128::from_str_radix(
+ gas_estimate_resp
+ .result()
+ .strip_prefix("0x")
+ .ok_or_else(|| anyhow!("eth_estimateGas strip error"))?,
+ 16,
+ )?;
+ Ok(gas_estimate)
+ }
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/mail.rs b/vm/wallet-gateway/net/src/endpoints/mail.rs
new file mode 100644
index 00000000..0458d248
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/mail.rs
@@ -0,0 +1,76 @@
+// 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::{anyhow, Result};
+use notification::email_task::SendEmailTask;
+
+pub struct MailServiceEndpoint {
+ url: url::Url,
+ domain: String,
+ token: String,
+ client: reqwest::Client,
+}
+
+impl MailServiceEndpoint {
+ pub fn new(domain: String, token: String) -> Self {
+ let url = url::Url::parse("https://api.mailgun.net/v3").unwrap();
+ Self {
+ url,
+ domain,
+ token,
+ client: reqwest::Client::new(),
+ }
+ }
+ pub async fn send_email(&self, send_email_tasks: &[SendEmailTask]) -> Result<()> {
+ let client = reqwest::Client::builder().build()?;
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert("Authorization", self.token.parse()?);
+ let url = url::Url::parse(&format!(
+ "https://api.mailgun.net/v3/{}/messages",
+ self.domain
+ ))?;
+
+ let from = format!("CK <notification@{}>", self.domain);
+
+ for send_email_task in send_email_tasks.iter() {
+ let email = &send_email_task.email;
+ let template_name = send_email_task.template_name.clone();
+ let email_template = send_email_task.email_template.clone();
+ let to: String = email.clone().into();
+
+ let form = reqwest::multipart::Form::new()
+ .text("from", from.clone())
+ .text("to", to.clone())
+ .text("template", template_name)
+ .text("h:X-Mailgun-Variables", email_template);
+ let response = client
+ .request(reqwest::Method::POST, url.clone())
+ .headers(headers.clone())
+ .multipart(form)
+ .send()
+ .await?;
+
+ if !response.status().is_success() {
+ let body = response.text().await?;
+ log::error!("send_email response body: {:?}", body);
+ return Err(anyhow!("send_email failed"));
+ }
+ log::info!("sent email to {:?}", send_email_task.email);
+ }
+ Ok(())
+ }
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/mod.rs b/vm/wallet-gateway/net/src/endpoints/mod.rs
new file mode 100644
index 00000000..af22f1c6
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/mod.rs
@@ -0,0 +1,23 @@
+// 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.
+
+pub mod asset_price;
+pub mod btc_rpc;
+pub mod eth_payment;
+pub mod eth_rpc;
+pub mod mail;
+pub mod params;
diff --git a/vm/wallet-gateway/net/src/endpoints/params/erc20.rs b/vm/wallet-gateway/net/src/endpoints/params/erc20.rs
new file mode 100644
index 00000000..873f214e
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/params/erc20.rs
@@ -0,0 +1,32 @@
+// 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 crate::params::infura::RpcParams;
+use serde::{Deserialize, Serialize};
+use serde_hex::{SerHex, StrictPfx};
+use types::serde_util;
+
+// contract call
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EthCallParams {
+ #[serde(with = "SerHex::<StrictPfx>")]
+ pub to: [u8; 20],
+ #[serde(with = "serde_util::bytes_hex")]
+ pub data: Vec<u8>,
+}
+
+impl RpcParams for serde_json::Value {}
diff --git a/vm/wallet-gateway/net/src/endpoints/params/gas.rs b/vm/wallet-gateway/net/src/endpoints/params/gas.rs
new file mode 100644
index 00000000..6554fb55
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/params/gas.rs
@@ -0,0 +1,85 @@
+// 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 crate::params::infura::RpcParams;
+use anyhow::{anyhow, bail, Result};
+use ethabi::Contract;
+use serde::{Deserialize, Serialize};
+use serde_hex::{SerHex, StrictPfx};
+use types::external::CkAmount;
+use types::external::TransferAbiData;
+use types::serde_util;
+use types::share::NetworkType;
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EstimateGasParams {
+ #[serde(with = "SerHex::<StrictPfx>")]
+ pub from: [u8; 20],
+ #[serde(with = "SerHex::<StrictPfx>")]
+ pub to: [u8; 20],
+ #[serde(with = "serde_util::u128_hex")]
+ pub value: u128,
+ #[serde(with = "serde_util::u128_hex")]
+ pub gas: u128,
+ #[serde(with = "serde_util::u128_hex")]
+ pub gas_price: u128,
+ #[serde(with = "serde_util::bytes_hex")]
+ pub data: Vec<u8>,
+}
+impl RpcParams for EstimateGasParams {}
+
+pub fn construct_gas_estimation_params(
+ from: [u8; 20],
+ to: [u8; 20],
+ amount: CkAmount,
+ erc20_abi: &Contract,
+ network: &NetworkType,
+) -> Result<EstimateGasParams> {
+ let asset_type = amount.asset_type();
+ let value = amount.value();
+
+ if !asset_type.is_evm_compatible() {
+ bail!("unsupported asset type: {:?}", asset_type);
+ }
+ if asset_type.is_erc20_compatible() {
+ let contract_address = asset_type
+ .config()
+ .contract_address(network)
+ .ok_or_else(|| anyhow!("contract_address is none for: {:?}", asset_type))?;
+ let data = TransferAbiData::new(to, value, erc20_abi)?.encoded();
+ Ok(EstimateGasParams {
+ from,
+ to: contract_address,
+ value: 0,
+ gas: 100000, // set a large number for estimation to avoid "Rejected by network: gas required exceeds allowance"
+ gas_price: 0,
+ data,
+ })
+ } else if asset_type.is_evm_native() {
+ // For native ETH or BSC transfer, we set the value and data to zero
+ Ok(EstimateGasParams {
+ from,
+ to,
+ value,
+ gas: 100000, // set a large number for estimation to avoid "Rejected by network: gas required exceeds allowance"
+ gas_price: 0,
+ data: vec![],
+ })
+ } else {
+ bail!("unsupported asset type: {:?}", asset_type);
+ }
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/params/infura.rs b/vm/wallet-gateway/net/src/endpoints/params/infura.rs
new file mode 100644
index 00000000..990f02ed
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/params/infura.rs
@@ -0,0 +1,99 @@
+// 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 serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct InfuraJsonRpcSuccessResponse {
+ jsonrpc: String,
+ id: u32,
+ result: String,
+}
+impl InfuraJsonRpcSuccessResponse {
+ pub fn result(&self) -> String {
+ self.result.clone()
+ }
+}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct InfuraJsonRpcErrorResponse {
+ jsonrpc: String,
+ id: u32,
+ error: RpcErrorInfo,
+}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct RpcErrorInfo {
+ code: i32,
+ message: String,
+}
+
+pub type HttpStatusCode = u16;
+#[derive(Error, Debug)]
+pub enum InfuraRpcError {
+ #[error("Infura connection error: {0}")]
+ ConnectionFailure(HttpStatusCode), //when request.status() != 200
+ #[error("Rejected by network: {0}")]
+ RejectedByNetwork(String), // when deserialization to InfuraJsonRpcErrorResponse succeeds
+ #[error("Unknown error: {0}")]
+ Unknown(String), // when deserialization fails
+}
+
+pub async fn parse_infura_json_rpc_response(
+ resp: reqwest::Response,
+) -> Result<InfuraJsonRpcSuccessResponse> {
+ if resp.status() != 200 {
+ log::error!("Infura connection error code: {}", resp.status());
+ return Err(InfuraRpcError::ConnectionFailure(resp.status().as_u16()).into());
+ }
+ let resp_text = resp.text().await?;
+ log::info!("Infura response body: {}", resp_text);
+ match serde_json::from_str::<InfuraJsonRpcSuccessResponse>(&resp_text) {
+ Ok(resp) => Ok(resp),
+ Err(_) => match serde_json::from_str::<InfuraJsonRpcErrorResponse>(&resp_text) {
+ Ok(err_resp) => bail!(InfuraRpcError::RejectedByNetwork(err_resp.error.message)),
+ Err(_) => bail!(InfuraRpcError::Unknown(resp_text)),
+ },
+ }
+}
+
+pub trait RpcParams: Serialize + Clone {}
+impl RpcParams for String {}
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct InfuraRpcRequest<T>
+where
+ T: RpcParams,
+{
+ pub jsonrpc: String,
+ pub method: String,
+ pub params: Vec<T>,
+ pub id: u32,
+}
+impl<T> InfuraRpcRequest<T>
+where
+ T: RpcParams,
+{
+ pub fn new(method: String, params: Vec<T>) -> Self {
+ InfuraRpcRequest {
+ jsonrpc: "2.0".to_string(),
+ method,
+ params,
+ id: 1,
+ }
+ }
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/params/mod.rs b/vm/wallet-gateway/net/src/endpoints/params/mod.rs
new file mode 100644
index 00000000..23505806
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/params/mod.rs
@@ -0,0 +1,27 @@
+// 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.
+
+mod erc20;
+mod gas;
+pub mod infura;
+mod payment;
+mod utxo;
+
+pub use erc20::EthCallParams;
+pub use gas::construct_gas_estimation_params;
+pub use payment::{construct_payment_params, PaymentQueryResult};
+pub use utxo::{UtxoQueryResult, UtxoQueryResultStatus};
diff --git a/vm/wallet-gateway/net/src/endpoints/params/payment.rs b/vm/wallet-gateway/net/src/endpoints/params/payment.rs
new file mode 100644
index 00000000..41111f06
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/params/payment.rs
@@ -0,0 +1,88 @@
+// 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::{anyhow, Result};
+use serde::{Deserialize, Serialize};
+use types::external::AssetType;
+use types::share::{EthAddress, NetworkType};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PaymentQueryResult {
+ pub hash: String,
+ pub from: String,
+ pub to: String,
+ pub value: String,
+ pub time_stamp: String,
+ pub block_number: String,
+ pub token_symbol: Option<String>,
+ pub is_error: Option<String>, // Some("0") is success, Some("1") is error; for ERC20 token tx, it's None
+}
+
+pub fn construct_payment_params(
+ url: &mut url::Url,
+ token: &str,
+ address: &EthAddress,
+ asset_type: &AssetType,
+ network_type: &NetworkType,
+ query_start_block_number: u64,
+ is_eth_internal_tx: bool,
+) -> Result<()> {
+ let address = address.as_hex();
+ match asset_type.is_erc20_compatible() {
+ // query normal ETH tx
+ false => {
+ let action = match is_eth_internal_tx {
+ true => "txlistinternal",
+ false => "txlist",
+ };
+ url.query_pairs_mut()
+ .append_pair("module", "account")
+ .append_pair("action", action)
+ .append_pair("address", &address)
+ .append_pair("startblock", &query_start_block_number.to_string())
+ .append_pair("endblock", "99999999")
+ .append_pair("page", "1")
+ .append_pair("offset", "100")
+ .append_pair("sort", "desc")
+ .append_pair("apikey", token);
+ }
+ // query ERC20 token tx
+ true => {
+ let asset_config = asset_type.config();
+ let contract_address = asset_config
+ .contract_address(network_type)
+ .ok_or(anyhow!("Contract address is none for: {:?}", asset_type))?;
+ url.query_pairs_mut()
+ .append_pair("module", "account")
+ .append_pair("action", "tokentx")
+ .append_pair("address", &address)
+ .append_pair("startblock", &query_start_block_number.to_string())
+ .append_pair("endblock", "999999999")
+ .append_pair("page", "1")
+ .append_pair("offset", "100")
+ .append_pair("sort", "desc")
+ .append_pair(
+ "contractaddress",
+ &format!("0x{}", hex::encode(contract_address)),
+ )
+ .append_pair("apikey", token);
+ log::info!("construct_payment_params: url: {}", url.as_str());
+ }
+ }
+ Ok(())
+}
diff --git a/vm/wallet-gateway/net/src/endpoints/params/utxo.rs b/vm/wallet-gateway/net/src/endpoints/params/utxo.rs
new file mode 100644
index 00000000..26e71f91
--- /dev/null
+++ b/vm/wallet-gateway/net/src/endpoints/params/utxo.rs
@@ -0,0 +1,34 @@
+// 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 serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UtxoQueryResult {
+ pub txid: String,
+ pub vout: u64,
+ pub status: UtxoQueryResultStatus,
+ pub value: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UtxoQueryResultStatus {
+ pub confirmed: bool,
+ pub block_height: u32,
+ pub block_hash: String,
+ pub block_time: u64,
+}
diff --git a/vm/wallet-gateway/net/src/lib.rs b/vm/wallet-gateway/net/src/lib.rs
new file mode 100644
index 00000000..e76ffb64
--- /dev/null
+++ b/vm/wallet-gateway/net/src/lib.rs
@@ -0,0 +1,25 @@
+// 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.
+
+mod endpoints;
+
+pub use endpoints::asset_price::AssetPriceEndpoint;
+pub use endpoints::btc_rpc::BtcRpcEndpoint;
+pub use endpoints::eth_payment::EthReceivedPaymentEndpoint;
+pub use endpoints::eth_rpc::EthRpcEndpoint;
+pub use endpoints::mail::MailServiceEndpoint;
+pub use endpoints::params;
diff --git a/vm/wallet-gateway/notification/Cargo.toml b/vm/wallet-gateway/notification/Cargo.toml
new file mode 100644
index 00000000..0ee371d0
--- /dev/null
+++ b/vm/wallet-gateway/notification/Cargo.toml
@@ -0,0 +1,39 @@
+# 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.
+
+[package]
+name = "notification"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+serde = "1.0"
+serde_json = "1.0"
+serde-hex = "0.1.0"
+serde_with = "3.8"
+hex = { version = "0.4", features = ["serde"] }
+anyhow = "1.0"
+log = "0.4"
+url = { version = "2.1.1", features = ["serde"] }
+bincode = "1.3.3"
+uuid = { version = "=1.3.0", features = ["serde", "v4"] }
+
+types = { path = "../share/types" }
+client-info = { path = "../types-client" }
+utils = { path = "../utils" }
+proto = { path = "../share/proto" }
+storable = { path = "../storable" }
\ No newline at end of file
diff --git a/vm/wallet-gateway/notification/src/email_event.rs b/vm/wallet-gateway/notification/src/email_event.rs
new file mode 100644
index 00000000..9018a3bc
--- /dev/null
+++ b/vm/wallet-gateway/notification/src/email_event.rs
@@ -0,0 +1,53 @@
+// 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 serde::{Deserialize, Serialize};
+use storable::pending_tx::PendingTx;
+use storable::received_payment::PaymentRecord;
+use storable::tx_history::HistoryTx;
+use storable::Storable;
+use uuid::Uuid;
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct NotifyEventInfo {
+ pub id: Uuid,
+ pub event: NotifyEvent,
+}
+
+impl NotifyEventInfo {
+ pub fn new(event: NotifyEvent) -> Self {
+ Self {
+ id: Uuid::new_v4(),
+ event,
+ }
+ }
+}
+
+impl Storable<String> for NotifyEventInfo {
+ fn unique_id(&self) -> String {
+ self.id.to_string()
+ }
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+#[serde(tag = "event")]
+pub enum NotifyEvent {
+ HistoryEvent(HistoryTx),
+ PendingEvent(PendingTx),
+ ReceivedPayment(PaymentRecord),
+}
diff --git a/vm/wallet-gateway/notification/src/email_task.rs b/vm/wallet-gateway/notification/src/email_task.rs
new file mode 100644
index 00000000..3a60574e
--- /dev/null
+++ b/vm/wallet-gateway/notification/src/email_task.rs
@@ -0,0 +1,33 @@
+// 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 types::external::Email;
+
+pub struct SendEmailTask {
+ pub email: Email,
+ pub template_name: String,
+ pub email_template: String,
+}
+impl SendEmailTask {
+ pub fn new(email: Email, template_name: String, email_template: String) -> Self {
+ Self {
+ email,
+ template_name,
+ email_template,
+ }
+ }
+}
diff --git a/vm/wallet-gateway/notification/src/email_template.rs b/vm/wallet-gateway/notification/src/email_template.rs
new file mode 100644
index 00000000..a58ac7d3
--- /dev/null
+++ b/vm/wallet-gateway/notification/src/email_template.rs
@@ -0,0 +1,260 @@
+// 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 crate::email_task::SendEmailTask;
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+use storable::nickname::NicknameValue;
+use types::external::{AssetType, Email};
+use types::serde_util;
+use url::Url;
+
+fn format_nickname_address(nickname: Option<NicknameValue>, address: &str) -> String {
+ match nickname {
+ Some(nickname) => format!("{} ({})", nickname.as_str(), address),
+ None => address.to_string(),
+ }
+}
+
+pub trait EmailTemplate: Send + Sync {
+ type T: EmailRequest;
+
+ fn template_name(&self) -> String;
+ fn inner(&self) -> &Self::T;
+ fn inner_mut(&mut self) -> &mut Self::T;
+ fn from(&self) -> String {
+ self.inner().from().to_string()
+ }
+ fn to(&self) -> String {
+ self.inner().to().to_string()
+ }
+ fn template_content_to_json(&self) -> Result<String, serde_json::Error> {
+ serde_json::to_string(self.inner())
+ }
+ fn add_nickname(
+ &mut self,
+ from_nickname: Option<NicknameValue>,
+ to_nickname: Option<NicknameValue>,
+ ) {
+ self.inner_mut().add_nickname(from_nickname, to_nickname);
+ }
+ fn to_email_task(&self, email: Email) -> Result<SendEmailTask> {
+ Ok(SendEmailTask {
+ email,
+ template_name: self.template_name(),
+ email_template: self.template_content_to_json()?,
+ })
+ }
+}
+
+macro_rules! impl_email_template {
+ // template struct, template parameter (for mailgun), template name (for mailgun)
+ ($struct_name:ident, $inner_type:ty, $template_name:expr) => {
+ impl EmailTemplate for $struct_name {
+ type T = $inner_type;
+
+ fn template_name(&self) -> String {
+ $template_name.to_string()
+ }
+
+ fn inner(&self) -> &Self::T {
+ &self.0
+ }
+
+ fn inner_mut(&mut self) -> &mut Self::T {
+ &mut self.0
+ }
+ }
+ };
+}
+
+// mail templates which uses basic info
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateCancelled(pub TxBasicInfoEmailRequest);
+impl_email_template!(
+ EmailTemplateCancelled,
+ TxBasicInfoEmailRequest,
+ "tx-cancelled"
+);
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateDeclined(pub TxBasicInfoEmailRequest);
+impl_email_template!(
+ EmailTemplateDeclined,
+ TxBasicInfoEmailRequest,
+ "tx-declined"
+);
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateReadyForSigning(pub TxBasicInfoEmailRequest);
+impl_email_template!(
+ EmailTemplateReadyForSigning,
+ TxBasicInfoEmailRequest,
+ "ready-to-sign"
+);
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateNeedReSign(pub TxBasicInfoEmailRequest);
+impl_email_template!(EmailTemplateNeedReSign, TxBasicInfoEmailRequest, "re-sign");
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateTxCreated(pub TxBasicInfoEmailRequest);
+impl_email_template!(
+ EmailTemplateTxCreated,
+ TxBasicInfoEmailRequest,
+ "tx-created"
+);
+
+// templates which uses specific info
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplatePendingForApproval(pub TxRequiredApprovalEmailRequest);
+impl_email_template!(
+ EmailTemplatePendingForApproval,
+ TxRequiredApprovalEmailRequest,
+ "require-approval"
+);
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateOnChain(pub TxCompletedEmailRequest);
+impl_email_template!(
+ EmailTemplateOnChain,
+ TxCompletedEmailRequest,
+ "tx-completed"
+);
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateReceived(pub TxReceivedEmailRequest);
+impl_email_template!(EmailTemplateReceived, TxReceivedEmailRequest, "tx-received");
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct EmailTemplateRejectedByNetwork(pub TxNetworkEmailRequest);
+impl_email_template!(
+ EmailTemplateRejectedByNetwork,
+ TxNetworkEmailRequest,
+ "tx-rejected-by-network"
+);
+
+pub trait EmailRequest: Serialize {
+ fn from(&self) -> &str;
+ fn to(&self) -> &str;
+ fn set_from(&mut self, from: String);
+ fn set_to(&mut self, to: String);
+ fn add_nickname(
+ &mut self,
+ from_nickname: Option<NicknameValue>,
+ to_nickname: Option<NicknameValue>,
+ ) {
+ self.set_from(format_nickname_address(from_nickname, self.from()));
+ self.set_to(format_nickname_address(to_nickname, self.to()));
+ }
+}
+
+macro_rules! impl_email_request_get_set {
+ ($struct_name:ident) => {
+ impl EmailRequest for $struct_name {
+ fn from(&self) -> &str {
+ &self.from
+ }
+
+ fn to(&self) -> &str {
+ &self.to
+ }
+
+ fn set_from(&mut self, from: String) {
+ self.from = from;
+ }
+
+ fn set_to(&mut self, to: String) {
+ self.to = to;
+ }
+ }
+ };
+}
+
+// PendingForApproval
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct TxRequiredApprovalEmailRequest {
+ pub from: String, // AccountId(Nickname)
+ pub to: String,
+ #[serde(with = "serde_util::f64_string")]
+ pub amount: f64,
+ pub asset: AssetType,
+ #[serde(with = "serde_util::url_string_for_email")]
+ pub tx_link: Url,
+ pub step: usize,
+}
+impl_email_request_get_set!(TxRequiredApprovalEmailRequest);
+
+// HistoryEvent(Failed) + ReadyForSigning
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct TxBasicInfoEmailRequest {
+ pub from: String,
+ pub to: String,
+ #[serde(with = "serde_util::f64_string")]
+ pub amount: f64,
+ pub asset: AssetType,
+ #[serde(with = "serde_util::url_string_for_email")]
+ pub tx_link: Url,
+}
+impl_email_request_get_set!(TxBasicInfoEmailRequest);
+
+// Onchain
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct TxCompletedEmailRequest {
+ pub from: String,
+ pub to: String,
+ #[serde(with = "serde_util::f64_string")]
+ pub amount: f64,
+ pub asset: AssetType,
+ #[serde(with = "serde_util::url_string_for_email")]
+ pub etherscan_link: Url,
+ #[serde(with = "serde_util::url_string_for_email")]
+ pub tx_link: Url,
+}
+impl_email_request_get_set!(TxCompletedEmailRequest);
+
+// Received
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct TxReceivedEmailRequest {
+ pub from: String,
+ pub to: String,
+ #[serde(with = "serde_util::f64_string")]
+ pub amount: f64,
+ pub asset: AssetType,
+ #[serde(with = "serde_util::url_string_for_email")]
+ pub etherscan_link: Url,
+}
+impl_email_request_get_set!(TxReceivedEmailRequest);
+
+// Rejected by Network
+#[derive(Serialize, Deserialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct TxNetworkEmailRequest {
+ pub from: String,
+ pub to: String,
+ #[serde(with = "serde_util::f64_string")]
+ pub amount: f64,
+ pub asset: AssetType,
+ pub message: String,
+ #[serde(with = "serde_util::url_string_for_email")]
+ pub tx_link: Url,
+}
+impl_email_request_get_set!(TxNetworkEmailRequest);
diff --git a/vm/wallet-gateway/notification/src/lib.rs b/vm/wallet-gateway/notification/src/lib.rs
new file mode 100644
index 00000000..3bc950c7
--- /dev/null
+++ b/vm/wallet-gateway/notification/src/lib.rs
@@ -0,0 +1,20 @@
+// 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.
+
+pub mod email_event;
+pub mod email_task;
+pub mod email_template;
diff --git a/vm/wallet-gateway/share/attestation/Cargo.toml b/vm/wallet-gateway/share/attestation/Cargo.toml
new file mode 100644
index 00000000..a130bf6a
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/Cargo.toml
@@ -0,0 +1,36 @@
+# 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.
+
+[package]
+name = "attestation"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+basic_utils = { path = "../basic_utils" }
+crypto = { path = "../crypto" }
+
+bit-vec = "0.6"
+num-bigint = "0.4"
+yasna = { version = "0.4", features = ["chrono", "bit-vec", "num-bigint"] }
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+anyhow = "1.0"
+
+rustls = { version = "0.21.0", features = ["dangerous_configuration"]}
+rustls-webpki = "0.100.1"
+rustls-pemfile = "1.0"
\ No newline at end of file
diff --git a/vm/wallet-gateway/share/attestation/src/cert.rs b/vm/wallet-gateway/share/attestation/src/cert.rs
new file mode 100644
index 00000000..6367c6a1
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/src/cert.rs
@@ -0,0 +1,485 @@
+// 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.
+
+//! This module provides a X.509 certificate parser.
+
+#![allow(clippy::unused_unit)]
+#![allow(clippy::needless_lifetimes)]
+
+use std::convert::TryFrom;
+use std::prelude::v1::*;
+
+use yasna::models::TaggedDerValue;
+use yasna::ASN1Error;
+use yasna::{ASN1ErrorKind, ASN1Result};
+use yasna::{BERReader, BERReaderSeq, BERReaderSet};
+use yasna::{DERWriter, DERWriterSeq, DERWriterSet};
+
+pub type Writer<'a> = DERWriter<'a>;
+pub type Reader<'a, 'b> = BERReader<'a, 'b>;
+
+pub trait ConsWriter {
+ fn next(&mut self) -> Writer<'_>;
+}
+
+pub trait ConsReader<'a> {
+ fn next(&mut self, tags: &[yasna::Tag]) -> ASN1Result<Reader<'a, '_>>;
+}
+
+impl ConsWriter for DERWriterSeq<'_> {
+ fn next(&mut self) -> Writer<'_> {
+ self.next()
+ }
+}
+
+impl ConsWriter for DERWriterSet<'_> {
+ fn next(&mut self) -> Writer<'_> {
+ self.next()
+ }
+}
+
+impl<'a> ConsReader<'a> for BERReaderSeq<'a, '_> {
+ fn next(&mut self, _tags: &[yasna::Tag]) -> ASN1Result<Reader<'a, '_>> {
+ Ok(self.next())
+ }
+}
+
+impl<'a> ConsReader<'a> for BERReaderSet<'a, '_> {
+ fn next(&mut self, tags: &[yasna::Tag]) -> ASN1Result<Reader<'a, '_>> {
+ self.next(tags)
+ }
+}
+
+pub trait Asn1Ty {
+ type ValueTy;
+ const TAG: yasna::Tag;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) -> ();
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy>;
+}
+
+pub trait Asn1ConsTy
+where
+ Self: std::marker::Sized,
+{
+ type ValueTy;
+
+ fn dump<W: ConsWriter>(writer: &mut W, value: Self::ValueTy) -> ();
+ fn load<'a, R>(reader: &mut R) -> ASN1Result<Self::ValueTy>
+ where
+ R: ConsReader<'a>;
+}
+
+pub trait Asn1Tag {
+ const TAG: yasna::Tag;
+}
+
+const fn context_tag(tnum: u64) -> yasna::Tag {
+ yasna::Tag {
+ tag_class: yasna::TagClass::ContextSpecific,
+ tag_number: tnum,
+ }
+}
+
+mod no_instance {
+ #![allow(dead_code)]
+
+ use super::{Asn1ConsTy, Asn1Tag, Asn1Ty};
+ use std::marker::PhantomData;
+
+ pub(crate) struct CtxT0;
+ pub(crate) struct CtxT1;
+ pub(crate) struct CtxT3;
+
+ pub(crate) struct Boolean;
+ pub(crate) struct Oid;
+ pub(crate) struct U8;
+ pub(crate) struct I8;
+ pub(crate) struct BigUint;
+ pub(crate) struct Utf8Str;
+ pub(crate) struct UtcTime;
+ pub(crate) struct BitVec;
+ pub(crate) struct Bytes;
+ pub(crate) struct DnsNameEntry;
+ pub(crate) struct AlterNamesPayloadSeq;
+ pub(crate) struct Tagged<T: Asn1Tag, S: Asn1Ty> {
+ t: PhantomData<T>,
+ s: PhantomData<S>,
+ }
+ pub(crate) struct Sequence<U: Asn1Ty, V: Asn1ConsTy> {
+ u: PhantomData<U>,
+ v: PhantomData<V>,
+ }
+ pub(crate) struct Set<U: Asn1Ty, V: Asn1ConsTy> {
+ u: PhantomData<U>,
+ v: PhantomData<V>,
+ }
+ pub(crate) struct Cons<U: Asn1Ty, V: Asn1ConsTy> {
+ u: PhantomData<U>,
+ v: PhantomData<V>,
+ }
+ pub(crate) struct Nil;
+}
+
+use no_instance::*;
+
+impl Asn1Tag for CtxT0 {
+ const TAG: yasna::Tag = context_tag(0);
+}
+
+impl Asn1Tag for CtxT1 {
+ const TAG: yasna::Tag = context_tag(1);
+}
+
+impl Asn1Tag for CtxT3 {
+ const TAG: yasna::Tag = context_tag(3);
+}
+
+impl<U: Asn1Ty, V: Asn1ConsTy> Asn1ConsTy for Cons<U, V> {
+ type ValueTy = (U::ValueTy, V::ValueTy);
+
+ fn dump<W: ConsWriter>(writer: &mut W, value: Self::ValueTy) -> () {
+ U::dump(writer.next(), value.0);
+ V::dump(writer, value.1);
+ }
+
+ fn load<'a, R>(reader: &mut R) -> ASN1Result<Self::ValueTy>
+ where
+ R: ConsReader<'a>,
+ {
+ let first = U::load(reader.next(&[U::TAG])?)?;
+ let second = V::load(reader)?;
+ Ok((first, second))
+ }
+}
+
+impl Asn1ConsTy for Nil {
+ type ValueTy = ();
+
+ fn dump<W: ConsWriter>(_writer: &mut W, _value: Self::ValueTy) -> () {}
+ fn load<'a, R>(_reader: &mut R) -> ASN1Result<Self::ValueTy>
+ where
+ R: ConsReader<'a>,
+ {
+ Ok(())
+ }
+}
+
+impl<T: Asn1Tag, S: Asn1Ty> Asn1Ty for Tagged<T, S> {
+ type ValueTy = S::ValueTy;
+ const TAG: yasna::Tag = T::TAG;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_tagged(T::TAG, |writer| S::dump(writer, value));
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_tagged(T::TAG, S::load)
+ }
+}
+
+impl<U: Asn1Ty, V: Asn1ConsTy> Asn1Ty for Sequence<U, V> {
+ type ValueTy = (U::ValueTy, V::ValueTy);
+ const TAG: yasna::Tag = yasna::tags::TAG_SEQUENCE;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_sequence(|writer| {
+ U::dump(writer.next(), value.0);
+ V::dump(writer, value.1);
+ });
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_sequence(|reader| {
+ let first = U::load(reader.next())?;
+ let second = V::load(reader)?;
+ Ok((first, second))
+ })
+ }
+}
+
+impl<U: Asn1Ty, V: Asn1ConsTy> Asn1Ty for Set<U, V> {
+ type ValueTy = (U::ValueTy, V::ValueTy);
+ const TAG: yasna::Tag = yasna::tags::TAG_SET;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_set(|writer| {
+ U::dump(writer.next(), value.0);
+ V::dump(writer, value.1);
+ });
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_set(|reader| {
+ let first = U::load(reader.next(&[U::TAG])?)?;
+ let second = V::load(reader)?;
+ Ok((first, second))
+ })
+ }
+}
+
+impl Asn1Ty for U8 {
+ type ValueTy = u8;
+ const TAG: yasna::Tag = yasna::tags::TAG_INTEGER;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_u8(value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_u8()
+ }
+}
+
+impl Asn1Ty for I8 {
+ type ValueTy = i8;
+ const TAG: yasna::Tag = yasna::tags::TAG_INTEGER;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_i8(value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_i8()
+ }
+}
+
+impl Asn1Ty for Boolean {
+ type ValueTy = bool;
+ const TAG: yasna::Tag = yasna::tags::TAG_BOOLEAN;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_bool(value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_bool()
+ }
+}
+
+impl Asn1Ty for BigUint {
+ type ValueTy = num_bigint::BigUint;
+ const TAG: yasna::Tag = yasna::tags::TAG_INTEGER;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_biguint(&value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_biguint()
+ }
+}
+
+impl Asn1Ty for Utf8Str {
+ type ValueTy = String;
+ const TAG: yasna::Tag = yasna::tags::TAG_UTF8STRING;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_utf8_string(value.as_str());
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_utf8string()
+ }
+}
+
+impl Asn1Ty for Oid {
+ type ValueTy = yasna::models::ObjectIdentifier;
+ const TAG: yasna::Tag = yasna::tags::TAG_OID;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_oid(&value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_oid()
+ }
+}
+
+impl Asn1Ty for UtcTime {
+ type ValueTy = yasna::models::UTCTime;
+ const TAG: yasna::Tag = yasna::tags::TAG_UTCTIME;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_utctime(&value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_utctime()
+ }
+}
+
+impl Asn1Ty for BitVec {
+ type ValueTy = bit_vec::BitVec;
+ const TAG: yasna::Tag = yasna::tags::TAG_BITSTRING;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_bitvec(&value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_bitvec()
+ }
+}
+
+impl Asn1Ty for Bytes {
+ type ValueTy = Vec<u8>;
+ const TAG: yasna::Tag = yasna::tags::TAG_OCTETSTRING;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_bytes(value.as_slice());
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ reader.read_bytes()
+ }
+}
+
+impl Asn1Ty for AlterNamesPayloadSeq {
+ type ValueTy = AlterNamesPayload;
+ const TAG: yasna::Tag = yasna::tags::TAG_OCTETSTRING;
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ writer.write_bytes(value.as_slice());
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ let bytes = reader.read_bytes()?;
+ AlterNamesPayload::try_from(bytes.as_slice())
+ }
+}
+
+pub struct DnsName(String);
+
+impl DnsName {
+ pub fn new(name: String) -> Self {
+ Self(name)
+ }
+
+ pub fn into_vec(self) -> Vec<u8> {
+ self.0.into_bytes()
+ }
+}
+
+impl Asn1Ty for DnsNameEntry {
+ type ValueTy = DnsName;
+ const TAG: yasna::Tag = context_tag(2);
+
+ fn dump(writer: Writer<'_>, value: Self::ValueTy) {
+ let der_value = TaggedDerValue::from_tag_and_bytes(Self::TAG, value.into_vec());
+ writer.write_tagged_der(&der_value);
+ }
+
+ fn load<'a>(reader: Reader<'a, '_>) -> ASN1Result<Self::ValueTy> {
+ let der_value = reader.read_tagged_der()?;
+ let bytes = der_value.value().to_vec();
+ let name = String::from_utf8(bytes).map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))?;
+ Ok(DnsName::new(name))
+ }
+}
+
+macro_rules! cons {
+ () => { Nil };
+ ($t: ty) => { Cons<$t, Nil> };
+ ($t: ty, $($tt: ty),* $(,)?) => {
+ Cons<$t, cons! { $($tt),* }>
+ };
+}
+
+macro_rules! asn1_seq_ty {
+ ($t: ty) => { Sequence<$t, Nil> };
+ ($t: ty, $($tt: ty),* $(,)?) => {
+ Sequence<$t, cons! { $($tt),* }>
+ };
+}
+
+macro_rules! asn1_set_ty {
+ ($t: ty) => { Set<$t, Nil> };
+ ($t: ty, $($tt: ty),* $(,)?) => {
+ Set<$t, cons! { $($tt),* }>
+ };
+}
+
+macro_rules! asn1_seq {
+ () => { () };
+ ($e: expr) => {
+ ($e, ())
+ };
+ ($e: expr , $($ee: expr),* $(,)?) => {
+ ($e, asn1_seq!{ $($ee),* } )
+ };
+}
+
+pub(crate) type Version = Tagged<CtxT0, I8>;
+pub(crate) type Serial = U8;
+pub(crate) type CertSignAlgo = asn1_seq_ty!(Oid);
+pub(crate) type ValidRange = asn1_seq_ty!(UtcTime, UtcTime);
+pub(crate) type Issuer = asn1_seq_ty!(asn1_set_ty!(asn1_seq_ty!(Oid, Utf8Str)));
+pub(crate) type Subject = Issuer;
+pub(crate) type PubKeyAlgo = asn1_seq_ty!(Oid, Oid);
+pub(crate) type PubKey = asn1_seq_ty!(PubKeyAlgo, BitVec);
+pub(crate) type RaCertExt = asn1_seq_ty!(Oid, Bytes);
+pub(crate) type AlterSubjectNames = asn1_seq_ty!(DnsNameEntry, DnsNameEntry);
+
+pub(crate) type AlterNamesExt = asn1_seq_ty!(Oid, AlterNamesPayloadSeq);
+pub(crate) type CertExtensions = Tagged<CtxT3, asn1_seq_ty!(RaCertExt, AlterNamesExt)>;
+pub(crate) type TbsCert = asn1_seq_ty!(
+ Version,
+ Serial,
+ CertSignAlgo,
+ Issuer,
+ ValidRange,
+ Subject,
+ PubKey,
+ CertExtensions,
+);
+pub(crate) type CertSig = BitVec;
+pub(crate) type X509 = asn1_seq_ty!(TbsCert, CertSignAlgo, CertSig);
+
+pub(crate) type BasicConstrainExt = asn1_seq_ty!(Oid, Boolean, Bytes);
+pub(crate) type IntermediateCertExtensions = Tagged<CtxT3, asn1_seq_ty!(BasicConstrainExt)>;
+pub(crate) type IntermediateCert = asn1_seq_ty!(
+ Version,
+ Serial,
+ CertSignAlgo,
+ Issuer,
+ ValidRange,
+ Subject,
+ PubKey,
+ IntermediateCertExtensions,
+);
+pub(crate) type _IntermediateX509 = asn1_seq_ty!(IntermediateCert, CertSignAlgo, CertSig);
+
+pub(crate) struct AlterNamesPayload(Vec<u8>);
+impl AlterNamesPayload {
+ pub fn new(name1: DnsName, name2: DnsName) -> Self {
+ let payload =
+ yasna::construct_der(|writer| AlterSubjectNames::dump(writer, asn1_seq!(name1, name2)));
+ AlterNamesPayload(payload)
+ }
+ pub fn as_slice(&self) -> &[u8] {
+ self.0.as_slice()
+ }
+}
+
+impl TryFrom<&[u8]> for AlterNamesPayload {
+ type Error = ASN1Error;
+ fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
+ let payload = yasna::parse_der(bytes, AlterSubjectNames::load)?;
+ Ok(AlterNamesPayload::new(payload.0, payload.1 .0))
+ }
+}
diff --git a/vm/wallet-gateway/share/attestation/src/date.rs b/vm/wallet-gateway/share/attestation/src/date.rs
new file mode 100644
index 00000000..5153fd19
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/src/date.rs
@@ -0,0 +1,315 @@
+// 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 std::fmt;
+
+/// Represents a date and time.
+///
+/// This structure stores date and time components as individual fields,
+/// providing a simple way to work with temporal data in attestation contexts.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct DateTime {
+ /// Seconds after the minute - [0, 59]
+ pub sec: i32,
+ /// Minutes after the hour - [0, 59]
+ pub min: i32,
+ /// Hours after midnight - [0, 23]
+ pub hour: i32,
+ /// Day of the month - [1, 31]
+ pub day: i32,
+ /// Months since January - [1, 12]
+ pub month: i32,
+ /// Years (full year, e.g., 2025)
+ pub year: i32,
+}
+
+impl DateTime {
+ /// Creates a new DateTime instance with default values (all zeros).
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Creates a DateTime from epoch seconds.
+ ///
+ /// # Arguments
+ /// * `timestamp` - Unix timestamp in seconds since January 1, 1970
+ ///
+ /// # Returns
+ /// A new DateTime instance representing the given timestamp
+ pub fn from_timestamp(timestamp: i64) -> Self {
+ let mut dt = Self::new();
+ seconds_to_datetime(timestamp, &mut dt);
+ dt
+ }
+
+ /// Extracts the date component from this DateTime.
+ pub fn date(&self) -> Date {
+ Date {
+ day: self.day,
+ month: self.month,
+ year: self.year,
+ }
+ }
+
+ /// Validates that all fields are within their expected ranges.
+ pub fn is_valid(&self) -> bool {
+ self.sec >= 0
+ && self.sec <= 59
+ && self.min >= 0
+ && self.min <= 59
+ && self.hour >= 0
+ && self.hour <= 23
+ && self.day >= 1
+ && self.day <= 31
+ && self.month >= 1
+ && self.month <= 12
+ && self.year >= 1970 // Assuming epoch-based timestamps
+ }
+
+ /// Returns the total seconds since midnight.
+ pub fn seconds_since_midnight(&self) -> i32 {
+ self.hour * 3600 + self.min * 60 + self.sec
+ }
+}
+
+impl fmt::Display for DateTime {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(
+ f,
+ "{:02}{:02}{:02}{:02}{:02}{:02}Z",
+ self.year % 100,
+ self.month,
+ self.day,
+ self.hour,
+ self.min,
+ self.sec
+ )
+ }
+}
+
+/// Represents a date without time information.
+///
+/// This structure stores only the date components (year, month, day),
+/// useful when time information is not needed or relevant.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Date {
+ /// Day of the month - [1, 31]
+ pub day: i32,
+ /// Months since January - [1, 12]
+ pub month: i32,
+ /// Years (full year, e.g., 2025)
+ pub year: i32,
+}
+
+impl Date {
+ /// Creates a new Date instance with default values (all zeros).
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Creates a Date with specific year, month, and day values.
+ ///
+ /// # Arguments
+ /// * `year` - The year (e.g., 2025)
+ /// * `month` - The month [1, 12]
+ /// * `day` - The day of the month [1, 31]
+ pub fn from_ymd(year: i32, month: i32, day: i32) -> Self {
+ Self { year, month, day }
+ }
+
+ /// Validates that all fields are within their expected ranges.
+ ///
+ /// Note: This performs basic range validation but doesn't check
+ /// for month-specific day limits (e.g., February 30th would pass).
+ pub fn is_valid(&self) -> bool {
+ self.day >= 1 && self.day <= 31 && self.month >= 1 && self.month <= 12 && self.year >= 1970
+ // Assuming epoch-based timestamps
+ }
+
+ /// Checks if the year is a leap year.
+ pub fn is_leap_year(&self) -> bool {
+ is_leap_year(self.year as i64)
+ }
+
+ /// Returns the number of days in the current month.
+ pub fn days_in_month(&self) -> i32 {
+ get_days_in_month(self.year as i64, self.month as i64) as i32
+ }
+}
+
+impl fmt::Display for Date {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "{:04}-{:02}-{:02} UTC", self.year, self.month, self.day)
+ }
+}
+
+/// Convert epoch seconds into date time.
+///
+/// Converts a Unix timestamp (seconds since January 1, 1970 00:00:00 UTC)
+/// into a DateTime structure. This function handles leap years correctly
+/// and updates the provided DateTime instance in-place.
+///
+/// # Arguments
+/// * `ts` - Unix timestamp in seconds
+/// * `tm` - Mutable reference to DateTime structure to be updated
+///
+/// # Note
+/// This function assumes the input timestamp is valid (>= 0) and
+/// represents a time after the Unix epoch.
+pub fn seconds_to_datetime(ts: i64, tm: &mut DateTime) {
+ // Constants
+ const SECONDS_PER_MINUTE: i64 = 60;
+ const SECONDS_PER_HOUR: i64 = 3600;
+ const SECONDS_PER_DAY: i64 = 86400;
+
+ // Calculate time components from seconds within the day
+ let day_seconds = ts % SECONDS_PER_DAY;
+ let mut day_number = ts / SECONDS_PER_DAY;
+
+ tm.sec = (day_seconds % SECONDS_PER_MINUTE) as i32;
+ tm.min = ((day_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE) as i32;
+ tm.hour = (day_seconds / SECONDS_PER_HOUR) as i32;
+
+ // Calculate year
+ let mut year = 1970i64;
+ loop {
+ let days_in_year = if is_leap_year(year) { 366 } else { 365 };
+ if day_number >= days_in_year {
+ day_number -= days_in_year;
+ year += 1;
+ } else {
+ break;
+ }
+ }
+ tm.year = year as i32;
+
+ // Calculate month and day
+ let mut month = 1;
+ while month <= 12 {
+ let days_in_month = get_days_in_month(year, month);
+ if day_number >= days_in_month {
+ day_number -= days_in_month;
+ month += 1;
+ } else {
+ break;
+ }
+ }
+ tm.month = month as i32;
+ tm.day = (day_number + 1) as i32; // Convert from 0-based to 1-based day
+}
+
+/// Helper function to determine if a year is a leap year.
+///
+/// A year is a leap year if:
+/// - It's divisible by 4, AND
+/// - If it's divisible by 100, it must also be divisible by 400
+fn is_leap_year(year: i64) -> bool {
+ year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
+}
+
+/// Helper function to get the number of days in a specific month of a year.
+///
+/// # Arguments
+/// * `year` - The year (used to determine if it's a leap year for February)
+/// * `month` - The month [1, 12]
+///
+/// # Returns
+/// Number of days in the specified month
+fn get_days_in_month(year: i64, month: i64) -> i64 {
+ match month {
+ 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
+ 4 | 6 | 9 | 11 => 30,
+ 2 => {
+ if is_leap_year(year) {
+ 29
+ } else {
+ 28
+ }
+ }
+ _ => 0, // Invalid month
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_datetime_from_timestamp() {
+ // Test Unix epoch
+ let dt = DateTime::from_timestamp(0);
+ assert_eq!(dt.year, 1970);
+ assert_eq!(dt.month, 1);
+ assert_eq!(dt.day, 1);
+ assert_eq!(dt.hour, 0);
+ assert_eq!(dt.min, 0);
+ assert_eq!(dt.sec, 0);
+
+ // Test timestamp for January 1, 1971 00:00:00 UTC (365 days = 31536000 seconds)
+ let dt = DateTime::from_timestamp(31536000);
+ assert_eq!(dt.year, 1971);
+ assert_eq!(dt.month, 1);
+ assert_eq!(dt.day, 1);
+ assert_eq!(dt.hour, 0);
+ assert_eq!(dt.min, 0);
+ assert_eq!(dt.sec, 0);
+
+ // Test timestamp for January 2, 1970 12:30:45 UTC
+ let dt = DateTime::from_timestamp(86400 + 12 * 3600 + 30 * 60 + 45); // 131445
+ assert_eq!(dt.year, 1970);
+ assert_eq!(dt.month, 1);
+ assert_eq!(dt.day, 2);
+ assert_eq!(dt.hour, 12);
+ assert_eq!(dt.min, 30);
+ assert_eq!(dt.sec, 45);
+ }
+
+ #[test]
+ fn test_leap_year() {
+ assert!(is_leap_year(2000)); // Divisible by 400
+ assert!(is_leap_year(2004)); // Divisible by 4
+ assert!(!is_leap_year(1900)); // Divisible by 100 but not 400
+ assert!(!is_leap_year(2001)); // Not divisible by 4
+ }
+
+ #[test]
+ fn test_days_in_month() {
+ assert_eq!(get_days_in_month(2023, 1), 31); // January
+ assert_eq!(get_days_in_month(2023, 2), 28); // February (non-leap)
+ assert_eq!(get_days_in_month(2024, 2), 29); // February (leap)
+ assert_eq!(get_days_in_month(2023, 4), 30); // April
+ }
+
+ #[test]
+ fn test_datetime_validation() {
+ let valid_dt = DateTime::from_timestamp(1262391174);
+ assert!(valid_dt.is_valid());
+
+ let mut invalid_dt = DateTime::new();
+ invalid_dt.sec = 70; // Invalid seconds
+ assert!(!invalid_dt.is_valid());
+ }
+
+ #[test]
+ fn test_date_validation() {
+ let valid_date = Date::from_ymd(2023, 6, 15);
+ assert!(valid_date.is_valid());
+
+ let invalid_date = Date::from_ymd(2023, 13, 15); // Invalid month
+ assert!(!invalid_date.is_valid());
+ }
+}
diff --git a/vm/wallet-gateway/share/attestation/src/lib.rs b/vm/wallet-gateway/share/attestation/src/lib.rs
new file mode 100644
index 00000000..e764b039
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/src/lib.rs
@@ -0,0 +1,24 @@
+// 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.
+
+#[macro_use]
+pub mod cert;
+pub mod date;
+pub mod report_verifier;
+pub mod sign;
+pub mod utils;
+pub mod verify;
diff --git a/vm/wallet-gateway/share/attestation/src/report_verifier.rs b/vm/wallet-gateway/share/attestation/src/report_verifier.rs
new file mode 100644
index 00000000..effbff86
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/src/report_verifier.rs
@@ -0,0 +1,217 @@
+// 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 crate::verify::{self, AttestationCertChain};
+use anyhow::{ensure, Result};
+use basic_utils::keccak_hash_to_bytes;
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+#[cfg(not(target_os = "optee"))]
+use std::time::SystemTime;
+
+#[cfg(target_os = "optee")]
+use optee_utee::trace_println as println;
+#[cfg(target_os = "optee")]
+use rustls::optee_time::SystemTime;
+
+#[derive(Serialize, Deserialize, PartialEq, Debug)]
+pub struct AttestationReport {
+ pub measurement: Vec<u8>,
+}
+impl AttestationReport {
+ pub fn from_cert(
+ presented_certs: &[rustls::Certificate],
+ report_ca_cert: &[u8],
+ ) -> Result<Self> {
+ // Extract information for attestation from TLS certification.
+ ensure!(
+ presented_certs.len() >= 3,
+ "[+] AttestationReport: presented_certs.len() >= 3"
+ );
+ let end_cert = presented_certs[0].clone().0;
+ let acc = AttestationCertChain {
+ end: end_cert.clone(),
+ intermediate: presented_certs[1].clone().0,
+ root: presented_certs[2].clone().0,
+ };
+ verify::verify_cert_chain(acc, &rustls::Certificate(report_ca_cert.to_vec())).unwrap();
+ let report = verify::extract_report_from_cert(&rustls::Certificate(end_cert)).unwrap();
+ Ok(report)
+ }
+}
+impl Default for AttestationReport {
+ fn default() -> Self {
+ Self {
+ measurement: vec![0u8; 32],
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Clone, Eq, PartialEq)]
+pub struct EnclaveAttr {
+ pub measurement: Vec<u8>,
+}
+
+/// User defined verification function to further verify the attestation report.
+pub type AttestationReportVerificationFn = fn(&AttestationReport) -> bool;
+
+/// Type used to verify attestation reports (this can be set as a certificate
+/// verifier in `rustls::ClientConfig`).
+#[derive(Clone)]
+pub struct AttestationReportVerifier {
+ /// Valid enclave attributes (only enclaves with attributes in this vector
+ /// will be accepted).
+ pub accepted_enclave_attrs: Vec<EnclaveAttr>,
+ /// Root certificate of the attestation service provider (e.g., IAS).
+ pub root_ca: Vec<u8>,
+ /// User defined function to verify the attestation report.
+ pub verifier: AttestationReportVerificationFn,
+}
+
+impl AttestationReportVerifier {
+ pub fn new(
+ accepted_enclave_attrs: Vec<EnclaveAttr>,
+ root_ca: &[u8],
+ verifier: AttestationReportVerificationFn,
+ ) -> Self {
+ Self {
+ accepted_enclave_attrs,
+ root_ca: root_ca.to_vec(),
+ verifier,
+ }
+ }
+
+ /// Verify whether the `MR_SIGNER` and `MR_ENCLAVE` in the attestation report is
+ /// accepted by us, which are defined in `accepted_enclave_attrs`.
+ fn verify_measures(&self, _attestation_report: &AttestationReport) -> bool {
+ println!("[+] AttestationReportVerifier::verify measures");
+ true
+ }
+
+ /// Verify TLS certificate.
+ fn verify_server_cert(&self, presented_certs: &[rustls::Certificate]) -> bool {
+ println!("[+] AttestationReportVerifier::verify server cert");
+
+ let report = match AttestationReport::from_cert(presented_certs, &self.root_ca) {
+ Ok(report) => report,
+ Err(e) => {
+ println!(
+ "[+] AttestationReportVerifier::cert verification error {:?}",
+ e
+ );
+ return false;
+ }
+ };
+ println!(
+ "[+] AttestationReportVerifier::extract report successfully, report: {:?}",
+ &report
+ );
+
+ self.verify_measures(&report) && (self.verifier)(&report)
+ }
+}
+
+impl rustls::client::ServerCertVerifier for AttestationReportVerifier {
+ fn verify_server_cert(
+ &self,
+ end_entity: &rustls::Certificate,
+ intermediates: &[rustls::Certificate],
+ _server_name: &rustls::ServerName,
+ _scts: &mut dyn Iterator<Item = &[u8]>,
+ _ocsp_response: &[u8],
+ _now: SystemTime,
+ ) -> Result<rustls::client::ServerCertVerified, rustls::Error> {
+ // This call automatically verifies certificate signature
+ println!("[+] ServerCertVerifier::verify server cert");
+ let mut presented_certs = intermediates.to_vec();
+ presented_certs.insert(0, end_entity.clone());
+ if self.verify_server_cert(presented_certs.as_slice()) {
+ Ok(rustls::client::ServerCertVerified::assertion())
+ } else {
+ Err(rustls::Error::General(
+ "server cert verification failed".to_string(),
+ ))
+ }
+ }
+}
+
+/// Type used to verify client certificates from server side
+pub type ClientVerifierFn = fn(&[u8]) -> bool;
+#[derive(Clone)]
+pub struct ClientVerifier {
+ pub accepted_pubkey_hash: HashSet<Vec<u8>>,
+ pub verifier_fn: ClientVerifierFn,
+}
+impl ClientVerifier {
+ pub fn new(accepted_pubkey_hash: HashSet<Vec<u8>>, verifier_fn: ClientVerifierFn) -> Self {
+ Self {
+ accepted_pubkey_hash,
+ verifier_fn,
+ }
+ }
+}
+
+impl rustls::server::ClientCertVerifier for ClientVerifier {
+ fn offer_client_auth(&self) -> bool {
+ true
+ }
+
+ #[allow(deprecated)]
+ fn client_auth_root_subjects(&self) -> &[rustls::DistinguishedName] {
+ &[]
+ }
+
+ fn verify_client_cert(
+ &self,
+ end_entity: &rustls::Certificate,
+ _intermediates: &[rustls::Certificate],
+ now: SystemTime,
+ ) -> Result<rustls::server::ClientCertVerified, rustls::Error> {
+ #[cfg(not(target_os = "optee"))]
+ let _now =
+ webpki::Time::try_from(now).map_err(|_| rustls::Error::FailedToGetCurrentTime)?;
+ #[cfg(target_os = "optee")]
+ let _now = webpki::Time::from_seconds_since_unix_epoch(now.secs());
+
+ println!("[+] ClientVerifier: invoke verify_client_cert");
+ // extract pubkey from client cert
+ // check if pub key exists in accepted_pub_keys
+ let pub_key = match verify::extract_pub_key_from_cert(end_entity) {
+ Ok(pub_key) => pub_key,
+ Err(e) => {
+ println!(
+ "[+] ClientVerifier: extract_pub_key_from_cert error {:?}",
+ e
+ );
+ return Err(rustls::Error::General(
+ "client cert verification failed".to_string(),
+ ));
+ }
+ };
+ println!("[+] ClientVerifier: pub_key: {:?}", pub_key);
+
+ // since attestation is a independent module, it doesn't import the "types"
+ // so we implement the hash function here
+ let pubkey_hash = keccak_hash_to_bytes(&pub_key)[..8].to_vec();
+ if self.accepted_pubkey_hash.contains(&pubkey_hash) {
+ return Ok(rustls::server::ClientCertVerified::assertion());
+ }
+
+ println!("[+] ClientVerifier: pub_key is not authorized");
+ Err(rustls::Error::HandshakeNotComplete)
+ }
+}
diff --git a/vm/wallet-gateway/share/attestation/src/sign.rs b/vm/wallet-gateway/share/attestation/src/sign.rs
new file mode 100644
index 00000000..d736a19b
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/src/sign.rs
@@ -0,0 +1,211 @@
+// 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.
+
+//! This module implements ECDSA (NIST P-256 curve) keys related functions. You
+//! can export private key to a DER format or create a certificate with
+//! extension for TLS-based remote attestation.
+
+use crate::date::{seconds_to_datetime, DateTime};
+use anyhow::{bail, Result};
+use basic_utils::get_system_time_seconds;
+use crypto::EcdsaKeyPair;
+use yasna::models::UTCTime;
+
+/// create_cert_with_extension makes a self-signed x509-v3 cert with SGX
+/// attestation report as extensions.
+/// @reference [Internet X.509 Public Key Infrastructure Certificate and
+/// Certificate Revocation List (CRL) Profile][1]
+///
+/// [1]: https://tools.ietf.org/pdf/rfc5280.pdf
+pub fn sign_csr_with_extension(
+ key_pair: &EcdsaKeyPair,
+ pub_key: &[u8],
+ issuer: &str,
+ subject: &str,
+ alter_dns_names: [&str; 2],
+ payload: &[u8],
+ cert_valid_seconds: i64,
+) -> Result<Vec<u8>> {
+ use crate::cert::*;
+ use bit_vec::BitVec;
+ use yasna::models::ObjectIdentifier;
+
+ // Construct useful OIDs.
+ let ecdsa_with_sha256_oid = ObjectIdentifier::from_slice(&[1, 2, 840, 10045, 4, 3, 2]);
+ let common_name_oid = ObjectIdentifier::from_slice(&[2, 5, 4, 3]);
+ let ec_public_key_oid = ObjectIdentifier::from_slice(&[1, 2, 840, 10045, 2, 1]);
+ let prime256v1_oid = ObjectIdentifier::from_slice(&[1, 2, 840, 10045, 3, 1, 7]);
+ let comment_oid = ObjectIdentifier::from_slice(&[2, 16, 840, 1, 113_730, 1, 13]);
+ let subject_alt_name_oid = ObjectIdentifier::from_slice(&[2, 5, 29, 17]);
+
+ let alter_names = (
+ DnsName::new(alter_dns_names[0].to_string()),
+ DnsName::new(alter_dns_names[1].to_string()),
+ );
+
+ let (issue_ts, expire_ts) = valid_time_range(cert_valid_seconds)?;
+ // Construct certificate with payload in extension in DER.
+ let tbs_cert_der = yasna::construct_der(|writer| {
+ let version = 2i8;
+ let serial = 1u8;
+ let cert_sign_algo = asn1_seq!(ecdsa_with_sha256_oid.clone());
+ let issuer = asn1_seq!(asn1_seq!(asn1_seq!(
+ common_name_oid.clone(),
+ issuer.to_owned()
+ )));
+ let valid_range = asn1_seq!(issue_ts, expire_ts);
+ let subject = asn1_seq!(asn1_seq!(asn1_seq!(
+ common_name_oid.clone(),
+ subject.to_string(),
+ )));
+ let pub_key = asn1_seq!(
+ asn1_seq!(ec_public_key_oid, prime256v1_oid,),
+ BitVec::from_bytes(pub_key),
+ );
+
+ let sgx_ra_cert_ext = asn1_seq!(comment_oid, payload.to_owned());
+
+ let alter_names_payload = AlterNamesPayload::new(alter_names.0, alter_names.1);
+ let alter_names = asn1_seq!(subject_alt_name_oid, alter_names_payload);
+
+ let cert_ext = asn1_seq!(sgx_ra_cert_ext, alter_names);
+
+ let tbs_cert = asn1_seq!(
+ version,
+ serial,
+ cert_sign_algo,
+ issuer,
+ valid_range,
+ subject,
+ pub_key,
+ cert_ext,
+ );
+ TbsCert::dump(writer, tbs_cert);
+ });
+
+ let sig = key_pair.sign(tbs_cert_der.as_slice()).unwrap();
+ let sig_der = yasna::construct_der(|writer| writer.write_der(sig.as_ref()));
+
+ let der = yasna::construct_der(|writer| {
+ writer.write_sequence(|writer| {
+ writer.next().write_der(tbs_cert_der.as_slice());
+ CertSignAlgo::dump(writer.next(), asn1_seq!(ecdsa_with_sha256_oid.clone()));
+ writer
+ .next()
+ .write_bitvec(&BitVec::from_bytes(sig_der.as_slice()));
+ });
+ });
+
+ Ok(der)
+}
+
+pub fn sign_intermediate(
+ key_pair: &EcdsaKeyPair,
+ pub_key: &[u8],
+ issuer: &str,
+ subject: &str,
+ cert_valid_seconds: i64,
+) -> Result<Vec<u8>> {
+ use crate::cert::*;
+ use bit_vec::BitVec;
+ use yasna::models::ObjectIdentifier;
+ // Construct useful OIDs.
+ let ecdsa_with_sha384_oid = ObjectIdentifier::from_slice(&[1, 2, 840, 10045, 4, 3, 3]);
+ let common_name_oid = ObjectIdentifier::from_slice(&[2, 5, 4, 3]);
+ let ec_public_key_oid = ObjectIdentifier::from_slice(&[1, 2, 840, 10045, 2, 1]);
+ let prime256v1_oid = ObjectIdentifier::from_slice(&[1, 2, 840, 10045, 3, 1, 7]);
+ let basic_constrain_oid = ObjectIdentifier::from_slice(&[2, 5, 29, 19]);
+
+ let (issue_ts, expire_ts) = valid_time_range(cert_valid_seconds)?;
+ // Construct certificate with payload in extension in DER.
+ let tbs_cert_der = yasna::construct_der(|writer| {
+ let version = 2i8;
+ let serial = 1u8;
+ let cert_sign_algo = asn1_seq!(ecdsa_with_sha384_oid.clone());
+ let issuer = asn1_seq!(asn1_seq!(asn1_seq!(
+ common_name_oid.clone(),
+ issuer.to_owned()
+ )));
+ println!("issuer: {:?}", issuer);
+ let valid_range = asn1_seq!(issue_ts, expire_ts);
+ let subject = asn1_seq!(asn1_seq!(asn1_seq!(
+ common_name_oid.clone(),
+ subject.to_string(),
+ )));
+ let pub_key = asn1_seq!(
+ asn1_seq!(ec_public_key_oid, prime256v1_oid,),
+ BitVec::from_bytes(pub_key),
+ );
+ let basic_constrain = asn1_seq!(
+ basic_constrain_oid,
+ true,
+ [0x30, 0x03, 0x01, 0x01, 0xff].to_vec()
+ );
+ let cert_ext = asn1_seq!(basic_constrain,);
+
+ let tbs_cert = asn1_seq!(
+ version,
+ serial,
+ cert_sign_algo,
+ issuer,
+ valid_range,
+ subject,
+ pub_key,
+ cert_ext,
+ );
+ IntermediateCert::dump(writer, tbs_cert);
+ });
+
+ let sig = key_pair.sign(tbs_cert_der.as_slice()).unwrap();
+ let sig_der = yasna::construct_der(|writer| writer.write_der(sig.as_ref()));
+
+ let der = yasna::construct_der(|writer| {
+ writer.write_sequence(|writer| {
+ writer.next().write_der(tbs_cert_der.as_slice());
+ CertSignAlgo::dump(writer.next(), asn1_seq!(ecdsa_with_sha384_oid.clone()));
+ writer
+ .next()
+ .write_bitvec(&BitVec::from_bytes(sig_der.as_slice()));
+ });
+ });
+ Ok(der)
+}
+
+fn valid_time_range(cert_valid_seconds: i64) -> Result<(UTCTime, UTCTime)> {
+ let issue_ts = get_system_time_seconds()? - 10; // set issued time as 10 seconds earlier
+ let mut issue_date_time = DateTime::default();
+ seconds_to_datetime(issue_ts, &mut issue_date_time);
+ let expire_ts = issue_ts + cert_valid_seconds;
+ let mut expire_date_time = DateTime::default();
+ seconds_to_datetime(expire_ts, &mut expire_date_time);
+ println!("issue_ts: {:?}, date: {}", issue_ts, issue_date_time);
+ println!("expire_ts: {:?}, date: {}", expire_ts, expire_date_time);
+
+ let issue_utc_time = match UTCTime::parse(format!("{}", issue_date_time).as_bytes()) {
+ Some(t) => t,
+ None => {
+ bail!("parse issue date time failed")
+ }
+ };
+ let expire_utc_time = match UTCTime::parse(format!("{}", expire_date_time).as_bytes()) {
+ Some(t) => t,
+ None => {
+ bail!("parse expire date time failed")
+ }
+ };
+ Ok((issue_utc_time, expire_utc_time))
+}
diff --git a/vm/wallet-gateway/share/attestation/src/utils.rs b/vm/wallet-gateway/share/attestation/src/utils.rs
new file mode 100644
index 00000000..f11b7665
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/src/utils.rs
@@ -0,0 +1,140 @@
+// 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 crate::report_verifier::AttestationReport;
+use crate::sign::{sign_csr_with_extension, sign_intermediate};
+use basic_utils::get_system_time_seconds;
+use crypto::{EcdsaKeyPair, ECDSA_P256_SHA256_ASN1_SIGNING, ECDSA_P384_SHA384_ASN1_SIGNING};
+
+use anyhow::{Context, Result};
+use std::convert::TryInto;
+use std::fs;
+use std::io::BufReader;
+
+pub fn load_pem_cert(filename: &str) -> Result<Vec<rustls::Certificate>> {
+ let certfile = fs::File::open(filename).with_context(|| "cannot open certificate file")?;
+ let mut reader = BufReader::new(certfile);
+ let certs = rustls_pemfile::certs(&mut reader)
+ .map_err(|_| anyhow::anyhow!("pemfile::load_pem_cert failed"));
+ Ok(certs
+ .unwrap()
+ .iter()
+ .map(|v| rustls::Certificate(v.clone()))
+ .collect())
+}
+
+pub fn load_pem_single_cert(filename: &str) -> Result<rustls::Certificate> {
+ let certs = load_pem_cert(filename)?;
+ assert!(certs.len() == 1);
+ Ok(certs[0].clone())
+}
+
+pub fn load_pem_cert_from_bytes(bytes: &[u8]) -> Result<Vec<rustls::Certificate>> {
+ let cursor = std::io::Cursor::new(bytes);
+ let mut reader = BufReader::new(cursor);
+ let certs = rustls_pemfile::certs(&mut reader)
+ .map_err(|_| anyhow::anyhow!("pemfile::load_pem_cert failed"));
+ Ok(certs
+ .unwrap()
+ .iter()
+ .map(|v| rustls::Certificate(v.clone()))
+ .collect())
+}
+
+pub fn load_pem_key(filename: &str) -> Result<rustls::PrivateKey> {
+ let keyfile = fs::File::open(filename).with_context(|| "cannot open private key file")?;
+ let mut reader = BufReader::new(keyfile);
+ let keys = rustls_pemfile::pkcs8_private_keys(&mut reader)
+ .map_err(|_| anyhow::anyhow!("pemfile::pkcs8_private_keys failed"))?;
+ assert!(keys.len() == 1);
+ Ok(rustls::PrivateKey(keys[0].clone()))
+}
+
+pub fn load_pem_key_from_bytes(bytes: &[u8]) -> Result<rustls::PrivateKey> {
+ let cursor = std::io::Cursor::new(bytes);
+ let mut reader = BufReader::new(cursor);
+ let keys = rustls_pemfile::pkcs8_private_keys(&mut reader)
+ .map_err(|_| anyhow::anyhow!("pemfile::pkcs8_private_keys failed"))?;
+ assert!(keys.len() == 1);
+ Ok(rustls::PrivateKey(keys[0].clone()))
+}
+
+pub fn generate_end_cert(
+ ca_key: &[u8],
+ end_key: &[u8],
+ user_name: &str,
+ cert_valid_seconds: i64,
+) -> Result<Vec<u8>> {
+ let ca_key = load_pem_key_from_bytes(ca_key)?;
+ let ca_kp = EcdsaKeyPair::from_bytes(&ca_key.0, &ECDSA_P384_SHA384_ASN1_SIGNING)?;
+ let end_kp = EcdsaKeyPair::from_bytes(end_key, &ECDSA_P256_SHA256_ASN1_SIGNING)?;
+ let end_pub = end_kp.pub_key();
+ assert_eq!(
+ end_pub[0], 0x4,
+ "Missing uncompressed public key indicator."
+ );
+
+ let report = AttestationReport::default();
+ let payload = serde_json::to_vec(&report).unwrap();
+ let end_der = sign_csr_with_extension(
+ &ca_kp,
+ end_pub,
+ "CK ECDSA CA",
+ &("CK client: ".to_string() + user_name),
+ ["client", "localhost"],
+ &payload,
+ cert_valid_seconds,
+ )?;
+ Ok(end_der)
+}
+
+pub fn generate_inter_cert(
+ ca_key: &[u8],
+ inter_pub_key: &[u8],
+ cert_valid_seconds: i64,
+) -> Result<Vec<u8>> {
+ let ca_key = load_pem_key_from_bytes(ca_key)?;
+ let ca_kp = EcdsaKeyPair::from_bytes(&ca_key.0, &ECDSA_P384_SHA384_ASN1_SIGNING)?;
+ assert!(
+ inter_pub_key[0] == 0x4,
+ "Missing uncompressed public key indicator."
+ );
+
+ let inter_der = sign_intermediate(
+ &ca_kp,
+ inter_pub_key,
+ "CK ECDSA CA",
+ "CK ECDSA level 2 intermediate",
+ cert_valid_seconds,
+ )?;
+ Ok(inter_der)
+}
+pub fn generate_key_pair() -> Result<(Vec<u8>, Vec<u8>)> {
+ let key_pair = EcdsaKeyPair::new()?;
+ let priv_key = key_pair.prv_key();
+ let pub_key = key_pair.pub_key();
+ Ok((pub_key.to_vec(), priv_key.to_vec()))
+}
+
+pub fn get_webpki_time() -> Result<webpki::Time> {
+ let time = webpki::Time::from_seconds_since_unix_epoch(
+ get_system_time_seconds()?
+ .try_into()
+ .map_err(|_| anyhow::anyhow!("time conversion failed"))?,
+ );
+ Ok(time)
+}
diff --git a/vm/wallet-gateway/share/attestation/src/verify.rs b/vm/wallet-gateway/share/attestation/src/verify.rs
new file mode 100644
index 00000000..3400d2df
--- /dev/null
+++ b/vm/wallet-gateway/share/attestation/src/verify.rs
@@ -0,0 +1,109 @@
+// 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 crate::{report_verifier::AttestationReport, utils::get_webpki_time};
+use anyhow::{anyhow, Result};
+use serde::{Deserialize, Serialize};
+use std::convert::TryFrom;
+
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
+pub struct CertInfo {
+ pub issuer: String,
+ pub subject: String,
+}
+
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
+pub struct AttestationCertChain {
+ pub end: Vec<u8>,
+ pub intermediate: Vec<u8>,
+ pub root: Vec<u8>,
+}
+
+type SignatureAlgorithms = &'static [&'static webpki::SignatureAlgorithm];
+static SUPPORTED_SIG_ALGS: SignatureAlgorithms = &[
+ &webpki::ECDSA_P256_SHA256,
+ &webpki::ECDSA_P256_SHA384,
+ &webpki::ECDSA_P384_SHA256,
+ &webpki::ECDSA_P384_SHA384,
+];
+
+/// Construct a AttestationReport from a X509 certificate and verify
+/// attestation report with the report_ca_cert which is from the attestation
+/// service provider.
+pub fn extract_report_from_cert(cert: &rustls::Certificate) -> Result<AttestationReport> {
+ use crate::cert::*;
+ let cert = &cert.0;
+ // Extract information for attestation from TLS certification.
+ let x509 = yasna::parse_der(cert, X509::load).unwrap();
+ let tbs_cert: <TbsCert as Asn1Ty>::ValueTy = x509.0;
+ let pub_key: <PubKey as Asn1Ty>::ValueTy = ((((((tbs_cert.1).1).1).1).1).1).0;
+ let _pub_k = (pub_key.1).0;
+ let cert_ext: <RaCertExt as Asn1Ty>::ValueTy = (((((((tbs_cert.1).1).1).1).1).1).1).0 .0;
+ let cert_ext_payload: Vec<u8> = (cert_ext.1).0;
+
+ // Convert to endorsed report
+ let report = serde_json::from_slice(&cert_ext_payload)?;
+ Ok(report)
+}
+
+/// extract issuer and subject from certificate
+pub fn extract_info_from_cert(cert: &rustls::Certificate) -> Result<CertInfo> {
+ use crate::cert::*;
+ let cert = &cert.0;
+ // Extract information from certificate
+ let x509 = yasna::parse_der(cert, X509::load).unwrap();
+ let tbs_cert: <TbsCert as Asn1Ty>::ValueTy = x509.0;
+ let issuer: <Issuer as Asn1Ty>::ValueTy = (((tbs_cert.1).1).1).0;
+ let issuer_payload = (((issuer.0).0).1).0;
+ let subject: <Subject as Asn1Ty>::ValueTy = (((((tbs_cert.1).1).1).1).1).0;
+ let subject_payload = (((subject.0).0).1).0;
+
+ Ok(CertInfo {
+ issuer: issuer_payload,
+ subject: subject_payload,
+ })
+}
+
+/// extract public key from certificate
+pub fn extract_pub_key_from_cert(cert: &rustls::Certificate) -> Result<Vec<u8>> {
+ use crate::cert::*;
+ let cert = &cert.0;
+ // Extract information from certificate
+ let x509 = yasna::parse_der(cert, X509::load).unwrap();
+ let tbs_cert: <TbsCert as Asn1Ty>::ValueTy = x509.0;
+ let pub_key: <PubKey as Asn1Ty>::ValueTy = ((((((tbs_cert.1).1).1).1).1).1).0;
+ let pub_k = (pub_key.1).0;
+
+ Ok(pub_k.to_bytes())
+}
+
+pub fn verify_cert_chain(acc: AttestationCertChain, ca_cert: &rustls::Certificate) -> Result<()> {
+ let end_cert = webpki::EndEntityCert::try_from(acc.end.as_slice())?;
+ let anchor = webpki::TrustAnchor::try_from_cert_der(ca_cert.0.as_ref())
+ .map_err(|_| anyhow!("invalid root cert"))?;
+ let trust_anchors = vec![anchor];
+
+ let chain = vec![&acc.intermediate[..], &acc.root[..]];
+ let time = get_webpki_time()?;
+ end_cert.verify_is_valid_tls_server_cert(
+ SUPPORTED_SIG_ALGS,
+ &webpki::TlsServerTrustAnchors(&trust_anchors),
+ &chain,
+ time,
+ )?;
+ Ok(())
+}
diff --git a/vm/wallet-gateway/share/basic_utils/Cargo.toml b/vm/wallet-gateway/share/basic_utils/Cargo.toml
new file mode 100644
index 00000000..a09d3226
--- /dev/null
+++ b/vm/wallet-gateway/share/basic_utils/Cargo.toml
@@ -0,0 +1,28 @@
+# 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.
+
+[package]
+name = "basic_utils"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+sha3 = "0.10.6"
+serde = { version = "1.0", features = ["derive"] }
+anyhow = "1.0"
+hex = "0.4"
+log = "=0.4.17"
\ No newline at end of file
diff --git a/vm/wallet-gateway/share/basic_utils/src/hash.rs b/vm/wallet-gateway/share/basic_utils/src/hash.rs
new file mode 100644
index 00000000..95632805
--- /dev/null
+++ b/vm/wallet-gateway/share/basic_utils/src/hash.rs
@@ -0,0 +1,38 @@
+// 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 serde::Serialize;
+use sha3::{Digest, Keccak256};
+
+pub fn keccak_hash<T>(data: &T) -> String
+where
+ T: ?Sized + Serialize + AsRef<[u8]>,
+{
+ let mut hasher = Keccak256::new();
+ hasher.update(data);
+ let result = hasher.finalize();
+ hex::encode(result)
+}
+
+pub fn keccak_hash_to_bytes<T>(data: &T) -> [u8; 32]
+where
+ T: ?Sized + Serialize + AsRef<[u8]>,
+{
+ let mut hasher = Keccak256::new();
+ hasher.update(data);
+ hasher.finalize().into()
+}
diff --git a/vm/wallet-gateway/share/basic_utils/src/lib.rs b/vm/wallet-gateway/share/basic_utils/src/lib.rs
new file mode 100644
index 00000000..65d37f2c
--- /dev/null
+++ b/vm/wallet-gateway/share/basic_utils/src/lib.rs
@@ -0,0 +1,26 @@
+// 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.
+
+mod random;
+pub use random::*;
+mod hash;
+pub use hash::*;
+mod time;
+pub use time::*;
+
+#[cfg(target_os = "optee")]
+pub use optee_utee::trace_println as println;
diff --git a/vm/wallet-gateway/share/basic_utils/src/random.rs b/vm/wallet-gateway/share/basic_utils/src/random.rs
new file mode 100644
index 00000000..efddac61
--- /dev/null
+++ b/vm/wallet-gateway/share/basic_utils/src/random.rs
@@ -0,0 +1,36 @@
+// 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::Result;
+
+#[cfg(target_os = "optee")]
+pub fn generate_random_bytes(len: usize) -> Result<Vec<u8>> {
+ use optee_utee::Random;
+ let mut random_bytes = vec![0u8; len];
+ Random::generate(random_bytes.as_mut() as _);
+ Ok(random_bytes)
+}
+
+#[cfg(not(target_os = "optee"))]
+pub fn generate_random_bytes(len: usize) -> Result<Vec<u8>> {
+ use std::io::Read;
+ let mut rng = std::fs::File::open("/dev/urandom")
+ .map_err(|_| anyhow::anyhow!("cannot open /dev/urandom"))?;
+ let mut buf = vec![0u8; len];
+ rng.read_exact(&mut buf)?;
+ Ok(buf)
+}
diff --git a/vm/wallet-gateway/share/basic_utils/src/time.rs b/vm/wallet-gateway/share/basic_utils/src/time.rs
new file mode 100644
index 00000000..ae79487a
--- /dev/null
+++ b/vm/wallet-gateway/share/basic_utils/src/time.rs
@@ -0,0 +1,32 @@
+// 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::Result;
+
+#[cfg(not(target_os = "optee"))]
+pub fn get_system_time_seconds() -> Result<i64> {
+ let seconds = std::time::SystemTime::now()
+ .duration_since(std::time::SystemTime::UNIX_EPOCH)?
+ .as_secs() as i64;
+ Ok(seconds)
+}
+#[cfg(target_os = "optee")]
+pub fn get_system_time_seconds() -> Result<i64> {
+ let mut time = optee_utee::Time::new();
+ time.ree_time();
+ Ok(time.seconds as i64)
+}
diff --git a/vm/wallet-gateway/share/crypto/Cargo.toml b/vm/wallet-gateway/share/crypto/Cargo.toml
new file mode 100644
index 00000000..20952328
--- /dev/null
+++ b/vm/wallet-gateway/share/crypto/Cargo.toml
@@ -0,0 +1,28 @@
+# 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.
+
+[package]
+name = "crypto"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+basic_utils = { path = "../basic_utils" }
+
+serde = { version = "1.0", features = ["derive"] }
+anyhow = "1.0"
+ring = { version = "0.16.20" }
\ No newline at end of file
diff --git a/vm/wallet-gateway/share/crypto/src/aead.rs b/vm/wallet-gateway/share/crypto/src/aead.rs
new file mode 100644
index 00000000..acbe954e
--- /dev/null
+++ b/vm/wallet-gateway/share/crypto/src/aead.rs
@@ -0,0 +1,201 @@
+// 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::{anyhow, Result};
+use basic_utils::generate_random_bytes;
+use ring::aead;
+use serde::{Deserialize, Serialize};
+
+// AES_GCM 128
+// encrypting/decrypting data-key
+pub const AES_GCM_128_KEY_LENGTH: usize = 16;
+pub const AES_GCM_128_IV_LENGTH: usize = 12;
+pub const CMAC_LENGTH: usize = 16;
+type CMac = [u8; CMAC_LENGTH];
+
+/// The above code defines a struct for AES-GCM 128-bit encryption and decryption with methods for
+/// encrypting and decrypting data and generating a CMAC.
+///
+/// Properties:
+///
+/// * `key`: A 128-bit AES key used for encryption and decryption in the AES-GCM mode of operation.
+/// * `iv`: `iv` stands for initialization vector. It is a fixed-size array of bytes used as an input to
+/// the AES-GCM encryption algorithm to ensure that the same plaintext message encrypted with the same
+/// key produces different ciphertexts. The `iv` is typically randomly generated for each encryption
+/// operation and must be kept
+#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct AesGcm128Key {
+ pub key: [u8; AES_GCM_128_KEY_LENGTH],
+ pub iv: [u8; AES_GCM_128_IV_LENGTH],
+}
+
+/// This is an implementation of methods for the `AesGcm128Key` struct.
+impl AesGcm128Key {
+ pub const _SCHEMA: &'static str = "aes-gcm-128";
+
+ /// This function creates a new instance of AesGcm128Key with the given key and initialization vector.
+ ///
+ /// Arguments:
+ ///
+ /// * `in_key`: in_key is a reference to a byte slice that represents the encryption key used in
+ /// AES-GCM-128 encryption. The length of the slice should be 16 bytes (AES_GCM_128_KEY_LENGTH).
+ /// * `in_iv`: `in_iv` is a slice of bytes representing the initialization vector (IV) used in AES-GCM
+ /// encryption. The IV is a random value that is used to ensure that each encryption operation produces
+ /// a unique ciphertext, even if the same plaintext is encrypted multiple times. The length of the IV is
+ /// typically
+ ///
+ /// Returns:
+ ///
+ /// The `new` function is returning a `Result` containing an `AesGcm128Key` struct.
+ pub fn new(in_key: &[u8], in_iv: &[u8]) -> Result<Self> {
+ let mut key = [0u8; AES_GCM_128_KEY_LENGTH];
+ let mut iv = [0u8; AES_GCM_128_IV_LENGTH];
+ key.copy_from_slice(in_key);
+ iv.copy_from_slice(in_iv);
+
+ Ok(AesGcm128Key { key, iv })
+ }
+
+ pub fn generate() -> Result<Self> {
+ let key = generate_random_bytes(AES_GCM_128_KEY_LENGTH)?;
+ let iv = generate_random_bytes(AES_GCM_128_IV_LENGTH)?;
+
+ Ok(AesGcm128Key {
+ key: key.try_into().map_err(|_| anyhow!("try_into error"))?,
+ iv: iv.try_into().map_err(|_| anyhow!("try_into error"))?,
+ })
+ }
+
+ /// This function decrypts a message using AES-128-GCM and returns a CMAC authentication tag.
+ ///
+ /// Arguments:
+ ///
+ /// * `in_out`: `in_out` is a mutable reference to a `Vec<u8>` that contains the ciphertext to be
+ /// decrypted. The decrypted plaintext will be written back to the same `Vec<u8>` in place of the
+ /// ciphertext.
+ ///
+ /// Returns:
+ ///
+ /// a `Result` containing a `CMac` value.
+ pub fn decrypt(&self, in_out: &mut Vec<u8>) -> Result<CMac> {
+ let plaintext_len = aead_decrypt(&aead::AES_128_GCM, in_out, &self.key, &self.iv)?.len();
+ let mut cmac: CMac = [0u8; CMAC_LENGTH];
+ cmac.copy_from_slice(&in_out[plaintext_len..]);
+ in_out.truncate(plaintext_len);
+ Ok(cmac)
+ }
+
+ /// This function encrypts a given input using AES-128-GCM and returns a CMAC value.
+ ///
+ /// Arguments:
+ ///
+ /// * `in_out`: `in_out` is a mutable reference to a vector of bytes (`Vec<u8>`). This vector contains
+ /// the plaintext to be encrypted and will also be used to store the resulting ciphertext. The function
+ /// will modify this vector in place to encrypt the plaintext and append the resulting CMAC
+ /// (Cipher-based Message
+ ///
+ /// Returns:
+ ///
+ /// a `Result` containing a `CMac` value.
+ pub fn encrypt(&self, in_out: &mut Vec<u8>) -> Result<CMac> {
+ aead_encrypt(&aead::AES_128_GCM, in_out, &self.key, &self.iv)?;
+ let mut cmac: CMac = [0u8; CMAC_LENGTH];
+ let n = in_out.len();
+ let cybertext_len = n - CMAC_LENGTH;
+ cmac.copy_from_slice(&in_out[cybertext_len..]);
+ Ok(cmac)
+ }
+}
+
+/// This function performs AEAD encryption on a given input using a specified algorithm, key, and
+/// initialization vector.
+///
+/// Arguments:
+///
+/// * `alg`: a reference to an AEAD (Authenticated Encryption with Associated Data) algorithm, which is
+/// used for encrypting and authenticating data.
+/// * `in_out`: `in_out` is a mutable reference to a vector of bytes that contains the plaintext to be
+/// encrypted. After encryption, the ciphertext will be appended to this vector.
+/// * `key`: The `key` parameter is a byte slice that contains the secret key used for encryption. It is
+/// used to create an `UnboundKey` object, which is then used to create a `LessSafeKey` object for
+/// encryption.
+/// * `iv`: `iv` stands for initialization vector. It is a fixed-size input to the encryption algorithm
+/// that is typically used to ensure that the same plaintext input does not produce the same ciphertext
+/// output. The `iv` should be unique for each encryption operation.
+///
+/// Returns:
+///
+/// a `Result` type, which can either be `Ok(())` if the encryption was successful or an error if
+/// something went wrong during the encryption process.
+pub fn aead_encrypt(
+ alg: &'static aead::Algorithm,
+ in_out: &mut Vec<u8>,
+ key: &[u8],
+ iv: &[u8],
+) -> Result<()> {
+ let key =
+ aead::UnboundKey::new(alg, key).map_err(|_| anyhow!("aead::UnboundKey::new() Error"))?;
+ let nonce = aead::Nonce::try_assume_unique_for_key(iv)
+ .map_err(|_| anyhow!("aead::Nonce::try_assume_unique_for_key() Error"))?;
+ let aad = aead::Aad::from([0u8; 8]);
+
+ let enc_key = aead::LessSafeKey::new(key);
+ enc_key
+ .seal_in_place_append_tag(nonce, aad, in_out)
+ .map_err(|_| anyhow!("aead::LessSafeKey::seal_in_place_append_tag() Error"))?;
+ Ok(())
+}
+
+/// This function performs authenticated encryption with associated data (AEAD) decryption using a given
+/// algorithm, key, initialization vector, and input/output buffer.
+///
+/// Arguments:
+///
+/// * `alg`: The AEAD (Authenticated Encryption with Associated Data) algorithm to be used for
+/// decryption.
+/// * `in_out`: `in_out` is a mutable reference to a byte slice that contains the ciphertext to be
+/// decrypted. The function will modify this slice in place to store the decrypted plaintext.
+/// * `key`: The `key` parameter is a byte slice representing the secret key used for decryption. It is
+/// used to create an `UnboundKey` object, which is then used to create a `LessSafeKey` object for
+/// decryption.
+/// * `iv`: `iv` stands for initialization vector. It is a fixed-size input to the encryption algorithm
+/// that is typically used to ensure that the same plaintext input does not produce the same ciphertext
+/// output. It is also used to derive the initial state of the encryption algorithm. In the context of
+/// this function, `iv
+///
+/// Returns:
+///
+/// a `Result` that contains a mutable reference to the input/output buffer (`&'a mut [u8]`) if the
+/// decryption is successful. If there is an error during decryption, the function will return an error.
+pub fn aead_decrypt<'a>(
+ alg: &'static aead::Algorithm,
+ in_out: &'a mut [u8],
+ key: &[u8],
+ iv: &[u8],
+) -> Result<&'a mut [u8]> {
+ let key =
+ aead::UnboundKey::new(alg, key).map_err(|_| anyhow!("aead::UnboundKey::new() Error"))?;
+ let nonce = aead::Nonce::try_assume_unique_for_key(iv)
+ .map_err(|_| anyhow!("aead::Nonce::try_assume_unique_for_key() Error"))?;
+ let aad = aead::Aad::from([0u8; 8]);
+
+ let dec_key = aead::LessSafeKey::new(key);
+ let slice = dec_key
+ .open_in_place(nonce, aad, in_out)
+ .map_err(|_| anyhow!("aead::LessSafeKey::open_in_place() Error"))?;
+ Ok(slice)
+}
diff --git a/vm/wallet-gateway/share/crypto/src/ecdsa.rs b/vm/wallet-gateway/share/crypto/src/ecdsa.rs
new file mode 100644
index 00000000..bcd140a5
--- /dev/null
+++ b/vm/wallet-gateway/share/crypto/src/ecdsa.rs
@@ -0,0 +1,103 @@
+// 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::{anyhow, Result};
+use ring::rand;
+use ring::signature::{self, EcdsaSigningAlgorithm, KeyPair, ECDSA_P384_SHA384_ASN1};
+pub use ring::signature::{
+ ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA256_ASN1_SIGNING, ECDSA_P384_SHA384_ASN1_SIGNING,
+};
+
+/// EcdsaKeyPair stores a pair of ECDSA (private, public) key based on the
+/// NIST P-256 curve (a.k.a secp256r1).
+pub struct EcdsaKeyPair {
+ key_pair: signature::EcdsaKeyPair,
+ pkcs8_bytes: Vec<u8>,
+}
+
+impl EcdsaKeyPair {
+ /// Generate a ECDSA key pair.
+ pub fn new() -> Result<Self> {
+ let rng = rand::SystemRandom::new();
+ let pkcs8_bytes = signature::EcdsaKeyPair::generate_pkcs8(
+ &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
+ &rng,
+ )
+ .unwrap();
+ let key_pair = signature::EcdsaKeyPair::from_pkcs8(
+ &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
+ pkcs8_bytes.as_ref(),
+ )
+ .unwrap();
+ Ok(Self {
+ key_pair,
+ pkcs8_bytes: pkcs8_bytes.as_ref().to_vec(),
+ })
+ }
+
+ pub fn from_bytes(pkcs8_bytes: &[u8], algo: &'static EcdsaSigningAlgorithm) -> Result<Self> {
+ let key_pair = signature::EcdsaKeyPair::from_pkcs8(algo, pkcs8_bytes).unwrap();
+ Ok(Self {
+ key_pair,
+ pkcs8_bytes: pkcs8_bytes.to_vec(),
+ })
+ }
+
+ pub fn pub_key(&self) -> &[u8] {
+ self.key_pair.public_key().as_ref()
+ }
+
+ pub fn prv_key(&self) -> &[u8] {
+ self.pkcs8_bytes.as_ref()
+ }
+
+ pub fn sign(&self, msg: &[u8]) -> Result<Vec<u8>> {
+ let rng = rand::SystemRandom::new();
+ match self.key_pair.sign(&rng, msg) {
+ Ok(sig) => Ok(sig.as_ref().to_vec()),
+ Err(_) => Err(anyhow!("failed to sign")),
+ }
+ }
+}
+
+pub fn sign_bytes_p256(priv_key: &[u8], bytes: &[u8]) -> Result<Vec<u8>> {
+ let key_pair = EcdsaKeyPair::from_bytes(priv_key, &ECDSA_P256_SHA256_ASN1_SIGNING)?;
+ let sig = key_pair.sign(bytes)?;
+ Ok(sig.to_vec())
+}
+
+pub fn verify_signature_p256(pub_key: &[u8], bytes: &[u8], sig: &[u8]) -> Result<()> {
+ let peer_pub_key = signature::UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, pub_key);
+ match peer_pub_key.verify(bytes, sig) {
+ Ok(_) => Ok(()),
+ Err(e) => Err(anyhow!("signature verification failed: {:?}", e)),
+ }
+}
+
+pub fn sign_bytes_p384(priv_key: &[u8], bytes: &[u8]) -> Result<Vec<u8>> {
+ let key_pair = EcdsaKeyPair::from_bytes(priv_key, &ECDSA_P384_SHA384_ASN1_SIGNING)?;
+ let sig = key_pair.sign(bytes)?;
+ Ok(sig.to_vec())
+}
+
+pub fn verify_signature_p384(pub_key: &[u8], bytes: &[u8], sig: &[u8]) -> Result<()> {
+ let peer_pub_key = signature::UnparsedPublicKey::new(&ECDSA_P384_SHA384_ASN1, pub_key);
+ match peer_pub_key.verify(bytes, sig) {
+ Ok(_) => Ok(()),
+ Err(e) => Err(anyhow!("signature verification failed: {:?}", e)),
+ }
+}
diff --git a/vm/wallet-gateway/share/crypto/src/lib.rs b/vm/wallet-gateway/share/crypto/src/lib.rs
new file mode 100644
index 00000000..a2d2d0cf
--- /dev/null
+++ b/vm/wallet-gateway/share/crypto/src/lib.rs
@@ -0,0 +1,21 @@
+// 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.
+
+mod aead;
+pub use aead::*;
+mod ecdsa;
+pub use ecdsa::*;
diff --git a/vm/wallet-gateway/share/proto/Cargo.toml b/vm/wallet-gateway/share/proto/Cargo.toml
new file mode 100644
index 00000000..bff563b8
--- /dev/null
+++ b/vm/wallet-gateway/share/proto/Cargo.toml
@@ -0,0 +1,35 @@
+# 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.
+
+[package]
+name = "proto"
+version = "0.2.0"
+authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
+license = "Apache-2.0"
+repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
+description = "Data structures and functions shared by host and TA."
+edition = "2018"
+
+[dependencies]
+types = { path = "../types" }
+
+serde = { version = "1.0", features = ["derive"] }
+anyhow = "1.0.50"
+bincode = "1.3.3"
+
+[build_dependencies]
+uuid = { version = "=1.3.0" }
\ No newline at end of file
diff --git a/vm/wallet-gateway/share/proto/src/device.rs b/vm/wallet-gateway/share/proto/src/device.rs
new file mode 100644
index 00000000..b04c6573
--- /dev/null
+++ b/vm/wallet-gateway/share/proto/src/device.rs
@@ -0,0 +1,107 @@
+// 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 std::collections::HashSet;
+
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+use types::share::{
+ CkEncryptedPayload, CkPublicKey, CkSignature, DeviceID, TeeOnlineStatus, WalletID,
+};
+
+// GetTeeStatus
+#[derive(Serialize, Deserialize, Debug)]
+pub struct GetTeeStatusInput {}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct GetTeeStatusOutput {
+ pub device_id: DeviceID,
+ pub tee_status: TeeOnlineStatus,
+}
+
+// Backup commands (local):
+// - InitBoard
+// - BackupWallet
+// - RestoreWallet
+
+// InitBoard
+#[derive(Serialize, Deserialize, Debug)]
+pub struct InitBoardInput {}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct InitBoardOutput {
+ pub device_id: DeviceID,
+ pub signing_pubkey: CkPublicKey,
+ pub backup_pubkey: CkPublicKey,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct BackupWalletInput {
+ pub backup_to_device_id: DeviceID,
+ pub backup_to_device_pubkey: CkPublicKey,
+ pub target_wallets: HashSet<WalletID>,
+ pub signature: Option<CkSignature>, // signature of requests
+}
+
+impl BackupWalletInput {
+ pub fn new_unsigned(
+ backup_to_device_id: DeviceID,
+ backup_to_device_pubkey: CkPublicKey,
+ target_wallets: HashSet<WalletID>,
+ ) -> Self {
+ Self {
+ backup_to_device_id,
+ backup_to_device_pubkey,
+ target_wallets,
+ signature: None,
+ }
+ }
+
+ pub fn serialize(&self) -> Result<Vec<u8>> {
+ let mut bytes = Vec::new();
+ bytes.extend(bincode::serialize(&self.backup_to_device_id)?);
+ bytes.extend(bincode::serialize(&self.backup_to_device_pubkey)?);
+ let mut target_wallets: Vec<WalletID> = self.target_wallets.iter().cloned().collect();
+ target_wallets.sort();
+ bytes.extend(bincode::serialize(&target_wallets)?);
+ Ok(bytes)
+ }
+
+ pub fn set_signature(&mut self, signature: CkSignature) {
+ self.signature = Some(signature);
+ }
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct BackupWalletOutput {
+ pub backup_to_device: DeviceID,
+ pub wallet_ids: HashSet<WalletID>, // backup wallets
+ pub encrypted: CkEncryptedPayload,
+}
+
+// RestoreWallet
+#[derive(Serialize, Deserialize, Debug)]
+pub struct RestoreWalletInput {
+ pub backup_to_device: DeviceID,
+ pub wallet_ids: HashSet<WalletID>, // backup wallets
+ pub encrypted: CkEncryptedPayload,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct RestoreWalletOutput {
+ pub wallet_ids: HashSet<WalletID>, // successfully restored wallets
+}
diff --git a/vm/wallet-gateway/share/proto/src/lib.rs b/vm/wallet-gateway/share/proto/src/lib.rs
new file mode 100644
index 00000000..f608c694
--- /dev/null
+++ b/vm/wallet-gateway/share/proto/src/lib.rs
@@ -0,0 +1,88 @@
+// 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.
+
+mod device;
+mod transaction;
+mod wallet;
+
+pub use device::*;
+pub use transaction::*;
+pub use wallet::*;
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct TlsCommandRequest {
+ pub command: TaCommand,
+ pub request: Vec<u8>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
+pub enum TaCommand {
+ // tls cmds
+ NewTlsSession,
+ CloseTlsSession,
+ DoTlsRead,
+ DoTlsWrite,
+ StartServer,
+ // wallet cmds
+ SyncWithTee,
+ AddAccount,
+ SyncFromTeeWallet, // deprecated
+ // transaction cmds
+ CreateTransaction,
+ ApproveTransaction,
+ RecallTransaction,
+ SignTransaction,
+ ListPendingTransaction,
+ // backup cmds
+ InitBoard,
+ BackupWallet,
+ RestoreWallet,
+ ClearWalletStorage,
+ // tee status cmds
+ GetTeeStatus,
+ // unknown command
+ Unknown,
+}
+
+impl From<u32> for TaCommand {
+ #[inline]
+ fn from(value: u32) -> TaCommand {
+ match value {
+ 0 => TaCommand::NewTlsSession,
+ 1 => TaCommand::CloseTlsSession,
+ 2 => TaCommand::DoTlsRead,
+ 3 => TaCommand::DoTlsWrite,
+ 4 => TaCommand::StartServer,
+ 5 => TaCommand::SyncWithTee,
+ 6 => TaCommand::AddAccount,
+ 7 => TaCommand::SyncFromTeeWallet,
+ 8 => TaCommand::CreateTransaction,
+ 9 => TaCommand::ApproveTransaction,
+ 10 => TaCommand::RecallTransaction,
+ 11 => TaCommand::SignTransaction,
+ 12 => TaCommand::ListPendingTransaction,
+ 13 => TaCommand::InitBoard,
+ 14 => TaCommand::BackupWallet,
+ 15 => TaCommand::RestoreWallet,
+ 16 => TaCommand::ClearWalletStorage,
+ 17 => TaCommand::GetTeeStatus,
+ _ => TaCommand::Unknown,
+ }
+ }
+}
diff --git a/vm/wallet-gateway/share/proto/src/transaction.rs b/vm/wallet-gateway/share/proto/src/transaction.rs
new file mode 100644
index 00000000..6bc90eb5
--- /dev/null
+++ b/vm/wallet-gateway/share/proto/src/transaction.rs
@@ -0,0 +1,94 @@
+// 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 serde::{Deserialize, Serialize};
+use types::share::{
+ ApprovalOperation, CkHash, CkSignature, MultiChainTransaction, TaApprovalChain,
+ TaOperatorsBasic, TransactionID, WalletID,
+};
+
+// Transaction cmds (tls):
+// - CreateTransaction
+// - ApproveTransaction
+// - DeleteTransaction
+// - SignTransaction
+// - ListPendingTransaction
+
+// CreateTransaction
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct CreateTransactionInput {
+ pub tx: MultiChainTransaction,
+}
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct CreateTransactionOutput {
+ pub tx_id: TransactionID,
+ pub latest_approval_chain: TaApprovalChain,
+}
+
+// ApproveTransaction
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct ApproveTransactionInput {
+ pub tx_id: TransactionID,
+ pub current_approval_chain: TaApprovalChain,
+ pub operation: ApprovalOperation,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub struct ApproveTransactionOutput {
+ pub latest_approval_chain: TaApprovalChain,
+}
+
... 14550 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org