Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
binarybaron committed Nov 21, 2024
1 parent 83314b6 commit fc2b05b
Show file tree
Hide file tree
Showing 5 changed files with 161 additions and 69 deletions.
90 changes: 49 additions & 41 deletions src-gui/src/renderer/components/alert/DaemonStatusAlert.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Box, Button, LinearProgress, makeStyles } from "@material-ui/core";
import { Alert } from "@material-ui/lab";
import { TauriContextInitializationProgress } from "models/tauriModel";
import { useNavigate } from "react-router-dom";
import { useAppSelector } from "store/hooks";
import { exhaustiveGuard } from "utils/typescriptUtils";
Expand All @@ -20,51 +19,60 @@ export default function DaemonStatusAlert() {
const contextStatus = useAppSelector((s) => s.rpc.status);
const navigate = useNavigate();

if (contextStatus === null) {
if (contextStatus === null || contextStatus.type === "NotInitialized") {
return <LoadingSpinnerAlert severity="warning">Checking for available remote nodes</LoadingSpinnerAlert>;
}

switch (contextStatus.type) {
case "Initializing":
switch (contextStatus.content.type) {
case "OpeningBitcoinWallet":
return (
<LoadingSpinnerAlert severity="warning">
Connecting to the Bitcoin network
</LoadingSpinnerAlert>
);
case "DownloadingMoneroWalletRpc":
return (
<LoadingSpinnerAlert severity="warning">
<Box className={classes.innerAlert}>
<Box>
Downloading and verifying the Monero wallet RPC (
{bytesToMb(contextStatus.content.content.size).toFixed(2)} MB)
</Box>
<LinearProgress variant="determinate" value={contextStatus.content.content.progress} />
</Box>
</LoadingSpinnerAlert >
);
case "OpeningMoneroWallet":
return (
<LoadingSpinnerAlert severity="warning">
Connecting to the Monero network
</LoadingSpinnerAlert>
);
case "OpeningDatabase":
return (
<LoadingSpinnerAlert severity="warning">
Opening the local database
</LoadingSpinnerAlert>
);
case "EstablishingTorCircuits":
return (
<LoadingSpinnerAlert severity="warning">
Connecting to the Tor network
</LoadingSpinnerAlert>
);
}
break;
return contextStatus.content
.map((status) => {
if (status.progress.type === "Completed") {
return null;
}

switch (status.componentName) {
case "OpeningBitcoinWallet":
return (
<LoadingSpinnerAlert severity="warning">
Syncing internal Bitcoin wallet
</LoadingSpinnerAlert>
);
case "DownloadingMoneroWalletRpc":
return (
<LoadingSpinnerAlert severity="warning">
<Box className={classes.innerAlert}>
<Box>
Downloading and verifying the Monero wallet RPC (
{bytesToMb(status.progress.content.size).toFixed(2)} MB)
</Box>
<LinearProgress variant="determinate" value={status.progress.content.progress} />
</Box>
</LoadingSpinnerAlert >
);
case "OpeningMoneroWallet":
return (
<LoadingSpinnerAlert severity="warning">
Opening the Monero wallet
</LoadingSpinnerAlert>
);
case "OpeningDatabase":
return (
<LoadingSpinnerAlert severity="warning">
Opening the local database
</LoadingSpinnerAlert>
);
case "EstablishingTorCircuits":
return (
<LoadingSpinnerAlert severity="warning">
Establishing Tor circuits
</LoadingSpinnerAlert>
)
default:
return exhaustiveGuard(status.componentName);
}
})
.filter((s) => s !== null);
case "Available":
return <Alert severity="success">The daemon is running</Alert>;
case "Failed":
Expand Down
20 changes: 18 additions & 2 deletions src-gui/src/store/features/rpcSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,26 @@ export const rpcSlice = createSlice({
slice,
action: PayloadAction<TauriContextStatusEvent>,
) {
slice.status = action.payload;
// If we are already initializing, and we receive a new partial status, we update the existing status
if (slice.status?.type === "Initializing" && action.payload.type === "Initializing") {
for (const partialStatus of action.payload.content) {
// We find the existing status with the same type
const existingStatus = slice.status.content.find(s => s.componentName === partialStatus.componentName);
if (existingStatus) {
// If we find it, we update the content
existingStatus.progress = partialStatus.progress;
} else {
// Otherwise, we add the new partial status
slice.status.content.push(partialStatus);
}
}
} else {
// Otherwise, we replace the whole status
slice.status = action.payload;
}
},
timelockChangeEventReceived(
slice,
slice: RPCSlice,
action: PayloadAction<TauriTimelockChangeEvent>
) {
if (slice.state.swapInfos[action.payload.swap_id]) {
Expand Down
51 changes: 50 additions & 1 deletion swap/src/cli/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use std::future::Future;
use std::path::PathBuf;
use std::sync::{Arc, Mutex as SyncMutex, Once};
use tauri_bindings::{
TauriContextInitializationProgress, TauriContextStatusEvent, TauriEmitter, TauriHandle,
PendingCompleted, TauriContextStatusEvent, TauriEmitter, TauriHandle, TauriPartialInitProgress,
};
use tokio::sync::{broadcast, broadcast::Sender, Mutex as TokioMutex, RwLock};
use tokio::task::JoinHandle;
Expand Down Expand Up @@ -315,10 +315,26 @@ impl ContextBuilder {
Some(bitcoin) => {
let (url, target_block) = bitcoin.apply_defaults(self.is_testnet)?;

self.tauri_handle.emit_context_init_progress_event(
TauriContextStatusEvent::Initializing(vec![
TauriPartialInitProgress::OpeningBitcoinWallet(
PendingCompleted::Pending(()),
),
]),
);

let wallet =
init_bitcoin_wallet(url, &seed, data_dir.clone(), env_config, target_block)
.await?;

self.tauri_handle.emit_context_init_progress_event(
TauriContextStatusEvent::Initializing(vec![
TauriPartialInitProgress::OpeningBitcoinWallet(
PendingCompleted::Completed,
),
]),
);

Ok::<std::option::Option<Arc<bitcoin::wallet::Wallet>>, Error>(Some(Arc::new(
wallet,
)))
Expand All @@ -332,6 +348,14 @@ impl ContextBuilder {
Some(monero) => {
let monero_daemon_address = monero.apply_defaults(self.is_testnet);

self.tauri_handle.emit_context_init_progress_event(
TauriContextStatusEvent::Initializing(vec![
TauriPartialInitProgress::OpeningMoneroWallet(
PendingCompleted::Pending(()),
),
]),
);

let (wlt, prc) = init_monero_wallet(
data_dir.clone(),
monero_daemon_address,
Expand All @@ -340,20 +364,42 @@ impl ContextBuilder {
)
.await?;

self.tauri_handle.emit_context_init_progress_event(
TauriContextStatusEvent::Initializing(vec![
TauriPartialInitProgress::OpeningMoneroWallet(
PendingCompleted::Completed,
),
]),
);

Ok((Some(Arc::new(wlt)), Some(Arc::new(SyncMutex::new(prc)))))
}
None => Ok((None, None)),
}
};

let initialize_tor_client = async {
self.tauri_handle.emit_context_init_progress_event(
TauriContextStatusEvent::Initializing(vec![
TauriPartialInitProgress::EstablishingTorCircuits(
PendingCompleted::Pending(()),
),
]),
);

let maybe_tor_client = init_tor_client(&data_dir)
.await
.inspect_err(|err| {
tracing::warn!(%err, "Failed to create Tor client. We will continue without Tor");
})
.ok();

self.tauri_handle.emit_context_init_progress_event(
TauriContextStatusEvent::Initializing(vec![
TauriPartialInitProgress::EstablishingTorCircuits(PendingCompleted::Completed),
]),
);

Ok(maybe_tor_client)
};

Expand All @@ -376,6 +422,9 @@ impl ContextBuilder {
}
}

self.tauri_handle
.emit_context_init_progress_event(TauriContextStatusEvent::Available);

let context = Context {
db,
bitcoin_wallet,
Expand Down
40 changes: 26 additions & 14 deletions swap/src/cli/api/tauri_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,27 +111,39 @@ impl TauriEmitter for Option<TauriHandle> {
#[typeshare]
#[derive(Display, Clone, Serialize)]
#[serde(tag = "type", content = "content")]
pub enum TauriContextInitializationProgress {
OpeningBitcoinWallet,
DownloadingMoneroWalletRpc {
// Progress of the download in percent (0-100)
#[typeshare(serialized_as = "number")]
progress: u64,
// Size of the download file in bytes
#[typeshare(serialized_as = "number")]
size: u64,
},
OpeningMoneroWallet,
OpeningDatabase,
EstablishingTorCircuits,
pub enum PendingCompleted<P> {
Pending(P),
Completed,
}

#[derive(Serialize, Clone)]
#[typeshare]
pub struct DownloadProgress {
// Progress of the download in percent (0-100)
#[typeshare(serialized_as = "number")]
pub progress: u64,
// Size of the download file in bytes
#[typeshare(serialized_as = "number")]
pub size: u64,
}

#[typeshare]
#[derive(Display, Clone, Serialize)]
#[serde(tag = "componentName", content = "progress")]
pub enum TauriPartialInitProgress {
OpeningBitcoinWallet(PendingCompleted<()>),
DownloadingMoneroWalletRpc(PendingCompleted<DownloadProgress>),
OpeningMoneroWallet(PendingCompleted<()>),
OpeningDatabase(PendingCompleted<()>),
EstablishingTorCircuits(PendingCompleted<()>),
}

#[typeshare]
#[derive(Display, Clone, Serialize)]
#[serde(tag = "type", content = "content")]
pub enum TauriContextStatusEvent {
NotInitialized,
Initializing(TauriContextInitializationProgress),
Initializing(Vec<TauriPartialInitProgress>),
Available,
Failed,
}
Expand Down
29 changes: 18 additions & 11 deletions swap/src/monero/wallet_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ use tokio_util::codec::{BytesCodec, FramedRead};
use tokio_util::io::StreamReader;

use crate::cli::api::tauri_bindings::{
TauriContextInitializationProgress, TauriContextStatusEvent, TauriEmitter, TauriHandle,
DownloadProgress, PendingCompleted, TauriPartialInitProgress,
TauriContextStatusEvent, TauriEmitter, TauriHandle,
};

// See: https://www.moneroworld.com/#nodes, https://monero.fail
Expand Down Expand Up @@ -264,10 +265,14 @@ impl WalletRpc {

// Emit a tauri event to update the progress
tauri_handle.emit_context_init_progress_event(TauriContextStatusEvent::Initializing(
TauriContextInitializationProgress::DownloadingMoneroWalletRpc {
progress: 0,
size: content_length,
},
vec![
TauriPartialInitProgress::DownloadingMoneroWalletRpc(
PendingCompleted::Pending(DownloadProgress {
progress: 0,
size: content_length,
}),
),
],
));

let mut hasher = Sha256::new();
Expand Down Expand Up @@ -310,12 +315,14 @@ impl WalletRpc {

// Emit a tauri event to update the progress
tauri_handle.emit_context_init_progress_event(
TauriContextStatusEvent::Initializing(
TauriContextInitializationProgress::DownloadingMoneroWalletRpc {
progress: percent,
size: content_length,
},
),
TauriContextStatusEvent::Initializing(vec![
TauriPartialInitProgress::DownloadingMoneroWalletRpc(
PendingCompleted::Pending(DownloadProgress {
progress: percent,
size: content_length,
}),
),
]),
);
}
file.write_all(&bytes).await?;
Expand Down

0 comments on commit fc2b05b

Please sign in to comment.