Skip to content

Commit 2b0c4a1

Browse files
committed
Update to LDK v.0.0.120
1 parent 5b81f38 commit 2b0c4a1

File tree

8 files changed

+301
-147
lines changed

8 files changed

+301
-147
lines changed

Cargo.lock

Lines changed: 218 additions & 81 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,16 @@ edition = "2018"
88
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
99

1010
[dependencies]
11-
lightning = { version = "0.0.118", features = ["max_level_trace"] }
12-
lightning-block-sync = { version = "0.0.118", features = [ "rpc-client", "tokio" ] }
13-
lightning-invoice = { version = "0.26.0" }
14-
lightning-net-tokio = { version = "0.0.118" }
15-
lightning-persister = { version = "0.0.118" }
16-
lightning-background-processor = { version = "0.0.118", features = [ "futures" ] }
17-
lightning-rapid-gossip-sync = { version = "0.0.118" }
11+
lightning = { version = "0.0.120", features = ["max_level_trace"] }
12+
lightning-block-sync = { version = "0.0.120", features = [ "rpc-client", "tokio" ] }
13+
lightning-invoice = { version = "0.28.0" }
14+
lightning-net-tokio = { version = "0.0.120" }
15+
lightning-persister = { version = "0.0.120" }
16+
lightning-background-processor = { version = "0.0.120", features = [ "futures" ] }
17+
lightning-rapid-gossip-sync = { version = "0.0.120" }
1818

1919
base64 = "0.13.0"
20-
bitcoin = "0.29.0"
20+
bitcoin = "0.30.2"
2121
bitcoin-bech32 = "0.12"
2222
bech32 = "0.8"
2323
libc = "0.2"

src/bitcoind_client.rs

Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@ use crate::disk::FilesystemLogger;
66
use crate::hex_utils;
77
use base64;
88
use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
9+
use bitcoin::blockdata::script::ScriptBuf;
910
use bitcoin::blockdata::transaction::Transaction;
1011
use bitcoin::consensus::{encode, Decodable, Encodable};
1112
use bitcoin::hash_types::{BlockHash, Txid};
1213
use bitcoin::hashes::Hash;
13-
use bitcoin::util::address::{Address, Payload, WitnessVersion};
14-
use bitcoin::{OutPoint, Script, TxOut, WPubkeyHash, XOnlyPublicKey};
14+
use bitcoin::address::{Address, Payload, WitnessVersion};
15+
use bitcoin::psbt::PartiallySignedTransaction;
16+
use bitcoin::{OutPoint, TxOut, WPubkeyHash, Network};
17+
use bitcoin::key::XOnlyPublicKey;
1518
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
1619
use lightning::events::bump_transaction::{Utxo, WalletSource};
1720
use lightning::log_error;
@@ -28,6 +31,7 @@ use std::time::Duration;
2831

2932
pub struct BitcoindClient {
3033
pub(crate) bitcoind_rpc_client: Arc<RpcClient>,
34+
network: Network,
3135
host: String,
3236
port: u16,
3337
rpc_user: String,
@@ -60,7 +64,7 @@ const MIN_FEERATE: u32 = 253;
6064

6165
impl BitcoindClient {
6266
pub(crate) async fn new(
63-
host: String, port: u16, rpc_user: String, rpc_password: String,
67+
host: String, port: u16, rpc_user: String, rpc_password: String, network: Network,
6468
handle: tokio::runtime::Handle, logger: Arc<FilesystemLogger>,
6569
) -> std::io::Result<Self> {
6670
let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
@@ -76,10 +80,6 @@ impl BitcoindClient {
7680
})?;
7781
let mut fees: HashMap<ConfirmationTarget, AtomicU32> = HashMap::new();
7882
fees.insert(ConfirmationTarget::OnChainSweep, AtomicU32::new(5000));
79-
fees.insert(
80-
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
81-
AtomicU32::new(25 * 250),
82-
);
8383
fees.insert(
8484
ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
8585
AtomicU32::new(MIN_FEERATE),
@@ -98,6 +98,7 @@ impl BitcoindClient {
9898
port,
9999
rpc_user,
100100
rpc_password,
101+
network,
101102
fees: Arc::new(fees),
102103
handle: handle.clone(),
103104
logger,
@@ -178,9 +179,6 @@ impl BitcoindClient {
178179
fees.get(&ConfirmationTarget::OnChainSweep)
179180
.unwrap()
180181
.store(high_prio_estimate, Ordering::Release);
181-
fees.get(&ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee)
182-
.unwrap()
183-
.store(std::cmp::max(25 * 250, high_prio_estimate * 10), Ordering::Release);
184182
fees.get(&ConfirmationTarget::MinAllowedAnchorChannelRemoteFee)
185183
.unwrap()
186184
.store(mempoolmin_estimate, Ordering::Release);
@@ -264,7 +262,7 @@ impl BitcoindClient {
264262
.call_method::<NewAddress>("getnewaddress", &addr_args)
265263
.await
266264
.unwrap();
267-
Address::from_str(addr.0.as_str()).unwrap()
265+
Address::from_str(addr.0.as_str()).unwrap().require_network(self.network).unwrap()
268266
}
269267

270268
pub async fn get_blockchain_info(&self) -> BlockchainInfo {
@@ -328,21 +326,29 @@ impl WalletSource for BitcoindClient {
328326
.into_iter()
329327
.filter_map(|utxo| {
330328
let outpoint = OutPoint { txid: utxo.txid, vout: utxo.vout };
331-
match utxo.address.payload {
332-
Payload::WitnessProgram { version, ref program } => match version {
333-
WitnessVersion::V0 => WPubkeyHash::from_slice(program)
334-
.map(|wpkh| Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &wpkh))
335-
.ok(),
329+
match utxo.address.payload.clone() {
330+
Payload::WitnessProgram(wp) => match wp.version() {
331+
WitnessVersion::V0 => {
332+
bitcoin::hashes::hash160::Hash::from_slice(wp.program().as_bytes())
333+
.map(|hash|
334+
Utxo::new_v0_p2wpkh(outpoint, utxo.amount, &WPubkeyHash::from_raw_hash(hash))
335+
)
336+
.ok()
337+
}
336338
// TODO: Add `Utxo::new_v1_p2tr` upstream.
337-
WitnessVersion::V1 => XOnlyPublicKey::from_slice(program)
338-
.map(|_| Utxo {
339-
outpoint,
340-
output: TxOut {
341-
value: utxo.amount,
342-
script_pubkey: Script::new_witness_program(version, program),
343-
},
344-
satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
345-
1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
339+
WitnessVersion::V1 => bitcoin::hashes::hash160::Hash::from_slice(wp.program().as_bytes())
340+
.map(|wp_hash| {
341+
let _pubkey = XOnlyPublicKey::from_slice(wp_hash.as_byte_array())
342+
.expect("Invalid pubkey length");
343+
Utxo {
344+
outpoint,
345+
output: TxOut {
346+
value: utxo.amount,
347+
script_pubkey: ScriptBuf::new_witness_program(&wp),
348+
},
349+
satisfaction_weight: 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64 +
350+
1 /* witness items */ + 1 /* schnorr sig len */ + 64, /* schnorr sig */
351+
}
346352
})
347353
.ok(),
348354
_ => None,
@@ -353,15 +359,15 @@ impl WalletSource for BitcoindClient {
353359
.collect())
354360
}
355361

356-
fn get_change_script(&self) -> Result<Script, ()> {
362+
fn get_change_script(&self) -> Result<ScriptBuf, ()> {
357363
tokio::task::block_in_place(move || {
358364
Ok(self.handle.block_on(async move { self.get_new_address().await.script_pubkey() }))
359365
})
360366
}
361367

362-
fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
368+
fn sign_psbt(&self, tx: PartiallySignedTransaction) -> Result<Transaction, ()> {
363369
let mut tx_bytes = Vec::new();
364-
let _ = tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
370+
let _ = tx.unsigned_tx.consensus_encode(&mut tx_bytes).map_err(|_| ());
365371
let tx_hex = hex_utils::hex_str(&tx_bytes);
366372
let signed_tx = tokio::task::block_in_place(move || {
367373
self.handle.block_on(async move { self.sign_raw_transaction_with_wallet(tx_hex).await })

src/cli.rs

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,14 @@ use bitcoin::secp256k1::PublicKey;
1111
use lightning::ln::channelmanager::{PaymentId, RecipientOnionFields, Retry};
1212
use lightning::ln::msgs::SocketAddress;
1313
use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage};
14-
use lightning::onion_message::OnionMessagePath;
15-
use lightning::onion_message::{Destination, OnionMessageContents};
14+
use lightning::onion_message::messenger::Destination;
15+
use lightning::onion_message::packet::OnionMessageContents;
1616
use lightning::routing::gossip::NodeId;
1717
use lightning::routing::router::{PaymentParameters, RouteParameters};
1818
use lightning::sign::{EntropySource, KeysManager};
1919
use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
2020
use lightning::util::persist::KVStore;
2121
use lightning::util::ser::{Writeable, Writer};
22-
use lightning_invoice::payment::pay_invoice;
2322
use lightning_invoice::{utils, Bolt11Invoice, Currency};
2423
use lightning_persister::fs_store::FilesystemStore;
2524
use std::env;
@@ -43,6 +42,7 @@ pub(crate) struct LdkUserInfo {
4342
pub(crate) network: Network,
4443
}
4544

45+
#[derive(Debug)]
4646
struct UserOnionMessageContents {
4747
tlv_type: u64,
4848
data: Vec<u8>,
@@ -442,13 +442,12 @@ pub(crate) fn poll_for_user_input(
442442
}
443443
};
444444
let destination = Destination::Node(intermediate_nodes.pop().unwrap());
445-
let message_path = OnionMessagePath { intermediate_nodes, destination };
446445
match onion_messenger.send_onion_message(
447-
message_path,
448446
UserOnionMessageContents { tlv_type, data },
447+
destination,
449448
None,
450449
) {
451-
Ok(()) => println!("SUCCESS: forwarded onion message to first hop"),
450+
Ok(success) => println!("SUCCESS: forwarded onion message to first hop {:?}", success),
452451
Err(e) => println!("ERROR: failed to send onion message: {:?}", e),
453452
}
454453
}
@@ -672,7 +671,7 @@ fn open_channel(
672671
..Default::default()
673672
};
674673

675-
match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, Some(config)) {
674+
match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None, Some(config)) {
676675
Ok(_) => {
677676
println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
678677
return Ok(());
@@ -688,7 +687,8 @@ fn send_payment(
688687
channel_manager: &ChannelManager, invoice: &Bolt11Invoice,
689688
outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
690689
) {
691-
let payment_id = PaymentId((*invoice.payment_hash()).into_inner());
690+
let payment_id = PaymentId((*invoice.payment_hash()).to_byte_array());
691+
let payment_hash = PaymentHash((*invoice.payment_hash()).to_byte_array());
692692
let payment_secret = Some(*invoice.payment_secret());
693693
outbound_payments.payments.insert(
694694
payment_id,
@@ -700,8 +700,20 @@ fn send_payment(
700700
},
701701
);
702702
fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound_payments.encode()).unwrap();
703-
match pay_invoice(invoice, Retry::Timeout(Duration::from_secs(10)), channel_manager) {
704-
Ok(_payment_id) => {
703+
704+
let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
705+
recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
706+
let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
707+
invoice.min_final_cltv_expiry_delta() as u32)
708+
.with_expiry_time(invoice.duration_since_epoch().as_secs() + invoice.expiry_time().as_secs())
709+
.with_route_hints(invoice.route_hints()).unwrap();
710+
if let Some(features) = invoice.features() {
711+
payment_params = payment_params.with_bolt11_features(features.clone()).unwrap();
712+
}
713+
let route_params = RouteParameters::from_payment_params_and_value(payment_params, invoice.amount_milli_satoshis().unwrap_or_default());
714+
715+
match channel_manager.send_payment(payment_hash, recipient_onion, payment_id, route_params, Retry::Timeout(Duration::from_secs(10))) {
716+
Ok(_) => {
705717
let payee_pubkey = invoice.recover_payee_pub_key();
706718
let amt_msat = invoice.amount_milli_satoshis().unwrap();
707719
println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
@@ -721,7 +733,7 @@ fn keysend<E: EntropySource>(
721733
outbound_payments: &mut OutboundPaymentInfoStorage, fs_store: Arc<FilesystemStore>,
722734
) {
723735
let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
724-
let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).into_inner());
736+
let payment_id = PaymentId(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
725737

726738
let route_params = RouteParameters::from_payment_params_and_value(
727739
PaymentParameters::for_keysend(payee_pubkey, 40, false),
@@ -764,9 +776,9 @@ fn get_invoice(
764776
) {
765777
let currency = match network {
766778
Network::Bitcoin => Currency::Bitcoin,
767-
Network::Testnet => Currency::BitcoinTestnet,
768779
Network::Regtest => Currency::Regtest,
769780
Network::Signet => Currency::Signet,
781+
Network::Testnet | _ => Currency::BitcoinTestnet,
770782
};
771783
let invoice = match utils::create_invoice_from_channelmanager(
772784
channel_manager,
@@ -788,7 +800,7 @@ fn get_invoice(
788800
}
789801
};
790802

791-
let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
803+
let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array());
792804
inbound_payments.payments.insert(
793805
payment_hash,
794806
PaymentInfo {

src/convert.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use bitcoin::hashes::hex::FromHex;
1+
use bitcoin::address::NetworkUnchecked;
22
use bitcoin::{Address, BlockHash, Txid};
33
use lightning_block_sync::http::JsonResponse;
44
use std::convert::TryInto;
@@ -111,7 +111,7 @@ impl TryInto<BlockchainInfo> for JsonResponse {
111111
fn try_into(self) -> std::io::Result<BlockchainInfo> {
112112
Ok(BlockchainInfo {
113113
latest_height: self.0["blocks"].as_u64().unwrap() as usize,
114-
latest_blockhash: BlockHash::from_hex(self.0["bestblockhash"].as_str().unwrap())
114+
latest_blockhash: BlockHash::from_str(self.0["bestblockhash"].as_str().unwrap())
115115
.unwrap(),
116116
chain: self.0["chain"].as_str().unwrap().to_string(),
117117
})
@@ -122,7 +122,7 @@ pub struct ListUnspentUtxo {
122122
pub txid: Txid,
123123
pub vout: u32,
124124
pub amount: u64,
125-
pub address: Address,
125+
pub address: Address<NetworkUnchecked>,
126126
}
127127

128128
pub struct ListUnspentResponse(pub Vec<ListUnspentUtxo>);

src/disk.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ impl FilesystemLogger {
2727
}
2828
}
2929
impl Logger for FilesystemLogger {
30-
fn log(&self, record: &Record) {
30+
fn log(&self, record: Record) {
3131
let raw_log = record.args.to_string();
3232
let log = format!(
3333
"{} {:<5} [{}:{}] {}\n",

src/main.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use lightning::ln::channelmanager::{
2525
use lightning::ln::msgs::DecodeError;
2626
use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler, SimpleArcPeerManager};
2727
use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
28-
use lightning::onion_message::{DefaultMessageRouter, SimpleArcOnionMessenger};
28+
use lightning::onion_message::messenger::{DefaultMessageRouter, SimpleArcOnionMessenger};
2929
use lightning::routing::gossip;
3030
use lightning::routing::gossip::{NodeId, P2PGossipSync};
3131
use lightning::routing::router::DefaultRouter;
@@ -145,11 +145,6 @@ pub(crate) type GossipVerifier = lightning_block_sync::gossip::GossipVerifier<
145145
lightning_block_sync::gossip::TokioSpawner,
146146
Arc<lightning_block_sync::rpc::RpcClient>,
147147
Arc<FilesystemLogger>,
148-
SocketDescriptor,
149-
Arc<ChannelManager>,
150-
Arc<OnionMessenger>,
151-
IgnoringMessageHandler,
152-
Arc<KeysManager>,
153148
>;
154149

155150
pub(crate) type PeerManager = SimpleArcPeerManager<
@@ -195,12 +190,12 @@ async fn handle_ldk_events(
195190
// Construct the raw transaction with one output, that is paid the amount of the
196191
// channel.
197192
let addr = WitnessProgram::from_scriptpubkey(
198-
&output_script[..],
193+
&output_script.as_bytes(),
199194
match network {
200195
Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
201-
Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
202196
Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
203197
Network::Signet => bitcoin_bech32::constants::Network::Signet,
198+
Network::Testnet | _ => bitcoin_bech32::constants::Network::Testnet,
204199
},
205200
)
206201
.expect("Lightning funding tx should always be to a SegWit output")
@@ -500,6 +495,7 @@ async fn handle_ldk_events(
500495
user_channel_id: _,
501496
counterparty_node_id,
502497
channel_capacity_sats: _,
498+
channel_funding_txo: _,
503499
} => {
504500
println!(
505501
"\nEVENT: Channel {} with counterparty {} closed due to: {:?}",
@@ -516,6 +512,7 @@ async fn handle_ldk_events(
516512
}
517513
Event::HTLCIntercepted { .. } => {}
518514
Event::BumpTransaction(event) => bump_tx_event_handler.handle_event(&event),
515+
Event::ConnectionNeeded{ .. } => {}
519516
}
520517
}
521518

@@ -539,6 +536,7 @@ async fn start_ldk() {
539536
args.bitcoind_rpc_port,
540537
args.bitcoind_rpc_username.clone(),
541538
args.bitcoind_rpc_password.clone(),
539+
args.network,
542540
tokio::runtime::Handle::current(),
543541
Arc::clone(&logger),
544542
)
@@ -556,9 +554,9 @@ async fn start_ldk() {
556554
if bitcoind_chain
557555
!= match args.network {
558556
bitcoin::Network::Bitcoin => "main",
559-
bitcoin::Network::Testnet => "test",
560557
bitcoin::Network::Regtest => "regtest",
561558
bitcoin::Network::Signet => "signet",
559+
bitcoin::Network::Testnet | _ => "test",
562560
} {
563561
println!(
564562
"Chain argument ({}) didn't match bitcoind chain ({})",
@@ -777,7 +775,7 @@ async fn start_ldk() {
777775
Arc::clone(&keys_manager),
778776
Arc::clone(&keys_manager),
779777
Arc::clone(&logger),
780-
Arc::new(DefaultMessageRouter {}),
778+
Arc::new(DefaultMessageRouter::new(Arc::clone(&network_graph))),
781779
Arc::clone(&channel_manager),
782780
IgnoringMessageHandler {},
783781
));
@@ -939,6 +937,7 @@ async fn start_ldk() {
939937
})
940938
},
941939
false,
940+
|| Some(Duration::ZERO),
942941
));
943942

944943
// Regularly reconnect to channel peers.

0 commit comments

Comments
 (0)