Skip to content

Commit

Permalink
feat: nut-08 lightning fee return in wallet
Browse files Browse the repository at this point in the history
  • Loading branch information
ngutech21 committed Nov 29, 2023
1 parent 19d5677 commit c969e26
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 10 deletions.
2 changes: 1 addition & 1 deletion moksha-core/src/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ fn split_amount(amount: u64) -> Vec<u64> {
.collect::<Vec<u64>>()
}

fn generate_random_string() -> String {
pub fn generate_random_string() -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(24)
Expand Down
67 changes: 60 additions & 7 deletions moksha-core/src/blind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@
//!
//! The `TotalAmount` trait is also defined in this module, which provides a `total_amount` method for calculating the total amount of a vector of `BlindedMessage` or `BlindedSignature` structs. The trait is implemented for both `Vec<BlindedMessage>` and `Vec<BlindedSignature>`.
use secp256k1::PublicKey;
use secp256k1::{PublicKey, SecretKey};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlindedMessage {
pub amount: u64,
#[serde(rename = "B_")]
pub b_: PublicKey,
}
use crate::{
amount::{generate_random_string, Amount},
dhke::Dhke,
error::MokshaCoreError,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlindedSignature {
Expand All @@ -26,6 +25,37 @@ pub struct BlindedSignature {
pub id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlindedMessage {
pub amount: u64,
#[serde(rename = "B_")]
pub b_: PublicKey,
}

impl BlindedMessage {
pub fn blank(
fee_reserve: Amount,
) -> Result<Vec<(BlindedMessage, SecretKey, String)>, MokshaCoreError> {
if fee_reserve.0 == 0 {
return Ok(vec![]);
}

let fee_reserve_float = fee_reserve.0 as f64;
let count = (fee_reserve_float.log2().ceil() as u64).max(1);
let dhke = Dhke::new();

let blinded_messages = (0..count)
.map(|_| {
let secret = generate_random_string();
let (b_, alice_secret_key) = dhke.step1_alice(secret.clone(), None).unwrap(); // FIXME
(BlindedMessage { amount: 0, b_ }, alice_secret_key, secret)
})
.collect::<Vec<(BlindedMessage, SecretKey, String)>>();

Ok(blinded_messages)
}
}

pub trait TotalAmount {
fn total_amount(&self) -> u64;
}
Expand All @@ -41,3 +71,26 @@ impl TotalAmount for Vec<BlindedMessage> {
self.iter().fold(0, |acc, x| acc + x.amount)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_1000_sats() {
let result = BlindedMessage::blank(1000.into());
println!("{:?}", result);
assert!(result.is_ok());
let result = result.unwrap();
assert!(result.clone().len() == 10);
assert!(result.get(0).unwrap().0.amount == 0);
}

#[test]
fn test_zero_sats() {
let result = BlindedMessage::blank(0.into());
println!("{:?}", result);
assert!(result.is_ok());
assert!(result.unwrap().is_empty());
}
}
32 changes: 30 additions & 2 deletions moksha-wallet/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,38 @@ impl<C: Client, L: LocalStore> Wallet<C, L> {
split_result.1.proofs()
};

match self.melt_token(invoice, ln_amount, &total_proofs).await {
let fee_blind = BlindedMessage::blank(fees.fee.into())?;

let msgs = fee_blind
.iter()
.map(|(msg, _, _)| msg.clone())
.collect::<Vec<BlindedMessage>>();

let secrets = fee_blind
.iter()
.map(|(_, _, secret)| secret.clone())
.collect::<Vec<String>>();

let outputs = fee_blind
.iter()
.map(|(msg, secret, _)| (msg.clone(), secret.to_owned()))
.collect::<Vec<(BlindedMessage, SecretKey)>>();

match self
.melt_token(invoice, ln_amount, &total_proofs, msgs)
.await
{
Ok(response) => {
if !response.paid {
self.localstore.add_proofs(&total_proofs).await?;
}
let change_proofs = self.create_proofs_from_blinded_signatures(
response.clone().change,
secrets,
outputs,
)?;
self.localstore.add_proofs(&change_proofs).await?;

Ok(response)
}
Err(e) => {
Expand Down Expand Up @@ -268,10 +295,11 @@ impl<C: Client, L: LocalStore> Wallet<C, L> {
pr: String,
_invoice_amount: u64,
proofs: &Proofs,
fee_blinded_messages: Vec<BlindedMessage>,
) -> Result<PostMeltResponse, MokshaWalletError> {
let melt_response = self
.client
.post_melt_tokens(&self.mint_url, proofs.clone(), pr, vec![])
.post_melt_tokens(&self.mint_url, proofs.clone(), pr, fee_blinded_messages)
.await?;

if melt_response.paid {
Expand Down

0 comments on commit c969e26

Please sign in to comment.