Skip to content

Commit

Permalink
Update to LDK 0.0.123.
Browse files Browse the repository at this point in the history
  • Loading branch information
valentinewallace authored and orbitalturtle committed Jun 21, 2024
1 parent adb6d93 commit 3e54666
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 83 deletions.
29 changes: 14 additions & 15 deletions Cargo.lock

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

14 changes: 7 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
lightning = { version = "0.0.121", features = ["max_level_trace"] }
lightning-block-sync = { version = "0.0.121", features = [ "rpc-client", "tokio" ] }
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 = { version = "0.0.123", features = ["max_level_trace"] }
lightning-block-sync = { version = "0.0.123", features = [ "rpc-client", "tokio" ] }
lightning-invoice = { version = "0.31.0" }
lightning-net-tokio = { version = "0.0.123" }
lightning-persister = { version = "0.0.123" }
lightning-background-processor = { version = "0.0.123", features = [ "futures" ] }
lightning-rapid-gossip-sync = { version = "0.0.123" }

base64 = "0.13.0"
bitcoin = "0.30.2"
Expand Down
17 changes: 8 additions & 9 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ pub(crate) fn poll_for_user_input(
);
},
"getoffer" => {
let offer_builder = channel_manager.create_offer_builder(String::new());
let offer_builder = channel_manager.create_offer_builder();
if let Err(e) = offer_builder {
println!("ERROR: Failed to initiate offer building: {:?}", e);
continue;
Expand Down Expand Up @@ -603,14 +603,14 @@ fn node_info(channel_manager: &Arc<ChannelManager>, peer_manager: &Arc<PeerManag
println!("\t\t num_usable_channels: {}", chans.iter().filter(|c| c.is_usable).count());
let local_balance_msat = chans.iter().map(|c| c.balance_msat).sum::<u64>();
println!("\t\t local_balance_msat: {}", local_balance_msat);
println!("\t\t num_peers: {}", peer_manager.get_peer_node_ids().len());
println!("\t\t num_peers: {}", peer_manager.list_peers().len());
println!("\t}},");
}

fn list_peers(peer_manager: Arc<PeerManager>) {
println!("\t{{");
for (pubkey, _) in peer_manager.get_peer_node_ids() {
println!("\t\t pubkey: {}", pubkey);
for peer_details in peer_manager.list_peers() {
println!("\t\t pubkey: {}", peer_details.counterparty_node_id);
}
println!("\t}},");
}
Expand Down Expand Up @@ -701,8 +701,8 @@ fn list_payments(
pub(crate) async fn connect_peer_if_necessary(
pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
) -> Result<(), ()> {
for (node_pubkey, _) in peer_manager.get_peer_node_ids() {
if node_pubkey == pubkey {
for peer_details in peer_manager.list_peers() {
if peer_details.counterparty_node_id == pubkey {
return Ok(());
}
}
Expand All @@ -725,7 +725,7 @@ pub(crate) async fn do_connect_peer(
_ = &mut connection_closed_future => return Err(()),
_ = tokio::time::sleep(Duration::from_millis(10)) => {},
};
if peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey).is_some() {
if peer_manager.peer_by_node_id(&pubkey).is_some() {
return Ok(());
}
}
Expand All @@ -747,8 +747,7 @@ fn do_disconnect_peer(
}

//check the pubkey matches a valid connected peer
let peers = peer_manager.get_peer_node_ids();
if !peers.iter().any(|(pk, _)| &pubkey == pk) {
if peer_manager.peer_by_node_id(&pubkey).is_none() {
println!("Error: Could not find peer {}", pubkey);
return Err(());
}
Expand Down
55 changes: 27 additions & 28 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,13 +177,16 @@ pub(crate) type ChannelManager =
pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;

// Reminder: We define the OnionMessenger as such because we need to use the OnionMessageHandler.
// This deviates from the main ldk-sample fork.
// This also impacts the PeerManager and GossipVerifier type definitions above.
// This deviates from the main ldk-sample fork. This also impacts the PeerManager and
// GossipVerifier type definitions above.
// TODO: We should sync this with ldk-sample. Now ChannelManager implements the OnionMessageHandler
// and we no longer need to do this.
pub(crate) type OnionMessengerType = OnionMessenger<
Arc<KeysManager>,
Arc<KeysManager>,
Arc<FilesystemLogger>,
Arc<DefaultMessageRouter<Arc<NetworkGraph>, Arc<FilesystemLogger>>>,
Arc<ChannelManager>,
Arc<DefaultMessageRouter<Arc<NetworkGraph>, Arc<FilesystemLogger>, Arc<KeysManager>>>,
Arc<OnionMessageHandler>,
Arc<OnionMessageHandler>,
>;
Expand Down Expand Up @@ -268,7 +271,9 @@ async fn handle_ldk_events(
payment_hash, amount_msat,
);
let payment_preimage = match purpose {
PaymentPurpose::InvoicePayment { payment_preimage, .. } => payment_preimage,
PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => payment_preimage,
PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => payment_preimage,
PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => payment_preimage,
PaymentPurpose::SpontaneousPayment(preimage) => Some(preimage),
};

Expand All @@ -289,9 +294,15 @@ async fn handle_ldk_events(
print!("> ");
io::stdout().flush().unwrap();
let (payment_preimage, payment_secret) = match purpose {
PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
PaymentPurpose::Bolt11InvoicePayment {
payment_preimage, payment_secret, ..
} => (payment_preimage, Some(payment_secret)),
PaymentPurpose::Bolt12OfferPayment { payment_preimage, payment_secret, .. } => {
(payment_preimage, Some(payment_secret))
},
PaymentPurpose::Bolt12RefundPayment {
payment_preimage, payment_secret, ..
} => (payment_preimage, Some(payment_secret)),
PaymentPurpose::SpontaneousPayment(preimage) => (Some(preimage), None),
};
let mut inbound = inbound_payments.lock().unwrap();
Expand Down Expand Up @@ -401,9 +412,12 @@ async fn handle_ldk_events(
Event::PaymentForwarded {
prev_channel_id,
next_channel_id,
fee_earned_msat,
total_fee_earned_msat,
claim_from_onchain_tx,
outbound_amount_forwarded_msat,
skimmed_fee_msat: _,
prev_user_channel_id: _,
next_user_channel_id: _,
} => {
let read_only_network_graph = network_graph.read_only();
let nodes = read_only_network_graph.nodes();
Expand Down Expand Up @@ -446,7 +460,7 @@ async fn handle_ldk_events(
} else {
"?".to_string()
};
if let Some(fee_earned) = fee_earned_msat {
if let Some(fee_earned) = total_fee_earned_msat {
println!(
"\nEVENT: Forwarded payment for {} msat{}{}, earning {} msat {}",
amt_args, from_prev_str, to_next_str, fee_earned, from_onchain_str
Expand Down Expand Up @@ -527,20 +541,7 @@ async fn handle_ldk_events(
},
Event::HTLCIntercepted { .. } => {},
Event::BumpTransaction(event) => bump_tx_event_handler.handle_event(&event),
Event::ConnectionNeeded { node_id, addresses } => {
tokio::spawn(async move {
for address in addresses {
if let Ok(sockaddrs) = address.to_socket_addrs() {
for addr in sockaddrs {
let pm = Arc::clone(&peer_manager);
if node_api::connect_peer_if_necessary(node_id, addr, pm).await.is_ok() {
return;
}
}
}
}
});
},
Event::ConnectionNeeded { node_id, addresses } => {},
}
}

Expand Down Expand Up @@ -686,7 +687,7 @@ pub async fn start_ldk(args: config::LdkUserInfo, test_name: &str) -> node_api::
let router = Arc::new(DefaultRouter::new(
network_graph.clone(),
logger.clone(),
keys_manager.get_secure_random_bytes(),
keys_manager.clone(),
scorer.clone(),
scoring_fee_params,
));
Expand Down Expand Up @@ -722,7 +723,7 @@ pub async fn start_ldk(args: config::LdkUserInfo, test_name: &str) -> node_api::
restarting_node = false;

let polled_best_block = polled_chain_tip.to_best_block();
let polled_best_block_hash = polled_best_block.block_hash();
let polled_best_block_hash = polled_best_block.block_hash;
let chain_params =
ChainParameters { network: args.network, best_block: polled_best_block };
let fresh_channel_manager = channelmanager::ChannelManager::new(
Expand Down Expand Up @@ -806,11 +807,10 @@ pub async fn start_ldk(args: config::LdkUserInfo, test_name: &str) -> node_api::
Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
Arc::clone(&logger),
Arc::new(DefaultMessageRouter::new(Arc::clone(&network_graph))),
Arc::clone(&channel_manager),
Arc::new(DefaultMessageRouter::new(Arc::clone(&network_graph), Arc::clone(&keys_manager))),
Arc::clone(&onion_message_handler),
Arc::clone(&onion_message_handler),
// Arc::clone(&channel_manager),
// IgnoringMessageHandler {},
));
let mut ephemeral_bytes = [0; 32];
let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
Expand Down Expand Up @@ -989,12 +989,11 @@ pub async fn start_ldk(args: config::LdkUserInfo, test_name: &str) -> node_api::
interval.tick().await;
match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
Ok(info) => {
let peers = &connect_pm.get_peer_node_ids();
for node_id in connect_cm
.list_channels()
.iter()
.map(|chan| chan.counterparty.node_id)
.filter(|id| !peers.iter().any(|(pk, _)| id == pk))
.filter(|id| connect_pm.peer_by_node_id(id).is_none())
{
if stop_connect.load(Ordering::Acquire) {
return;
Expand Down
24 changes: 10 additions & 14 deletions src/node_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use tokio::sync::watch::Sender;
pub(crate) type Router = DefaultRouter<
Arc<NetworkGraph>,
Arc<FilesystemLogger>,
Arc<KeysManager>,
Arc<RwLock<Scorer>>,
ProbabilisticScoringFeeParameters,
Scorer,
Expand Down Expand Up @@ -69,8 +70,8 @@ impl Node {
&self, pubkey: PublicKey, peer_addr: SocketAddr,
) -> Result<(), ()> {
// If we're already connected to peer, then we're good to go.
for (node_pubkey, _) in self.peer_manager.get_peer_node_ids() {
if node_pubkey == pubkey {
for peer_details in self.peer_manager.list_peers() {
if peer_details.counterparty_node_id == pubkey {
return Ok(());
}
}
Expand Down Expand Up @@ -104,17 +105,11 @@ impl Node {
_ = &mut connection_closed_future => return Err(()),
_ = tokio::time::sleep(Duration::from_millis(10)) => {},
};
if self
.peer_manager
.get_peer_node_ids()
.iter()
.find(|(id, _)| *id == pubkey)
.is_some()
{
if self.peer_manager.peer_by_node_id(&pubkey).is_some() {
return Ok(());
}
}
}
},
None => Err(()),
}
}
Expand Down Expand Up @@ -186,7 +181,8 @@ impl Node {
BlindedPath::new_for_message(path_pubkeys, &*self.keys_manager, &secp_ctx).unwrap();
let (pubkey, _) = self.get_node_info();

OfferBuilder::new("testing offer".to_string(), pubkey)
OfferBuilder::new(pubkey)
.description("testing offer".to_string())
.amount_msats(msats)
.chain(network)
.supported_quantity(quantity)
Expand Down Expand Up @@ -230,8 +226,8 @@ fn open_channel(
pub(crate) async fn connect_peer_if_necessary(
pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManagerType>,
) -> Result<(), ()> {
for (node_pubkey, _) in peer_manager.get_peer_node_ids() {
if node_pubkey == pubkey {
for peer_details in peer_manager.list_peers() {
if peer_details.counterparty_node_id == pubkey {
return Ok(());
}
}
Expand All @@ -254,7 +250,7 @@ pub(crate) async fn do_connect_peer(
_ = &mut connection_closed_future => return Err(()),
_ = tokio::time::sleep(Duration::from_millis(10)) => {},
};
if peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey).is_some() {
if peer_manager.peer_by_node_id(&pubkey).is_some() {
return Ok(());
}
}
Expand Down
Loading

0 comments on commit 3e54666

Please sign in to comment.