Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,17 @@ default = []
#lightning-liquidity = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "main" }
#lightning-macros = { git = "https://github.com/lightningdevkit/rust-lightning", branch = "main" }

lightning = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab", features = ["std"] }
lightning-types = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab" }
lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab", features = ["std"] }
lightning-net-tokio = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab" }
lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab" }
lightning-background-processor = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab" }
lightning-rapid-gossip-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab" }
lightning-block-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab", features = ["rest-client", "rpc-client", "tokio"] }
lightning-transaction-sync = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab", features = ["esplora-async-https", "electrum-rustls-ring", "time"] }
lightning-liquidity = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab" }
lightning-macros = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab" }
lightning = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp", features = ["std"] }
lightning-types = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp" }
lightning-invoice = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp", features = ["std"] }
lightning-net-tokio = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp" }
lightning-persister = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp" }
lightning-background-processor = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp" }
lightning-rapid-gossip-sync = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp" }
lightning-block-sync = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp", features = ["rest-client", "rpc-client", "tokio"] }
lightning-transaction-sync = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp", features = ["esplora-async-https", "electrum-rustls-ring", "time"] }
lightning-liquidity = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp" }
lightning-macros = { git = "https://github.com/martinsaposnic/rust-lightning", branch = "client-trusts-lsp" }

#lightning = { path = "../rust-lightning/lightning", features = ["std"] }
#lightning-types = { path = "../rust-lightning/lightning-types" }
Expand Down Expand Up @@ -109,7 +109,7 @@ winapi = { version = "0.3", features = ["winbase"] }
[dev-dependencies]
#lightning = { version = "0.1.0", features = ["std", "_test_utils"] }
#lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["std", "_test_utils"] }
lightning = { git = "https://github.com/lightningdevkit/rust-lightning", rev = "4e32d85249359d8ef8ece97d89848e40154363ab", features = ["std", "_test_utils"] }
lightning = { git = "https://github.com/martinsaposnic/rust-lightning", branch="client-trusts-lsp", features = ["std", "_test_utils"] }
#lightning = { path = "../rust-lightning/lightning", features = ["std", "_test_utils"] }
proptest = "1.0.0"
regex = "1.5.6"
Expand Down
8 changes: 8 additions & 0 deletions bindings/ldk_node.udl
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ dictionary LSPS2ServiceConfig {
u32 max_client_to_self_delay;
u64 min_payment_size_msat;
u64 max_payment_size_msat;
boolean client_trusts_lsp;
};

enum LogLevel {
Expand Down Expand Up @@ -194,6 +195,13 @@ interface Bolt11Payment {
Bolt11Invoice receive_variable_amount_via_jit_channel([ByRef]Bolt11InvoiceDescription description, u32 expiry_secs, u64? max_proportional_lsp_fee_limit_ppm_msat);
[Throws=NodeError]
Bolt11Invoice receive_variable_amount_via_jit_channel_for_hash([ByRef]Bolt11InvoiceDescription description, u32 expiry_secs, u64? max_proportional_lsp_fee_limit_ppm_msat, PaymentHash payment_hash);
[Throws=NodeError]
JitChannelManualClaim receive_via_jit_channel_manual_claim(u64 amount_msat, [ByRef]Bolt11InvoiceDescription description, u32 expiry_secs, u64? max_total_lsp_fee_limit_msat);
};

dictionary JitChannelManualClaim {
Bolt11Invoice invoice;
PaymentPreimage preimage;
};

interface Bolt12Payment {
Expand Down
1 change: 1 addition & 0 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1507,6 +1507,7 @@ fn build_with_store_internal(
Arc::clone(&chain_source),
Arc::clone(&config),
Arc::clone(&logger),
Arc::clone(&tx_broadcaster),
);

lsc.lsps1_client.as_ref().map(|config| {
Expand Down
55 changes: 44 additions & 11 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ where
counterparty_node_id,
channel_value_satoshis,
output_script,
..
user_channel_id,
} => {
// Construct the raw transaction with the output that is paid the amount of the
// channel.
Expand All @@ -516,12 +516,43 @@ where
locktime,
) {
Ok(final_tx) => {
// Give the funding transaction back to LDK for opening the channel.
match self.channel_manager.funding_transaction_generated(
temporary_channel_id,
counterparty_node_id,
final_tx,
) {
let needs_manual_broadcast =
match self.liquidity_source.as_ref().map(|ls| {
ls.as_ref().lsps2_channel_needs_manual_broadcast(
counterparty_node_id,
user_channel_id,
)
}) {
Some(Ok(v)) => v,
Some(Err(e)) => {
log_error!(self.logger, "Failed to determine if channel needs manual broadcast: {:?}", e);
false
},
None => false,
};

let result = if needs_manual_broadcast {
self.liquidity_source.as_ref().map(|ls| {
ls.lsps2_store_funding_transaction(
user_channel_id,
counterparty_node_id,
final_tx.clone(),
);
});
self.channel_manager.funding_transaction_generated_manual_broadcast(
temporary_channel_id,
counterparty_node_id,
final_tx,
)
} else {
self.channel_manager.funding_transaction_generated(
temporary_channel_id,
counterparty_node_id,
final_tx,
)
};

match result {
Ok(()) => {},
Err(APIError::APIMisuseError { err }) => {
log_error!(self.logger, "Panicking due to APIMisuseError: {}", err);
Expand Down Expand Up @@ -560,8 +591,10 @@ where
},
}
},
LdkEvent::FundingTxBroadcastSafe { .. } => {
debug_assert!(false, "We currently only support safe funding, so this event should never be emitted.");
LdkEvent::FundingTxBroadcastSafe { user_channel_id, counterparty_node_id, .. } => {
self.liquidity_source.as_ref().map(|ls| {
ls.lsps2_funding_tx_broadcast_safe(user_channel_id, counterparty_node_id);
});
},
LdkEvent::PaymentClaimable {
payment_hash,
Expand Down Expand Up @@ -686,7 +719,7 @@ where
match info.kind {
PaymentKind::Bolt11 { preimage, .. }
| PaymentKind::Bolt11Jit { preimage, .. } => {
if purpose.preimage().is_none() {
if preimage.is_none() || purpose.preimage().is_none() {
debug_assert!(
preimage.is_none(),
"We would have registered the preimage if we knew"
Expand Down Expand Up @@ -1280,7 +1313,7 @@ where
}

if let Some(liquidity_source) = self.liquidity_source.as_ref() {
liquidity_source.handle_payment_forwarded(next_channel_id);
liquidity_source.handle_payment_forwarded(next_channel_id, skimmed_fee_msat);
}

let event = Event::PaymentForwarded {
Expand Down
9 changes: 9 additions & 0 deletions src/ffi/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,15 @@ impl UniffiCustomTypeConverter for LSPSDateTime {
}
}

/// A payable invoice and its corresponding preimage for manual claiming via a JIT channel.
#[derive(Debug, Clone)]
pub struct JitChannelManualClaim {
/// The payable invoice.
pub invoice: Arc<Bolt11Invoice>,
/// The payment preimage.
pub preimage: PaymentPreimage,
}

#[cfg(test)]
mod tests {
use std::{
Expand Down
96 changes: 91 additions & 5 deletions src/liquidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ use crate::chain::ChainSource;
use crate::connection::ConnectionManager;
use crate::logger::{log_debug, log_error, log_info, LdkLogger, Logger};
use crate::runtime::Runtime;
use crate::types::{ChannelManager, KeysManager, LiquidityManager, PeerManager, Wallet};
use crate::types::{
Broadcaster, ChannelManager, KeysManager, LiquidityManager, PeerManager, Wallet,
};
use crate::{total_anchor_channels_reserve_sats, Config, Error};

use lightning::events::HTLCHandlingFailureType;
use lightning::ln::channelmanager::{InterceptId, MIN_FINAL_CLTV_EXPIRY_DELTA};
use lightning::ln::msgs::SocketAddress;
use lightning::ln::types::ChannelId;
use lightning::routing::router::{RouteHint, RouteHintHop};
use lightning::util::errors::APIError;

use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, InvoiceBuilder, RoutingFees};

Expand All @@ -40,6 +43,7 @@ use lightning_types::payment::PaymentHash;

use bitcoin::hashes::{sha256, Hash};
use bitcoin::secp256k1::{PublicKey, Secp256k1};
use bitcoin::Transaction;

use tokio::sync::oneshot;

Expand All @@ -55,7 +59,6 @@ use std::time::Duration;
const LIQUIDITY_REQUEST_TIMEOUT_SECS: u64 = 5;

const LSPS2_GETINFO_REQUEST_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);
const LSPS2_CLIENT_TRUSTS_LSP_MODE: bool = true;
const LSPS2_CHANNEL_CLTV_EXPIRY_DELTA: u32 = 72;

struct LSPS1Client {
Expand Down Expand Up @@ -134,6 +137,8 @@ pub struct LSPS2ServiceConfig {
pub min_payment_size_msat: u64,
/// The maximum payment size that we will accept when opening a channel.
pub max_payment_size_msat: u64,
/// Use the client trusts lsp model
pub client_trusts_lsp: bool,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm trying to understand the client_trusts_lsp configuration here. According to bLIP-52, I expect the LSP to dynamically switch from lsp_trusts_client to client_trusts_lsp mode upon detecting an attack, without requiring a restart.
However, this configuration appears to be static and set at node startup. If that's the case, what happens when:

  1. A node initially running in lsp_trusts_client mode detects an attack
  2. The node restarts with client_trusts_lsp: true to switch modes
  3. There's an existing outbound JIT channel where the client expects the LSP to broadcast the funding transaction before sending the preimage to claim.

What are the potential consequences for that in-flight JIT channel during the mode transition?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just pushed a fixup that makes the flag dynamic

There's an existing outbound JIT channel where the client expects the LSP to broadcast the funding transaction before sending the preimage to claim.

I just posted a question about this https://discord.com/channels/915026692102316113/994015949176963183/1397280758196080660

my current interpretation about this is that once lsps2.buy succeeds, that flag is part of the contract for this flow. the LSP can always abort and make you start over, but it cannot change the trust model mid negotiation

we will see what they respond on discord

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my current interpretation about this is that once lsps2.buy succeeds, that flag is part of the contract for this flow. the LSP can always abort and make you start over, but it cannot change the trust model mid negotiation

I created a test that shows how this works (test lsps2_in_flight_under_attack_switch)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my current interpretation about this is that once lsps2.buy succeeds, that flag is part of the contract for this flow. the LSP can always abort and make you start over, but it cannot change the trust model mid negotiation

Yes, as also noted on Discord, I agree with that interpretation and even think that for now we can leave the flag to be statically determined at startup.

}

pub(crate) struct LiquiditySourceBuilder<L: Deref>
Expand All @@ -149,6 +154,7 @@ where
chain_source: Arc<ChainSource>,
config: Arc<Config>,
logger: L,
broadcaster: Arc<Broadcaster>,
}

impl<L: Deref> LiquiditySourceBuilder<L>
Expand All @@ -158,6 +164,7 @@ where
pub(crate) fn new(
wallet: Arc<Wallet>, channel_manager: Arc<ChannelManager>, keys_manager: Arc<KeysManager>,
chain_source: Arc<ChainSource>, config: Arc<Config>, logger: L,
broadcaster: Arc<Broadcaster>,
) -> Self {
let lsps1_client = None;
let lsps2_client = None;
Expand All @@ -172,6 +179,7 @@ where
chain_source,
config,
logger,
broadcaster,
}
}

Expand Down Expand Up @@ -242,6 +250,7 @@ where
Arc::clone(&self.keys_manager),
Arc::clone(&self.channel_manager),
Some(Arc::clone(&self.chain_source)),
Arc::clone(&self.broadcaster),
None,
liquidity_service_config,
liquidity_client_config,
Expand Down Expand Up @@ -298,6 +307,79 @@ where
self.lsps2_client.as_ref().map(|s| (s.lsp_node_id, s.lsp_address.clone()))
}

pub(crate) fn lsps2_channel_needs_manual_broadcast(
&self, counterparty_node_id: PublicKey, user_channel_id: u128,
) -> Result<bool, APIError> {
// if we are not in a client_trusts_lsp model, we don't check and just return false
if !self.is_client_trusts_lsp() {
log_debug!(self.logger, "Skipping funding transaction broadcast as client trusts LSP.");
return Ok(false);
}

// if we are in a client_trusts_lsp model, then we check if the LSP has an LSPS2 operation in progress
self.lsps2_service.as_ref().map_or(Ok(false), |_| {
let lsps2_service_handler = self.liquidity_manager.lsps2_service_handler();
if let Some(handler) = lsps2_service_handler {
handler.channel_needs_manual_broadcast(user_channel_id, &counterparty_node_id)
} else {
log_error!(self.logger, "LSPS2 service handler is not available.");
Ok(false)
}
})
}

pub(crate) fn lsps2_store_funding_transaction(
&self, user_channel_id: u128, counterparty_node_id: PublicKey, funding_tx: Transaction,
) {
if !self.is_client_trusts_lsp() {
log_debug!(self.logger, "Skipping funding transaction broadcast as client trusts LSP.");
return;
}
self.lsps2_service.as_ref().map(|_| {
let lsps2_service_handler = self.liquidity_manager.lsps2_service_handler();
if let Some(handler) = lsps2_service_handler {
handler
.store_funding_transaction(user_channel_id, &counterparty_node_id, funding_tx)
.unwrap_or_else(|e| {
debug_assert!(false, "Failed to store funding transaction: {:?}", e);
log_error!(self.logger, "Failed to store funding transaction: {:?}", e);
});
} else {
log_error!(self.logger, "LSPS2 service handler is not available.");
}
});
}

pub(crate) fn lsps2_funding_tx_broadcast_safe(
&self, user_channel_id: u128, counterparty_node_id: PublicKey,
) {
if !self.is_client_trusts_lsp() {
log_debug!(self.logger, "Skipping funding transaction broadcast as client trusts LSP.");
return;
}
self.lsps2_service.as_ref().map(|_| {
let lsps2_service_handler = self.liquidity_manager.lsps2_service_handler();
if let Some(handler) = lsps2_service_handler {
handler
.set_funding_tx_broadcast_safe(user_channel_id, &counterparty_node_id)
.unwrap_or_else(|e| {
debug_assert!(false, "Failed to store funding transaction: {:?}", e);
log_error!(self.logger, "Failed to store funding transaction: {:?}", e);
});
} else {
log_error!(self.logger, "LSPS2 service handler is not available.");
}
});
}

fn is_client_trusts_lsp(&self) -> bool {
if let Some(lsps2_service) = self.lsps2_service.as_ref() {
lsps2_service.service_config.client_trusts_lsp
} else {
false
}
}

pub(crate) async fn handle_next_event(&self) {
match self.liquidity_manager.next_event_async().await {
LiquidityEvent::LSPS1Client(LSPS1ClientEvent::SupportedOptionsReady {
Expand Down Expand Up @@ -586,7 +668,7 @@ where
request_id,
intercept_scid,
LSPS2_CHANNEL_CLTV_EXPIRY_DELTA,
LSPS2_CLIENT_TRUSTS_LSP_MODE,
service_config.client_trusts_lsp,
user_channel_id,
) {
Ok(()) => {},
Expand Down Expand Up @@ -1296,10 +1378,14 @@ where
}
}

pub(crate) fn handle_payment_forwarded(&self, next_channel_id: Option<ChannelId>) {
pub(crate) fn handle_payment_forwarded(
&self, next_channel_id: Option<ChannelId>, skimmed_fee_msat: Option<u64>,
) {
if let Some(next_channel_id) = next_channel_id {
if let Some(lsps2_service_handler) = self.liquidity_manager.lsps2_service_handler() {
if let Err(e) = lsps2_service_handler.payment_forwarded(next_channel_id) {
if let Err(e) = lsps2_service_handler
.payment_forwarded(next_channel_id, skimmed_fee_msat.unwrap_or(0))
{
log_error!(
self.logger,
"LSPS2 service failed to handle PaymentForwarded: {:?}",
Expand Down
Loading
Loading