diff --git a/common/primitives/core/src/assertion/network.rs b/common/primitives/core/src/assertion/network.rs index 8c3d98d9b3..9737e1792f 100644 --- a/common/primitives/core/src/assertion/network.rs +++ b/common/primitives/core/src/assertion/network.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Litentry. If not, see <https://www.gnu.org/licenses/>. -use crate::{CoreHash as Hash, String, Vec}; +use crate::{String, Vec}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{traits::ConstU32, BoundedVec}; diff --git a/common/primitives/core/src/identity.rs b/common/primitives/core/src/identity.rs index ffc9940cde..81384cc3aa 100644 --- a/common/primitives/core/src/identity.rs +++ b/common/primitives/core/src/identity.rs @@ -35,7 +35,7 @@ use sp_core::{ use sp_io::hashing::blake2_256; use sp_runtime::{ traits::{BlakeTwo256, ConstU32}, - BoundedVec, RuntimeDebug, + BoundedVec, }; use strum_macros::EnumIter; @@ -359,14 +359,20 @@ impl Identity { } } - /// Currently we only support mapping from Address32/Address20 to AccountId, not opposite. - pub fn to_account_id(&self) -> Option<AccountId> { + /// map an `Identity` to a native parachain account that: + /// - has a private key for substrate and evm accounts, or any connect that can connect to parachain directly + /// - appears as origin when submitting extrinsics + /// + /// this account is also used within the worker as e.g. sidechain accounts + pub fn to_native_account(&self) -> Option<AccountId> { match self { - Identity::Substrate(address) | Identity::Solana(address) => Some(address.into()), + Identity::Substrate(address) => Some(address.into()), Identity::Evm(address) => Some(HashedAddressMapping::into_account_id( H160::from_slice(address.as_ref()), )), - Identity::Bitcoin(address) => Some(blake2_256(address.as_ref()).into()), + // we use `to_omni_account` impl for non substrate/evm web3 accounts, as they + // can't connect to the parachain directly + Identity::Bitcoin(_) | Identity::Solana(_) => Some(self.to_omni_account()), Identity::Twitter(_) | Identity::Discord(_) | Identity::Github(_) @@ -374,6 +380,14 @@ impl Identity { } } + /// derive an `OmniAccount` from `Identity` by hashing the encoded identity, + /// it should always be successful + /// + /// an `OmniAccount` has no private key and can only be controlled by its MemberAccount + pub fn to_omni_account(&self) -> AccountId { + self.hash().to_fixed_bytes().into() + } + pub fn from_did(s: &str) -> Result<Self, &'static str> { let did_prefix = String::from("did:litentry:"); if s.starts_with(&did_prefix) { @@ -528,24 +542,6 @@ impl From<[u8; 33]> for Identity { } } -#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] -pub enum MemberIdentity { - Public(Identity), - Private(Vec<u8>), -} - -impl MemberIdentity { - pub fn is_public(&self) -> bool { - matches!(self, Self::Public(..)) - } -} - -impl From<Identity> for MemberIdentity { - fn from(identity: Identity) -> Self { - Self::Public(identity) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/common/primitives/core/src/lib.rs b/common/primitives/core/src/lib.rs index 1ef747b5f0..647280f5c2 100644 --- a/common/primitives/core/src/lib.rs +++ b/common/primitives/core/src/lib.rs @@ -32,10 +32,10 @@ pub use assertion::Assertion; pub mod identity; pub use identity::*; -extern crate core; +mod omni_account; +pub use omni_account::*; + use alloc::{format, str, str::FromStr, string::String, vec, vec::Vec}; -use core::hash::Hash as CoreHash; -use sp_core::H256; use sp_runtime::{traits::ConstU32, BoundedVec}; pub use constants::*; @@ -47,7 +47,7 @@ pub type ParameterString = BoundedVec<u8, ConstU32<64>>; /// Common types of parachains. mod types { - use super::H256; + use sp_core::H256; use sp_runtime::{ traits::{IdentifyAccount, Verify}, MultiSignature, diff --git a/common/primitives/core/src/omni_account.rs b/common/primitives/core/src/omni_account.rs new file mode 100644 index 0000000000..62385f802f --- /dev/null +++ b/common/primitives/core/src/omni_account.rs @@ -0,0 +1,78 @@ +// Copyright 2020-2024 Trust Computing GmbH. +// This file is part of Litentry. +// +// Litentry is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Litentry is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Litentry. If not, see <https://www.gnu.org/licenses/>. + +use crate::{AccountId, Hash, Identity, Vec}; +use parity_scale_codec::{Decode, Encode}; +use scale_info::TypeInfo; +use sp_io::hashing::blake2_256; +use sp_runtime::{BoundedVec, RuntimeDebug}; + +#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] +pub enum MemberAccount { + Public(Identity), + Private(Vec<u8>, Hash), +} + +impl MemberAccount { + pub fn is_public(&self) -> bool { + matches!(self, Self::Public(..)) + } + + pub fn hash(&self) -> Hash { + match self { + Self::Public(id) => id.hash(), + Self::Private(_, h) => *h, + } + } +} + +impl From<Identity> for MemberAccount { + fn from(identity: Identity) -> Self { + Self::Public(identity) + } +} + +pub trait GetAccountStoreHash { + fn hash(&self) -> Hash; +} + +pub trait OmniAccountConverter { + type OmniAccount; + fn convert(identity: &Identity) -> Self::OmniAccount; +} + +pub struct DefaultOmniAccountConverter; + +impl OmniAccountConverter for DefaultOmniAccountConverter { + type OmniAccount = AccountId; + fn convert(identity: &Identity) -> AccountId { + identity.to_omni_account() + } +} + +impl<T> GetAccountStoreHash for BoundedVec<MemberAccount, T> { + fn hash(&self) -> Hash { + let hashes: Vec<Hash> = self.iter().map(|member| member.hash()).collect(); + hashes.using_encoded(blake2_256).into() + } +} + +impl GetAccountStoreHash for Vec<MemberAccount> { + fn hash(&self) -> Hash { + let hashes: Vec<Hash> = self.iter().map(|member| member.hash()).collect(); + hashes.using_encoded(blake2_256).into() + } +} diff --git a/common/primitives/core/src/teebag/types.rs b/common/primitives/core/src/teebag/types.rs index 5920d539ee..bf8b02edf5 100644 --- a/common/primitives/core/src/teebag/types.rs +++ b/common/primitives/core/src/teebag/types.rs @@ -14,11 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Litentry. If not, see <https://www.gnu.org/licenses/>. -use crate::H256; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; -use sp_core::{ed25519::Public as Ed25519Public, RuntimeDebug}; +use sp_core::{ed25519::Public as Ed25519Public, RuntimeDebug, H256}; use sp_std::prelude::*; pub type MrSigner = [u8; 32]; diff --git a/parachain/pallets/omni-account/src/lib.rs b/parachain/pallets/omni-account/src/lib.rs index f2676ec01d..aa61609ee0 100644 --- a/parachain/pallets/omni-account/src/lib.rs +++ b/parachain/pallets/omni-account/src/lib.rs @@ -21,7 +21,7 @@ mod mock; #[cfg(test)] mod tests; -pub use core_primitives::{Identity, MemberIdentity}; +pub use core_primitives::{GetAccountStoreHash, Identity, MemberAccount, OmniAccountConverter}; pub use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; @@ -32,34 +32,12 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use sp_core::H256; -use sp_core_hashing::blake2_256; use sp_runtime::traits::Dispatchable; use sp_std::boxed::Box; use sp_std::vec::Vec; pub type MemberCount = u32; -#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct MemberAccount { - pub id: MemberIdentity, - pub hash: H256, -} - -pub trait AccountIdConverter<T: Config> { - fn convert(identity: &Identity) -> Option<T::AccountId>; -} - -pub trait GetAccountStoreHash { - fn hash(&self) -> H256; -} - -impl<T> GetAccountStoreHash for BoundedVec<MemberAccount, T> { - fn hash(&self) -> H256 { - let hashes: Vec<H256> = self.iter().map(|member| member.hash).collect(); - hashes.using_encoded(blake2_256).into() - } -} - // Customized origin for this pallet, to: // 1. to decouple `TEECallOrigin` and extrinsic that should be sent from `OmniAccount` origin only // 2. allow other pallets to specify ensure_origin using this origin @@ -112,14 +90,14 @@ pub mod pallet { #[pallet::constant] type MaxAccountStoreLength: Get<MemberCount>; - /// AccountId converter - type AccountIdConverter: AccountIdConverter<Self>; - /// The origin that represents the customised OmniAccount type type OmniAccountOrigin: EnsureOrigin< <Self as frame_system::Config>::RuntimeOrigin, Success = Self::AccountId, >; + + /// Convert an `Identity` to OmniAccount type + type OmniAccountConverter: OmniAccountConverter<OmniAccount = Self::AccountId>; } pub type MemberAccounts<T> = BoundedVec<MemberAccount, <T as Config>::MaxAccountStoreLength>; @@ -166,10 +144,7 @@ pub mod pallet { AccountNotFound, InvalidAccount, UnknownAccountStore, - AccountIsPrivate, EmptyAccount, - AccountStoreHashMismatch, - AccountStoreHashMissing, } #[pallet::call] @@ -179,12 +154,12 @@ pub mod pallet { #[pallet::weight((195_000_000, DispatchClass::Normal))] pub fn dispatch_as_omni_account( origin: OriginFor<T>, - account_hash: H256, + member_account_hash: H256, call: Box<<T as Config>::RuntimeCall>, ) -> DispatchResult { let _ = T::TEECallOrigin::ensure_origin(origin)?; - let omni_account = - MemberAccountHash::<T>::get(account_hash).ok_or(Error::<T>::AccountNotFound)?; + let omni_account = MemberAccountHash::<T>::get(member_account_hash) + .ok_or(Error::<T>::AccountNotFound)?; let result = call.dispatch(RawOrigin::OmniAccount(omni_account.clone()).into()); Self::deposit_event(Event::DispatchedAsOmniAccount { who: omni_account, @@ -199,14 +174,16 @@ pub mod pallet { #[pallet::weight((195_000_000, DispatchClass::Normal))] pub fn dispatch_as_signed( origin: OriginFor<T>, - account_hash: H256, + member_account_hash: H256, call: Box<<T as Config>::RuntimeCall>, ) -> DispatchResult { let _ = T::TEECallOrigin::ensure_origin(origin)?; - let omni_account = - MemberAccountHash::<T>::get(account_hash).ok_or(Error::<T>::AccountNotFound)?; - let result = - call.dispatch(frame_system::RawOrigin::Signed(omni_account.clone()).into()); + let omni_account = MemberAccountHash::<T>::get(member_account_hash) + .ok_or(Error::<T>::AccountNotFound)?; + let result: Result< + PostDispatchInfo, + sp_runtime::DispatchErrorWithPostInfo<PostDispatchInfo>, + > = call.dispatch(frame_system::RawOrigin::Signed(omni_account.clone()).into()); Self::deposit_event(Event::DispatchedAsSigned { who: omni_account, result: result.map(|_| ()).map_err(|e| e.error), @@ -218,37 +195,29 @@ pub mod pallet { #[pallet::weight((195_000_000, DispatchClass::Normal))] pub fn add_account( origin: OriginFor<T>, - who: Identity, - member_account: MemberAccount, - maybe_account_store_hash: Option<H256>, + who: Identity, // `Identity` used to derive OmniAccount + member_account: MemberAccount, // account to be added ) -> DispatchResult { // We can't use `T::OmniAccountOrigin` here as the ownership of member account needs to // be firstly validated by the TEE-worker before dispatching the extrinsic let _ = T::TEECallOrigin::ensure_origin(origin)?; ensure!( - !MemberAccountHash::<T>::contains_key(member_account.hash), + !MemberAccountHash::<T>::contains_key(member_account.hash()), Error::<T>::AccountAlreadyAdded ); - let who_account_id = match T::AccountIdConverter::convert(&who) { - Some(account_id) => account_id, - None => return Err(Error::<T>::InvalidAccount.into()), - }; - let hash = member_account.hash; - let mut account_store = Self::get_or_create_account_store( - who.clone(), - who_account_id.clone(), - maybe_account_store_hash, - )?; - account_store + let hash = member_account.hash(); + let mut store = Self::get_or_create_account_store(who.clone())?; + store .try_push(member_account) .map_err(|_| Error::<T>::AccountStoreLenLimitReached)?; - MemberAccountHash::<T>::insert(hash, who_account_id.clone()); - AccountStoreHash::<T>::insert(who_account_id.clone(), account_store.hash()); - AccountStore::<T>::insert(who_account_id.clone(), account_store); + let who_account = T::OmniAccountConverter::convert(&who); + MemberAccountHash::<T>::insert(hash, who_account.clone()); + AccountStoreHash::<T>::insert(who_account.clone(), store.hash()); + AccountStore::<T>::insert(who_account.clone(), store); Self::deposit_event(Event::AccountAdded { - who: who_account_id, + who: who_account, member_account_hash: hash, }); @@ -264,12 +233,14 @@ pub mod pallet { let who = T::OmniAccountOrigin::ensure_origin(origin)?; ensure!(!member_account_hashes.is_empty(), Error::<T>::EmptyAccount); + // TODO: shall we verify if MemberAccountHash's value is actually `who`? + let mut member_accounts = AccountStore::<T>::get(&who).ok_or(Error::<T>::UnknownAccountStore)?; member_accounts.retain(|member| { - if member_account_hashes.contains(&member.hash) { - MemberAccountHash::<T>::remove(member.hash); + if member_account_hashes.contains(&member.hash()) { + MemberAccountHash::<T>::remove(member.hash()); false } else { true @@ -287,80 +258,51 @@ pub mod pallet { Ok(()) } + /// make a member account public in the AccountStore + /// we force `Identity` type to avoid misuse and additional check #[pallet::call_index(4)] #[pallet::weight((195_000_000, DispatchClass::Normal))] - pub fn publicize_account( - origin: OriginFor<T>, - member_account_hash: H256, - public_identity: MemberIdentity, - ) -> DispatchResult { + pub fn publicize_account(origin: OriginFor<T>, member_account: Identity) -> DispatchResult { let who = T::OmniAccountOrigin::ensure_origin(origin)?; - ensure!(public_identity.is_public(), Error::<T>::AccountIsPrivate); + let hash = member_account.hash(); let mut member_accounts = AccountStore::<T>::get(&who).ok_or(Error::<T>::UnknownAccountStore)?; - let member_account = member_accounts + let m = member_accounts .iter_mut() - .find(|member| member.hash == member_account_hash) + .find(|member| member.hash() == hash) .ok_or(Error::<T>::AccountNotFound)?; - member_account.id = public_identity; + *m = member_account.into(); AccountStore::<T>::insert(who.clone(), member_accounts); - Self::deposit_event(Event::AccountMadePublic { who, member_account_hash }); + Self::deposit_event(Event::AccountMadePublic { who, member_account_hash: hash }); Ok(()) } } impl<T: Config> Pallet<T> { - pub fn get_or_create_account_store( - who: Identity, - who_account_id: T::AccountId, - maybe_account_store_hash: Option<H256>, - ) -> Result<MemberAccounts<T>, Error<T>> { - match AccountStore::<T>::get(&who_account_id) { - Some(member_accounts) => { - Self::verify_account_store_hash(&who_account_id, maybe_account_store_hash)?; - Ok(member_accounts) - }, - None => Self::create_account_store(who, who_account_id), + pub fn get_or_create_account_store(who: Identity) -> Result<MemberAccounts<T>, Error<T>> { + match AccountStore::<T>::get(T::OmniAccountConverter::convert(&who)) { + Some(member_accounts) => Ok(member_accounts), + None => Self::create_account_store(who), } } - fn verify_account_store_hash( - who: &T::AccountId, - maybe_account_store_hash: Option<H256>, - ) -> Result<(), Error<T>> { - let current_account_store_hash = - AccountStoreHash::<T>::get(who).ok_or(Error::<T>::AccountStoreHashMissing)?; - match maybe_account_store_hash { - Some(h) => { - ensure!(current_account_store_hash == h, Error::<T>::AccountStoreHashMismatch); - }, - None => return Err(Error::<T>::AccountStoreHashMissing), - } + fn create_account_store(who: Identity) -> Result<MemberAccounts<T>, Error<T>> { + let hash = who.hash(); + let who_account = T::OmniAccountConverter::convert(&who); - Ok(()) - } + ensure!(!MemberAccountHash::<T>::contains_key(hash), Error::<T>::AccountAlreadyAdded); - fn create_account_store( - owner_identity: Identity, - owner_account_id: T::AccountId, - ) -> Result<MemberAccounts<T>, Error<T>> { - let owner_identity_hash = owner_identity.hash(); - if MemberAccountHash::<T>::contains_key(owner_identity_hash) { - return Err(Error::<T>::AccountAlreadyAdded); - } let mut member_accounts: MemberAccounts<T> = BoundedVec::new(); member_accounts - .try_push(MemberAccount { - id: MemberIdentity::from(owner_identity.clone()), - hash: owner_identity_hash, - }) + .try_push(who.into()) .map_err(|_| Error::<T>::AccountStoreLenLimitReached)?; - MemberAccountHash::<T>::insert(owner_identity_hash, owner_account_id.clone()); - AccountStore::<T>::insert(owner_account_id.clone(), member_accounts.clone()); + + MemberAccountHash::<T>::insert(hash, who_account.clone()); + AccountStore::<T>::insert(who_account, member_accounts.clone()); Ok(member_accounts) } diff --git a/parachain/pallets/omni-account/src/mock.rs b/parachain/pallets/omni-account/src/mock.rs index 056d754096..932f77d60e 100644 --- a/parachain/pallets/omni-account/src/mock.rs +++ b/parachain/pallets/omni-account/src/mock.rs @@ -15,7 +15,7 @@ // along with Litentry. If not, see <https://www.gnu.org/licenses/>. use crate::{self as pallet_omni_account, EnsureOmniAccount}; -use core_primitives::Identity; +use core_primitives::DefaultOmniAccountConverter; use frame_support::{ assert_ok, pallet_prelude::EnsureOrigin, @@ -159,22 +159,14 @@ impl pallet_teebag::Config for TestRuntime { type WeightInfo = (); } -pub struct IdentityToAccountIdConverter; - -impl pallet_omni_account::AccountIdConverter<TestRuntime> for IdentityToAccountIdConverter { - fn convert(identity: &Identity) -> Option<AccountId> { - identity.to_account_id() - } -} - impl pallet_omni_account::Config for TestRuntime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type TEECallOrigin = EnsureEnclaveSigner<Self>; type MaxAccountStoreLength = ConstU32<3>; - type AccountIdConverter = IdentityToAccountIdConverter; type OmniAccountOrigin = EnsureOmniAccount<Self::AccountId>; + type OmniAccountConverter = DefaultOmniAccountConverter; } pub fn get_tee_signer() -> SystemAccountId { diff --git a/parachain/pallets/omni-account/src/tests.rs b/parachain/pallets/omni-account/src/tests.rs index 0e3855195a..f2213e0218 100644 --- a/parachain/pallets/omni-account/src/tests.rs +++ b/parachain/pallets/omni-account/src/tests.rs @@ -17,6 +17,7 @@ use crate::{mock::*, AccountStore, MemberAccountHash, *}; use core_primitives::Identity; use frame_support::{assert_noop, assert_ok}; +use sp_core::hashing::blake2_256; use sp_runtime::{traits::BadOrigin, ModuleError}; use sp_std::vec; @@ -26,11 +27,8 @@ fn remove_accounts_call(hashes: Vec<H256>) -> Box<RuntimeCall> { Box::new(call) } -fn publicize_account_call(hash: H256, id: MemberIdentity) -> Box<RuntimeCall> { - let call = RuntimeCall::OmniAccount(crate::Call::publicize_account { - member_account_hash: hash, - public_identity: id, - }); +fn publicize_account_call(id: Identity) -> Box<RuntimeCall> { + let call = RuntimeCall::OmniAccount(crate::Call::publicize_account { member_account: id }); Box::new(call) } @@ -46,29 +44,21 @@ fn add_account_works() { let who = alice(); let who_identity = Identity::from(who.clone()); - let who_identity_hash = who_identity.hash(); + let who_omni_account = who_identity.to_omni_account(); - let bob_member_account = MemberAccount { - id: MemberIdentity::Private(bob().encode()), - hash: Identity::from(bob()).hash(), - }; - let charlie_member_account = MemberAccount { - id: MemberIdentity::Public(Identity::from(charlie())), - hash: Identity::from(charlie()).hash(), - }; + let bob_member_account = + MemberAccount::Private(bob().encode(), Identity::from(bob()).hash()); + let charlie_member_account = MemberAccount::Public(Identity::from(charlie())); let expected_member_accounts: MemberAccounts<TestRuntime> = BoundedVec::truncate_from(vec![ - MemberAccount { - id: MemberIdentity::from(who_identity.clone()), - hash: who_identity_hash, - }, + MemberAccount::Public(who_identity.clone()), bob_member_account.clone(), ]); let expected_account_store_hash = H256::from(blake2_256( &expected_member_accounts .iter() - .map(|member| member.hash) + .map(|member| member.hash()) .collect::<Vec<H256>>() .encode(), )); @@ -77,17 +67,21 @@ fn add_account_works() { RuntimeOrigin::signed(tee_signer.clone()), who_identity.clone(), bob_member_account.clone(), - None )); System::assert_last_event( - Event::AccountAdded { who: who.clone(), member_account_hash: bob_member_account.hash } - .into(), + Event::AccountAdded { + who: who_omni_account.clone(), + member_account_hash: bob_member_account.hash(), + } + .into(), ); - assert!(AccountStore::<TestRuntime>::contains_key(&who)); - assert_eq!(AccountStore::<TestRuntime>::get(&who).unwrap(), expected_member_accounts); assert_eq!( - AccountStoreHash::<TestRuntime>::get(&who).unwrap(), + AccountStore::<TestRuntime>::get(&who_omni_account).unwrap(), + expected_member_accounts + ); + assert_eq!( + AccountStoreHash::<TestRuntime>::get(&who_omni_account).unwrap(), expected_account_store_hash ); @@ -95,77 +89,40 @@ fn add_account_works() { RuntimeOrigin::signed(tee_signer), who_identity.clone(), charlie_member_account.clone(), - Some(expected_account_store_hash), )); System::assert_last_event( Event::AccountAdded { - who: who.clone(), - member_account_hash: charlie_member_account.hash, + who: who_identity.to_omni_account(), + member_account_hash: charlie_member_account.hash(), } .into(), ); let expected_member_accounts: MemberAccounts<TestRuntime> = BoundedVec::truncate_from(vec![ - MemberAccount { - id: MemberIdentity::from(who_identity.clone()), - hash: who_identity_hash, - }, + MemberAccount::Public(who_identity.clone()), bob_member_account.clone(), charlie_member_account.clone(), ]); let expected_account_store_hash = H256::from(blake2_256( &expected_member_accounts .iter() - .map(|member| member.hash) + .map(|member| member.hash()) .collect::<Vec<H256>>() .encode(), )); - assert_eq!(AccountStore::<TestRuntime>::get(&who).unwrap(), expected_member_accounts); assert_eq!( - AccountStoreHash::<TestRuntime>::get(&who).unwrap(), + AccountStore::<TestRuntime>::get(&who_omni_account).unwrap(), + expected_member_accounts + ); + assert_eq!( + AccountStoreHash::<TestRuntime>::get(&who_omni_account).unwrap(), expected_account_store_hash ); - assert!(MemberAccountHash::<TestRuntime>::contains_key(bob_member_account.hash)); - assert!(MemberAccountHash::<TestRuntime>::contains_key(charlie_member_account.hash)); - }); -} - -#[test] -fn add_account_hash_checking_works() { - new_test_ext().execute_with(|| { - let tee_signer = get_tee_signer(); - let who_identity = Identity::from(alice()); - - let bob_member_account = MemberAccount { - id: MemberIdentity::Private(bob().encode()), - hash: Identity::from(bob()).hash(), - }; - let charlie_member_account = MemberAccount { - id: MemberIdentity::Public(Identity::from(charlie())), - hash: Identity::from(charlie()).hash(), - }; - - // AccountStore gets created with the first account - assert_ok!(OmniAccount::add_account( - RuntimeOrigin::signed(tee_signer.clone()), - who_identity.clone(), - bob_member_account, - None - )); - - // to mutate AccountStore with a new account, the current account_store_hash must be provided - assert_noop!( - OmniAccount::add_account( - RuntimeOrigin::signed(tee_signer), - who_identity, - charlie_member_account, - None - ), - Error::<TestRuntime>::AccountStoreHashMissing - ); + assert!(MemberAccountHash::<TestRuntime>::contains_key(bob_member_account.hash())); + assert!(MemberAccountHash::<TestRuntime>::contains_key(charlie_member_account.hash())); }); } @@ -173,13 +130,11 @@ fn add_account_hash_checking_works() { fn add_account_origin_check_works() { new_test_ext().execute_with(|| { let who = Identity::from(alice()); - let member_account = MemberAccount { - id: MemberIdentity::Private(vec![1, 2, 3]), - hash: H256::from(blake2_256(&[1, 2, 3])), - }; + let member_account = + MemberAccount::Private(vec![1, 2, 3], H256::from(blake2_256(&[1, 2, 3]))); assert_noop!( - OmniAccount::add_account(RuntimeOrigin::signed(bob()), who, member_account, None), + OmniAccount::add_account(RuntimeOrigin::signed(bob()), who, member_account), BadOrigin ); }); @@ -192,39 +147,30 @@ fn add_account_already_linked_works() { let who = alice(); let who_identity = Identity::from(who.clone()); - let member_account = MemberAccount { - id: MemberIdentity::Public(Identity::from(bob())), - hash: Identity::from(bob()).hash(), - }; + let member_account = MemberAccount::Public(Identity::from(bob())); assert_ok!(OmniAccount::add_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity.clone(), member_account.clone(), - None )); assert_noop!( OmniAccount::add_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity.clone(), member_account, - None ), Error::<TestRuntime>::AccountAlreadyAdded ); // intent to create a new AccountStore with an account that is already added let who = Identity::from(bob()); - let alice_member_account = MemberAccount { - id: MemberIdentity::Public(Identity::from(alice())), - hash: Identity::from(alice()).hash(), - }; + let alice_member_account = MemberAccount::Public(Identity::from(alice())); assert_noop!( OmniAccount::add_account( RuntimeOrigin::signed(tee_signer), who.clone(), alice_member_account, - None ), Error::<TestRuntime>::AccountAlreadyAdded ); @@ -238,120 +184,32 @@ fn add_account_store_len_limit_reached_works() { let who = alice(); let who_identity = Identity::from(who.clone()); - let who_identity_hash = who_identity.hash(); + let who_omni_account = who_identity.to_omni_account(); - let member_account_2 = MemberAccount { - id: MemberIdentity::Private(vec![1, 2, 3]), - hash: H256::from(blake2_256(&[1, 2, 3])), - }; - let member_account_3 = MemberAccount { - id: MemberIdentity::Private(vec![4, 5, 6]), - hash: H256::from(blake2_256(&[4, 5, 6])), - }; + let member_account_2 = + MemberAccount::Private(vec![1, 2, 3], H256::from(blake2_256(&[1, 2, 3]))); + let member_account_3 = + MemberAccount::Private(vec![4, 5, 6], H256::from(blake2_256(&[4, 5, 6]))); let member_accounts: MemberAccounts<TestRuntime> = BoundedVec::truncate_from(vec![ - MemberAccount { - id: MemberIdentity::from(who_identity.clone()), - hash: who_identity_hash, - }, + MemberAccount::Public(who_identity.clone()), member_account_2.clone(), member_account_3.clone(), ]); - let account_store_hash = H256::from(blake2_256(&member_accounts.encode())); - AccountStore::<TestRuntime>::insert(who.clone(), member_accounts.clone()); - AccountStoreHash::<TestRuntime>::insert(who.clone(), account_store_hash); + AccountStore::<TestRuntime>::insert(who_omni_account, member_accounts); assert_noop!( OmniAccount::add_account( RuntimeOrigin::signed(tee_signer), who_identity, - MemberAccount { - id: MemberIdentity::Private(vec![7, 8, 9]), - hash: H256::from(blake2_256(&[7, 8, 9])), - }, - Some(account_store_hash), + MemberAccount::Private(vec![7, 8, 9], H256::from(blake2_256(&[7, 8, 9]))), ), Error::<TestRuntime>::AccountStoreLenLimitReached ); }); } -#[test] -fn add_account_store_hash_mismatch_works() { - new_test_ext().execute_with(|| { - let tee_signer = get_tee_signer(); - - let who = alice(); - let who_identity = Identity::from(who.clone()); - let who_identity_hash = who_identity.hash(); - - let member_account = MemberAccount { - id: MemberIdentity::Private(vec![1, 2, 3]), - hash: H256::from(blake2_256(&[1, 2, 3])), - }; - - let member_accounts: MemberAccounts<TestRuntime> = BoundedVec::truncate_from(vec![ - MemberAccount { - id: MemberIdentity::from(who_identity.clone()), - hash: who_identity_hash, - }, - member_account.clone(), - ]); - let account_store_hash = H256::from(blake2_256( - &member_accounts.iter().map(|member| member.hash).collect::<Vec<H256>>().encode(), - )); - - assert_ok!(OmniAccount::add_account( - RuntimeOrigin::signed(tee_signer.clone()), - who_identity.clone(), - member_account.clone(), - None - )); - - assert_eq!(AccountStore::<TestRuntime>::get(&who).unwrap(), member_accounts); - assert_eq!(AccountStoreHash::<TestRuntime>::get(&who).unwrap(), account_store_hash); - - // add another account to the store with the correct AccountStoreHash - assert_ok!(OmniAccount::add_account( - RuntimeOrigin::signed(tee_signer.clone()), - who_identity.clone(), - MemberAccount { - id: MemberIdentity::Private(vec![4, 5, 6]), - hash: H256::from(blake2_256(&[4, 5, 6])), - }, - Some(account_store_hash), - )); - - let member_accounts: MemberAccounts<TestRuntime> = BoundedVec::truncate_from(vec![ - MemberAccount { - id: MemberIdentity::from(who_identity.clone()), - hash: who_identity_hash, - }, - member_account.clone(), - MemberAccount { - id: MemberIdentity::Private(vec![4, 5, 6]), - hash: H256::from(blake2_256(&[4, 5, 6])), - }, - ]); - assert_eq!(AccountStore::<TestRuntime>::get(&who).unwrap(), member_accounts); - - // attempt to add an account with an old AccountStoreHash - assert_noop!( - OmniAccount::add_account( - RuntimeOrigin::signed(tee_signer), - who_identity, - MemberAccount { - id: MemberIdentity::Private(vec![7, 8, 9]), - hash: H256::from(blake2_256(&[7, 8, 9])), - }, - Some(account_store_hash), - ), - Error::<TestRuntime>::AccountStoreHashMismatch - ); - }); -} - #[test] fn remove_account_works() { new_test_ext().execute_with(|| { @@ -359,19 +217,17 @@ fn remove_account_works() { let who = alice(); let who_identity = Identity::from(who.clone()); let who_identity_hash = who_identity.hash(); + let who_omni_account = who_identity.to_omni_account(); - let member_account = MemberAccount { - id: MemberIdentity::Private(vec![1, 2, 3]), - hash: H256::from(blake2_256(&[1, 2, 3])), - }; - let identity_hash = member_account.hash; + let member_account = + MemberAccount::Private(vec![1, 2, 3], H256::from(blake2_256(&[1, 2, 3]))); + let identity_hash = member_account.hash(); let hashes = vec![identity_hash]; assert_ok!(OmniAccount::add_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity.clone(), member_account.clone(), - None )); // normal signed origin should give `BadOrigin`, no matter @@ -382,7 +238,10 @@ fn remove_account_works() { ); assert_noop!( - OmniAccount::remove_accounts(RuntimeOrigin::signed(who.clone()), hashes.clone()), + OmniAccount::remove_accounts( + RuntimeOrigin::signed(who_omni_account.clone()), + hashes.clone() + ), sp_runtime::DispatchError::BadOrigin ); @@ -394,21 +253,25 @@ fn remove_account_works() { )); System::assert_has_event( - Event::DispatchedAsOmniAccount { who: who.clone(), result: DispatchResult::Ok(()) } - .into(), + Event::DispatchedAsOmniAccount { + who: who_omni_account.clone(), + result: DispatchResult::Ok(()), + } + .into(), ); System::assert_has_event( - Event::AccountRemoved { who: who.clone(), member_account_hashes: hashes }.into(), + Event::AccountRemoved { who: who_omni_account.clone(), member_account_hashes: hashes } + .into(), ); let expected_member_accounts: MemberAccounts<TestRuntime> = - BoundedVec::truncate_from(vec![MemberAccount { - id: MemberIdentity::Public(who_identity.clone()), - hash: who_identity_hash, - }]); + BoundedVec::truncate_from(vec![MemberAccount::Public(who_identity.clone())]); - assert_eq!(AccountStore::<TestRuntime>::get(&who).unwrap(), expected_member_accounts); + assert_eq!( + AccountStore::<TestRuntime>::get(&who_omni_account).unwrap(), + expected_member_accounts + ); assert!(!MemberAccountHash::<TestRuntime>::contains_key(identity_hash)); let call = remove_accounts_call(vec![who_identity_hash]); @@ -418,7 +281,7 @@ fn remove_account_works() { call )); - assert!(!AccountStore::<TestRuntime>::contains_key(&who)); + assert!(!AccountStore::<TestRuntime>::contains_key(&who_omni_account)); }); } @@ -429,15 +292,12 @@ fn remove_account_empty_account_check_works() { let who = alice(); let who_identity = Identity::from(who.clone()); let who_identity_hash = who_identity.hash(); + let who_omni_account = who_identity.to_omni_account(); assert_ok!(OmniAccount::add_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity, - MemberAccount { - id: MemberIdentity::Private(vec![1, 2, 3]), - hash: H256::from(blake2_256(&[1, 2, 3])), - }, - None + MemberAccount::Private(vec![1, 2, 3], H256::from(blake2_256(&[1, 2, 3]))), )); let call = remove_accounts_call(vec![]); @@ -449,10 +309,10 @@ fn remove_account_empty_account_check_works() { )); System::assert_has_event( Event::DispatchedAsOmniAccount { - who, + who: who_omni_account, result: Err(DispatchError::Module(ModuleError { index: 5, - error: [6, 0, 0, 0], + error: [5, 0, 0, 0], message: Some("EmptyAccount"), })), } @@ -468,30 +328,29 @@ fn publicize_account_works() { let who = alice(); let who_identity = Identity::from(who.clone()); let who_identity_hash = who_identity.hash(); + let who_omni_account = who_identity.to_omni_account(); - let private_identity = MemberIdentity::Private(vec![1, 2, 3]); - let public_identity = MemberIdentity::Public(Identity::from(bob())); - let identity_hash = - H256::from(blake2_256(&Identity::from(bob()).to_did().unwrap().encode())); + let private_account = MemberAccount::Private(vec![1, 2, 3], Identity::from(bob()).hash()); + let public_account = MemberAccount::Public(Identity::from(bob())); + let public_account_hash = public_account.hash(); assert_ok!(OmniAccount::add_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity.clone(), - MemberAccount { id: private_identity.clone(), hash: identity_hash }, - None + private_account.clone() )); let expected_member_accounts: MemberAccounts<TestRuntime> = BoundedVec::truncate_from(vec![ - MemberAccount { - id: MemberIdentity::Public(who_identity.clone()), - hash: who_identity.hash(), - }, - MemberAccount { id: private_identity.clone(), hash: identity_hash }, + MemberAccount::Public(who_identity.clone()), + private_account.clone(), ]); - assert_eq!(AccountStore::<TestRuntime>::get(&who).unwrap(), expected_member_accounts); + assert_eq!( + AccountStore::<TestRuntime>::get(&who_omni_account).unwrap(), + expected_member_accounts + ); - let call = publicize_account_call(identity_hash, public_identity.clone()); + let call = publicize_account_call(Identity::from(bob())); assert_ok!(OmniAccount::dispatch_as_omni_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity_hash, @@ -499,24 +358,30 @@ fn publicize_account_works() { )); System::assert_has_event( - Event::DispatchedAsOmniAccount { who: who.clone(), result: DispatchResult::Ok(()) } - .into(), + Event::DispatchedAsOmniAccount { + who: who_omni_account.clone(), + result: DispatchResult::Ok(()), + } + .into(), ); System::assert_has_event( - Event::AccountMadePublic { who: who.clone(), member_account_hash: identity_hash } - .into(), + Event::AccountMadePublic { + who: who_omni_account.clone(), + member_account_hash: public_account_hash, + } + .into(), ); let expected_member_accounts: MemberAccounts<TestRuntime> = BoundedVec::truncate_from(vec![ - MemberAccount { - id: MemberIdentity::Public(who_identity.clone()), - hash: who_identity.hash(), - }, - MemberAccount { id: public_identity.clone(), hash: identity_hash }, + MemberAccount::Public(who_identity.clone()), + MemberAccount::Public(Identity::from(bob())), ]); - assert_eq!(AccountStore::<TestRuntime>::get(&who).unwrap(), expected_member_accounts); + assert_eq!( + AccountStore::<TestRuntime>::get(&who_omni_account).unwrap(), + expected_member_accounts + ); }); } @@ -527,14 +392,12 @@ fn publicize_account_identity_not_found_works() { let who = alice(); let who_identity = Identity::from(who.clone()); let who_identity_hash = who_identity.hash(); + let who_omni_account = who_identity.to_omni_account(); - let private_identity = MemberIdentity::Private(vec![1, 2, 3]); - let identity = Identity::from(bob()); - let public_identity = MemberIdentity::Public(identity.clone()); - let identity_hash = - H256::from(blake2_256(&Identity::from(bob()).to_did().unwrap().encode())); + let private_account = + MemberAccount::Private(vec![1, 2, 3], H256::from(blake2_256(&[1, 2, 3]))); - let call = publicize_account_call(identity_hash, public_identity.clone()); + let call = publicize_account_call(Identity::from(bob())); assert_noop!( OmniAccount::dispatch_as_omni_account( RuntimeOrigin::signed(tee_signer.clone()), @@ -547,16 +410,12 @@ fn publicize_account_identity_not_found_works() { assert_ok!(OmniAccount::add_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity, - MemberAccount { id: private_identity.clone(), hash: identity_hash }, - None + private_account.clone(), )); let charlie_identity = Identity::from(charlie()); - let other_identity = MemberIdentity::Public(charlie_identity.clone()); - let other_identity_hash = - H256::from(blake2_256(&charlie_identity.to_did().unwrap().encode())); - let call = publicize_account_call(other_identity_hash, other_identity); + let call = publicize_account_call(charlie_identity.clone()); assert_ok!(OmniAccount::dispatch_as_omni_account( RuntimeOrigin::signed(tee_signer.clone()), who_identity_hash, @@ -564,7 +423,7 @@ fn publicize_account_identity_not_found_works() { )); System::assert_has_event( Event::DispatchedAsOmniAccount { - who, + who: who_omni_account, result: Err(DispatchError::Module(ModuleError { index: 5, error: [2, 0, 0, 0], @@ -576,44 +435,6 @@ fn publicize_account_identity_not_found_works() { }); } -#[test] -fn publicize_account_identity_is_private_check_works() { - new_test_ext().execute_with(|| { - let tee_signer = get_tee_signer(); - let who = alice(); - let who_identity = Identity::from(who.clone()); - let who_identity_hash = who_identity.hash(); - - let private_identity = MemberIdentity::Private(vec![1, 2, 3]); - let identity_hash = Identity::from(bob()).hash(); - - assert_ok!(OmniAccount::add_account( - RuntimeOrigin::signed(tee_signer.clone()), - who_identity, - MemberAccount { id: private_identity.clone(), hash: identity_hash }, - None - )); - - let call = publicize_account_call(identity_hash, private_identity); - assert_ok!(OmniAccount::dispatch_as_omni_account( - RuntimeOrigin::signed(tee_signer.clone()), - who_identity_hash, - call - )); - System::assert_has_event( - Event::DispatchedAsOmniAccount { - who, - result: Err(DispatchError::Module(ModuleError { - index: 5, - error: [5, 0, 0, 0], - message: Some("AccountIsPrivate"), - })), - } - .into(), - ); - }); -} - #[test] fn dispatch_as_signed_works() { new_test_ext().execute_with(|| { @@ -621,15 +442,16 @@ fn dispatch_as_signed_works() { let who = alice(); let who_identity = Identity::from(who.clone()); let who_identity_hash = who_identity.hash(); + let who_omni_account = who_identity.to_omni_account(); - let private_identity = MemberIdentity::Private(vec![1, 2, 3]); - let identity_hash = Identity::from(bob()).hash(); + assert_ok!(Balances::transfer(RuntimeOrigin::signed(who.clone()), who_omni_account, 6)); + + let private_account = MemberAccount::Private(vec![1, 2, 3], Identity::from(bob()).hash()); assert_ok!(OmniAccount::add_account( RuntimeOrigin::signed(tee_signer.clone()), - who_identity, - MemberAccount { id: private_identity.clone(), hash: identity_hash }, - None + who_identity.clone(), + private_account, )); let call = make_balance_transfer_call(bob(), 5); @@ -639,7 +461,11 @@ fn dispatch_as_signed_works() { call )); System::assert_has_event( - Event::DispatchedAsSigned { who, result: DispatchResult::Ok(()) }.into(), + Event::DispatchedAsSigned { + who: who_identity.to_omni_account(), + result: DispatchResult::Ok(()), + } + .into(), ); assert_eq!(Balances::free_balance(bob()), 5); diff --git a/parachain/pallets/score-staking/src/lib.rs b/parachain/pallets/score-staking/src/lib.rs index 9d8b09aa7b..ce5f0f813a 100644 --- a/parachain/pallets/score-staking/src/lib.rs +++ b/parachain/pallets/score-staking/src/lib.rs @@ -361,7 +361,7 @@ pub mod pallet { Error::<T>::UnauthorizedOrigin ); let account = T::AccountIdConvert::convert( - user.to_account_id().ok_or(Error::<T>::ConvertIdentityFailed)?, + user.to_native_account().ok_or(Error::<T>::ConvertIdentityFailed)?, ); Scores::<T>::try_mutate(&account, |payment| { let state = ParaStaking::Pallet::<T>::delegator_state(&account) @@ -395,7 +395,7 @@ pub mod pallet { Error::<T>::UnauthorizedOrigin ); let account = T::AccountIdConvert::convert( - user.to_account_id().ok_or(Error::<T>::ConvertIdentityFailed)?, + user.to_native_account().ok_or(Error::<T>::ConvertIdentityFailed)?, ); let user_score = Scores::<T>::get(&account).ok_or(Error::<T>::UserNotExist)?.score; Self::update_total_score(user_score, 0)?; diff --git a/parachain/runtime/litentry/src/lib.rs b/parachain/runtime/litentry/src/lib.rs index 63ff46a5c6..3417e4080a 100644 --- a/parachain/runtime/litentry/src/lib.rs +++ b/parachain/runtime/litentry/src/lib.rs @@ -60,8 +60,8 @@ use xcm_executor::XcmExecutor; pub use constants::currency::deposit; pub use core_primitives::{ opaque, teebag::OperationalMode as TeebagOperationalMode, AccountId, Amount, AssetId, Balance, - BlockNumber, Hash, Header, Identity, Nonce, Signature, DAYS, HOURS, LITENTRY_PARA_ID, MINUTES, - SLOT_DURATION, + BlockNumber, DefaultOmniAccountConverter, Hash, Header, Identity, Nonce, Signature, DAYS, + HOURS, LITENTRY_PARA_ID, MINUTES, SLOT_DURATION, }; pub use runtime_common::currency::*; use runtime_common::{ @@ -951,22 +951,14 @@ impl pallet_identity_management::Config for Runtime { type MaxOIDCClientRedirectUris = ConstU32<10>; } -pub struct IdentityToAccountIdConverter; - -impl pallet_omni_account::AccountIdConverter<Runtime> for IdentityToAccountIdConverter { - fn convert(identity: &Identity) -> Option<AccountId> { - identity.to_account_id() - } -} - impl pallet_omni_account::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type TEECallOrigin = EnsureEnclaveSigner<Runtime>; type MaxAccountStoreLength = ConstU32<64>; - type AccountIdConverter = IdentityToAccountIdConverter; type OmniAccountOrigin = EnsureOmniAccount; + type OmniAccountConverter = DefaultOmniAccountConverter; } impl pallet_bitacross::Config for Runtime { diff --git a/parachain/runtime/paseo/src/lib.rs b/parachain/runtime/paseo/src/lib.rs index 887408ebd7..410247ec29 100644 --- a/parachain/runtime/paseo/src/lib.rs +++ b/parachain/runtime/paseo/src/lib.rs @@ -69,7 +69,8 @@ use xcm_executor::XcmExecutor; pub use constants::currency::deposit; pub use core_primitives::{ opaque, teebag::OperationalMode as TeebagOperationalMode, AccountId, Amount, AssetId, Balance, - BlockNumber, Hash, Header, Identity, Nonce, Signature, DAYS, HOURS, MINUTES, SLOT_DURATION, + BlockNumber, DefaultOmniAccountConverter, Hash, Header, Identity, Nonce, Signature, DAYS, + HOURS, MINUTES, SLOT_DURATION, }; pub use runtime_common::currency::*; @@ -993,22 +994,14 @@ impl pallet_identity_management::Config for Runtime { type MaxOIDCClientRedirectUris = ConstU32<10>; } -pub struct IdentityToAccountIdConverter; - -impl pallet_omni_account::AccountIdConverter<Runtime> for IdentityToAccountIdConverter { - fn convert(identity: &Identity) -> Option<AccountId> { - identity.to_account_id() - } -} - impl pallet_omni_account::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type TEECallOrigin = EnsureEnclaveSigner<Runtime>; type MaxAccountStoreLength = ConstU32<64>; - type AccountIdConverter = IdentityToAccountIdConverter; type OmniAccountOrigin = EnsureOmniAccount; + type OmniAccountConverter = DefaultOmniAccountConverter; } impl pallet_bitacross::Config for Runtime { diff --git a/parachain/runtime/rococo/src/lib.rs b/parachain/runtime/rococo/src/lib.rs index 1325f53191..bcf5efea33 100644 --- a/parachain/runtime/rococo/src/lib.rs +++ b/parachain/runtime/rococo/src/lib.rs @@ -68,8 +68,8 @@ use xcm_executor::XcmExecutor; pub use constants::currency::deposit; pub use core_primitives::{ opaque, teebag::OperationalMode as TeebagOperationalMode, AccountId, Amount, AssetId, Balance, - BlockNumber, Hash, Header, Identity, Nonce, Signature, DAYS, HOURS, MINUTES, ROCOCO_PARA_ID, - SLOT_DURATION, + BlockNumber, DefaultOmniAccountConverter, Hash, Header, Identity, Nonce, Signature, DAYS, + HOURS, MINUTES, ROCOCO_PARA_ID, SLOT_DURATION, }; pub use runtime_common::currency::*; @@ -993,22 +993,14 @@ impl pallet_identity_management::Config for Runtime { type MaxOIDCClientRedirectUris = ConstU32<10>; } -pub struct IdentityToAccountIdConverter; - -impl pallet_omni_account::AccountIdConverter<Runtime> for IdentityToAccountIdConverter { - fn convert(identity: &Identity) -> Option<AccountId> { - identity.to_account_id() - } -} - impl pallet_omni_account::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type TEECallOrigin = EnsureEnclaveSigner<Runtime>; type MaxAccountStoreLength = ConstU32<64>; - type AccountIdConverter = IdentityToAccountIdConverter; type OmniAccountOrigin = EnsureOmniAccount; + type OmniAccountConverter = DefaultOmniAccountConverter; } impl pallet_bitacross::Config for Runtime { diff --git a/tee-worker/bitacross/app-libs/stf/src/getter.rs b/tee-worker/bitacross/app-libs/stf/src/getter.rs index d6ce2661da..662fa355e5 100644 --- a/tee-worker/bitacross/app-libs/stf/src/getter.rs +++ b/tee-worker/bitacross/app-libs/stf/src/getter.rs @@ -166,7 +166,7 @@ impl ExecuteGetter for TrustedGetterSigned { fn execute(self) -> Option<Vec<u8>> { match self.getter { TrustedGetter::free_balance(who) => - if let Some(account_id) = who.to_account_id() { + if let Some(account_id) = who.to_native_account() { let info = System::account(&account_id); debug!("TrustedGetter free_balance"); debug!("AccountInfo for {} is {:?}", account_id_to_string(&who), info); @@ -176,7 +176,7 @@ impl ExecuteGetter for TrustedGetterSigned { None }, TrustedGetter::reserved_balance(who) => - if let Some(account_id) = who.to_account_id() { + if let Some(account_id) = who.to_native_account() { let info = System::account(&account_id); debug!("TrustedGetter reserved_balance"); debug!("AccountInfo for {} is {:?}", account_id_to_string(&who), info); @@ -198,7 +198,7 @@ impl ExecuteGetter for PublicGetter { match self { PublicGetter::some_value => Some(42u32.encode()), PublicGetter::nonce(identity) => - if let Some(account_id) = identity.to_account_id() { + if let Some(account_id) = identity.to_native_account() { let nonce = System::account_nonce(&account_id); debug!("PublicGetter nonce"); debug!("Account nonce is {}", nonce); diff --git a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs b/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs index 8d8167d46b..ac2a93ffef 100644 --- a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs @@ -205,7 +205,8 @@ where _node_metadata_repo: Arc<NodeMetadataRepository>, ) -> Result<Self::Result, Self::Error> { let sender = self.call.sender_identity().clone(); - let account_id: AccountId = sender.to_account_id().ok_or(Self::Error::InvalidAccount)?; + let account_id: AccountId = + sender.to_native_account().ok_or(Self::Error::InvalidAccount)?; let system_nonce = System::account_nonce(&account_id); ensure!(self.nonce == system_nonce, Self::Error::InvalidNonce(self.nonce, system_nonce)); @@ -221,7 +222,7 @@ where }, TrustedCall::balance_set_balance(root, who, free_balance, reserved_balance) => { let root_account_id: AccountId = - root.to_account_id().ok_or(Self::Error::InvalidAccount)?; + root.to_native_account().ok_or(Self::Error::InvalidAccount)?; ensure!( is_root::<Runtime, AccountId>(&root_account_id), Self::Error::MissingPrivileges(root_account_id) @@ -251,7 +252,7 @@ where }, TrustedCall::balance_transfer(from, to, value) => { let origin = ita_sgx_runtime::RuntimeOrigin::signed( - from.to_account_id().ok_or(Self::Error::InvalidAccount)?, + from.to_native_account().ok_or(Self::Error::InvalidAccount)?, ); std::println!("⣿STF⣿ 🔄 balance_transfer from ⣿⣿⣿ to ⣿⣿⣿ amount ⣿⣿⣿"); // endow fee to enclave (self) @@ -304,7 +305,7 @@ where ); let origin = ita_sgx_runtime::RuntimeOrigin::signed( - account_incognito.to_account_id().ok_or(StfError::InvalidAccount)?, + account_incognito.to_native_account().ok_or(StfError::InvalidAccount)?, ); ita_sgx_runtime::BalancesCall::<Runtime>::transfer { dest: MultiAddress::Id(fee_recipient), @@ -315,14 +316,14 @@ where Self::Error::Dispatch(format!("Balance Unshielding error: {:?}", e.error)) })?; burn_funds( - account_incognito.to_account_id().ok_or(StfError::InvalidAccount)?, + account_incognito.to_native_account().ok_or(StfError::InvalidAccount)?, value, )?; Ok(TrustedCallResult::Empty) }, TrustedCall::balance_shield(enclave_account, who, value, parentchain_id) => { let account_id: AccountId32 = - enclave_account.to_account_id().ok_or(Self::Error::InvalidAccount)?; + enclave_account.to_native_account().ok_or(Self::Error::InvalidAccount)?; ensure_enclave_signer_account(&account_id)?; debug!( "balance_shield({}, {}, {:?})", @@ -337,7 +338,7 @@ where }, TrustedCall::timestamp_set(enclave_account, now, parentchain_id) => { let account_id: AccountId32 = - enclave_account.to_account_id().ok_or(Self::Error::InvalidAccount)?; + enclave_account.to_native_account().ok_or(Self::Error::InvalidAccount)?; ensure_enclave_signer_account(&account_id)?; // Litentry: we don't actually set the timestamp, see `BlockMetadata` warn!("unused timestamp_set({}, {:?})", now, parentchain_id); diff --git a/tee-worker/common/core-primitives/stf-primitives/src/types.rs b/tee-worker/common/core-primitives/stf-primitives/src/types.rs index a96da4087c..db1f8c1d62 100644 --- a/tee-worker/common/core-primitives/stf-primitives/src/types.rs +++ b/tee-worker/common/core-primitives/stf-primitives/src/types.rs @@ -109,8 +109,8 @@ where pub fn signed_caller_account(&self) -> Option<AccountId> { match self { - TrustedOperation::direct_call(c) => c.sender_identity().to_account_id(), - TrustedOperation::indirect_call(c) => c.sender_identity().to_account_id(), + TrustedOperation::direct_call(c) => c.sender_identity().to_native_account(), + TrustedOperation::indirect_call(c) => c.sender_identity().to_native_account(), _ => None, } } diff --git a/tee-worker/common/core-primitives/types/src/parentchain/events.rs b/tee-worker/common/core-primitives/types/src/parentchain/events.rs index 0442e2094d..e013f159b1 100644 --- a/tee-worker/common/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/common/core-primitives/types/src/parentchain/events.rs @@ -293,7 +293,7 @@ pub struct RelayerAdded { impl core::fmt::Display for RelayerAdded { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(account_id) = self.who.to_account_id() { + if let Some(account_id) = self.who.to_native_account() { let message = format!("RelayerAdded :: account_id: {:?}", account_id); write!(f, "{}", message) } else { @@ -314,7 +314,7 @@ pub struct RelayerRemoved { impl core::fmt::Display for RelayerRemoved { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(account_id) = self.who.to_account_id() { + if let Some(account_id) = self.who.to_native_account() { let message = format!("RelayerRemoved :: account_id: {:?}", account_id); write!(f, "{}", message) } else { diff --git a/tee-worker/identity/app-libs/stf/src/getter.rs b/tee-worker/identity/app-libs/stf/src/getter.rs index 7ece797689..d8a4640393 100644 --- a/tee-worker/identity/app-libs/stf/src/getter.rs +++ b/tee-worker/identity/app-libs/stf/src/getter.rs @@ -213,7 +213,7 @@ impl ExecuteGetter for TrustedGetterSigned { fn execute(self) -> Option<Vec<u8>> { match self.getter { TrustedGetter::free_balance(who) => - if let Some(account_id) = who.to_account_id() { + if let Some(account_id) = who.to_native_account() { let info = System::account(&account_id); debug!("TrustedGetter free_balance"); debug!("AccountInfo for {} is {:?}", account_id_to_string(&who), info); @@ -223,7 +223,7 @@ impl ExecuteGetter for TrustedGetterSigned { None }, TrustedGetter::reserved_balance(who) => - if let Some(account_id) = who.to_account_id() { + if let Some(account_id) = who.to_native_account() { let info = System::account(&account_id); debug!("TrustedGetter reserved_balance"); debug!("AccountInfo for {} is {:?}", account_id_to_string(&who), info); @@ -234,7 +234,7 @@ impl ExecuteGetter for TrustedGetterSigned { }, #[cfg(feature = "evm")] TrustedGetter::evm_nonce(who) => - if let Some(account_id) = who.to_account_id() { + if let Some(account_id) = who.to_native_account() { let evm_account = get_evm_account(&account_id); let evm_account = HashedAddressMapping::into_account_id(evm_account); let nonce = System::account_nonce(&evm_account); @@ -279,7 +279,7 @@ impl ExecuteGetter for PublicGetter { match self { PublicGetter::some_value => Some(42u32.encode()), PublicGetter::nonce(identity) => - if let Some(account_id) = identity.to_account_id() { + if let Some(account_id) = identity.to_native_account() { let nonce = System::account_nonce(&account_id); debug!("PublicGetter nonce"); debug!("Account nonce is {}", nonce); diff --git a/tee-worker/identity/app-libs/stf/src/trusted_call.rs b/tee-worker/identity/app-libs/stf/src/trusted_call.rs index 567069faf9..92be79ded3 100644 --- a/tee-worker/identity/app-libs/stf/src/trusted_call.rs +++ b/tee-worker/identity/app-libs/stf/src/trusted_call.rs @@ -393,7 +393,8 @@ where node_metadata_repo: Arc<NodeMetadataRepository>, ) -> Result<Self::Result, Self::Error> { let sender = self.call.sender_identity().clone(); - let account_id: AccountId = sender.to_account_id().ok_or(Self::Error::InvalidAccount)?; + let account_id: AccountId = + sender.to_native_account().ok_or(Self::Error::InvalidAccount)?; let system_nonce = System::account_nonce(&account_id); ensure!(self.nonce == system_nonce, Self::Error::InvalidNonce(self.nonce, system_nonce)); @@ -409,7 +410,7 @@ where }, TrustedCall::balance_set_balance(root, who, free_balance, reserved_balance) => { let root_account_id: AccountId = - root.to_account_id().ok_or(Self::Error::InvalidAccount)?; + root.to_native_account().ok_or(Self::Error::InvalidAccount)?; ensure!( is_root::<Runtime, AccountId>(&root_account_id), Self::Error::MissingPrivileges(root_account_id) @@ -439,7 +440,7 @@ where }, TrustedCall::balance_transfer(from, to, value) => { let origin = ita_sgx_runtime::RuntimeOrigin::signed( - from.to_account_id().ok_or(Self::Error::InvalidAccount)?, + from.to_native_account().ok_or(Self::Error::InvalidAccount)?, ); std::println!("⣿STF⣿ 🔄 balance_transfer from ⣿⣿⣿ to ⣿⣿⣿ amount ⣿⣿⣿"); // endow fee to enclave (self) @@ -473,7 +474,7 @@ where }, TrustedCall::timestamp_set(enclave_account, now, parentchain_id) => { let account_id: AccountId32 = - enclave_account.to_account_id().ok_or(Self::Error::InvalidAccount)?; + enclave_account.to_native_account().ok_or(Self::Error::InvalidAccount)?; ensure_enclave_signer_account(&account_id)?; // Litentry: we don't actually set the timestamp, see `BlockMetadata` warn!("unused timestamp_set({}, {:?})", now, parentchain_id); @@ -485,7 +486,7 @@ where debug!("evm_withdraw({}, {}, {})", account_id_to_string(&from), address, value); ita_sgx_runtime::EvmCall::<Runtime>::withdraw { address, value } .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::signed( - from.to_account_id().ok_or(Self::Error::InvalidAccount)?, + from.to_native_account().ok_or(Self::Error::InvalidAccount)?, )) .map_err(|e| { Self::Error::Dispatch(format!("Evm Withdraw error: {:?}", e.error)) @@ -523,7 +524,7 @@ where access_list, } .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::signed( - from.to_account_id().ok_or(Self::Error::InvalidAccount)?, + from.to_native_account().ok_or(Self::Error::InvalidAccount)?, )) .map_err(|e| Self::Error::Dispatch(format!("Evm Call error: {:?}", e.error)))?; Ok(TrustedCallResult::Empty) @@ -559,7 +560,7 @@ where access_list, } .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::signed( - from.to_account_id().ok_or(Self::Error::InvalidAccount)?, + from.to_native_account().ok_or(Self::Error::InvalidAccount)?, )) .map_err(|e| Self::Error::Dispatch(format!("Evm Create error: {:?}", e.error)))?; let contract_address = evm_create_address(source, nonce_evm_account); @@ -598,7 +599,7 @@ where access_list, } .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::signed( - from.to_account_id().ok_or(Self::Error::InvalidAccount)?, + from.to_native_account().ok_or(Self::Error::InvalidAccount)?, )) .map_err(|e| Self::Error::Dispatch(format!("Evm Create2 error: {:?}", e.error)))?; let contract_address = evm_create2_address(source, salt, code_hash); @@ -620,7 +621,7 @@ where debug!("link_identity, who: {}", account_id_to_string(&who)); let verification_done = Self::link_identity_internal( shard, - signer.to_account_id().ok_or(Self::Error::InvalidAccount)?, + signer.to_native_account().ok_or(Self::Error::InvalidAccount)?, who.clone(), identity.clone(), validation_data, @@ -659,7 +660,7 @@ where TrustedCall::remove_identity(signer, who, identities) => { debug!("remove_identity, who: {}", account_id_to_string(&who)); - let account = signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; + let account = signer.to_native_account().ok_or(Self::Error::InvalidAccount)?; use crate::helpers::ensure_enclave_signer_or_alice; ensure!( ensure_enclave_signer_or_alice(&account), @@ -679,7 +680,7 @@ where let old_id_graph = IMT::id_graph(&who); Self::deactivate_identity_internal( - signer.to_account_id().ok_or(Self::Error::InvalidAccount)?, + signer.to_native_account().ok_or(Self::Error::InvalidAccount)?, who.clone(), identity, ) @@ -724,7 +725,7 @@ where let old_id_graph = IMT::id_graph(&who); Self::activate_identity_internal( - signer.to_account_id().ok_or(Self::Error::InvalidAccount)?, + signer.to_native_account().ok_or(Self::Error::InvalidAccount)?, who.clone(), identity, ) @@ -867,7 +868,7 @@ where TrustedCall::maybe_create_id_graph(signer, who) => { debug!("maybe_create_id_graph, who: {:?}", who); let signer_account: AccountId32 = - signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; + signer.to_native_account().ok_or(Self::Error::InvalidAccount)?; ensure_enclave_signer_account(&signer_account)?; // we only log the error @@ -882,7 +883,7 @@ where TrustedCall::clean_id_graphs(signer) => { debug!("clean_id_graphs"); - let account = signer.to_account_id().ok_or(Self::Error::InvalidAccount)?; + let account = signer.to_native_account().ok_or(Self::Error::InvalidAccount)?; use crate::helpers::ensure_enclave_signer_or_alice; ensure!( ensure_enclave_signer_or_alice(&account), diff --git a/tee-worker/identity/app-libs/stf/src/trusted_call_litentry.rs b/tee-worker/identity/app-libs/stf/src/trusted_call_litentry.rs index ea4bf0ed1b..a41de7576d 100644 --- a/tee-worker/identity/app-libs/stf/src/trusted_call_litentry.rs +++ b/tee-worker/identity/app-libs/stf/src/trusted_call_litentry.rs @@ -57,7 +57,7 @@ impl TrustedCallSigned { req_ext_hash: H256, ) -> StfResult<bool> { ensure!( - ensure_enclave_signer_or_self(&signer, who.to_account_id()), + ensure_enclave_signer_or_self(&signer, who.to_native_account()), StfError::LinkIdentityFailed(ErrorDetail::UnauthorizedSigner) ); @@ -111,7 +111,7 @@ impl TrustedCallSigned { identity: Identity, ) -> StfResult<()> { ensure!( - ensure_enclave_signer_or_self(&signer, who.to_account_id()), + ensure_enclave_signer_or_self(&signer, who.to_native_account()), StfError::DeactivateIdentityFailed(ErrorDetail::UnauthorizedSigner) ); @@ -128,7 +128,7 @@ impl TrustedCallSigned { identity: Identity, ) -> StfResult<()> { ensure!( - ensure_enclave_signer_or_self(&signer, who.to_account_id()), + ensure_enclave_signer_or_self(&signer, who.to_native_account()), StfError::ActivateIdentityFailed(ErrorDetail::UnauthorizedSigner) ); @@ -190,7 +190,7 @@ impl TrustedCallSigned { let old_id_graph = IMT::id_graph(&who); Self::link_identity_callback_internal( - signer.to_account_id().ok_or(StfError::InvalidAccount)?, + signer.to_native_account().ok_or(StfError::InvalidAccount)?, who.clone(), identity, web3networks, diff --git a/tee-worker/identity/cli/src/base_cli/commands/litentry/link_identity.rs b/tee-worker/identity/cli/src/base_cli/commands/litentry/link_identity.rs index bb13dd9b73..ec554f0b95 100644 --- a/tee-worker/identity/cli/src/base_cli/commands/litentry/link_identity.rs +++ b/tee-worker/identity/cli/src/base_cli/commands/litentry/link_identity.rs @@ -115,7 +115,7 @@ impl LinkIdentityCommand { let tee_shielding_key = get_shielding_key(cli).unwrap(); let encrypted_web3network = tee_shielding_key.encrypt(&web3network.encode()).unwrap(); - let identity_account_id = identity.to_account_id().unwrap(); + let identity_account_id = identity.to_native_account().unwrap(); let identity_public_key = format!("{}", identity_account_id); let identity_pair: sr25519_core::Pair = get_pair_from_str(&identity_public_key).into(); diff --git a/tee-worker/identity/enclave-runtime/src/rpc/common_api.rs b/tee-worker/identity/enclave-runtime/src/rpc/common_api.rs index a0178c754f..48c85a11dc 100644 --- a/tee-worker/identity/enclave-runtime/src/rpc/common_api.rs +++ b/tee-worker/identity/enclave-runtime/src/rpc/common_api.rs @@ -138,7 +138,7 @@ pub fn add_common_api<Author, GetterExecutor, AccessShieldingKey, OcallApi, Stat let account_id = match Identity::from_hex(identity_hex.as_str()) { Ok(identity) => - if let Some(account_id) = identity.to_account_id() { + if let Some(account_id) = identity.to_native_account() { account_id } else { return Ok(json!(compute_hex_encoded_return_error( @@ -427,7 +427,7 @@ pub fn add_common_api<Author, GetterExecutor, AccessShieldingKey, OcallApi, Stat Ok((encoded_did, redirect_url)) => { let account_id = match Identity::from_did(encoded_did.as_str()) { Ok(identity) => - if let Some(account_id) = identity.to_account_id() { + if let Some(account_id) = identity.to_native_account() { account_id } else { return Ok(json!(compute_hex_encoded_return_error("Invalid identity"))) @@ -465,7 +465,7 @@ pub fn add_common_api<Author, GetterExecutor, AccessShieldingKey, OcallApi, Stat Ok((encoded_did, email)) => { let account_id = match Identity::from_did(encoded_did.as_str()) { Ok(identity) => - if let Some(account_id) = identity.to_account_id() { + if let Some(account_id) = identity.to_native_account() { account_id } else { return Ok(json!(compute_hex_encoded_return_error("Invalid identity"))) diff --git a/tee-worker/identity/litentry/core/assertion-build/src/lit_staking.rs b/tee-worker/identity/litentry/core/assertion-build/src/lit_staking.rs index 6d695668aa..36826426f0 100644 --- a/tee-worker/identity/litentry/core/assertion-build/src/lit_staking.rs +++ b/tee-worker/identity/litentry/core/assertion-build/src/lit_staking.rs @@ -192,7 +192,7 @@ impl DelegatorState { // 0xa686a3043d0adcf2fa655e57bc595a78131da8bc800de21b19b3ba9ed33cfacc let params = "0xa686a3043d0adcf2fa655e57bc595a78131da8bc800de21b19b3ba9ed33cfacc"; let acc = identity - .to_account_id() + .to_native_account() .ok_or(Error::RequestVCFailed(Assertion::LITStaking, ErrorDetail::ParseError))?; let cocat = Twox64Concat::hash(acc.as_ref()); diff --git a/tee-worker/identity/litentry/core/identity-verification/src/web2/mod.rs b/tee-worker/identity/litentry/core/identity-verification/src/web2/mod.rs index bac2c85022..1bac3a62b5 100644 --- a/tee-worker/identity/litentry/core/identity-verification/src/web2/mod.rs +++ b/tee-worker/identity/litentry/core/identity-verification/src/web2/mod.rs @@ -92,7 +92,7 @@ pub fn verify( .map_err(|e| Error::LinkIdentityFailed(e.into_error_detail()))?; let state = vec_to_string(state.to_vec()) .map_err(|e| Error::LinkIdentityFailed(e.into_error_detail()))?; - let Some(account_id) = who.to_account_id() else { + let Some(account_id) = who.to_native_account() else { return Err(Error::LinkIdentityFailed(ErrorDetail::ParseError)); }; let (code_verifier, state_verifier) = @@ -207,7 +207,7 @@ pub fn verify( .map_err(|e| Error::LinkIdentityFailed(e.into_error_detail()))?; let verification_code = vec_to_string(data.verification_code.to_vec()) .map_err(|e| Error::LinkIdentityFailed(e.into_error_detail()))?; - let Some(account_id) = who.to_account_id() else { + let Some(account_id) = who.to_native_account() else { return Err(Error::LinkIdentityFailed(ErrorDetail::ParseError)); }; let stored_verification_code = diff --git a/tee-worker/identity/litentry/core/stf-task/receiver/src/lib.rs b/tee-worker/identity/litentry/core/stf-task/receiver/src/lib.rs index 87301516f0..2402623ca5 100644 --- a/tee-worker/identity/litentry/core/stf-task/receiver/src/lib.rs +++ b/tee-worker/identity/litentry/core/stf-task/receiver/src/lib.rs @@ -162,7 +162,7 @@ where .author_api .get_pending_trusted_calls_for( *shard, - &trusted_call.sender_identity().to_account_id().ok_or_else(|| { + &trusted_call.sender_identity().to_native_account().ok_or_else(|| { Error::OtherError(format!( "Not a valid account: {:?}", trusted_call.sender_identity() diff --git a/tee-worker/identity/litentry/core/vc-task/receiver/src/lib.rs b/tee-worker/identity/litentry/core/vc-task/receiver/src/lib.rs index d8cce8567f..31d13726e6 100644 --- a/tee-worker/identity/litentry/core/vc-task/receiver/src/lib.rs +++ b/tee-worker/identity/litentry/core/vc-task/receiver/src/lib.rs @@ -542,7 +542,7 @@ where ensure!(!identities.is_empty(), RequestVcErrorDetail::NoEligibleIdentity); let signer_account = - signer.to_account_id().ok_or(RequestVcErrorDetail::InvalidSignerAccount)?; + signer.to_native_account().ok_or(RequestVcErrorDetail::InvalidSignerAccount)?; match assertion { // the signer will be checked inside A13, as we don't seem to have access to ocall_api here