Skip to content

Commit

Permalink
chore: Minimise need to depend on rust-dlc in other crates
Browse files Browse the repository at this point in the history
This dependency should ideally only be known by core crates such as
`ln-dlc-node`.

We define a method `get_new_address` on `Node` so that we can control
how we call the underlying on-chain wallet, rather than letting
consumers call the wallet through a trait that is designed for a
completely different purpose.

We also turn the generic `get_dlcs` API into the more specific
`get_confirmed_dlcs`, as this is the only thing that is currently
needed. This way we can avoid consumers needing to understand types
defined by `rust-dlc`. The `get_confirmed_dlcs` API and the matching
`Dlc` type should evolve (and perhaps even disappear) as we meet new
requirements.
  • Loading branch information
luckysori committed Mar 7, 2023
1 parent c5c95ba commit 09d9710
Show file tree
Hide file tree
Showing 11 changed files with 64 additions and 34 deletions.
2 changes: 0 additions & 2 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion coordinator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ bitcoin = "0.29"
clap = { version = "4", features = ["derive"] }
diesel = { version = "2.0.0", features = ["r2d2", "postgres"] }
diesel_migrations = "2.0.0"
dlc-manager = { version = "0.4.0", features = ["use-serde"] }
dlc-manager = { version = "0.4.0", features = ["use-serde"] } # required for the ContractInput type
futures = "0.3"
ln-dlc-node = { path = "../crates/ln-dlc-node" }
rand = "0.8.5"
Expand Down
9 changes: 4 additions & 5 deletions coordinator/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use diesel::r2d2::ConnectionManager;
use diesel::r2d2::Pool;
use diesel::PgConnection;
use dlc_manager::contract::contract_input::ContractInput;
use dlc_manager::Wallet;
use ln_dlc_node::node::Node;
use serde::Deserialize;
use serde::Serialize;
Expand Down Expand Up @@ -88,10 +87,10 @@ pub async fn post_fake_scid(
pub async fn get_new_address(
State(app_state): State<Arc<AppState>>,
) -> Result<Json<String>, AppError> {
let address =
app_state.node.wallet.get_new_address().map_err(|e| {
AppError::InternalServerError(format!("Failed to get new address: {e:#}"))
})?;
let address = app_state
.node
.get_new_address()
.map_err(|e| AppError::InternalServerError(format!("Failed to get new address: {e:#}")))?;
Ok(Json(address.to_string()))
}

Expand Down
2 changes: 2 additions & 0 deletions crates/ln-dlc-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub mod seed;
#[cfg(test)]
mod tests;

pub use node::dlc_channel::Dlc;

type ConfirmableMonitor = (
ChannelMonitor<CustomSigner>,
Arc<LnDlcWallet>,
Expand Down
30 changes: 27 additions & 3 deletions crates/ln-dlc-node/src/node/dlc_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ use std::time::UNIX_EPOCH;
use trade::cfd::calculate_margin;
use trade::TradeParams;

pub struct Dlc {
pub id: [u8; 32],
pub offer_collateral: u64,
pub accept_collateral: u64,
}

impl Node {
// TODO: This API doesn't belong in this crate!
pub fn trade(&self, trade_params: TradeParams) -> Result<ContractInput> {
Expand Down Expand Up @@ -130,11 +136,29 @@ impl Node {
Ok(())
}

pub fn get_dlcs(&self) -> Result<Vec<Contract>> {
self.dlc_manager
pub fn get_confirmed_dlcs(&self) -> Result<Vec<Dlc>> {
let confimed_dlcs = self
.dlc_manager
.get_store()
.get_contracts()
.map_err(|e| anyhow!("Unable to get contracts from manager: {e:#}"))
.map_err(|e| anyhow!("Unable to get contracts from manager: {e:#}"))?
.iter()
.filter_map(|contract| match contract {
Contract::Confirmed(signed) => Some((contract.get_id(), signed)),
_ => None,
})
.map(|(id, signed)| Dlc {
id,
offer_collateral: signed
.accepted_contract
.offered_contract
.offer_params
.collateral,
accept_collateral: signed.accepted_contract.accept_params.collateral,
})
.collect();

Ok(confimed_dlcs)
}

pub fn process_incoming_messages(&self) -> Result<()> {
Expand Down
4 changes: 2 additions & 2 deletions crates/ln-dlc-node/src/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ use std::time::SystemTime;

mod channel_manager;
mod connection;
mod dlc_channel;
pub(crate) mod dlc_channel;
mod dlc_manager;
pub(crate) mod invoice;
mod ln_channel;
Expand All @@ -76,7 +76,7 @@ const BROADCAST_NODE_ANNOUNCEMENT_INTERVAL: Duration = Duration::from_secs(60);
pub struct Node {
network: Network,

pub wallet: Arc<LnDlcWallet>,
pub(crate) wallet: Arc<LnDlcWallet>,
pub(crate) peer_manager: Arc<PeerManager>,
invoice_payer: Arc<InvoicePayer<EventHandler>>,
pub(crate) channel_manager: Arc<ChannelManager>,
Expand Down
13 changes: 13 additions & 0 deletions crates/ln-dlc-node/src/node/wallet.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::node::Node;
use anyhow::anyhow;
use anyhow::Result;
use bdk::wallet::AddressIndex;
use bitcoin::Address;
use lightning::chain::Confirm;

#[derive(Debug, Clone)]
Expand All @@ -19,6 +21,17 @@ impl Node {
self.wallet.inner().sync(confirmables).unwrap();
}

pub fn get_new_address(&self) -> Result<Address> {
let address = self
.wallet
.inner()
.get_wallet()
.unwrap()
.get_address(AddressIndex::New)?;

Ok(address.address)
}

pub fn get_on_chain_balance(&self) -> Result<bdk::Balance> {
self.wallet.inner().get_balance().map_err(|e| anyhow!(e))
}
Expand Down
1 change: 0 additions & 1 deletion maker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ bitcoin = "0.29"
clap = { version = "4", features = ["derive"] }
diesel = { version = "2.0.0", features = ["r2d2", "postgres"] }
diesel_migrations = "2.0.0"
dlc-manager = { version = "0.4.0", features = ["use-serde"] }
futures = "0.3"
hex = "0.4.3"
ln-dlc-node = { path = "../crates/ln-dlc-node" }
Expand Down
17 changes: 8 additions & 9 deletions maker/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use diesel::r2d2;
use diesel::r2d2::ConnectionManager;
use diesel::r2d2::Pool;
use diesel::PgConnection;
use dlc_manager::Wallet;
use ln_dlc_node::node::Node;
use ln_dlc_node::node::NodeInfo;
use serde::Deserialize;
Expand Down Expand Up @@ -54,10 +53,10 @@ pub struct Invoice {
}

pub async fn index(State(app_state): State<Arc<AppState>>) -> Result<Json<Index>, AppError> {
let address =
app_state.node.wallet.get_new_address().map_err(|e| {
AppError::InternalServerError(format!("Failed to get new address: {e:#}"))
})?;
let address = app_state
.node
.get_new_address()
.map_err(|e| AppError::InternalServerError(format!("Failed to get new address: {e:#}")))?;

let offchain = app_state.node.get_ldk_balance();
let onchain = app_state
Expand Down Expand Up @@ -87,10 +86,10 @@ pub async fn index(State(app_state): State<Arc<AppState>>) -> Result<Json<Index>
pub async fn get_new_address(
State(app_state): State<Arc<AppState>>,
) -> Result<Json<String>, AppError> {
let address =
app_state.node.wallet.get_new_address().map_err(|e| {
AppError::InternalServerError(format!("Failed to get new address: {e:#}"))
})?;
let address = app_state
.node
.get_new_address()
.map_err(|e| AppError::InternalServerError(format!("Failed to get new address: {e:#}")))?;
Ok(Json(address.to_string()))
}

Expand Down
1 change: 0 additions & 1 deletion mobile/native/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ anyhow = "1"
bdk = { version = "0.24.0", features = ["key-value-db"] }
diesel = { version = "2.0.0", features = ["sqlite", "r2d2"] }
diesel_migrations = "2.0.0"
dlc-manager = { version = "0.4.0", features = ["use-serde"] } # required for the dlc_manager::Wallet trait
flutter_rust_bridge = "1.63.1"
lightning-invoice = { version = "0.21" }
ln-dlc-node = { path = "../../crates/ln-dlc-node" }
Expand Down
17 changes: 7 additions & 10 deletions mobile/native/src/ln_dlc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@ use bdk::bitcoin::secp256k1::rand::thread_rng;
use bdk::bitcoin::secp256k1::rand::RngCore;
use bdk::bitcoin::Network;
use bdk::bitcoin::XOnlyPublicKey;
use dlc_manager::contract::Contract;
use dlc_manager::Wallet;
use lightning_invoice::Invoice;
use ln_dlc_node::node::Node;
use ln_dlc_node::node::NodeInfo;
use ln_dlc_node::seed::Bip39Seed;
use ln_dlc_node::Dlc;
use state::Storage;
use std::net::TcpListener;
use std::path::Path;
Expand Down Expand Up @@ -134,7 +133,7 @@ pub fn run(data_dir: String) -> Result<()> {
// periodically update for positions
runtime.spawn(async move {
loop {
let contracts = match node_cloned.get_dlcs() {
let contracts = match node_cloned.get_confirmed_dlcs() {
Ok(contracts) => contracts,
Err(e) => {
tracing::error!("Failed to retrieve DLCs from node: {e:#}");
Expand All @@ -144,7 +143,10 @@ pub fn run(data_dir: String) -> Result<()> {
};

// Assumes that there is only one contract, i.e. one position
if let Some(Contract::Confirmed(contract)) = contracts.get(0) {
if let Some(Dlc {
offer_collateral, ..
}) = contracts.get(0)
{
// TODO: Load position data from database and fill in the values; the collateral
// can be taken from the DLC
event::publish(&EventInternal::PositionUpdateNotification(PositionTrade {
Expand All @@ -156,11 +158,7 @@ pub fn run(data_dir: String) -> Result<()> {
liquidation_price: 0.0,
unrealized_pnl: 0,
position_state: PositionStateTrade::Open,
collateral: contract
.accepted_contract
.offered_contract
.offer_params
.collateral,
collateral: *offer_collateral,
}));
}

Expand All @@ -177,7 +175,6 @@ pub fn run(data_dir: String) -> Result<()> {
pub fn get_new_address() -> Result<String> {
let node = NODE.try_get().context("failed to get ln dlc node")?;
let address = node
.wallet
.get_new_address()
.map_err(|e| anyhow!("Failed to get new address: {e}"))?;
Ok(address.to_string())
Expand Down

0 comments on commit 09d9710

Please sign in to comment.