From 6453a33234e38065b1b85c68a283064a38f9200c Mon Sep 17 00:00:00 2001 From: Samuel Onoja Date: Wed, 25 Sep 2024 07:55:51 +0100 Subject: [PATCH] fix cyclic deps and continue storage implementations --- Cargo.lock | 4 ++- .../src/tendermint_with_assets_activation.rs | 6 +++-- mm2src/kdf_walletconnect/Cargo.toml | 4 +++ mm2src/kdf_walletconnect/src/chain/cosmos.rs | 2 +- mm2src/kdf_walletconnect/src/error.rs | 2 ++ mm2src/kdf_walletconnect/src/lib.rs | 11 ++++---- mm2src/kdf_walletconnect/src/session.rs | 15 ++++++----- mm2src/kdf_walletconnect/src/storage/mod.rs | 4 +-- .../kdf_walletconnect/src/storage/sqlite.rs | 6 ++--- mm2src/kdf_walletconnect/src/storage/wasm.rs | 27 +++++++++++++++++++ mm2src/mm2_core/Cargo.toml | 1 - mm2src/mm2_core/src/mm_ctx.rs | 5 ++-- mm2src/mm2_main/Cargo.toml | 1 + mm2src/mm2_main/src/lp_native_dex.rs | 9 ++++--- .../src/rpc/lp_commands/lp_commands.rs | 11 +++++--- 15 files changed, 76 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 70b45b19cb..28ed4208d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3561,6 +3561,8 @@ dependencies = [ "futures 0.3.28", "hex", "hkdf", + "mm2_core", + "mm2_db", "mm2_err_handle", "pairing_api", "rand 0.8.4", @@ -4494,7 +4496,6 @@ dependencies = [ "gstuff", "hex", "instant", - "kdf_walletconnect", "lazy_static", "mm2_err_handle", "mm2_event_stream", @@ -4675,6 +4676,7 @@ dependencies = [ "instant", "itertools", "js-sys", + "kdf_walletconnect", "keys", "lazy_static", "libc", diff --git a/mm2src/coins_activation/src/tendermint_with_assets_activation.rs b/mm2src/coins_activation/src/tendermint_with_assets_activation.rs index c15e6cad0d..54134daae5 100644 --- a/mm2src/coins_activation/src/tendermint_with_assets_activation.rs +++ b/mm2src/coins_activation/src/tendermint_with_assets_activation.rs @@ -19,6 +19,7 @@ use coins::{CoinBalance, CoinProtocol, MarketCoinOps, MmCoin, MmCoinEnum, PrivKe use common::executor::{AbortSettings, SpawnAbortable}; use common::{true_f, Future01CompatExt}; use kdf_walletconnect::chain::cosmos::CosmosAccountAlgo; +use kdf_walletconnect::WalletConnectCtx; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use mm2_event_stream::behaviour::{EventBehaviour, EventInitStatus}; @@ -241,8 +242,9 @@ async fn get_walletconnect_pubkey( }); }; - let account = ctx - .wallect_connect + let walletconnect_ctx = WalletConnectCtx::from_ctx(ctx).expect("WalletConnectCtx should be initialized by now!"); + + let account = walletconnect_ctx .cosmos_get_account(param.account_index, "cosmos", chain_id) .await .mm_err(|err| TendermintInitError { diff --git a/mm2src/kdf_walletconnect/Cargo.toml b/mm2src/kdf_walletconnect/Cargo.toml index 3c15f941e0..b73e75c2c2 100644 --- a/mm2src/kdf_walletconnect/Cargo.toml +++ b/mm2src/kdf_walletconnect/Cargo.toml @@ -17,6 +17,8 @@ futures = { version = "0.3", package = "futures", features = [ ] } hex = "0.4.2" hkdf = "0.12.4" +mm2_core = { path = "../mm2_core" } +mm2_db = { path = "../mm2_db" } mm2_err_handle = { path = "../mm2_err_handle" } pairing_api = { path = "../../../kdf-wc/pairing_api" } rand = "0.8" @@ -30,3 +32,5 @@ serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order", "raw_value"] } x25519-dalek = { version = "2.0", features = ["static_secrets"] } +[target.'cfg(target_arch = "wasm32")'.dependencies] +mm2_db = { path = "../mm2_db" } diff --git a/mm2src/kdf_walletconnect/src/chain/cosmos.rs b/mm2src/kdf_walletconnect/src/chain/cosmos.rs index 9bd944c941..cc8ca0b1c5 100644 --- a/mm2src/kdf_walletconnect/src/chain/cosmos.rs +++ b/mm2src/kdf_walletconnect/src/chain/cosmos.rs @@ -13,7 +13,7 @@ use super::WcRequestMethods; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum CosmosAccountAlgo { - #[serde(rename = "lowercase")] + #[serde(rename = "secp256k")] Secp256k1, #[serde(rename = "tendermint/PubKeySecp256k1")] TendermintSecp256k1, diff --git a/mm2src/kdf_walletconnect/src/error.rs b/mm2src/kdf_walletconnect/src/error.rs index f996967a2c..c73146e05d 100644 --- a/mm2src/kdf_walletconnect/src/error.rs +++ b/mm2src/kdf_walletconnect/src/error.rs @@ -72,6 +72,8 @@ pub enum WalletConnectCtxError { NoAccountFoundForIndex(u8), #[error("Empty account approved for chain_id: {0}")] EmptyAccount(String), + #[error("WalletConnect is not initaliazed yet!")] + NotInitialized, } impl From> for WalletConnectCtxError { diff --git a/mm2src/kdf_walletconnect/src/lib.rs b/mm2src/kdf_walletconnect/src/lib.rs index 5984bee4b0..931d5e9c4a 100644 --- a/mm2src/kdf_walletconnect/src/lib.rs +++ b/mm2src/kdf_walletconnect/src/lib.rs @@ -19,6 +19,7 @@ use futures::{channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}, use handler::Handler; use inbound_message::{process_inbound_request, process_inbound_response}; use metadata::{generate_metadata, AUTH_TOKEN_SUB, PROJECT_ID, RELAY_ADDRESS}; +use mm2_core::mm_ctx::{from_ctx, MmArc}; use mm2_err_handle::prelude::MmResult; use mm2_err_handle::prelude::*; use pairing_api::PairingClient; @@ -59,12 +60,8 @@ pub struct WalletConnectCtx { session_request_handler: Arc>>, } -impl Default for WalletConnectCtx { - fn default() -> Self { Self::new() } -} - impl WalletConnectCtx { - pub fn new() -> Self { + pub fn init() -> Self { let (msg_sender, msg_receiver) = unbounded(); let (conn_live_sender, conn_live_receiver) = unbounded(); let (session_request_sender, session_request_receiver) = unbounded(); @@ -96,6 +93,10 @@ impl WalletConnectCtx { } } + pub fn from_ctx(ctx: &MmArc) -> MmResult, WalletConnectCtxError> { + from_ctx(&ctx.wallet_connect, move || Ok(Self::init())).map_to_mm(WalletConnectCtxError::InternalError) + } + pub async fn connect_client(&self) -> MmResult<(), WalletConnectCtxError> { let auth = { let key = SigningKey::generate(&mut rand::thread_rng()); diff --git a/mm2src/kdf_walletconnect/src/session.rs b/mm2src/kdf_walletconnect/src/session.rs index 0f65cd05f8..9d6d5269ec 100644 --- a/mm2src/kdf_walletconnect/src/session.rs +++ b/mm2src/kdf_walletconnect/src/session.rs @@ -16,6 +16,7 @@ use relay_rpc::rpc::params::session_propose::Proposer; use relay_rpc::rpc::params::IrnMetadata; use relay_rpc::{domain::{SubscriptionId, Topic}, rpc::params::{session::ProposeNamespaces, session_settle::Controller, Metadata, Relay}}; +use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::BTreeMap; use x25519_dalek::{SharedSecret, StaticSecret}; @@ -30,10 +31,10 @@ pub(crate) const THIRTY_DAYS: u64 = 60 * 60 * 30; pub(crate) type WcRequestResponseResult = MmResult<(Value, IrnMetadata), WalletConnectCtxError>; -#[derive(Clone)] +#[derive(Clone, Serialize, Deserialize)] pub struct SessionKey { sym_key: [u8; 32], - public_key: PublicKey, + public_key: [u8; 32], } impl std::fmt::Debug for SessionKey { @@ -50,7 +51,7 @@ impl SessionKey { pub fn new(public_key: PublicKey) -> Self { Self { sym_key: [0u8; 32], - public_key, + public_key: public_key.to_bytes(), } } @@ -69,7 +70,7 @@ impl SessionKey { let mut session_key = Self { sym_key: [0u8; 32], - public_key, + public_key: public_key.to_bytes(), }; session_key.derive_symmetric_key(&shared_secret)?; @@ -97,7 +98,7 @@ impl SessionKey { pub fn symmetric_key(&self) -> &[u8; 32] { &self.sym_key } /// Gets "our" public key used in symmetric key derivation. - pub fn diffie_public_key(&self) -> &[u8; 32] { self.public_key.as_bytes() } + pub fn diffie_public_key(&self) -> &[u8; 32] { &self.public_key } /// Generates new session topic. pub fn generate_topic(&self) -> String { @@ -110,7 +111,7 @@ impl SessionKey { /// In the WalletConnect protocol, a session involves two parties: a controller /// (typically a wallet) and a proposer (typically a dApp). This enum is used /// to distinguish between these two roles. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub enum SessionType { /// Represents the controlling party in a session, typically a wallet. Controller, @@ -130,7 +131,7 @@ impl ToString for SessionType { /// This struct is typically used in the core session management logic of a WalletConnect /// implementation. It's used to store, retrieve, and update session information throughout /// the lifecycle of a WalletConnect connection. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct Session { /// Session topic pub topic: Topic, diff --git a/mm2src/kdf_walletconnect/src/storage/mod.rs b/mm2src/kdf_walletconnect/src/storage/mod.rs index 4a9c0ccf82..19e6442a01 100644 --- a/mm2src/kdf_walletconnect/src/storage/mod.rs +++ b/mm2src/kdf_walletconnect/src/storage/mod.rs @@ -5,8 +5,8 @@ use relay_rpc::{domain::Topic, rpc::params::session::SettleNamespaces}; use crate::session::Session; -pub(crate) mod sqlite; -pub(crate) mod wasm; +#[cfg(not(target_arch = "wasm32"))] pub(crate) mod sqlite; +#[cfg(target_arch = "wasm32")] pub(crate) mod wasm; pub(crate) const SESSION_STORAGE_TABLE_NAME: &str = "kdf_wc_session_storage"; diff --git a/mm2src/kdf_walletconnect/src/storage/sqlite.rs b/mm2src/kdf_walletconnect/src/storage/sqlite.rs index 01ac12acd9..761c89cb1d 100644 --- a/mm2src/kdf_walletconnect/src/storage/sqlite.rs +++ b/mm2src/kdf_walletconnect/src/storage/sqlite.rs @@ -75,8 +75,8 @@ impl WalletConnectStorageOps for MutexGuard<'_, AsyncConnection> { self.call(move |conn| { let transaction = conn.transaction()?; - let session_key = - serde_json::to_string(&session.session_key).map_err(|err| AsyncConnError::from(err.to_string()))?; + //let session_key = + // serde_json::to_string(&session.session_key).map_err(|err| AsyncConnError::from(err.to_string()))?; let relay = serde_json::to_string(&session.relay).map_err(|err| AsyncConnError::from(err.to_string()))?; let proposer = serde_json::to_string(&session.proposer).map_err(|err| AsyncConnError::from(err.to_string()))?; @@ -90,7 +90,7 @@ impl WalletConnectStorageOps for MutexGuard<'_, AsyncConnection> { let params = [ session.topic.to_string(), session.subscription_id.to_string(), - session_key, + "session_key".to_string(), session.expiry.to_string(), session.pairing_topic.to_string(), session.session_type.to_string(), diff --git a/mm2src/kdf_walletconnect/src/storage/wasm.rs b/mm2src/kdf_walletconnect/src/storage/wasm.rs index 8b13789179..b336a0f354 100644 --- a/mm2src/kdf_walletconnect/src/storage/wasm.rs +++ b/mm2src/kdf_walletconnect/src/storage/wasm.rs @@ -1 +1,28 @@ +use async_trait::async_trait; +use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbLocked, IndexedDb, IndexedDbBuilder, InitDbResult}; +const DB_VERSION: u32 = 1; + +pub type SessionStorageIDBLocked<'a> = DbLocked<'a, SessionStorageIDB>; + +pub struct SessionStorageIDB { + inner: IndexedDb, +} + +#[async_trait] +impl DbInstance for SessionStorageIDB { + const DB_NAME: &'static str = "nft_cache"; + + async fn init(db_id: DbIdentifier) -> InitDbResult { + let inner = IndexedDbBuilder::new(db_id) + .with_version(DB_VERSION) + //.with_table::() + .build() + .await?; + Ok(SessionStorageIDB { inner }) + } +} + +impl SessionStorageIDB { + pub(crate) fn get_inner(&self) -> &IndexedDb { &self.inner } +} diff --git a/mm2src/mm2_core/Cargo.toml b/mm2src/mm2_core/Cargo.toml index 47c9d4270f..9c5c362a93 100644 --- a/mm2src/mm2_core/Cargo.toml +++ b/mm2src/mm2_core/Cargo.toml @@ -16,7 +16,6 @@ db_common = { path = "../db_common" } derive_more = "0.99" futures = { version = "0.3", package = "futures", features = ["compat", "async-await", "thread-pool"] } hex = "0.4.2" -kdf_walletconnect = { path = "../kdf_walletconnect" } lazy_static = "1.4" mm2_err_handle = { path = "../mm2_err_handle" } mm2_event_stream = { path = "../mm2_event_stream" } diff --git a/mm2src/mm2_core/src/mm_ctx.rs b/mm2src/mm2_core/src/mm_ctx.rs index acbb4355e9..145ead33c2 100644 --- a/mm2src/mm2_core/src/mm_ctx.rs +++ b/mm2src/mm2_core/src/mm_ctx.rs @@ -5,7 +5,6 @@ use common::executor::{abortable_queue::{AbortableQueue, WeakSpawner}, use common::log::{self, LogLevel, LogOnError, LogState}; use common::{cfg_native, cfg_wasm32, small_rng}; use gstuff::{try_s, Constructible, ERR, ERRL}; -use kdf_walletconnect::WalletConnectCtx; use lazy_static::lazy_static; use mm2_event_stream::{controller::Controller, Event, EventStreamConfiguration}; use mm2_metrics::{MetricsArc, MetricsOps}; @@ -143,7 +142,7 @@ pub struct MmCtx { /// asynchronous handle for rusqlite connection. #[cfg(not(target_arch = "wasm32"))] pub async_sqlite_connection: Constructible>>, - pub wallect_connect: Arc, + pub wallet_connect: Mutex>>, } impl MmCtx { @@ -193,7 +192,7 @@ impl MmCtx { nft_ctx: Mutex::new(None), #[cfg(not(target_arch = "wasm32"))] async_sqlite_connection: Constructible::default(), - wallect_connect: Arc::new(WalletConnectCtx::default()), + wallet_connect: Mutex::new(None), } } diff --git a/mm2src/mm2_main/Cargo.toml b/mm2src/mm2_main/Cargo.toml index 9cf79be15d..e51d12123a 100644 --- a/mm2src/mm2_main/Cargo.toml +++ b/mm2src/mm2_main/Cargo.toml @@ -64,6 +64,7 @@ http = "0.2" hw_common = { path = "../hw_common" } instant = { version = "0.1.12" } itertools = "0.10" +kdf_walletconnect = { path = "../kdf_walletconnect" } keys = { path = "../mm2_bitcoin/keys" } lazy_static = "1.4" # ledger = { path = "../ledger" } diff --git a/mm2src/mm2_main/src/lp_native_dex.rs b/mm2src/mm2_main/src/lp_native_dex.rs index cb2d5e91e4..08fdaa9e46 100644 --- a/mm2src/mm2_main/src/lp_native_dex.rs +++ b/mm2src/mm2_main/src/lp_native_dex.rs @@ -25,6 +25,7 @@ use common::log::{info, warn}; use crypto::{from_hw_error, CryptoCtx, HwError, HwProcessingError, HwRpcError, WithHwRpcError}; use derive_more::Display; use enum_derives::EnumFromTrait; +use kdf_walletconnect::WalletConnectCtx; use mm2_core::mm_ctx::{MmArc, MmCtx}; use mm2_err_handle::common_errors::InternalError; use mm2_err_handle::prelude::*; @@ -473,14 +474,16 @@ pub async fn lp_init_continue(ctx: MmArc) -> MmInitResult<()> { init_message_service(&ctx).await?; // connect walletconnect - ctx.wallect_connect + let wallet_connect = + WalletConnectCtx::from_ctx(&ctx).map_err(|err| MmInitError::WalletInitError(err.to_string()))?; + wallet_connect .connect_client() .await .map_err(|err| MmInitError::WalletInitError(err.to_string()))?; ctx.spawner() - .spawn(ctx.wallect_connect.clone().published_message_event_loop()); + .spawn(wallet_connect.clone().published_message_event_loop()); ctx.spawner() - .spawn(ctx.wallect_connect.clone().spawn_connection_live_watcher()); + .spawn(wallet_connect.clone().spawn_connection_live_watcher()); let balance_update_ordermatch_handler = BalanceUpdateOrdermatchHandler::new(ctx.clone()); register_balance_update_handler(ctx.clone(), Box::new(balance_update_ordermatch_handler)).await; diff --git a/mm2src/mm2_main/src/rpc/lp_commands/lp_commands.rs b/mm2src/mm2_main/src/rpc/lp_commands/lp_commands.rs index d9628f38df..d76ceb6013 100644 --- a/mm2src/mm2_main/src/rpc/lp_commands/lp_commands.rs +++ b/mm2src/mm2_main/src/rpc/lp_commands/lp_commands.rs @@ -2,6 +2,7 @@ use common::HttpStatusCode; use crypto::{CryptoCtx, CryptoCtxError, HwConnectionStatus, HwPubkey}; use derive_more::Display; use http::StatusCode; +use kdf_walletconnect::WalletConnectCtx; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use rpc::v1::types::H160 as H160Json; @@ -133,8 +134,9 @@ pub async fn connect_to_peer( ctx: MmArc, req: ConnectPairingRequest, ) -> MmResult { - let topic = ctx - .wallect_connect + let walletconnect_ctx = WalletConnectCtx::from_ctx(&ctx).expect("WalletConnectCtx should be initialized by now!"); + + let topic = walletconnect_ctx .connect_to_pairing(&req.url, true) .await .map_err(|err| TrezorConnectionError::Internal(err.to_string()))?; @@ -157,8 +159,9 @@ pub async fn create_new_pairing( ctx: MmArc, _req: CreatePairingRequest, ) -> MmResult { - let url = ctx - .wallect_connect + let walletconnect_ctx = WalletConnectCtx::from_ctx(&ctx).expect("WalletConnectCtx should be initialized by now!"); + + let url = walletconnect_ctx .create_pairing(None) .await .map_err(|err| TrezorConnectionError::Internal(err.to_string()))?;