Skip to content

Commit

Permalink
Merge pull request #123 from TheBlueMatt/main
Browse files Browse the repository at this point in the history
Upgrade to LDK 0.0.118
  • Loading branch information
tnull committed Nov 14, 2023
2 parents 941cab5 + 37da86a commit 5b81f38
Show file tree
Hide file tree
Showing 7 changed files with 131 additions and 90 deletions.
7 changes: 0 additions & 7 deletions Cargo.lock

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

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

[dependencies]
lightning = { version = "0.0.117", features = ["max_level_trace"] }
lightning-block-sync = { version = "0.0.117", features = [ "rpc-client", "tokio" ] }
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 = { version = "0.0.118", features = ["max_level_trace"] }
lightning-block-sync = { version = "0.0.118", features = [ "rpc-client", "tokio" ] }
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" }

base64 = "0.13.0"
bitcoin = "0.29.0"
bitcoin-bech32 = "0.12"
bech32 = "0.8"
hex = "0.3"
libc = "0.2"

chrono = { version = "0.4", default-features = false, features = ["clock"] }
Expand Down
52 changes: 34 additions & 18 deletions src/bitcoind_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use bitcoin::{OutPoint, Script, TxOut, WPubkeyHash, XOnlyPublicKey};
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning::events::bump_transaction::{Utxo, WalletSource};
use lightning::log_error;
use lightning::routing::utxo::{UtxoLookup, UtxoResult};
use lightning::util::logger::Logger;
use lightning_block_sync::http::HttpEndpoint;
use lightning_block_sync::rpc::RpcClient;
Expand Down Expand Up @@ -76,10 +75,23 @@ impl BitcoindClient {
"Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
})?;
let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
fees.insert(ConfirmationTarget::MempoolMinimum, AtomicU32::new(MIN_FEERATE));
fees.insert(ConfirmationTarget::Background, AtomicU32::new(MIN_FEERATE));
fees.insert(ConfirmationTarget::Normal, AtomicU32::new(2000));
fees.insert(ConfirmationTarget::HighPriority, AtomicU32::new(5000));
fees.insert(ConfirmationTarget::OnChainSweep, AtomicU32::new(5000));
fees.insert(
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
AtomicU32::new(25 * 250),
);
fees.insert(
ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
AtomicU32::new(MIN_FEERATE),
);
fees.insert(
ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
AtomicU32::new(MIN_FEERATE),
);
fees.insert(ConfirmationTarget::AnchorChannelFee, AtomicU32::new(MIN_FEERATE));
fees.insert(ConfirmationTarget::NonAnchorChannelFee, AtomicU32::new(2000));
fees.insert(ConfirmationTarget::ChannelCloseMinimum, AtomicU32::new(MIN_FEERATE));

let client = Self {
bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
host,
Expand Down Expand Up @@ -163,18 +175,28 @@ impl BitcoindClient {
}
};

fees.get(&ConfirmationTarget::MempoolMinimum)
fees.get(&ConfirmationTarget::OnChainSweep)
.unwrap()
.store(high_prio_estimate, Ordering::Release);
fees.get(&ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee)
.unwrap()
.store(std::cmp::max(25 * 250, high_prio_estimate * 10), Ordering::Release);
fees.get(&ConfirmationTarget::MinAllowedAnchorChannelRemoteFee)
.unwrap()
.store(mempoolmin_estimate, Ordering::Release);
fees.get(&ConfirmationTarget::Background)
fees.get(&ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee)
.unwrap()
.store(background_estimate - 250, Ordering::Release);
fees.get(&ConfirmationTarget::AnchorChannelFee)
.unwrap()
.store(background_estimate, Ordering::Release);
fees.get(&ConfirmationTarget::Normal)
fees.get(&ConfirmationTarget::NonAnchorChannelFee)
.unwrap()
.store(normal_estimate, Ordering::Release);
fees.get(&ConfirmationTarget::HighPriority)
fees.get(&ConfirmationTarget::ChannelCloseMinimum)
.unwrap()
.store(high_prio_estimate, Ordering::Release);
.store(background_estimate, Ordering::Release);

tokio::time::sleep(Duration::from_secs(60)).await;
}
});
Expand Down Expand Up @@ -204,7 +226,8 @@ impl BitcoindClient {
// LDK gives us feerates in satoshis per KW but Bitcoin Core here expects fees
// denominated in satoshis per vB. First we need to multiply by 4 to convert weight
// units to virtual bytes, then divide by 1000 to convert KvB to vB.
"fee_rate": self.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as f64 / 250.0,
"fee_rate": self
.get_est_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee) as f64 / 250.0,
// While users could "cancel" a channel open by RBF-bumping and paying back to
// themselves, we don't allow it here as its easy to have users accidentally RBF bump
// and pay to the channel funding address, which results in loss of funds. Real
Expand Down Expand Up @@ -296,13 +319,6 @@ impl BroadcasterInterface for BitcoindClient {
}
}

impl UtxoLookup for BitcoindClient {
fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
// P2PGossipSync takes None for a UtxoLookup, so this will never be called.
todo!();
}
}

impl WalletSource for BitcoindClient {
fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
let utxos = tokio::task::block_in_place(move || {
Expand Down
44 changes: 23 additions & 21 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::disk::{self, INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
use crate::hex_utils;
use crate::{
ChannelManager, HTLCStatus, MillisatAmount, NetworkGraph, OnionMessenger, PaymentInfo,
PaymentInfoStorage, PeerManager,
ChannelManager, HTLCStatus, InboundPaymentInfoStorage, MillisatAmount, NetworkGraph,
OnionMessenger, OutboundPaymentInfoStorage, PaymentInfo, PeerManager,
};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::Hash;
Expand All @@ -12,7 +12,7 @@ use lightning::ln::channelmanager::{PaymentId, RecipientOnionFields, Retry};
use lightning::ln::msgs::SocketAddress;
use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage};
use lightning::onion_message::OnionMessagePath;
use lightning::onion_message::{CustomOnionMessageContents, Destination, OnionMessageContents};
use lightning::onion_message::{Destination, OnionMessageContents};
use lightning::routing::gossip::NodeId;
use lightning::routing::router::{PaymentParameters, RouteParameters};
use lightning::sign::{EntropySource, KeysManager};
Expand Down Expand Up @@ -48,7 +48,7 @@ struct UserOnionMessageContents {
data: Vec<u8>,
}

impl CustomOnionMessageContents for UserOnionMessageContents {
impl OnionMessageContents for UserOnionMessageContents {
fn tlv_type(&self) -> u64 {
self.tlv_type
}
Expand All @@ -63,9 +63,9 @@ impl Writeable for UserOnionMessageContents {
pub(crate) fn poll_for_user_input(
peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<PaymentInfoStorage>>,
outbound_payments: Arc<Mutex<PaymentInfoStorage>>, ldk_data_dir: String, network: Network,
logger: Arc<disk::FilesystemLogger>, fs_store: Arc<FilesystemStore>,
onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<InboundPaymentInfoStorage>>,
outbound_payments: Arc<Mutex<OutboundPaymentInfoStorage>>, ldk_data_dir: String,
network: Network, logger: Arc<disk::FilesystemLogger>, fs_store: Arc<FilesystemStore>,
) {
println!(
"LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
Expand Down Expand Up @@ -445,7 +445,7 @@ pub(crate) fn poll_for_user_input(
let message_path = OnionMessagePath { intermediate_nodes, destination };
match onion_messenger.send_onion_message(
message_path,
OnionMessageContents::Custom(UserOnionMessageContents { tlv_type, data }),
UserOnionMessageContents { tlv_type, data },
None,
) {
Ok(()) => println!("SUCCESS: forwarded onion message to first hop"),
Expand Down Expand Up @@ -553,7 +553,9 @@ fn list_channels(channel_manager: &Arc<ChannelManager>, network_graph: &Arc<Netw
println!("]");
}

fn list_payments(inbound_payments: &PaymentInfoStorage, outbound_payments: &PaymentInfoStorage) {
fn list_payments(
inbound_payments: &InboundPaymentInfoStorage, outbound_payments: &OutboundPaymentInfoStorage,
) {
print!("[");
for (payment_hash, payment_info) in &inbound_payments.payments {
println!("");
Expand Down Expand Up @@ -684,12 +686,12 @@ fn open_channel(

fn send_payment(
channel_manager: &ChannelManager, invoice: &Bolt11Invoice,
outbound_payments: &mut PaymentInfoStorage, fs_store: Arc<FilesystemStore>,
outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
) {
let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
let payment_id = PaymentId((*invoice.payment_hash()).into_inner());
let payment_secret = Some(*invoice.payment_secret());
outbound_payments.payments.insert(
payment_hash,
payment_id,
PaymentInfo {
preimage: None,
secret: payment_secret,
Expand All @@ -708,25 +710,25 @@ fn send_payment(
Err(e) => {
println!("ERROR: failed to send payment: {:?}", e);
print!("> ");
outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed;
outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
}
};
}

fn keysend<E: EntropySource>(
channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E,
outbound_payments: &mut PaymentInfoStorage, fs_store: Arc<FilesystemStore>,
outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
) {
let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).into_inner());

let route_params = RouteParameters::from_payment_params_and_value(
PaymentParameters::for_keysend(payee_pubkey, 40, false),
amt_msat,
);
outbound_payments.payments.insert(
payment_hash,
payment_id,
PaymentInfo {
preimage: None,
secret: None,
Expand All @@ -738,7 +740,7 @@ fn keysend<E: EntropySource>(
match channel_manager.send_spontaneous_payment_with_retry(
Some(payment_preimage),
RecipientOnionFields::spontaneous_empty(),
PaymentId(payment_hash.0),
payment_id,
route_params,
Retry::Timeout(Duration::from_secs(10)),
) {
Expand All @@ -749,16 +751,16 @@ fn keysend<E: EntropySource>(
Err(e) => {
println!("ERROR: failed to send payment: {:?}", e);
print!("> ");
outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed;
outbound_payments.payments.get_mut(&payment_id).unwrap().status = HTLCStatus::Failed;
fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
}
};
}

fn get_invoice(
amt_msat: u64, inbound_payments: &mut PaymentInfoStorage, channel_manager: &ChannelManager,
keys_manager: Arc<KeysManager>, network: Network, expiry_secs: u32,
logger: Arc<disk::FilesystemLogger>,
amt_msat: u64, inbound_payments: &mut InboundPaymentInfoStorage,
channel_manager: &ChannelManager, keys_manager: Arc<KeysManager>, network: Network,
expiry_secs: u32, logger: Arc<disk::FilesystemLogger>,
) {
let currency = match network {
Network::Bitcoin => Currency::Bitcoin,
Expand Down
17 changes: 13 additions & 4 deletions src/disk.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{cli, NetworkGraph, PaymentInfoStorage};
use crate::{cli, InboundPaymentInfoStorage, NetworkGraph, OutboundPaymentInfoStorage};
use bitcoin::secp256k1::PublicKey;
use bitcoin::Network;
use chrono::Utc;
Expand Down Expand Up @@ -86,13 +86,22 @@ pub(crate) fn read_network(
NetworkGraph::new(network, logger)
}

pub(crate) fn read_payment_info(path: &Path) -> PaymentInfoStorage {
pub(crate) fn read_inbound_payment_info(path: &Path) -> InboundPaymentInfoStorage {
if let Ok(file) = File::open(path) {
if let Ok(info) = PaymentInfoStorage::read(&mut BufReader::new(file)) {
if let Ok(info) = InboundPaymentInfoStorage::read(&mut BufReader::new(file)) {
return info;
}
}
PaymentInfoStorage { payments: HashMap::new() }
InboundPaymentInfoStorage { payments: HashMap::new() }
}

pub(crate) fn read_outbound_payment_info(path: &Path) -> OutboundPaymentInfoStorage {
if let Ok(file) = File::open(path) {
if let Ok(info) = OutboundPaymentInfoStorage::read(&mut BufReader::new(file)) {
return info;
}
}
OutboundPaymentInfoStorage { payments: HashMap::new() }
}

pub(crate) fn read_scorer(
Expand Down
Loading

0 comments on commit 5b81f38

Please sign in to comment.