Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade to LDK 0.0.118 #175

Merged
merged 1 commit into from
Oct 31, 2023
Merged
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
16 changes: 8 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ panic = 'abort' # Abort on panic
default = []

[dependencies]
lightning = { version = "0.0.117", features = ["max_level_trace", "std"] }
lightning-invoice = { version = "0.25.0" }
lightning-net-tokio = { version = "0.0.117" }
lightning-persister = { version = "0.0.117" }
lightning-background-processor = { version = "0.0.117", features = ["futures"] }
lightning-rapid-gossip-sync = { version = "0.0.117" }
lightning-transaction-sync = { version = "0.0.117", features = ["esplora-async-https"] }
lightning = { version = "0.0.118", features = ["max_level_trace", "std"] }
lightning-invoice = { version = "0.26.0" }
lightning-net-tokio = { version = "0.0.118" }
lightning-persister = { version = "0.0.118" }
lightning-background-processor = { version = "0.0.118", features = ["futures"] }
lightning-rapid-gossip-sync = { version = "0.0.118" }
lightning-transaction-sync = { version = "0.0.118", features = ["esplora-async-https"] }

# lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["max_level_trace", "std"] }
# lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
Expand Down Expand Up @@ -75,7 +75,7 @@ uniffi = { version = "0.23.0", features = ["build"], optional = true }
winapi = { version = "0.3", features = ["winbase"] }

[dev-dependencies]
lightning = { version = "0.0.117", features = ["max_level_trace", "std", "_test_utils"] }
lightning = { version = "0.0.118", features = ["max_level_trace", "std", "_test_utils"] }
#lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["max_level_trace", "std", "_test_utils"] }
electrsd = { version = "0.22.0", features = ["legacy", "esplora_a33e97e1", "bitcoind_23_0"] }
electrum-client = "0.12.0"
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ LDK Node is a self-custodial Lightning node in library form. Its central goal is
The primary abstraction of the library is the [`Node`][api_docs_node], which can be retrieved by setting up and configuring a [`Builder`][api_docs_builder] to your liking and calling one of the `build` methods. `Node` can then be controlled via commands such as `start`, `stop`, `connect_open_channel`, `send_payment`, etc.

```rust
use ldk_node::{Builder, SocketAddress};
use ldk_node::Builder;
use ldk_node::lightning_invoice::Invoice;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::bitcoin::secp256k1::PublicKey;
use ldk_node::bitcoin::Network;
use std::str::FromStr;
Expand Down
4 changes: 2 additions & 2 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::payment_store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::types::{
ChainMonitor, ChannelManager, FakeMessageRouter, GossipSync, KeysManager, NetworkGraph,
OnionMessenger, PeerManager, SocketAddress,
OnionMessenger, PeerManager,
};
use crate::wallet::Wallet;
use crate::LogLevel;
Expand All @@ -18,7 +18,7 @@ use crate::{

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::ln::channelmanager::{self, ChainParameters, ChannelManagerReadArgs};
use lightning::ln::msgs::RoutingMessageHandler;
use lightning::ln::msgs::{RoutingMessageHandler, SocketAddress};
use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler};
use lightning::routing::router::DefaultRouter;
use lightning::routing::scoring::{
Expand Down
8 changes: 5 additions & 3 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ where
} => {
// Construct the raw transaction with the output that is paid the amount of the
// channel.
let confirmation_target = ConfirmationTarget::Normal;
let confirmation_target = ConfirmationTarget::NonAnchorChannelFee;
tnull marked this conversation as resolved.
Show resolved Hide resolved

// We set nLockTime to the current height to discourage fee sniping.
let cur_height = self.channel_manager.current_best_block().height();
Expand Down Expand Up @@ -581,8 +581,9 @@ where
});

let output_descriptors = &outputs.iter().collect::<Vec<_>>();
let tx_feerate =
self.wallet.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
let tx_feerate = self
.wallet
.get_est_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);

// We set nLockTime to the current height to discourage fee sniping.
let cur_height = self.channel_manager.current_best_block().height();
Expand Down Expand Up @@ -781,6 +782,7 @@ where
LdkEvent::DiscardFunding { .. } => {}
LdkEvent::HTLCIntercepted { .. } => {}
LdkEvent::BumpTransaction(_) => {}
LdkEvent::InvoiceRequestFailed { .. } => {}
}
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@
//! [`send_payment`], etc.:
//!
//! ```no_run
//! use ldk_node::{Builder, SocketAddress};
//! use ldk_node::Builder;
//! use ldk_node::lightning_invoice::Bolt11Invoice;
//! use ldk_node::lightning::ln::msgs::SocketAddress;
//! use ldk_node::bitcoin::secp256k1::PublicKey;
//! use ldk_node::bitcoin::Network;
//! use std::str::FromStr;
Expand Down Expand Up @@ -100,7 +101,6 @@ use error::Error;

pub use event::Event;
pub use types::ChannelConfig;
pub use types::SocketAddress;

pub use io::utils::generate_entropy_mnemonic;

Expand All @@ -126,6 +126,7 @@ use logger::{log_error, log_info, log_trace, FilesystemLogger, Logger};

use lightning::chain::Confirm;
use lightning::ln::channelmanager::{self, PaymentId, RecipientOnionFields, Retry};
use lightning::ln::msgs::SocketAddress;
use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage};
use lightning::sign::EntropySource;

Expand Down Expand Up @@ -631,7 +632,7 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
}

let addresses =
bcast_config.listening_address.iter().cloned().map(|a| a.0).collect();
bcast_config.listening_address.iter().cloned().collect();
bcast_pm.broadcast_node_announcement([0; 3], [0; 32], addresses);

let unix_time_secs = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
Expand Down Expand Up @@ -1516,7 +1517,7 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
let stored_peer = self.peer_store.get_peer(&node_id);
let stored_addr_opt = stored_peer.as_ref().map(|p| p.address.clone());
let address = match (con_addr_opt, stored_addr_opt) {
(Some(con_addr), _) => SocketAddress(con_addr),
(Some(con_addr), _) => con_addr,
(None, Some(stored_addr)) => stored_addr,
(None, None) => continue,
};
Expand Down
105 changes: 1 addition & 104 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::wallet::{Wallet, WalletKeysManager};
use lightning::chain::chainmonitor;
use lightning::ln::channelmanager::ChannelDetails as LdkChannelDetails;
use lightning::ln::msgs::RoutingMessageHandler;
use lightning::ln::msgs::SocketAddress as LdkSocketAddress;
use lightning::ln::msgs::SocketAddress;
use lightning::ln::peer_handler::IgnoringMessageHandler;
use lightning::ln::ChannelId;
use lightning::routing::gossip;
Expand All @@ -20,9 +20,6 @@ use lightning_transaction_sync::EsploraSyncClient;
use bitcoin::secp256k1::PublicKey;
use bitcoin::OutPoint;

use std::fmt::Display;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
use std::str::FromStr;
use std::sync::{Arc, Mutex, RwLock};

pub(crate) type ChainMonitor<K> = chainmonitor::ChainMonitor<
Expand Down Expand Up @@ -320,106 +317,6 @@ pub struct PeerDetails {
pub is_connected: bool,
}

/// The network address of a Lightning node.
///
/// Currently only IPv4, IPv6, and DNS hostnames are supported.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SocketAddress(pub LdkSocketAddress);
tnull marked this conversation as resolved.
Show resolved Hide resolved

impl Display for SocketAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
LdkSocketAddress::TcpIpV4 { addr, port } => {
let ip_addr = Ipv4Addr::from(addr);
write!(f, "{}:{}", ip_addr, port)
}
LdkSocketAddress::TcpIpV6 { addr, port } => {
let ip_addr = Ipv6Addr::from(addr);
write!(f, "[{}]:{}", ip_addr, port)
}
LdkSocketAddress::Hostname { ref hostname, port } => {
write!(f, "{}:{}", hostname.as_str(), port)
}
LdkSocketAddress::OnionV2(o) => {
write!(f, "OnionV2 (unsupported): {:?}", o)
}
LdkSocketAddress::OnionV3 { ed25519_pubkey, checksum, version, port } => write!(
f,
"OnionV3 (unsupported): {:?}/{:?}/{:?}/{:?}",
ed25519_pubkey, checksum, version, port
),
}
}
}

impl FromStr for SocketAddress {
type Err = ();

fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(LdkSocketAddress::from_str(s).map_err(|_| ())?))
}
}

impl From<SocketAddr> for SocketAddress {
fn from(value: SocketAddr) -> Self {
match value {
SocketAddr::V4(v4addr) => SocketAddress::from(v4addr),
SocketAddr::V6(v6addr) => SocketAddress::from(v6addr),
}
}
}

impl From<SocketAddrV4> for SocketAddress {
fn from(value: SocketAddrV4) -> Self {
Self(LdkSocketAddress::TcpIpV4 { addr: value.ip().octets(), port: value.port() })
}
}

impl From<SocketAddrV6> for SocketAddress {
fn from(value: SocketAddrV6) -> Self {
Self(LdkSocketAddress::TcpIpV6 { addr: value.ip().octets(), port: value.port() })
}
}

impl ToSocketAddrs for SocketAddress {
type Iter = std::option::IntoIter<SocketAddr>;

fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
match self.0 {
LdkSocketAddress::TcpIpV4 { addr, port } => {
let ip_addr = Ipv4Addr::from(addr);
(ip_addr, port).to_socket_addrs()
}
LdkSocketAddress::TcpIpV6 { addr, port } => {
let ip_addr = Ipv6Addr::from(addr);
(ip_addr, port).to_socket_addrs()
}
LdkSocketAddress::Hostname { ref hostname, port } => {
Ok((hostname.as_str(), port).to_socket_addrs()?.next().into_iter())
}
LdkSocketAddress::OnionV2(..) => {
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}
LdkSocketAddress::OnionV3 { .. } => {
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}
}
}
}

impl Writeable for SocketAddress {
fn write<W: lightning::util::ser::Writer>(&self, writer: &mut W) -> Result<(), std::io::Error> {
self.0.write(writer)
}
}

impl Readable for SocketAddress {
fn read<R: std::io::Read>(reader: &mut R) -> Result<Self, lightning::ln::msgs::DecodeError> {
let addr: LdkSocketAddress = Readable::read(reader)?;
Ok(Self(addr))
}
}

/// Options which apply on a per-channel basis.
///
/// See documentation of [`LdkChannelConfig`] for details.
Expand Down
52 changes: 37 additions & 15 deletions src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,29 +116,48 @@ where
let mut locked_fee_rate_cache = self.fee_rate_cache.write().unwrap();

let confirmation_targets = vec![
ConfirmationTarget::MempoolMinimum,
ConfirmationTarget::Background,
ConfirmationTarget::Normal,
ConfirmationTarget::HighPriority,
ConfirmationTarget::OnChainSweep,
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
ConfirmationTarget::AnchorChannelFee,
ConfirmationTarget::NonAnchorChannelFee,
ConfirmationTarget::ChannelCloseMinimum,
];
for target in confirmation_targets {
let num_blocks = match target {
ConfirmationTarget::MempoolMinimum => 1008,
ConfirmationTarget::Background => 12,
ConfirmationTarget::Normal => 6,
ConfirmationTarget::HighPriority => 3,
ConfirmationTarget::OnChainSweep => 6,
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => 1,
tnull marked this conversation as resolved.
Show resolved Hide resolved
ConfirmationTarget::MinAllowedAnchorChannelRemoteFee => 1008,
ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => 144,
ConfirmationTarget::AnchorChannelFee => 1008,
ConfirmationTarget::NonAnchorChannelFee => 12,
ConfirmationTarget::ChannelCloseMinimum => 144,
};

let est_fee_rate = self.blockchain.estimate_fee(num_blocks).await;

match est_fee_rate {
Ok(rate) => {
locked_fee_rate_cache.insert(target, rate);
// LDK 0.0.118 introduced changes to the `ConfirmationTarget` semantics that
// require some post-estimation adjustments to the fee rates, which we do here.
let adjusted_fee_rate = match target {
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => {
let really_high_prio = rate.as_sat_per_vb() * 10.0;
FeeRate::from_sat_per_vb(really_high_prio)
}
ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => {
let slightly_less_than_background = rate.fee_wu(1000) - 250;
FeeRate::from_sat_per_kwu(slightly_less_than_background as f32)
}
_ => rate,
};
locked_fee_rate_cache.insert(target, adjusted_fee_rate);
log_trace!(
self.logger,
"Fee rate estimation updated for {:?}: {} sats/kwu",
target,
rate.fee_wu(1000)
adjusted_fee_rate.fee_wu(1000)
);
}
Err(e) => {
Expand Down Expand Up @@ -211,7 +230,7 @@ where
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_msat_or_drain: Option<u64>,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::Normal;
let confirmation_target = ConfirmationTarget::NonAnchorChannelFee;
tnull marked this conversation as resolved.
Show resolved Hide resolved
let fee_rate = self.estimate_fee_rate(confirmation_target);

let tx = {
Expand Down Expand Up @@ -284,10 +303,13 @@ where
let locked_fee_rate_cache = self.fee_rate_cache.read().unwrap();

let fallback_sats_kwu = match confirmation_target {
ConfirmationTarget::MempoolMinimum => FEERATE_FLOOR_SATS_PER_KW,
ConfirmationTarget::Background => 500,
ConfirmationTarget::Normal => 2000,
ConfirmationTarget::HighPriority => 5000,
ConfirmationTarget::OnChainSweep => 5000,
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => 25 * 250,
ConfirmationTarget::MinAllowedAnchorChannelRemoteFee => FEERATE_FLOOR_SATS_PER_KW,
ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => FEERATE_FLOOR_SATS_PER_KW,
ConfirmationTarget::AnchorChannelFee => 500,
ConfirmationTarget::NonAnchorChannelFee => 1000,
ConfirmationTarget::ChannelCloseMinimum => 500,
};

// We'll fall back on this, if we really don't have any other information.
Expand Down