Skip to content

Commit

Permalink
wip(feat): reissue ecash notes from OOBNotes`
Browse files Browse the repository at this point in the history
  • Loading branch information
oleonardolima committed Feb 17, 2024
1 parent 9e1f35a commit 72fda2a
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 1 deletion.
Empty file added .editorconfig
Empty file.
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions mutiny-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ pub enum MutinyError {
/// Payjoin configuration error
#[error("Payjoin configuration failed.")]
PayjoinConfigError,
#[error("Fedimint external note reissuance failed.")]
FedimintReissueFailed,
#[error(transparent)]
Other(#[from] anyhow::Error),
}
Expand Down
57 changes: 56 additions & 1 deletion mutiny-core/src/federation.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::utils::{convert_from_fedimint_invoice, convert_to_fedimint_invoice, spawn};
use crate::DEFAULT_REISSUE_TIMEOUT;
use crate::{
error::{MutinyError, MutinyStorageError},
event::PaymentInfo,
Expand All @@ -12,6 +13,7 @@ use crate::{
HTLCStatus, MutinyInvoice, DEFAULT_PAYMENT_TIMEOUT,
};
use async_trait::async_trait;
use bip39::rand_core::le;
use bip39::Mnemonic;
use bitcoin::secp256k1::ThirtyTwoByteHash;
use bitcoin::{
Expand Down Expand Up @@ -52,7 +54,7 @@ use fedimint_ln_client::{
};
use fedimint_ln_common::lightning_invoice::RoutingFees;
use fedimint_ln_common::LightningCommonInit;
use fedimint_mint_client::MintClientInit;
use fedimint_mint_client::{MintClientInit, MintClientModule, OOBNotes, ReissueExternalNotesState};
use fedimint_wallet_client::{WalletClientInit, WalletClientModule};
use futures::future::{self};
use futures_util::{pin_mut, StreamExt};
Expand Down Expand Up @@ -603,6 +605,59 @@ impl<S: MutinyStorage> FederationClient<S> {
}
}

pub(crate) async fn reissue(&self, oob_notes: OOBNotes) -> Result<bool, MutinyError> {
let logger = Arc::clone(&self.logger);

// Get the `MintClientModule`
let mint_module = self.fedimint_client.get_first_module::<MintClientModule>();

// TODO: (@leonardo) Do we need any `extra_meta` ?
// Reissue `OOBNotes`
let operation_id = mint_module.reissue_external_notes(oob_notes, ()).await?;

// Subscribe/Process the outcome based on `ReissueExternalNotesState`
let mut stream_or_outcome = mint_module
.subscribe_reissue_external_notes(operation_id)
.await
.map_err(|e| MutinyError::Other(e))?;

let mut reissue_state = ReissueExternalNotesState::Created;

let _ = match stream_or_outcome {
UpdateStreamOrOutcome::Outcome(outcome) => {
reissue_state = outcome;
log_trace!(logger, "Outcome received: {:?}", reissue_state);
}
UpdateStreamOrOutcome::UpdateStream(mut stream) => {
let timeout = DEFAULT_REISSUE_TIMEOUT * 1_000;
let timeout_future = sleep(timeout as i32);
pin_mut!(timeout_future);

log_trace!(logger, "Start timeout stream features");
while let future::Either::Left((outcome_opt, _)) =
future::select(stream.next(), &mut timeout_future).await
{
if let Some(outcome) = outcome_opt {
reissue_state = outcome;
log_trace!(logger, "Streamed Outcome received: {:?}", reissue_state);
if let ReissueExternalNotesState::Failed(_) = reissue_state {
log_trace!(logger, "Streamed Outcome final, returning");
break;
}
}
}
}
};

// TODO: (@leonardo) re-think about the results and errors that we need/want
match reissue_state {
ReissueExternalNotesState::Created | ReissueExternalNotesState::Failed(_) => {
Err(MutinyError::FedimintReissueFailed)
}
_ => Ok(true),
}
}

pub async fn get_mutiny_federation_identity(&self) -> FederationIdentity {
let gateway_fees = self.gateway_fee().await.ok();

Expand Down
18 changes: 18 additions & 0 deletions mutiny-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ use bitcoin::hashes::Hash;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{hashes::sha256, Network};
use fedimint_core::{api::InviteCode, config::FederationId};
use fedimint_mint_client::OOBNotes;
use futures::{pin_mut, select, FutureExt};
use futures_util::join;
use hex_conservative::{DisplayHex, FromHex};
Expand Down Expand Up @@ -113,6 +114,7 @@ use crate::utils::parse_profile_metadata;
use mockall::{automock, predicate::*};

const DEFAULT_PAYMENT_TIMEOUT: u64 = 30;
const DEFAULT_REISSUE_TIMEOUT: u64 = 30;
const MAX_FEDERATION_INVOICE_AMT: u64 = 200_000;
const SWAP_LABEL: &str = "SWAP";

Expand Down Expand Up @@ -1308,6 +1310,22 @@ impl<S: MutinyStorage> MutinyWallet<S> {
})
}

pub async fn reissue_oob_notes(&self, oob_notes: OOBNotes) -> Result<bool, MutinyError> {
let federation_lock = self.federations.read().await;
let federation_ids = self.list_federation_ids().await?;

let maybe_federation_id = federation_ids
.iter()
.find(|id| id.to_prefix() == oob_notes.federation_id_prefix());

if let Some(fed_id) = maybe_federation_id {
let fedimint_client = federation_lock.get(&fed_id).ok_or(MutinyError::NotFound)?;
Ok(fedimint_client.reissue(oob_notes).await?)
} else {
return Err(MutinyError::NotFound);
}
}

/// Estimate the fee before trying to sweep from federation
pub async fn estimate_sweep_federation_fee(
&self,
Expand Down
1 change: 1 addition & 0 deletions mutiny-wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ once_cell = "1.18.0"
hex-conservative = "0.1.1"
payjoin = { version = "0.13.0", features = ["send", "base64"] }
fedimint-core = { git = "https://github.com/fedimint/fedimint", rev = "6a923ee10c3a578cd835044e3fdd94aa5123735a" }
fedimint-mint-client = { git = "https://github.com/fedimint/fedimint", rev = "6a923ee10c3a578cd835044e3fdd94aa5123735a" }

# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
Expand Down
3 changes: 3 additions & 0 deletions mutiny-wasm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ pub enum MutinyJsError {
/// Payjoin configuration error
#[error("Payjoin configuration failed.")]
PayjoinConfigError,
#[error("Fedimint external note reissuance failed.")]
FedimintReissueFailed,
/// Unknown error.
#[error("Unknown Error")]
UnknownError,
Expand Down Expand Up @@ -226,6 +228,7 @@ impl From<MutinyError> for MutinyJsError {
MutinyError::PayjoinConfigError => MutinyJsError::PayjoinConfigError,
MutinyError::PayjoinCreateRequest => MutinyJsError::PayjoinCreateRequest,
MutinyError::PayjoinResponse(e) => MutinyJsError::PayjoinResponse(e.to_string()),
MutinyError::FedimintReissueFailed => MutinyJsError::FedimintReissueFailed,
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions mutiny-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use bitcoin::hashes::sha256;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{Address, Network, OutPoint, Transaction, Txid};
use fedimint_core::{api::InviteCode, config::FederationId};
use fedimint_mint_client::OOBNotes;
use futures::lock::Mutex;
use gloo_utils::format::JsValueSerdeExt;
use hex_conservative::DisplayHex;
Expand Down Expand Up @@ -1023,6 +1024,17 @@ impl MutinyWallet {
Ok(self.inner.sweep_federation_balance(amount).await?.into())
}

pub async fn reissue_oob_notes(&self, oob_notes: String) -> Result<bool, MutinyJsError> {
let notes = OOBNotes::from_str(&oob_notes).map_err(|e| {
log_error!(
self.inner.logger,
"Error parsing federation `OOBNotes` ({oob_notes}): {e}"
);
MutinyJsError::InvalidArgumentsError
})?;
Ok(self.inner.reissue_oob_notes(notes).await?)
}

/// Estimate the fee before trying to sweep from federation
pub async fn estimate_sweep_federation_fee(
&self,
Expand Down

0 comments on commit 72fda2a

Please sign in to comment.