Skip to content

Commit a8ff4e8

Browse files
authored
Clean up to_hex() usage (#3785)
* init * update * update oa type check * remove unneeded * fix tests * fix tests
1 parent d2fb677 commit a8ff4e8

23 files changed

+143
-282
lines changed

tee-worker/omni-executor/executor-primitives/src/auth.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::{
33
BitcoinSignature, EthereumSignature, HeimaMultiSignature, SolanaSignature,
44
SubstrateSignature,
55
},
6-
utils::hex::{decode_hex, ToHexPrefixed},
6+
utils::hex::{decode_hex, hex_encode},
77
OmniAccountAuthType,
88
};
99
use base58::{FromBase58, ToBase58};
@@ -123,9 +123,9 @@ impl TryFrom<Identity> for UserId {
123123
Identity::Github(handle) => {
124124
Ok(UserId::Github(String::from_utf8(handle.inner.to_vec()).map_err(|_| ())?))
125125
},
126-
Identity::Substrate(address) => Ok(UserId::Substrate(address.to_hex())),
127-
Identity::Evm(address) => Ok(UserId::Evm(address.to_hex())),
128-
Identity::Bitcoin(address) => Ok(UserId::Bitcoin(address.to_hex())),
126+
Identity::Substrate(address) => Ok(UserId::Substrate(hex_encode(&address.encode()))),
127+
Identity::Evm(address) => Ok(UserId::Evm(hex_encode(&address.encode()))),
128+
Identity::Bitcoin(address) => Ok(UserId::Bitcoin(hex_encode(&address.encode()))),
129129
Identity::Solana(address) => Ok(UserId::Solana(address.as_ref().to_base58())),
130130
Identity::Email(handle) => {
131131
Ok(UserId::Email(String::from_utf8(handle.inner.to_vec()).map_err(|_| ())?))

tee-worker/omni-executor/executor-primitives/src/utils/hex.rs

Lines changed: 8 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -15,51 +15,8 @@
1515
// along with Litentry. If not, see <https://www.gnu.org/licenses/>.
1616

1717
use hex::FromHexError;
18-
use parity_scale_codec::{Decode, Encode, Error as CodecError};
1918
use std::{string::String, vec::Vec};
2019

21-
#[derive(Debug)]
22-
pub enum Error {
23-
Hex(FromHexError),
24-
Codec(CodecError),
25-
}
26-
27-
impl std::fmt::Display for Error {
28-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29-
match self {
30-
Error::Hex(e) => write!(f, "Hex error: {}", e),
31-
Error::Codec(e) => write!(f, "Codec error: {}", e),
32-
}
33-
}
34-
}
35-
36-
/// Trait to encode a given value to a hex string, prefixed with "0x".
37-
pub trait ToHexPrefixed {
38-
fn to_hex(&self) -> String;
39-
}
40-
41-
impl<T: Encode> ToHexPrefixed for T {
42-
fn to_hex(&self) -> String {
43-
hex_encode(&self.encode())
44-
}
45-
}
46-
47-
/// Trait to decode a hex string to a given output.
48-
pub trait FromHexPrefixed {
49-
type Output;
50-
51-
fn from_hex(msg: &str) -> Result<Self::Output, Error>;
52-
}
53-
54-
impl<T: Decode> FromHexPrefixed for T {
55-
type Output = T;
56-
57-
fn from_hex(msg: &str) -> Result<Self::Output, Error> {
58-
let byte_array = decode_hex(msg).map_err(Error::Hex)?;
59-
Decode::decode(&mut byte_array.as_slice()).map_err(Error::Codec)
60-
}
61-
}
62-
6320
/// Hex encodes given data and preappends a "0x".
6421
pub fn hex_encode(data: &[u8]) -> String {
6522
let mut hex_str = hex::encode(data);
@@ -82,38 +39,24 @@ pub fn decode_hex<T: AsRef<[u8]>>(message: T) -> Result<Vec<u8>, FromHexError> {
8239
#[cfg(test)]
8340
mod tests {
8441
use super::*;
85-
use parity_scale_codec::{Decode, Encode};
86-
use std::string::ToString;
8742

8843
#[test]
8944
fn hex_encode_decode_works() {
90-
let data = "Hello World!".to_string();
45+
let data = "Hello World!".as_bytes();
9146

92-
let hex_encoded_data = hex_encode(&data.encode());
93-
let decoded_data =
94-
String::decode(&mut decode_hex(hex_encoded_data).unwrap().as_slice()).unwrap();
47+
let hex_encoded_data = hex_encode(data);
48+
let decoded_data = decode_hex(&hex_encoded_data).unwrap();
9549

96-
assert_eq!(data, decoded_data);
50+
assert_eq!(data, decoded_data.as_slice());
9751
}
9852

9953
#[test]
10054
fn hex_encode_decode_works_empty_input() {
101-
let data = String::new();
102-
103-
let hex_encoded_data = hex_encode(&data.encode());
104-
let decoded_data =
105-
String::decode(&mut decode_hex(hex_encoded_data).unwrap().as_slice()).unwrap();
106-
107-
assert_eq!(data, decoded_data);
108-
}
109-
110-
#[test]
111-
fn to_hex_from_hex_works() {
112-
let data = "Hello World!".to_string();
55+
let data = "".as_bytes();
11356

114-
let hex_encoded_data = data.to_hex();
115-
let decoded_data = String::from_hex(&hex_encoded_data).unwrap();
57+
let hex_encoded_data = hex_encode(data);
58+
let decoded_data = decode_hex(&hex_encoded_data).unwrap();
11659

117-
assert_eq!(data, decoded_data);
60+
assert_eq!(data, decoded_data.as_slice());
11861
}
11962
}

tee-worker/omni-executor/heima/authentication/src/auth_token.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,8 @@ mod tests {
111111

112112
use super::*;
113113
use chrono::{Days, Utc};
114-
use executor_primitives::{utils::hex::ToHexPrefixed, Identity, Web2IdentityType};
114+
use executor_primitives::{utils::hex::hex_encode, Identity, Web2IdentityType};
115+
use parity_scale_codec::Encode;
115116
use rsa::{pkcs1::EncodeRsaPrivateKey, RsaPrivateKey};
116117

117118
#[derive(PartialEq, Debug, Serialize, Deserialize)]
@@ -142,7 +143,7 @@ mod tests {
142143
let omni_account = uid.to_omni_account(CLIENT_ID_HEIMA);
143144

144145
let claims = AuthTokenClaims::new(
145-
omni_account.to_hex(),
146+
hex_encode(omni_account.as_ref()),
146147
AUTH_TOKEN_ID_TYPE.to_string(),
147148
CLIENT_ID_HEIMA.to_string(),
148149
AuthOptions { expires_at },
@@ -166,7 +167,7 @@ mod tests {
166167
let omni_account = uid.to_omni_account(CLIENT_ID_HEIMA);
167168

168169
let claims = AuthTokenClaims::new(
169-
omni_account.to_hex(),
170+
hex_encode(omni_account.as_ref()),
170171
AUTH_TOKEN_ID_TYPE.to_string(),
171172
CLIENT_ID_HEIMA.to_string(),
172173
AuthOptions { expires_at: 100 },
@@ -242,7 +243,7 @@ mod tests {
242243
let omni_account = email_identity.to_omni_account(CLIENT_ID_HEIMA);
243244

244245
let claims = AuthTokenClaims::new(
245-
omni_account.to_hex(),
246+
hex_encode(omni_account.as_ref()),
246247
AUTH_TOKEN_ACCESS_TYPE.to_string(),
247248
CLIENT_ID_HEIMA.to_string(),
248249
AuthOptions { expires_at },

tee-worker/omni-executor/rpc-server/src/auth_utils.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use executor_core::types::SerializablePackedUserOperation;
66
use executor_crypto::ecdsa;
77
use executor_primitives::{
88
signature::{EthereumSignature, HeimaMultiSignature},
9-
utils::hex::{decode_hex, FromHexPrefixed},
9+
utils::hex::decode_hex,
1010
ChainId,
1111
};
1212
use executor_storage::{Storage, WildmetaTimestampStorage};
@@ -34,8 +34,12 @@ pub fn verify_wildmeta_signature(
3434
})?;
3535
let heima_sig = HeimaMultiSignature::Ethereum(ethereum_signature);
3636

37-
let agent_address = Address20::from_hex(agent_address).map_err(|e| {
38-
error!("Failed to parse agent address: {:?}", e);
37+
let agent_address_bytes = decode_hex(agent_address).map_err(|e| {
38+
error!("Failed to decode signature: {:?}", e);
39+
ErrorObject::from(ErrorCode::ParseError)
40+
})?;
41+
let agent_address = Address20::try_from(agent_address_bytes.as_slice()).map_err(|_| {
42+
error!("Failed to parse agent address");
3943
ErrorObject::from(ErrorCode::ParseError)
4044
})?;
4145

tee-worker/omni-executor/rpc-server/src/error_code.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ pub const INVALID_EMAIL_FORMAT_CODE: i32 = -32107;
5757

5858
// Account/Identity Error Codes (-32120 to -32139)
5959
pub const ACCOUNT_PARSE_ERROR_CODE: i32 = -32121;
60-
pub const INVALID_ACCOUNT_LENGTH_CODE: i32 = -32124;
6160

6261
// External Service Error Codes (-32160 to -32179)
6362
pub const SIGNER_SERVICE_ERROR_CODE: i32 = -32160;

tee-worker/omni-executor/rpc-server/src/methods/omni/add_wallet.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,11 @@ use crate::{
44
error_code::*,
55
methods::omni::{common::check_auth, PumpxRpcError},
66
server::RpcContext,
7+
utils::omni::to_omni_account,
78
};
89
use executor_core::intent_executor::IntentExecutor;
9-
use executor_primitives::{utils::hex::FromHexPrefixed, AccountId};
1010
use executor_storage::{HeimaJwtStorage, Storage};
1111
use heima_authentication::constants::AUTH_TOKEN_ACCESS_TYPE;
12-
use heima_primitives::Address32;
1312
use jsonrpsee::RpcModule;
1413
use pumpx::methods::add_wallet::AddWalletResponse;
1514
use serde::Serialize;
@@ -25,7 +24,7 @@ pub fn register_add_wallet<CrossChainIntentExecutor: IntentExecutor + Send + Syn
2524
) {
2625
module
2726
.register_async_method("omni_addWallet", |_params, ctx, ext| async move {
28-
let omni_account = check_auth(&ext).map_err(|e| {
27+
let oa_str = check_auth(&ext).map_err(|e| {
2928
error!("Authentication check failed: {:?}", e);
3029
PumpxRpcError::from(
3130
DetailedError::new(
@@ -38,18 +37,16 @@ pub fn register_add_wallet<CrossChainIntentExecutor: IntentExecutor + Send + Syn
3837

3938
debug!("Received omni_addWallet");
4039

41-
let Ok(address) = Address32::from_hex(&omni_account) else {
42-
error!("Failed to parse from omni account token");
43-
return Err(PumpxRpcError::from(
44-
DetailedError::new(INTERNAL_ERROR_CODE, "Internal error")
45-
.with_reason("Failed to parse omni account from authentication token"),
46-
));
47-
};
48-
let omni_account_id = AccountId::from(address);
40+
let omni_account = to_omni_account(&oa_str).map_err(|_| {
41+
PumpxRpcError::from(DetailedError::new(
42+
PARSE_ERROR_CODE,
43+
"Failed to parse omni account",
44+
))
45+
})?;
4946

5047
// Inlined handler logic from handle_pumpx_add_wallet
5148
let storage = HeimaJwtStorage::new(ctx.storage_db.clone());
52-
let Ok(Some(access_token)) = storage.get(&(omni_account_id, AUTH_TOKEN_ACCESS_TYPE))
49+
let Ok(Some(access_token)) = storage.get(&(omni_account, AUTH_TOKEN_ACCESS_TYPE))
5350
else {
5451
error!("Failed to get pumpx_{}_jwt_token", AUTH_TOKEN_ACCESS_TYPE);
5552
return Err(PumpxRpcError::from(

tee-worker/omni-executor/rpc-server/src/methods/omni/estimate_user_op_gas.rs

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,17 @@
1616

1717
use super::common::PumpxRpcError;
1818
use crate::detailed_error::DetailedError;
19+
use crate::error_code::PARSE_ERROR_CODE;
1920
use crate::server::RpcContext;
2021
use crate::utils::gas_estimation::estimate_user_op_gas;
22+
use crate::utils::omni::to_omni_account;
2123
use crate::utils::user_op::convert_to_packed_user_op;
22-
use crate::validation_helpers::{
23-
validate_ethereum_address, validate_omni_account_hex, validate_omni_account_length,
24-
};
24+
use crate::validation_helpers::validate_ethereum_address;
2525
use alloy::primitives::utils::format_units;
2626
use executor_core::intent_executor::IntentExecutor;
2727
use executor_core::types::SerializablePackedUserOperation;
28-
use executor_primitives::{AccountId, ChainId};
28+
use executor_primitives::ChainId;
2929
use jsonrpsee::RpcModule;
30-
use parity_scale_codec::Decode;
3130
use serde::{Deserialize, Serialize};
3231
use tracing::{debug, error, info};
3332

@@ -108,14 +107,10 @@ pub fn register_estimate_user_op_gas<
108107

109108
debug!("Received omni_estimateUserOpGas, params: {:?}", params);
110109

111-
let account_bytes = validate_omni_account_hex(&params.omni_account, "omni_account")
112-
.map_err(PumpxRpcError::from)?;
113-
validate_omni_account_length(&account_bytes, "omni_account")
114-
.map_err(PumpxRpcError::from)?;
115-
let account_id = AccountId::decode(&mut &account_bytes[..]).map_err(|e| {
116-
PumpxRpcError::from(DetailedError::account_parse_error(
117-
&params.omni_account,
118-
&e.to_string(),
110+
let omni_account = to_omni_account(&params.omni_account).map_err(|_| {
111+
PumpxRpcError::from(DetailedError::new(
112+
PARSE_ERROR_CODE,
113+
"Failed to parse omni account",
119114
))
120115
})?;
121116

@@ -125,7 +120,7 @@ pub fn register_estimate_user_op_gas<
125120
// Inlined handler logic from handle_estimate_user_op_gas
126121
info!(
127122
"Processing EstimateUserOpGas for account {:?}, wallet_index: {}, chain_id: {}",
128-
account_id, params.wallet_index, params.chain_id
123+
omni_account, params.wallet_index, params.chain_id
129124
);
130125

131126
// Get EntryPoint client for this chain

tee-worker/omni-executor/rpc-server/src/methods/omni/export_wallet.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,17 @@ use crate::{
33
error_code::{INTERNAL_ERROR_CODE, PARSE_ERROR_CODE, *},
44
methods::omni::{common::check_auth, PumpxRpcError},
55
server::RpcContext,
6+
utils::omni::to_omni_account,
67
Deserialize,
78
};
89
use ::pumpx::signer_client::PumpxChainId as _;
910
use ethers::types::Bytes;
1011
use executor_core::intent_executor::IntentExecutor;
1112
use executor_core::native_task::*;
1213
use executor_crypto::aes256::{aes_decrypt, aes_encrypt_default, Aes256Key, SerdeAesOutput};
13-
use executor_primitives::{utils::hex::FromHexPrefixed, AccountId, PumpxAccountProfile};
14+
use executor_primitives::PumpxAccountProfile;
1415
use executor_storage::{HeimaJwtStorage, PumpxProfileStorage, Storage};
1516
use heima_authentication::constants::AUTH_TOKEN_ACCESS_TYPE;
16-
use heima_primitives::Address32;
1717
use jsonrpsee::RpcModule;
1818
use rsa::Oaep;
1919
use sha2::Sha256;
@@ -34,7 +34,7 @@ pub fn register_export_wallet<CrossChainIntentExecutor: IntentExecutor + Send +
3434
) {
3535
module
3636
.register_async_method("omni_exportWallet", |params, ctx, ext| async move {
37-
let omni_account = check_auth(&ext).map_err(|e| {
37+
let oa_str = check_auth(&ext).map_err(|e| {
3838
error!("Authentication check failed: {:?}", e);
3939
PumpxRpcError::from(DetailedError::new(
4040
AUTH_VERIFICATION_FAILED_CODE,
@@ -52,14 +52,12 @@ pub fn register_export_wallet<CrossChainIntentExecutor: IntentExecutor + Send +
5252

5353
debug!("Received omni_exportWallet, chain_id: {}, wallet_index: {}, expected_wallet_address: {}", params.chain_id, params.wallet_index, params.wallet_address);
5454

55-
let Ok(address) = Address32::from_hex(&omni_account) else {
56-
error!("Failed to parse from omni account token");
57-
return Err(PumpxRpcError::from(DetailedError::new(
58-
INTERNAL_ERROR_CODE,
59-
"Internal error"
60-
).with_reason("Failed to parse omni account from authentication token")));
61-
};
62-
let omni_account_id = AccountId::from(address);
55+
let omni_account = to_omni_account(&oa_str).map_err(|_| {
56+
PumpxRpcError::from(DetailedError::new(
57+
PARSE_ERROR_CODE,
58+
"Failed to parse omni account",
59+
))
60+
})?;
6361

6462
let aes_key = ctx
6563
.shielding_key
@@ -82,7 +80,7 @@ pub fn register_export_wallet<CrossChainIntentExecutor: IntentExecutor + Send +
8280

8381
// Inlined handler logic from handle_pumpx_export_wallet
8482
let storage = HeimaJwtStorage::new(ctx.storage_db.clone());
85-
let Ok(Some(access_token)) = storage.get(&(omni_account_id.clone(), AUTH_TOKEN_ACCESS_TYPE))
83+
let Ok(Some(access_token)) = storage.get(&(omni_account.clone(), AUTH_TOKEN_ACCESS_TYPE))
8684
else {
8785
error!("Failed to get pumpx_{}_jwt_token", AUTH_TOKEN_ACCESS_TYPE);
8886
return Err(PumpxRpcError::from(
@@ -133,7 +131,7 @@ pub fn register_export_wallet<CrossChainIntentExecutor: IntentExecutor + Send +
133131
.export_wallet(
134132
chain,
135133
params.wallet_index,
136-
omni_account_id.clone().into(),
134+
omni_account.clone().into(),
137135
ctx.aes256_key.to_vec(),
138136
params.wallet_address,
139137
)
@@ -157,14 +155,14 @@ pub fn register_export_wallet<CrossChainIntentExecutor: IntentExecutor + Send +
157155
};
158156

159157
let omni_account_profile_storage = PumpxProfileStorage::new(ctx.storage_db.clone());
160-
if let Ok(maybe_profile) = omni_account_profile_storage.get(&omni_account_id) {
158+
if let Ok(maybe_profile) = omni_account_profile_storage.get(&omni_account) {
161159
let profile = maybe_profile
162160
.map(|mut p| {
163161
p.wallet_exported = true;
164162
p
165163
})
166164
.unwrap_or_else(|| PumpxAccountProfile { wallet_exported: true });
167-
if let Err(e) = omni_account_profile_storage.insert(&omni_account_id, profile) {
165+
if let Err(e) = omni_account_profile_storage.insert(&omni_account, profile) {
168166
error!("Failed to update pumpx account profile: {:?}", e);
169167
return Err(PumpxRpcError::from(
170168
DetailedError::new(INTERNAL_ERROR_CODE, "Internal error")

tee-worker/omni-executor/rpc-server/src/methods/omni/get_omni_account.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::detailed_error::DetailedError;
1818
use crate::error_code::PARSE_ERROR_CODE;
1919
use crate::{methods::omni::common::PumpxRpcError, server::RpcContext};
2020
use executor_core::intent_executor::IntentExecutor;
21-
use executor_primitives::{utils::hex::ToHexPrefixed, Web2IdentityType};
21+
use executor_primitives::{utils::hex::hex_encode, Web2IdentityType};
2222
use heima_primitives::Identity;
2323
use jsonrpsee::{types::ErrorObject, RpcModule};
2424
use serde::{Deserialize, Serialize};
@@ -49,7 +49,7 @@ pub fn register_get_omni_account<
4949
let account =
5050
Identity::from_web2_account(params.user_email.as_str(), Web2IdentityType::Email)
5151
.to_omni_account(&params.client_id);
52-
Ok::<String, ErrorObject>(account.to_hex())
52+
Ok::<String, ErrorObject>(hex_encode(account.as_ref()))
5353
})
5454
.expect("Failed to register omni_getOmniAccount method");
5555
}

0 commit comments

Comments
 (0)