Skip to content

Commit

Permalink
feat: Add Lightning-node capabilities to the maker
Browse files Browse the repository at this point in the history
Fixes #926.

The main goal of this patch is to give the maker the ability to open a
channel with the coordinator to make direct payments. These will
firstly be used to pay order-matching fees. Eventually they will also
be used to set up DLC channels corresponding to trades.
  • Loading branch information
luckysori committed Aug 18, 2023
1 parent 36d7bcf commit 3fdd820
Show file tree
Hide file tree
Showing 20 changed files with 737 additions and 87 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions coordinator/src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ use tracing::instrument;

#[derive(Serialize, Deserialize)]
pub struct Balance {
offchain: u64,
onchain: u64,
pub offchain: u64,
pub onchain: u64,
}

#[autometrics]
Expand Down
4 changes: 3 additions & 1 deletion crates/ln-dlc-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ mod disk;
mod dlc_custom_signer;
mod fee_rate_estimator;
mod ldk_node_wallet;
mod ln;
mod ln_dlc_wallet;
mod on_chain_wallet;
mod shadow;

pub mod channel;
pub mod config;
pub mod ln;
pub mod node;
pub mod scorer;
pub mod seed;
Expand All @@ -45,6 +45,8 @@ pub use config::CONFIRMATION_TARGET;
pub use config::CONTRACT_TX_FEE_RATE;
pub use config::LIQUIDITY_MULTIPLIER;
pub use ldk_node_wallet::WalletSettings;
pub use lightning;
pub use lightning_invoice;
pub use ln::AppEventHandler;
pub use ln::ChannelDetails;
pub use ln::CoordinatorEventHandler;
Expand Down
22 changes: 11 additions & 11 deletions crates/ln-dlc-node/src/ln/common_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use time::OffsetDateTime;
use tokio::task::block_in_place;
use uuid::Uuid;

pub(crate) fn handle_payment_claimable(
pub fn handle_payment_claimable(
channel_manager: &Arc<ChannelManager>,
payment_hash: PaymentHash,
purpose: PaymentPurpose,
Expand All @@ -57,7 +57,7 @@ pub(crate) fn handle_payment_claimable(
Ok(())
}

pub(crate) fn handle_htlc_handling_failed(
pub fn handle_htlc_handling_failed(
prev_channel_id: [u8; 32],
failed_next_destination: lightning::util::events::HTLCDestination,
) {
Expand All @@ -68,7 +68,7 @@ pub(crate) fn handle_htlc_handling_failed(
);
}

pub(crate) fn handle_discard_funding(transaction: bitcoin::Transaction, channel_id: [u8; 32]) {
pub fn handle_discard_funding(transaction: bitcoin::Transaction, channel_id: [u8; 32]) {
let tx_hex = serialize_hex(&transaction);
tracing::info!(
channel_id = %channel_id.to_hex(),
Expand All @@ -82,7 +82,7 @@ pub(crate) fn handle_discard_funding(transaction: bitcoin::Transaction, channel_
// generated.
}

pub(crate) fn handle_payment_forwarded<S>(
pub fn handle_payment_forwarded<S>(
node: &Arc<Node<S>>,
prev_channel_id: Option<[u8; 32]>,
next_channel_id: Option<[u8; 32]>,
Expand Down Expand Up @@ -217,7 +217,7 @@ where
Ok(())
}

pub(crate) fn handle_channel_closed<S>(
pub fn handle_channel_closed<S>(
node: &Arc<Node<S>>,
pending_intercepted_htlcs: &PendingInterceptedHtlcs,
user_channel_id: u128,
Expand Down Expand Up @@ -257,7 +257,7 @@ where
Ok(())
}

pub(crate) fn handle_spendable_outputs<S>(
pub fn handle_spendable_outputs<S>(
node: &Arc<Node<S>>,
outputs: Vec<SpendableOutputDescriptor>,
) -> Result<()>
Expand Down Expand Up @@ -297,7 +297,7 @@ where
Ok(())
}

pub(crate) fn handle_payment_claimed<S>(
pub fn handle_payment_claimed<S>(
node: &Arc<Node<S>>,
amount_msat: u64,
payment_hash: PaymentHash,
Expand Down Expand Up @@ -336,7 +336,7 @@ pub(crate) fn handle_payment_claimed<S>(
}
}

pub(crate) fn handle_payment_failed<S>(node: &Arc<Node<S>>, payment_hash: PaymentHash)
pub fn handle_payment_failed<S>(node: &Arc<Node<S>>, payment_hash: PaymentHash)
where
S: Storage,
{
Expand All @@ -361,7 +361,7 @@ where
}
}

pub(crate) async fn handle_funding_generation_ready<S>(
pub async fn handle_funding_generation_ready<S>(
node: &Arc<Node<S>>,
user_channel_id: u128,
counterparty_node_id: PublicKey,
Expand Down Expand Up @@ -441,7 +441,7 @@ where
})
}

pub(crate) fn handle_channel_ready_internal<S>(
fn handle_channel_ready_internal<S>(
node: &Arc<Node<S>>,
pending_intercepted_htlcs: &PendingInterceptedHtlcs,
user_channel_id: u128,
Expand Down Expand Up @@ -509,7 +509,7 @@ pub(crate) fn fail_intercepted_htlc(
let _ = channel_manager.fail_intercepted_htlc(*intercept_id);
}

pub(crate) fn handle_pending_htlcs_forwardable(
pub fn handle_pending_htlcs_forwardable(
forwarding_channel_manager: Arc<ChannelManager>,
time_forwardable: Duration,
) {
Expand Down
13 changes: 7 additions & 6 deletions crates/ln-dlc-node/src/ln/mod.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
mod app_event_handler;
mod channel_details;
/// A collection of handlers for events emitted by the lightning node.
///
/// When constructing a new [`Node`], you can pass in a custom [`EventHandler`]
/// to handle events; these handlers are useful to reduce boilerplate if you
/// don't require custom behaviour
pub mod common_handlers;
mod coordinator_event_handler;
mod dlc_channel_details;
mod event_handler;
mod logger;
mod manage_spendable_outputs;

/// A collection of handlers for events emitted by the Lightning node.
///
/// When constructing a new [`Node`], you can pass in a custom [`EventHandler`]
/// to handle events; these handlers are useful to reduce boilerplate if you
/// don't require custom behaviour.
pub mod common_handlers;

pub use app_event_handler::AppEventHandler;
pub use channel_details::ChannelDetails;
pub use coordinator_event_handler::CoordinatorEventHandler;
Expand Down
14 changes: 8 additions & 6 deletions crates/ln-dlc-node/src/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::node::peer_manager::alias_as_bytes;
use crate::node::peer_manager::broadcast_node_announcement;
use crate::on_chain_wallet::OnChainWallet;
use crate::seed::Bip39Seed;
use crate::shadow::Shadow;
use crate::ChainMonitor;
use crate::EventHandlerTrait;
use crate::NetworkGraph;
Expand All @@ -30,6 +31,7 @@ use lightning::ln::msgs::NetAddress;
use lightning::ln::peer_handler::MessageHandler;
use lightning::routing::gossip::P2PGossipSync;
use lightning::routing::router::DefaultRouter;
use lightning::routing::scoring::ProbabilisticScorer;
use lightning::routing::utxo::UtxoLookup;
use lightning::util::config::UserConfig;
use lightning_background_processor::process_events_async;
Expand Down Expand Up @@ -57,25 +59,25 @@ use tokio::task::spawn_blocking;

mod channel_manager;
mod connection;
pub(crate) mod dlc_channel;
mod dlc_manager;
pub(crate) mod invoice;
mod ln_channel;
mod oracle;
pub mod peer_manager;
mod storage;
mod sub_channel_manager;
mod wallet;

pub(crate) mod dlc_channel;
pub(crate) mod invoice;

pub mod peer_manager;

pub use self::dlc_manager::DlcManager;
pub use crate::node::oracle::OracleInfo;
use crate::shadow::Shadow;
pub use ::dlc_manager as rust_dlc_manager;
pub use channel_manager::ChannelManager;
pub use dlc_channel::dlc_message_name;
pub use dlc_channel::sub_channel_message_name;
pub use invoice::HTLCStatus;
use lightning::routing::scoring::ProbabilisticScorer;
pub use storage::InMemoryStore;
pub use storage::Storage;
pub use sub_channel_manager::SubChannelManager;
Expand Down Expand Up @@ -122,7 +124,7 @@ pub struct Node<S> {
pub sub_channel_manager: Arc<SubChannelManager>,
oracle: Arc<P2PDOracleClient>,
pub dlc_message_handler: Arc<DlcMessageHandler>,
pub(crate) storage: Arc<S>,
pub storage: Arc<S>,
pub ldk_config: Arc<parking_lot::RwLock<UserConfig>>,

// fields below are needed only to start the node
Expand Down
1 change: 1 addition & 0 deletions crates/tests-e2e/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ coordinator = { path = "../../coordinator" }
coordinator-commons = { path = "../coordinator-commons" }
flutter_rust_bridge = "1.78.0"
ln-dlc-node = { path = "../ln-dlc-node" }
maker = { path = "../../maker" }
native = { path = "../../mobile/native" }
orderbook-commons = { path = "../orderbook-commons" }
quote = "1.0.28"
Expand Down
6 changes: 5 additions & 1 deletion crates/tests-e2e/examples/fund.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ async fn fund_everything(faucet: &str, coordinator: &str) -> Result<()> {
mine(10, faucet).await?;

let coordinator_balance = coordinator.get_balance().await?;
tracing::info!("coordinator BTC balance: {}", coordinator_balance);
tracing::info!(
onchain = %coordinator_balance.onchain,
offchain = %coordinator_balance.offchain,
"Coordinator balance",
);

let node: NodeInfo = coordinator.get_node_info().await?;
tracing::info!("lightning node: {}", node);
Expand Down
19 changes: 11 additions & 8 deletions crates/tests-e2e/src/coordinator.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use anyhow::Context;
use anyhow::Result;
use coordinator::admin::Balance;
use coordinator::routes::InvoiceParams;
use ln_dlc_node::lightning_invoice;
use ln_dlc_node::node::NodeInfo;
use reqwest::Client;
use serde::Deserialize;

/// A wrapper over the coordinator HTTP API
/// A wrapper over the coordinator HTTP API.
///
/// It does not aim to be complete, functionality will be added as needed
/// It does not aim to be complete, functionality will be added as needed.
pub struct Coordinator {
client: Client,
host: String,
Expand Down Expand Up @@ -48,7 +50,7 @@ impl Coordinator {
Self::new(client, "http://localhost:8000")
}

/// Check whether the coordinator is running
/// Check whether the coordinator is running.
pub async fn is_running(&self) -> bool {
self.get("/health").await.is_ok()
}
Expand All @@ -73,7 +75,7 @@ impl Coordinator {
Ok(())
}

pub async fn create_invoice(&self, amount: Option<u64>) -> Result<String> {
pub async fn create_invoice(&self, amount: Option<u64>) -> Result<lightning_invoice::Invoice> {
let invoice_params = InvoiceParams {
amount,
description: Some("Fee for tests".to_string()),
Expand All @@ -86,7 +88,9 @@ impl Coordinator {
.get(&format!("/api/invoice?{encoded_params}"))
.await?
.text()
.await?;
.await?
.parse()?;

Ok(invoice)
}

Expand All @@ -105,9 +109,8 @@ impl Coordinator {
.to_owned())
}

// TODO: Introduce strong type
pub async fn get_balance(&self) -> Result<String> {
Ok(self.get("/api/admin/balance").await?.text().await?)
pub async fn get_balance(&self) -> Result<Balance> {
Ok(self.get("/api/admin/balance").await?.json().await?)
}

pub async fn get_node_info(&self) -> Result<NodeInfo> {
Expand Down
1 change: 1 addition & 0 deletions crates/tests-e2e/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod coordinator;
pub mod fund;
pub mod http;
pub mod logger;
pub mod maker;
pub mod setup;
pub mod test_flow;
pub mod test_subscriber;
Loading

0 comments on commit 3fdd820

Please sign in to comment.