Skip to content

Commit

Permalink
Upgrade to LDK v0.0.123-beta
Browse files Browse the repository at this point in the history
  • Loading branch information
tnull committed Apr 25, 2024
1 parent 71b1d3c commit a624501
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 100 deletions.
20 changes: 11 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,16 @@ panic = 'abort' # Abort on panic
default = []

[dependencies]
lightning = { version = "0.0.121", features = ["std"] }
lightning-invoice = { version = "0.29.0" }
lightning-net-tokio = { version = "0.0.121" }
lightning-persister = { version = "0.0.121" }
lightning-background-processor = { version = "0.0.121", features = ["futures"] }
lightning-rapid-gossip-sync = { version = "0.0.121" }
lightning-transaction-sync = { version = "0.0.121", features = ["esplora-async-https", "time"] }
lightning-liquidity = { version = "0.1.0-alpha.1", features = ["std"] }
lightning = { version = "0.0.123-beta", features = ["std"] }
lightning-invoice = { version = "0.31.0-beta" }
lightning-net-tokio = { version = "0.0.123-beta" }
lightning-persister = { version = "0.0.123-beta" }
lightning-background-processor = { version = "0.0.123-beta", features = ["futures"] }
lightning-rapid-gossip-sync = { version = "0.0.123-beta" }
lightning-transaction-sync = { version = "0.0.123-beta", features = ["esplora-async-https", "time"] }
#lightning-liquidity = { version = "0.1.0-alpha.1", features = ["std"] }

lightning-liquidity = { git = "https://github.com/tnull/lightning-liquidity", rev = "abf7088c0e03221c0f122e797f34802c9e99a3d4", features = ["std"] }

#lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["std"] }
#lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
Expand Down Expand Up @@ -78,7 +80,7 @@ prost = { version = "0.11.6", default-features = false}
winapi = { version = "0.3", features = ["winbase"] }

[dev-dependencies]
lightning = { version = "0.0.121", features = ["std", "_test_utils"] }
lightning = { version = "0.0.123-beta", features = ["std", "_test_utils"] }
#lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["std", "_test_utils"] }
electrum-client = { version = "0.15.1", default-features = true }
bitcoincore-rpc = { version = "0.17.0", default-features = false }
Expand Down
23 changes: 13 additions & 10 deletions bindings/ldk_node.udl
Original file line number Diff line number Diff line change
Expand Up @@ -190,16 +190,19 @@ enum PaymentFailureReason {

[Enum]
interface ClosureReason {
CounterpartyForceClosed ( UntrustedString peer_msg );
HolderForceClosed ();
CooperativeClosure ();
CommitmentTxConfirmed ();
FundingTimedOut ();
ProcessingError ( string err );
DisconnectedPeer ();
OutdatedChannelManager ();
CounterpartyCoopClosedUnfundedChannel ();
FundingBatchClosure ();
CounterpartyForceClosed(UntrustedString peer_msg);
HolderForceClosed();
LegacyCooperativeClosure();
CounterpartyInitiatedCooperativeClosure();
LocallyInitiatedCooperativeClosure();
CommitmentTxConfirmed();
FundingTimedOut();
ProcessingError(string err);
DisconnectedPeer();
OutdatedChannelManager();
CounterpartyCoopClosedUnfundedChannel();
FundingBatchClosure();
HTLCsTimedOut();
};

enum PaymentDirection {
Expand Down
11 changes: 7 additions & 4 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::peer_store::PeerStore;
use crate::sweep::OutputSweeper;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, FakeMessageRouter, GossipSync, KeysManager, NetworkGraph,
ChainMonitor, ChannelManager, GossipSync, KeysManager, MessageRouter, NetworkGraph,
OnionMessenger, PeerManager,
};
use crate::wallet::Wallet;
Expand Down Expand Up @@ -664,7 +664,7 @@ fn build_with_store_internal<K: KVStore + Sync + Send + 'static>(
let router = Arc::new(DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
keys_manager.get_secure_random_bytes(),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
Expand Down Expand Up @@ -776,12 +776,15 @@ fn build_with_store_internal<K: KVStore + Sync + Send + 'static>(
})?;
}

let message_router = MessageRouter::new(Arc::clone(&network_graph), Arc::clone(&keys_manager));

// Initialize the PeerManager
let onion_messenger: Arc<OnionMessenger> = Arc::new(OnionMessenger::new(
let onion_messenger: Arc<OnionMessenger<K>> = Arc::new(OnionMessenger::new(
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
Arc::clone(&logger),
Arc::new(FakeMessageRouter {}),
Arc::clone(&channel_manager),
Arc::new(message_router),
IgnoringMessageHandler {},
IgnoringMessageHandler {},
));
Expand Down
54 changes: 49 additions & 5 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ where
let confirmation_target = ConfirmationTarget::NonAnchorChannelFee;

// We set nLockTime to the current height to discourage fee sniping.
let cur_height = self.channel_manager.current_best_block().height();
let cur_height = self.channel_manager.current_best_block().height;
let locktime = LockTime::from_height(cur_height).unwrap_or(LockTime::ZERO);

// Sign the final funding transaction and broadcast it.
Expand Down Expand Up @@ -474,7 +474,7 @@ where
amount_msat,
);
let payment_preimage = match purpose {
PaymentPurpose::InvoicePayment { payment_preimage, payment_secret } => {
PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret } => {
if payment_preimage.is_some() {
payment_preimage
} else {
Expand All @@ -483,6 +483,26 @@ where
.ok()
}
},
PaymentPurpose::Bolt12OfferPayment { .. } => {
// TODO: support BOLT12.
log_error!(
self.logger,
"Failed to claim unsupported BOLT12 payment with hash: {}",
payment_hash
);
self.channel_manager.fail_htlc_backwards(&payment_hash);
return;
},
PaymentPurpose::Bolt12RefundPayment { .. } => {
// TODO: support BOLT12.
log_error!(
self.logger,
"Failed to claim unsupported BOLT12 payment with hash: {}",
payment_hash
);
self.channel_manager.fail_htlc_backwards(&payment_hash);
return;
},
PaymentPurpose::SpontaneousPayment(preimage) => Some(preimage),
};

Expand Down Expand Up @@ -521,7 +541,11 @@ where
amount_msat,
);
match purpose {
PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
PaymentPurpose::Bolt11InvoicePayment {
payment_preimage,
payment_secret,
..
} => {
let update = PaymentDetailsUpdate {
preimage: Some(payment_preimage),
secret: Some(Some(payment_secret)),
Expand Down Expand Up @@ -550,6 +574,24 @@ where
},
}
},
PaymentPurpose::Bolt12OfferPayment { .. } => {
// TODO: support BOLT12.
log_error!(
self.logger,
"Failed to claim unsupported BOLT12 payment with hash: {}",
payment_hash
);
return;
},
PaymentPurpose::Bolt12RefundPayment { .. } => {
// TODO: support BOLT12.
log_error!(
self.logger,
"Failed to claim unsupported BOLT12 payment with hash: {}",
payment_hash
);
return;
},
PaymentPurpose::SpontaneousPayment(preimage) => {
let payment = PaymentDetails {
preimage: Some(preimage),
Expand Down Expand Up @@ -717,9 +759,10 @@ where
LdkEvent::PaymentForwarded {
prev_channel_id,
next_channel_id,
fee_earned_msat,
total_fee_earned_msat,
claim_from_onchain_tx,
outbound_amount_forwarded_msat,
..
} => {
let read_only_network_graph = self.network_graph.read_only();
let nodes = read_only_network_graph.nodes();
Expand Down Expand Up @@ -752,7 +795,7 @@ where
let to_next_str =
format!(" to {}{}", node_str(&next_channel_id), channel_str(&next_channel_id));

let fee_earned = fee_earned_msat.unwrap_or(0);
let fee_earned = total_fee_earned_msat.unwrap_or(0);
let outbound_amount_forwarded_msat = outbound_amount_forwarded_msat.unwrap_or(0);
if claim_from_onchain_tx {
log_info!(
Expand Down Expand Up @@ -780,6 +823,7 @@ where
former_temporary_channel_id,
counterparty_node_id,
funding_txo,
..
} => {
log_info!(
self.logger,
Expand Down
3 changes: 3 additions & 0 deletions src/fee_estimator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ where
ConfirmationTarget::AnchorChannelFee,
ConfirmationTarget::NonAnchorChannelFee,
ConfirmationTarget::ChannelCloseMinimum,
ConfirmationTarget::OutputSpendingFee,
];
for target in confirmation_targets {
let num_blocks = match target {
Expand All @@ -51,6 +52,7 @@ where
ConfirmationTarget::AnchorChannelFee => 1008,
ConfirmationTarget::NonAnchorChannelFee => 12,
ConfirmationTarget::ChannelCloseMinimum => 144,
ConfirmationTarget::OutputSpendingFee => 12,
};

let estimates = self.esplora_client.get_fee_estimates().await.map_err(|e| {
Expand Down Expand Up @@ -119,6 +121,7 @@ where
ConfirmationTarget::AnchorChannelFee => 500,
ConfirmationTarget::NonAnchorChannelFee => 1000,
ConfirmationTarget::ChannelCloseMinimum => 500,
ConfirmationTarget::OutputSpendingFee => 1000,
};

// We'll fall back on this, if we really don't have any other information.
Expand Down
32 changes: 14 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub use error::Error as NodeError;
use error::Error;

pub use event::Event;
pub use types::{BestBlock, ChannelConfig};
pub use types::ChannelConfig;

pub use io::utils::generate_entropy_mnemonic;

Expand Down Expand Up @@ -138,7 +138,7 @@ pub use types::{ChannelDetails, PeerDetails, UserChannelId};

use logger::{log_error, log_info, log_trace, FilesystemLogger, Logger};

use lightning::chain::Confirm;
use lightning::chain::{BestBlock, Confirm};
use lightning::ln::channelmanager::{self, PaymentId, RecipientOnionFields, Retry};
use lightning::ln::msgs::SocketAddress;
use lightning::ln::{PaymentHash, PaymentPreimage};
Expand All @@ -157,7 +157,6 @@ use lightning_transaction_sync::EsploraSyncClient;
use lightning::routing::router::{PaymentParameters, RouteParameters};
use lightning_invoice::{payment, Bolt11Invoice, Currency};

use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::PublicKey;

Expand Down Expand Up @@ -515,9 +514,9 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
}
_ = interval.tick() => {
let pm_peers = connect_pm
.get_peer_node_ids()
.list_peers()
.iter()
.map(|(peer, _addr)| *peer)
.map(|peer| peer.counterparty_node_id)
.collect::<Vec<_>>();

for peer_info in connect_peer_store.list_peers().iter().filter(|info| !pm_peers.contains(&info.node_id)) {
Expand Down Expand Up @@ -579,7 +578,7 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
continue;
}

if bcast_pm.get_peer_node_ids().is_empty() {
if bcast_pm.list_peers().is_empty() {
// Skip if we don't have any connected peers to gossip to.
continue;
}
Expand Down Expand Up @@ -1301,7 +1300,7 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
}

let payment_preimage = PaymentPreimage(self.keys_manager.get_secure_random_bytes());
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
let payment_hash = PaymentHash::from(payment_preimage);

if let Some(payment) = self.payment_store.get(&payment_hash) {
if payment.status == PaymentStatus::Pending
Expand Down Expand Up @@ -1690,11 +1689,9 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {

let mut total_lightning_balance_sats = 0;
let mut lightning_balances = Vec::new();
for funding_txo in self.chain_monitor.list_monitors() {
for (funding_txo, channel_id) in self.chain_monitor.list_monitors() {
match self.chain_monitor.get_monitor(funding_txo) {
Ok(monitor) => {
// TODO: Switch to `channel_id` with LDK 0.0.122: let channel_id = monitor.channel_id();
let channel_id = funding_txo.to_channel_id();
// unwrap safety: `get_counterparty_node_id` will always be `Some` after 0.0.110 and
// LDK Node 0.1 depended on 0.0.115 already.
let counterparty_node_id = monitor.get_counterparty_node_id().unwrap();
Expand Down Expand Up @@ -1758,12 +1755,13 @@ impl<K: KVStore + Sync + Send + 'static> Node<K> {
let mut peers = Vec::new();

// First add all connected peers, preferring to list the connected address if available.
let connected_peers = self.peer_manager.get_peer_node_ids();
let connected_peers = self.peer_manager.list_peers();
let connected_peers_len = connected_peers.len();
for (node_id, con_addr_opt) in connected_peers {
for connected_peer in connected_peers {
let node_id = connected_peer.counterparty_node_id;
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) {
let address = match (connected_peer.socket_address, stored_addr_opt) {
(Some(con_addr), _) => con_addr,
(None, Some(stored_addr)) => stored_addr,
(None, None) => continue,
Expand Down Expand Up @@ -1858,10 +1856,8 @@ async fn connect_peer_if_necessary<K: KVStore + Sync + Send + 'static>(
node_id: PublicKey, addr: SocketAddress, peer_manager: Arc<PeerManager<K>>,
logger: Arc<FilesystemLogger>,
) -> Result<(), Error> {
for (pman_node_id, _pman_addr) in peer_manager.get_peer_node_ids() {
if node_id == pman_node_id {
return Ok(());
}
if peer_manager.peer_by_node_id(&node_id).is_some() {
return Ok(());
}

do_connect_peer(node_id, addr, peer_manager, logger).await
Expand Down Expand Up @@ -1896,7 +1892,7 @@ async fn do_connect_peer<K: KVStore + Sync + Send + 'static>(
std::task::Poll::Pending => {},
}
// Avoid blocking the tokio context by sleeping a bit
match peer_manager.get_peer_node_ids().iter().find(|(id, _addr)| *id == node_id) {
match peer_manager.peer_by_node_id(&node_id) {
Some(_) => return Ok(()),
None => tokio::time::sleep(Duration::from_millis(10)).await,
}
Expand Down
14 changes: 7 additions & 7 deletions src/sweep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ where
fn rebroadcast_if_necessary(&self) {
let (cur_height, cur_hash) = {
let best_block = self.best_block.lock().unwrap();
(best_block.height(), best_block.block_hash())
(best_block.height, best_block.block_hash)
};

let mut respend_descriptors = Vec::new();
Expand Down Expand Up @@ -277,7 +277,7 @@ where
}

fn prune_confirmed_outputs(&self) {
let cur_height = self.best_block.lock().unwrap().height();
let cur_height = self.best_block.lock().unwrap().height;
let mut locked_outputs = self.outputs.lock().unwrap();

// Prune all outputs that have sufficient depth by now.
Expand Down Expand Up @@ -314,7 +314,7 @@ where
&self, output_descriptors: &Vec<SpendableOutputDescriptor>, cur_height: u32,
) -> Result<Transaction, ()> {
let tx_feerate =
self.fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
self.fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::OutputSpendingFee);

let destination_address = self.wallet.get_new_address().map_err(|e| {
log_error!(self.logger, "Failed to get destination address from wallet: {}", e);
Expand Down Expand Up @@ -370,9 +370,9 @@ where
) {
{
let best_block = self.best_block.lock().unwrap();
assert_eq!(best_block.block_hash(), header.prev_blockhash,
assert_eq!(best_block.block_hash, header.prev_blockhash,
"Blocks must be connected in chain-order - the connected header must build on the last connected header");
assert_eq!(best_block.height(), height - 1,
assert_eq!(best_block.height, height - 1,
"Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
}

Expand All @@ -384,9 +384,9 @@ where
let new_height = height - 1;
{
let mut best_block = self.best_block.lock().unwrap();
assert_eq!(best_block.block_hash(), header.block_hash(),
assert_eq!(best_block.block_hash, header.block_hash(),
"Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
assert_eq!(best_block.height(), height,
assert_eq!(best_block.height, height,
"Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
*best_block = BestBlock::new(header.prev_blockhash, new_height)
}
Expand Down
Loading

0 comments on commit a624501

Please sign in to comment.