Skip to content

Commit

Permalink
fix cyclic deps and continue storage implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
borngraced committed Sep 25, 2024
1 parent be98c40 commit 6453a33
Show file tree
Hide file tree
Showing 15 changed files with 76 additions and 32 deletions.
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions mm2src/kdf_walletconnect/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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" }
2 changes: 1 addition & 1 deletion mm2src/kdf_walletconnect/src/chain/cosmos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions mm2src/kdf_walletconnect/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Error<PublishError>> for WalletConnectCtxError {
Expand Down
11 changes: 6 additions & 5 deletions mm2src/kdf_walletconnect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -59,12 +60,8 @@ pub struct WalletConnectCtx {
session_request_handler: Arc<Mutex<UnboundedReceiver<SessionEventMessage>>>,
}

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();
Expand Down Expand Up @@ -96,6 +93,10 @@ impl WalletConnectCtx {
}
}

pub fn from_ctx(ctx: &MmArc) -> MmResult<Arc<WalletConnectCtx>, 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());
Expand Down
15 changes: 8 additions & 7 deletions mm2src/kdf_walletconnect/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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 {
Expand All @@ -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(),
}
}

Expand All @@ -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)?;

Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions mm2src/kdf_walletconnect/src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
6 changes: 3 additions & 3 deletions mm2src/kdf_walletconnect/src/storage/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))?;
Expand All @@ -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(),
Expand Down
27 changes: 27 additions & 0 deletions mm2src/kdf_walletconnect/src/storage/wasm.rs
Original file line number Diff line number Diff line change
@@ -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<Self> {
let inner = IndexedDbBuilder::new(db_id)
.with_version(DB_VERSION)
//.with_table::<LastScannedBlockTable>()
.build()
.await?;
Ok(SessionStorageIDB { inner })
}
}

impl SessionStorageIDB {
pub(crate) fn get_inner(&self) -> &IndexedDb { &self.inner }
}
1 change: 0 additions & 1 deletion mm2src/mm2_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
5 changes: 2 additions & 3 deletions mm2src/mm2_core/src/mm_ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -143,7 +142,7 @@ pub struct MmCtx {
/// asynchronous handle for rusqlite connection.
#[cfg(not(target_arch = "wasm32"))]
pub async_sqlite_connection: Constructible<Arc<AsyncMutex<AsyncConnection>>>,
pub wallect_connect: Arc<WalletConnectCtx>,
pub wallet_connect: Mutex<Option<Arc<dyn Any + 'static + Send + Sync>>>,
}

impl MmCtx {
Expand Down Expand Up @@ -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),
}
}

Expand Down
1 change: 1 addition & 0 deletions mm2src/mm2_main/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
9 changes: 6 additions & 3 deletions mm2src/mm2_main/src/lp_native_dex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -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;
Expand Down
11 changes: 7 additions & 4 deletions mm2src/mm2_main/src/rpc/lp_commands/lp_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -133,8 +134,9 @@ pub async fn connect_to_peer(
ctx: MmArc,
req: ConnectPairingRequest,
) -> MmResult<ConnectPairingResponse, TrezorConnectionError> {
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()))?;
Expand All @@ -157,8 +159,9 @@ pub async fn create_new_pairing(
ctx: MmArc,
_req: CreatePairingRequest,
) -> MmResult<CreatePairingResponse, TrezorConnectionError> {
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()))?;
Expand Down

0 comments on commit 6453a33

Please sign in to comment.