Skip to content

Commit

Permalink
Add session id to logs (#822)
Browse files Browse the repository at this point in the history
  • Loading branch information
benthecarman authored Nov 2, 2023
1 parent b29f107 commit 0bfe14d
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 19 deletions.
19 changes: 11 additions & 8 deletions mutiny-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ impl<S: MutinyStorage> MutinyWallet<S> {
pub async fn new(
storage: S,
config: MutinyWalletConfig,
session_id: Option<String>,
) -> Result<MutinyWallet<S>, MutinyError> {
let expected_network = storage.get::<Network>(EXPECTED_NETWORK_KEY)?;
match expected_network {
Expand All @@ -159,7 +160,8 @@ impl<S: MutinyStorage> MutinyWallet<S> {
None => storage.set_data(EXPECTED_NETWORK_KEY, config.network, None)?,
}

let node_manager = Arc::new(NodeManager::new(config.clone(), storage.clone()).await?);
let node_manager =
Arc::new(NodeManager::new(config.clone(), storage.clone(), session_id).await?);

NodeManager::start_sync(node_manager.clone());

Expand Down Expand Up @@ -210,8 +212,9 @@ impl<S: MutinyStorage> MutinyWallet<S> {
/// Not needed after [NodeManager]'s `new()` function.
pub async fn start(&mut self) -> Result<(), MutinyError> {
self.storage.start().await?;
// when we restart, gen a new session id
self.node_manager =
Arc::new(NodeManager::new(self.config.clone(), self.storage.clone()).await?);
Arc::new(NodeManager::new(self.config.clone(), self.storage.clone(), None).await?);
NodeManager::start_sync(self.node_manager.clone());

// Redshifts disabled in safe mode
Expand Down Expand Up @@ -634,7 +637,7 @@ mod tests {
None,
false,
);
let mw = MutinyWallet::new(storage.clone(), config)
let mw = MutinyWallet::new(storage.clone(), config, None)
.await
.expect("mutiny wallet should initialize");
mw.storage.insert_mnemonic(mnemonic).unwrap();
Expand Down Expand Up @@ -664,7 +667,7 @@ mod tests {
None,
false,
);
let mut mw = MutinyWallet::new(storage.clone(), config)
let mut mw = MutinyWallet::new(storage.clone(), config, None)
.await
.expect("mutiny wallet should initialize");

Expand Down Expand Up @@ -700,7 +703,7 @@ mod tests {
None,
false,
);
let mut mw = MutinyWallet::new(storage.clone(), config)
let mut mw = MutinyWallet::new(storage.clone(), config, None)
.await
.expect("mutiny wallet should initialize");

Expand Down Expand Up @@ -737,7 +740,7 @@ mod tests {
None,
false,
);
let mw = MutinyWallet::new(storage.clone(), config)
let mw = MutinyWallet::new(storage.clone(), config, None)
.await
.expect("mutiny wallet should initialize");
let seed = mw.node_manager.xprivkey;
Expand All @@ -762,7 +765,7 @@ mod tests {
None,
false,
);
let mw2 = MutinyWallet::new(storage2.clone(), config2.clone())
let mw2 = MutinyWallet::new(storage2.clone(), config2.clone(), None)
.await
.expect("mutiny wallet should initialize");
let seed2 = mw2.node_manager.xprivkey;
Expand All @@ -783,7 +786,7 @@ mod tests {
let seed = storage3.get_mnemonic().unwrap().unwrap();
ExtendedPrivKey::new_master(Network::Regtest, &seed.to_seed("")).unwrap()
};
let mw2 = MutinyWallet::new(storage3, config2)
let mw2 = MutinyWallet::new(storage3, config2, None)
.await
.expect("mutiny wallet should initialize");
let restored_seed = mw2.node_manager.xprivkey;
Expand Down
23 changes: 20 additions & 3 deletions mutiny-core/src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use bitcoin::hashes::hex::ToHex;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
Expand All @@ -16,13 +17,19 @@ const MAX_LOG_ITEMS: usize = 10_000;

#[derive(Clone)]
pub struct MutinyLogger {
pub session_id: String,
should_write_to_storage: bool,
memory_logs: Arc<Mutex<Vec<String>>>,
}

impl MutinyLogger {
pub fn with_writer<S: MutinyStorage>(stop: Arc<AtomicBool>, logging_db: S) -> Self {
pub fn with_writer<S: MutinyStorage>(
stop: Arc<AtomicBool>,
logging_db: S,
session_id: Option<String>,
) -> Self {
let l = MutinyLogger {
session_id: session_id.unwrap_or_else(gen_session_id),
should_write_to_storage: true,
memory_logs: Arc::new(Mutex::new(vec![])),
};
Expand Down Expand Up @@ -82,17 +89,27 @@ impl MutinyLogger {
impl Default for MutinyLogger {
fn default() -> Self {
Self {
session_id: gen_session_id(),
should_write_to_storage: Default::default(),
memory_logs: Arc::new(Mutex::new(vec![])),
}
}
}

fn gen_session_id() -> String {
let mut entropy = vec![0u8; 2];
getrandom::getrandom(&mut entropy).unwrap();
entropy.to_hex()
}

impl Logger for MutinyLogger {
fn log(&self, record: &Record) {
let raw_log = record.args.to_string();
let log = format!(
"{} {:<5} [{}:{}] {}\n",
"{} {} {:<5} [{}:{}] {}\n",
// log the session id so we can tie logs to a particular session, useful for detecting
// if we have multiple sessions running at once
self.session_id,
// Note that a "real" lightning node almost certainly does *not* want subsecond
// precision for message-receipt information as it makes log entries a target for
// deanonymization attacks. For testing, however, its quite useful.
Expand Down Expand Up @@ -214,7 +231,7 @@ mod tests {
let storage = MemoryStorage::default();

let stop = Arc::new(AtomicBool::new(false));
let logger = MutinyLogger::with_writer(stop.clone(), storage.clone());
let logger = MutinyLogger::with_writer(stop.clone(), storage.clone(), None);

let log_str = "testing logging with storage";
log_debug!(logger, "{}", log_str);
Expand Down
20 changes: 14 additions & 6 deletions mutiny-core/src/nodemanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -580,15 +580,23 @@ impl<S: MutinyStorage> NodeManager<S> {
/// Creates a new [NodeManager] with the given parameters.
/// The mnemonic seed is read from storage, unless one is provided.
/// If no mnemonic is provided, a new one is generated and stored.
pub async fn new(c: MutinyWalletConfig, storage: S) -> Result<NodeManager<S>, MutinyError> {
pub async fn new(
c: MutinyWalletConfig,
storage: S,
session_id: Option<String>,
) -> Result<NodeManager<S>, MutinyError> {
let stop = Arc::new(AtomicBool::new(false));

#[cfg(target_arch = "wasm32")]
let websocket_proxy_addr = c
.websocket_proxy_addr
.unwrap_or_else(|| String::from("wss://p.mutinywallet.com"));

let logger = Arc::new(MutinyLogger::with_writer(stop.clone(), storage.clone()));
let logger = Arc::new(MutinyLogger::with_writer(
stop.clone(),
storage.clone(),
session_id,
));

// Need to prevent other devices from running at the same time
if !c.skip_device_lock {
Expand Down Expand Up @@ -2745,7 +2753,7 @@ mod tests {
None,
false,
);
NodeManager::new(c, storage.clone())
NodeManager::new(c, storage.clone(), None)
.await
.expect("node manager should initialize");
storage.insert_mnemonic(seed).unwrap();
Expand Down Expand Up @@ -2775,7 +2783,7 @@ mod tests {
None,
false,
);
let nm = NodeManager::new(c, storage)
let nm = NodeManager::new(c, storage, None)
.await
.expect("node manager should initialize");

Expand Down Expand Up @@ -2828,7 +2836,7 @@ mod tests {
);
let c = c.with_safe_mode();

let nm = NodeManager::new(c, storage)
let nm = NodeManager::new(c, storage, None)
.await
.expect("node manager should initialize");

Expand Down Expand Up @@ -2862,7 +2870,7 @@ mod tests {
None,
false,
);
let nm = NodeManager::new(c, storage)
let nm = NodeManager::new(c, storage, None)
.await
.expect("node manager should initialize");

Expand Down
10 changes: 8 additions & 2 deletions mutiny-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,9 @@ impl MutinyWallet {
config = config.with_safe_mode();
}

let inner = mutiny_core::MutinyWallet::new(storage, config).await?;
let inner =
mutiny_core::MutinyWallet::new(storage, config, Some(logger.session_id.clone()))
.await?;
Ok(MutinyWallet { mnemonic, inner })
}

Expand Down Expand Up @@ -1203,7 +1205,11 @@ impl MutinyWallet {
.transpose()?;
let storage = IndexedDbStorage::new(password, cipher, None, logger.clone()).await?;
let stop = Arc::new(AtomicBool::new(false));
let logger = Arc::new(MutinyLogger::with_writer(stop.clone(), storage.clone()));
let logger = Arc::new(MutinyLogger::with_writer(
stop.clone(),
storage.clone(),
None,
));
let res = JsValue::from_serde(&NodeManager::get_logs(storage, logger)?)?;
stop.swap(true, Ordering::Relaxed);
Ok(res)
Expand Down

0 comments on commit 0bfe14d

Please sign in to comment.