Skip to content

Commit

Permalink
remove active_session/topic and some other minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
borngraced committed Jan 9, 2025
1 parent 020ecb8 commit 432b056
Show file tree
Hide file tree
Showing 7 changed files with 16 additions and 87 deletions.
13 changes: 6 additions & 7 deletions mm2src/coins/tendermint/wallet_connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,15 +93,15 @@ impl WalletConnectOps for TendermintCoin {
params: Self::Params<'a>,
) -> Result<Self::SignTxData, Self::Error> {
let chain_id = self.wc_chain_id(wc).await?;
let method = if wc.is_ledger_connection() {
let session_topic = self
.session_topic()
.expect("TODO: handle after updating tendermint coin init");
let method = if wc.is_ledger_connection(session_topic) {
WcRequestMethods::CosmosSignAmino
} else {
WcRequestMethods::CosmosSignDirect
};

let session_topic = self
.session_topic()
.expect("TODO: handle after updating tendermint coin init");
wc.send_session_request_and_wait(session_topic, &chain_id, method, params, |data: CosmosTxSignedData| {
let signature = general_purpose::STANDARD
.decode(data.signature.signature)
Expand Down Expand Up @@ -194,13 +194,12 @@ where
match value {
Value::Object(map) => map
.iter()
.enumerate()
.map(|(_, (_, value))| {
.map(|(_, value)| {
value
.as_u64()
.ok_or_else(|| serde::de::Error::custom("Invalid byte value"))
.and_then(|n| {
if n <= 255 {
if n <= 0xff {
Ok(n as u8)
} else {
Err(serde::de::Error::custom("Invalid byte value"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ async fn activate_with_walletconnect(
ticker: ticker.to_string(),
kind: TendermintInitErrorKind::UnableToFetchChainAccount(err.to_string()),
})?;
let wallet_type = if wc.is_ledger_connection() {
let wallet_type = if wc.is_ledger_connection(&session_topic) {
TendermintWalletConnectionType::WcLedger(session_topic)
} else {
TendermintWalletConnectionType::Wc(session_topic)
Expand Down
5 changes: 3 additions & 2 deletions mm2src/kdf_walletconnect/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,10 @@ impl WalletConnectCtxImpl {

/// Checks if the current session is connected to a Ledger device.
/// NOTE: for COSMOS chains only.
pub fn is_ledger_connection(&self) -> bool {
pub fn is_ledger_connection(&self, session_topic: &str) -> bool {
let session_topic = session_topic.into();
self.session_manager
.get_session_active()
.get_session(&session_topic)
.and_then(|session| session.session_properties)
.and_then(|props| props.keys.as_ref().cloned())
.and_then(|keys| keys.first().cloned())
Expand Down
60 changes: 3 additions & 57 deletions mm2src/kdf_walletconnect/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Debug;
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use wc_common::SymKey;

pub(crate) const FIVE_MINUTES: u64 = 5 * 60;
Expand Down Expand Up @@ -176,8 +176,6 @@ impl Session {

/// Internal implementation of session management.
struct SessionManagerImpl {
/// The currently active session topic.
active_topic: Mutex<Option<Topic>>,
/// A thread-safe map of sessions indexed by topic.
sessions: Arc<RwLock<HashMap<Topic, Session>>>,
pub(crate) storage: SessionStorageDb,
Expand Down Expand Up @@ -205,7 +203,6 @@ impl SessionManager {
pub(crate) fn new(storage: SessionStorageDb) -> Self {
Self(
SessionManagerImpl {
active_topic: Default::default(),
sessions: Default::default(),
storage,
}
Expand All @@ -223,23 +220,9 @@ impl SessionManager {

pub(crate) fn storage(&self) -> &SessionStorageDb { &self.0.storage }

/// Get active session topic or return error if no session has been activated.
pub fn get_active_topic_or_err(&self) -> MmResult<Topic, WalletConnectError> {
self.0
.active_topic
.lock()
.unwrap()
.clone()
.ok_or(MmError::new(WalletConnectError::SessionError(
"No active session".to_owned(),
)))
}

/// Inserts `Session` into the session store, associated with the specified topic.
/// If a session with the same topic already exists, it will be overwritten.
pub(crate) fn add_session(&self, session: Session) {
// set active session topic.
*self.0.active_topic.lock().unwrap() = Some(session.topic.clone());
// insert session
self.write().insert(session.topic.clone(), session);
}
Expand All @@ -248,50 +231,13 @@ impl SessionManager {
/// If the session does not exist, this method does nothing.
pub(crate) fn delete_session(&self, topic: &Topic) -> Option<Session> {
info!("[{topic}] Deleting session with topic");
let mut active_topic = self.0.active_topic.lock().unwrap();

// Remove the session and get the removed session (if any)
let removed_session = self.write().remove(topic);

// Update active topic if necessary
if active_topic.as_ref() == Some(topic) {
// If the deleted session was the active one, find a new active session
*active_topic = self.read().iter().next().map(|(topic, session)| topic.clone());

if let Some(new_active_topic) = active_topic.as_ref() {
info!("[{new_active_topic}] New session with topic activated!");
}
}

removed_session
}

pub fn set_active_session(&self, topic: &Topic) -> MmResult<(), WalletConnectError> {
let mut active_topic = self.0.active_topic.lock().unwrap();
let session = self
.get_session(topic)
.ok_or(MmError::new(WalletConnectError::SessionError(
"Session not found".to_owned(),
)))?;

*active_topic = Some(session.topic);

Ok(())
// Remove the session and return the removed session (if any)
self.write().remove(topic)
}

/// Retrieves a cloned session associated with a given topic.
pub fn get_session(&self, topic: &Topic) -> Option<Session> { self.read().get(topic).cloned() }

/// returns an `option<session>` containing the active session if it exists; otherwise, returns `none`.
pub fn get_session_active(&self) -> Option<Session> {
self.0
.active_topic
.lock()
.unwrap()
.as_ref()
.and_then(|topic| self.get_session(topic))
}

/// Retrieves all sessions(active and inactive)
pub fn get_sessions(&self) -> impl Iterator<Item = SessionRpcInfo> {
self.read().clone().into_values().map(|session| session.into())
Expand Down
4 changes: 2 additions & 2 deletions mm2src/kdf_walletconnect/src/session/rpc/settle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ pub(crate) async fn reply_session_settle_request(
let session_properties = serde_json::from_value::<SessionProperties>(value)?;
session.session_properties = Some(session_properties);
};
};
}

// Update storage session.
// Update storage session.
let session = ctx
.session_manager
.get_session(topic)
Expand Down
3 changes: 1 addition & 2 deletions mm2src/mm2_main/src/rpc/dispatcher/dispatcher.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::wc_commands::{disconnect_session, get_all_sessions, get_session, set_active_session};
use super::wc_commands::{disconnect_session, get_all_sessions, get_session};
use super::{DispatcherError, DispatcherResult, PUBLIC_METHODS};
use crate::lp_healthcheck::peer_connection_healthcheck_rpc;
use crate::lp_native_dex::init_hw::{cancel_init_trezor, init_trezor, init_trezor_status, init_trezor_user_action};
Expand Down Expand Up @@ -242,7 +242,6 @@ async fn dispatcher_v2(request: MmRpcRequest, ctx: MmArc) -> DispatcherResult<Re
"wc_get_session" => handle_mmrpc(ctx, request, get_session).await,
"wc_get_sessions" => handle_mmrpc(ctx, request, get_all_sessions).await,
"wc_delete_session" => handle_mmrpc(ctx, request, disconnect_session).await,
"wc_set_active_session" => handle_mmrpc(ctx, request, set_active_session).await,
"wc_ping_session" => handle_mmrpc(ctx, request, ping_session).await,
_ => MmError::err(DispatcherError::NoSuchMethod),
}
Expand Down
16 changes: 0 additions & 16 deletions mm2src/mm2_main/src/rpc/wc_commands/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,6 @@ pub async fn get_session(ctx: MmArc, req: GetSessionRequest) -> MmResult<GetSess
Ok(GetSessionResponse { session })
}

/// `Get session connection` RPC command implementation.
pub async fn set_active_session(
ctx: MmArc,
req: GetSessionRequest,
) -> MmResult<SessionResponse, WalletConnectRpcError> {
let ctx =
WalletConnectCtx::from_ctx(&ctx).mm_err(|err| WalletConnectRpcError::InitializationError(err.to_string()))?;
ctx.session_manager
.set_active_session(&req.topic.into())
.mm_err(|err| WalletConnectRpcError::SessionRequestError(err.to_string()))?;

Ok(SessionResponse {
result: "active session updated!".to_owned(),
})
}

/// `Delete session connection` RPC command implementation.
pub async fn disconnect_session(
ctx: MmArc,
Expand Down

0 comments on commit 432b056

Please sign in to comment.