Skip to content

Commit

Permalink
Merge pull request fedimint#448 from evanlinjin/refactor_client_lib
Browse files Browse the repository at this point in the history
Remove unnecessary struct `BorrowedClientContext`
  • Loading branch information
elsirion authored Aug 24, 2022
2 parents 85e6602 + 83ce8df commit d1e696d
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 131 deletions.
89 changes: 35 additions & 54 deletions client/client-lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ pub mod transaction;
pub mod utils;
pub mod wallet;

use std::time::Duration;
use std::time::SystemTime;
use std::{sync::Arc, time::Duration};

use futures::StreamExt;

Expand Down Expand Up @@ -64,7 +64,7 @@ use crate::ln::LnClientError;
use crate::mint::db::{CoinKey, PendingCoinsKeyPrefix};
use crate::mint::{CoinFinalizationData, MintClientError};
use crate::transaction::TransactionBuilder;
use crate::utils::{network_to_currency, OwnedClientContext};
use crate::utils::{network_to_currency, ClientContext};
use crate::wallet::WalletClientError;
use crate::{
api::{ApiError, FederationApi},
Expand Down Expand Up @@ -110,7 +110,8 @@ impl From<GatewayClientConfig> for LightningGateway {
}

pub struct Client<C> {
context: Arc<OwnedClientContext<C>>,
config: C,
context: ClientContext,
}

impl AsRef<ClientConfig> for GatewayClientConfig {
Expand All @@ -128,30 +129,27 @@ impl AsRef<ClientConfig> for UserClientConfig {
impl<T: AsRef<ClientConfig> + Clone> Client<T> {
pub fn ln_client(&self) -> LnClient {
LnClient {
context: self
.context
.borrow_with_module_config(|cfg| &cfg.as_ref().ln),
config: &self.config.as_ref().ln,
context: &self.context,
}
}

pub fn mint_client(&self) -> MintClient {
MintClient {
context: self
.context
.borrow_with_module_config(|cfg| &cfg.as_ref().mint),
config: &self.config.as_ref().mint,
context: &self.context,
}
}

pub fn wallet_client(&self) -> WalletClient {
WalletClient {
context: self
.context
.borrow_with_module_config(|cfg| &cfg.as_ref().wallet),
config: &self.config.as_ref().wallet,
context: &self.context,
}
}

pub fn config(&self) -> T {
self.context.config.clone()
self.config.clone()
}

pub fn new(config: T, db: Box<dyn Database>, secp: Secp256k1<All>) -> Self {
Expand All @@ -178,13 +176,10 @@ impl<T: AsRef<ClientConfig> + Clone> Client<T> {
api: Box<dyn FederationApi>,
secp: Secp256k1<All>,
) -> Client<T> {
let context = Arc::new(OwnedClientContext {
Self {
config,
db,
api,
secp,
});
Self { context }
context: ClientContext { db, api, secp },
}
}

pub async fn peg_in<R: RngCore + CryptoRng>(
Expand Down Expand Up @@ -213,12 +208,7 @@ impl<T: AsRef<ClientConfig> + Clone> Client<T> {
) -> Result<TransactionId> {
Ok(self
.mint_client()
.submit_tx_with_change(
&self.context.config.as_ref().fee_consensus(),
tx,
batch,
rng,
)
.submit_tx_with_change(&self.config.as_ref().fee_consensus(), tx, batch, rng)
.await?)
}

Expand Down Expand Up @@ -297,13 +287,7 @@ impl<T: AsRef<ClientConfig> + Clone> Client<T> {
let batch = DbBatch::new();
let mut tx = TransactionBuilder::default();

let funding_amount = self
.context
.config
.as_ref()
.wallet
.fee_consensus
.peg_out_abs
let funding_amount = self.config.as_ref().wallet.fee_consensus.peg_out_abs
+ (peg_out.amount + peg_out.fees.amount()).into();
let coins = self.mint_client().select_coins(funding_amount)?;
tx.input_coins(coins, &self.context.secp)?;
Expand Down Expand Up @@ -541,21 +525,20 @@ impl Client<UserClientConfig> {
let duration_since_epoch =
Duration::from_secs_f64(js_sys::Date::new_0().get_time() / 1000.);

let invoice =
InvoiceBuilder::new(network_to_currency(self.context.config.0.wallet.network))
.amount_milli_satoshis(amount.milli_sat)
.description(description)
.payment_hash(payment_hash)
.payment_secret(payment_secret)
.duration_since_epoch(duration_since_epoch)
.min_final_cltv_expiry(18)
.payee_pub_key(node_public_key)
.private_route(gateway_route_hint)
.build_signed(|hash| {
self.context
.secp
.sign_ecdsa_recoverable(hash, &node_secret_key)
})?;
let invoice = InvoiceBuilder::new(network_to_currency(self.config.0.wallet.network))
.amount_milli_satoshis(amount.milli_sat)
.description(description)
.payment_hash(payment_hash)
.payment_secret(payment_secret)
.duration_since_epoch(duration_since_epoch)
.min_final_cltv_expiry(18)
.payee_pub_key(node_public_key)
.private_route(gateway_route_hint)
.build_signed(|hash| {
self.context
.secp
.sign_ecdsa_recoverable(hash, &node_secret_key)
})?;

let offer_output =
self.ln_client()
Expand Down Expand Up @@ -641,8 +624,7 @@ impl Client<GatewayClientConfig> {
&self,
account: &OutgoingContractAccount,
) -> Result<PaymentParameters> {
let our_pub_key =
secp256k1_zkp::XOnlyPublicKey::from_keypair(&self.context.config.redeem_key);
let our_pub_key = secp256k1_zkp::XOnlyPublicKey::from_keypair(&self.config.redeem_key);

if account.contract.gateway_key != our_pub_key {
return Err(ClientError::NotOurKey);
Expand Down Expand Up @@ -672,7 +654,7 @@ impl Client<GatewayClientConfig> {
// margin.
let max_delay = (account.contract.timelock as u64)
.checked_sub(consensus_block_height)
.and_then(|delta| delta.checked_sub(self.context.config.timelock_delta))
.and_then(|delta| delta.checked_sub(self.config.timelock_delta))
.ok_or(ClientError::TimeoutTooClose)?;

Ok(PaymentParameters {
Expand Down Expand Up @@ -738,7 +720,7 @@ impl Client<GatewayClientConfig> {
batch.append_insert(OutgoingPaymentClaimKey(contract_id), ());
});

tx.input(&mut vec![self.context.config.redeem_key], input);
tx.input(&mut vec![self.config.redeem_key], input);
let txid = self.submit_tx_with_change(tx, batch, rng).await?;

Ok(OutPoint { txid, out_idx: 0 })
Expand All @@ -764,8 +746,7 @@ impl Client<GatewayClientConfig> {
builder.input_coins(coins, &self.context.secp)?;

// Outputs
let our_pub_key =
secp256k1_zkp::XOnlyPublicKey::from_keypair(&self.context.config.redeem_key);
let our_pub_key = secp256k1_zkp::XOnlyPublicKey::from_keypair(&self.config.redeem_key);
let contract = Contract::Incoming(IncomingContract {
hash: offer.hash,
encrypted_preimage: offer.encrypted_preimage.clone(),
Expand Down Expand Up @@ -801,7 +782,7 @@ impl Client<GatewayClientConfig> {

// Input claims this contract
builder.input(
&mut vec![self.context.config.redeem_key],
&mut vec![self.config.redeem_key],
Input::LN(contract_account.claim()),
);
let mint_tx_id = self.submit_tx_with_change(builder, batch, rng).await?;
Expand Down
25 changes: 14 additions & 11 deletions client/client-lib/src/ln/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::api::ApiError;
use crate::ln::db::{OutgoingPaymentKey, OutgoingPaymentKeyPrefix};
use crate::ln::incoming::IncomingContractAccount;
use crate::ln::outgoing::{OutgoingContractAccount, OutgoingContractData};
use crate::utils::BorrowedClientContext;
use crate::utils::ClientContext;
use bitcoin_hashes::sha256::Hash as Sha256Hash;
use fedimint_api::db::batch::BatchTx;
use fedimint_api::Amount;
Expand All @@ -29,7 +29,8 @@ use self::db::ConfirmedInvoiceKey;
use self::incoming::ConfirmedInvoice;

pub struct LnClient<'c> {
pub context: BorrowedClientContext<'c, LightningModuleClientConfig>,
pub config: &'c LightningModuleClientConfig,
pub context: &'c ClientContext,
}

#[allow(dead_code)]
Expand All @@ -54,7 +55,7 @@ impl<'c> LnClient<'c> {
Amount::from_msat(contract_amount_msat)
};

let user_sk = bitcoin::KeyPair::new(self.context.secp, &mut rng);
let user_sk = bitcoin::KeyPair::new(&self.context.secp, &mut rng);

let contract = OutgoingContract {
hash: *invoice.payment_hash(),
Expand Down Expand Up @@ -147,7 +148,7 @@ impl<'c> LnClient<'c> {
hash: payment_hash,
encrypted_preimage: EncryptedPreimage::new(
payment_secret,
&self.context.config.threshold_pub_key,
&self.config.threshold_pub_key,
),
})
}
Expand Down Expand Up @@ -196,7 +197,7 @@ pub enum LnClientError {
mod tests {
use crate::api::FederationApi;
use crate::ln::LnClient;
use crate::OwnedClientContext;
use crate::ClientContext;
use async_trait::async_trait;
use bitcoin::Address;
use fedimint_api::db::batch::DbBatch;
Expand Down Expand Up @@ -290,7 +291,8 @@ mod tests {

async fn new_mint_and_client() -> (
Arc<tokio::sync::Mutex<Fed>>,
OwnedClientContext<LightningModuleClientConfig>,
LightningModuleClientConfig,
ClientContext,
) {
let fed = Arc::new(tokio::sync::Mutex::new(
FakeFed::<LightningModule, LightningModuleClientConfig>::new(
Expand All @@ -302,24 +304,25 @@ mod tests {
.await,
));
let api = FakeApi { mint: fed.clone() };
let client_config = fed.lock().await.client_cfg().clone();

let client_context = OwnedClientContext {
config: fed.lock().await.client_cfg().clone(),
let client_context = ClientContext {
db: Box::new(MemDatabase::new()),
api: Box::new(api),
secp: secp256k1_zkp::Secp256k1::new(),
};

(fed, client_context)
(fed, client_config, client_context)
}

#[test_log::test(tokio::test)]
async fn test_outgoing() {
let mut rng = rand::thread_rng();
let (fed, client_context) = new_mint_and_client().await;
let (fed, client_config, client_context) = new_mint_and_client().await;

let client = LnClient {
context: client_context.borrow_with_module_config(|x| x),
config: &client_config,
context: &client_context,
};

fed.lock().await.set_block_height(1);
Expand Down
Loading

0 comments on commit d1e696d

Please sign in to comment.