Skip to content

Commit 09bec6e

Browse files
committed
Return ExpandedKey from NodeSigner
NodeSinger::get_inbound_payment_key_material returns KeyMaterial, which is used for constructing an ExpandedKey. Change the trait to return an ExpandedKey directly instead. This allows for direct access to the ExpandedKey when a NodeSigner referenced is available. Otherwise, it would either need to be reconstructed or passed in separately.
1 parent bd0dd9b commit 09bec6e

File tree

10 files changed

+43
-47
lines changed

10 files changed

+43
-47
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ use lightning::ln::channelmanager::{
5050
ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId, RecipientOnionFields, Retry,
5151
};
5252
use lightning::ln::functional_test_utils::*;
53+
use lightning::ln::inbound_payment::ExpandedKey;
5354
use lightning::ln::msgs::{
5455
self, ChannelMessageHandler, CommitmentUpdate, DecodeError, Init, UpdateAddHTLC,
5556
};
@@ -334,10 +335,10 @@ impl NodeSigner for KeyProvider {
334335
Ok(SharedSecret::new(other_key, &node_secret))
335336
}
336337

337-
fn get_inbound_payment_key_material(&self) -> KeyMaterial {
338+
fn get_inbound_payment_key(&self) -> ExpandedKey {
338339
#[rustfmt::skip]
339340
let random_bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_secret[31]];
340-
KeyMaterial(random_bytes)
341+
ExpandedKey::new(&KeyMaterial(random_bytes))
341342
}
342343

343344
fn sign_invoice(

fuzz/src/full_stack.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ use lightning::ln::channelmanager::{
4343
ChainParameters, ChannelManager, InterceptId, PaymentId, RecipientOnionFields, Retry,
4444
};
4545
use lightning::ln::functional_test_utils::*;
46+
use lightning::ln::inbound_payment::ExpandedKey;
4647
use lightning::ln::msgs::{self, DecodeError};
4748
use lightning::ln::peer_handler::{
4849
IgnoringMessageHandler, MessageHandler, PeerManager, SocketDescriptor,
@@ -79,7 +80,6 @@ use bitcoin::secp256k1::{self, Message, PublicKey, Scalar, Secp256k1, SecretKey}
7980

8081
use std::cell::RefCell;
8182
use std::cmp;
82-
use std::convert::TryInto;
8383
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
8484
use std::sync::{Arc, Mutex};
8585

@@ -364,7 +364,7 @@ impl<'a> Drop for MoneyLossDetector<'a> {
364364

365365
struct KeyProvider {
366366
node_secret: SecretKey,
367-
inbound_payment_key: KeyMaterial,
367+
inbound_payment_key: ExpandedKey,
368368
counter: AtomicU64,
369369
signer_state: RefCell<HashMap<u8, (bool, Arc<Mutex<EnforcementState>>)>>,
370370
}
@@ -402,8 +402,8 @@ impl NodeSigner for KeyProvider {
402402
Ok(SharedSecret::new(other_key, &node_secret))
403403
}
404404

405-
fn get_inbound_payment_key_material(&self) -> KeyMaterial {
406-
self.inbound_payment_key.clone()
405+
fn get_inbound_payment_key(&self) -> ExpandedKey {
406+
self.inbound_payment_key
407407
}
408408

409409
fn sign_invoice(
@@ -636,7 +636,7 @@ pub fn do_test(mut data: &[u8], logger: &Arc<dyn Logger>) {
636636

637637
let keys_manager = Arc::new(KeyProvider {
638638
node_secret: our_network_key.clone(),
639-
inbound_payment_key: KeyMaterial(inbound_payment_key.try_into().unwrap()),
639+
inbound_payment_key: ExpandedKey::new(&KeyMaterial(inbound_payment_key)),
640640
counter: AtomicU64::new(0),
641641
signer_state: RefCell::new(new_hash_map()),
642642
});

fuzz/src/onion_message.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use lightning::blinded_path::message::{
99
AsyncPaymentsContext, BlindedMessagePath, MessageContext, OffersContext,
1010
};
1111
use lightning::blinded_path::EmptyNodeIdLookUp;
12+
use lightning::ln::inbound_payment::ExpandedKey;
1213
use lightning::ln::msgs::{self, DecodeError, OnionMessageHandler};
1314
use lightning::ln::peer_handler::IgnoringMessageHandler;
1415
use lightning::ln::script::ShutdownScript;
@@ -22,7 +23,7 @@ use lightning::onion_message::messenger::{
2223
};
2324
use lightning::onion_message::offers::{OffersMessage, OffersMessageHandler};
2425
use lightning::onion_message::packet::OnionMessageContents;
25-
use lightning::sign::{EntropySource, KeyMaterial, NodeSigner, Recipient, SignerProvider};
26+
use lightning::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
2627
use lightning::types::features::InitFeatures;
2728
use lightning::util::logger::Logger;
2829
use lightning::util::ser::{Readable, Writeable, Writer};
@@ -223,7 +224,7 @@ impl NodeSigner for KeyProvider {
223224
Ok(SharedSecret::new(other_key, &node_secret))
224225
}
225226

226-
fn get_inbound_payment_key_material(&self) -> KeyMaterial {
227+
fn get_inbound_payment_key(&self) -> ExpandedKey {
227228
unreachable!()
228229
}
229230

lightning/src/ln/blinded_payment_tests.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use crate::ln::channelmanager;
2020
use crate::ln::channelmanager::{HTLCFailureMsg, PaymentId, RecipientOnionFields};
2121
use crate::types::features::{BlindedHopFeatures, ChannelFeatures, NodeFeatures};
2222
use crate::ln::functional_test_utils::*;
23+
use crate::ln::inbound_payment::ExpandedKey;
2324
use crate::ln::msgs;
2425
use crate::ln::msgs::{ChannelMessageHandler, UnsignedGossipMessage};
2526
use crate::ln::onion_payment;
@@ -29,7 +30,7 @@ use crate::ln::outbound_payment::{Retry, IDEMPOTENCY_TIMEOUT_TICKS};
2930
use crate::offers::invoice::UnsignedBolt12Invoice;
3031
use crate::prelude::*;
3132
use crate::routing::router::{BlindedTail, Path, Payee, PaymentParameters, RouteHop, RouteParameters};
32-
use crate::sign::{KeyMaterial, NodeSigner, Recipient};
33+
use crate::sign::{NodeSigner, Recipient};
3334
use crate::util::config::UserConfig;
3435
use crate::util::ser::WithoutLength;
3536
use crate::util::test_utils;
@@ -1221,9 +1222,7 @@ fn blinded_keysend() {
12211222
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
12221223
let chan_upd_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
12231224

1224-
let inbound_payment_key = inbound_payment::ExpandedKey::new(
1225-
&nodes[2].keys_manager.get_inbound_payment_key_material()
1226-
);
1225+
let inbound_payment_key = nodes[2].keys_manager.get_inbound_payment_key();
12271226
let payment_secret = inbound_payment::create_for_spontaneous_payment(
12281227
&inbound_payment_key, None, u32::MAX, nodes[2].node.duration_since_epoch().as_secs(), None
12291228
).unwrap();
@@ -1262,9 +1261,7 @@ fn blinded_mpp_keysend() {
12621261
let chan_1_3 = create_announced_chan_between_nodes(&nodes, 1, 3);
12631262
let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
12641263

1265-
let inbound_payment_key = inbound_payment::ExpandedKey::new(
1266-
&nodes[3].keys_manager.get_inbound_payment_key_material()
1267-
);
1264+
let inbound_payment_key = nodes[3].keys_manager.get_inbound_payment_key();
12681265
let payment_secret = inbound_payment::create_for_spontaneous_payment(
12691266
&inbound_payment_key, None, u32::MAX, nodes[3].node.duration_since_epoch().as_secs(), None
12701267
).unwrap();
@@ -1528,7 +1525,7 @@ fn route_blinding_spec_test_vector() {
15281525
}
15291526
Ok(SharedSecret::new(other_key, &node_secret))
15301527
}
1531-
fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!() }
1528+
fn get_inbound_payment_key(&self) -> ExpandedKey { unreachable!() }
15321529
fn get_node_id(&self, _recipient: Recipient) -> Result<PublicKey, ()> { unreachable!() }
15331530
fn sign_invoice(
15341531
&self, _invoice: &RawBolt11Invoice, _recipient: Recipient,

lightning/src/ln/channelmanager.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ pub enum PendingHTLCRouting {
233233
requires_blinded_error: bool,
234234
/// Set if we are receiving a keysend to a blinded path, meaning we created the
235235
/// [`PaymentSecret`] and should verify it using our
236-
/// [`NodeSigner::get_inbound_payment_key_material`].
236+
/// [`NodeSigner::get_inbound_payment_key`].
237237
has_recipient_created_payment_secret: bool,
238238
},
239239
}
@@ -3494,8 +3494,7 @@ where
34943494
) -> Self {
34953495
let mut secp_ctx = Secp256k1::new();
34963496
secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
3497-
let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
3498-
let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
3497+
let expanded_inbound_key = node_signer.get_inbound_payment_key();
34993498
ChannelManager {
35003499
default_configuration: config.clone(),
35013500
chain_hash: ChainHash::using_genesis_block(params.network),
@@ -13902,8 +13901,7 @@ where
1390213901
}, None));
1390313902
}
1390413903

13905-
let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
13906-
let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
13904+
let expanded_inbound_key = args.node_signer.get_inbound_payment_key();
1390713905

1390813906
let mut claimable_payments = hash_map_with_capacity(claimable_htlcs_list.len());
1390913907
if let Some(purposes) = claimable_htlc_purposes {

lightning/src/ln/inbound_payment.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@ const AMT_MSAT_LEN: usize = 8;
3737
// retrieve said payment type bits.
3838
const METHOD_TYPE_OFFSET: usize = 5;
3939

40-
/// A set of keys that were HKDF-expanded from an initial call to
41-
/// [`NodeSigner::get_inbound_payment_key_material`].
40+
/// A set of keys that were HKDF-expanded. Returned by [`NodeSigner::get_inbound_payment_key`].
4241
///
43-
/// [`NodeSigner::get_inbound_payment_key_material`]: crate::sign::NodeSigner::get_inbound_payment_key_material
42+
/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
43+
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
4444
pub struct ExpandedKey {
4545
/// The key used to encrypt the bytes containing the payment metadata (i.e. the amount and
4646
/// expiry, included for payment verification on decryption).
@@ -129,17 +129,16 @@ fn min_final_cltv_expiry_delta_from_metadata(bytes: [u8; METADATA_LEN]) -> u16 {
129129
/// `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without
130130
/// a `ChannelManager`.
131131
///
132-
/// `keys` is generated by calling [`NodeSigner::get_inbound_payment_key_material`] and then
133-
/// calling [`ExpandedKey::new`] with its result. It is recommended to cache this value and not
134-
/// regenerate it for each new inbound payment.
132+
/// `keys` is generated by calling [`NodeSigner::get_inbound_payment_key`]. It is recommended to
133+
/// cache this value and not regenerate it for each new inbound payment.
135134
///
136135
/// `current_time` is a Unix timestamp representing the current time.
137136
///
138137
/// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
139138
/// on versions of LDK prior to 0.0.114.
140139
///
141140
/// [phantom node payments]: crate::sign::PhantomKeysManager
142-
/// [`NodeSigner::get_inbound_payment_key_material`]: crate::sign::NodeSigner::get_inbound_payment_key_material
141+
/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
143142
pub fn create<ES: Deref>(keys: &ExpandedKey, min_value_msat: Option<u64>,
144143
invoice_expiry_delta_secs: u32, entropy_source: &ES, current_time: u64,
145144
min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()>
@@ -281,7 +280,7 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
281280
/// For payments including a custom `min_final_cltv_expiry_delta`, the metadata is constructed as:
282281
/// payment method (3 bits) || payment amount (8 bytes - 3 bits) || min_final_cltv_expiry_delta (2 bytes) || expiry (6 bytes)
283282
///
284-
/// In both cases the result is then encrypted using a key derived from [`NodeSigner::get_inbound_payment_key_material`].
283+
/// In both cases the result is then encrypted using a key derived from [`NodeSigner::get_inbound_payment_key`].
285284
///
286285
/// Then on payment receipt, we verify in this method that the payment preimage and payment secret
287286
/// match what was constructed.
@@ -302,7 +301,7 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
302301
///
303302
/// See [`ExpandedKey`] docs for more info on the individual keys used.
304303
///
305-
/// [`NodeSigner::get_inbound_payment_key_material`]: crate::sign::NodeSigner::get_inbound_payment_key_material
304+
/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
306305
/// [`create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
307306
/// [`create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
308307
pub(super) fn verify<L: Deref>(payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData,

lightning/src/ln/invoice_utils.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::sign::{Recipient, NodeSigner, SignerProvider, EntropySource};
1212
use crate::types::payment::PaymentHash;
1313
use crate::ln::channel_state::ChannelDetails;
1414
use crate::ln::channelmanager::{Bolt11InvoiceParameters, ChannelManager, PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA, MIN_FINAL_CLTV_EXPIRY_DELTA};
15-
use crate::ln::inbound_payment::{create, create_from_hash, ExpandedKey};
15+
use crate::ln::inbound_payment::{create, create_from_hash};
1616
use crate::routing::gossip::RoutingFees;
1717
use crate::routing::router::{RouteHint, RouteHintHop, Router};
1818
use crate::onion_message::messenger::MessageRouter;
@@ -165,8 +165,7 @@ where
165165
Bolt11InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
166166
};
167167

168-
// If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead.
169-
let keys = ExpandedKey::new(&node_signer.get_inbound_payment_key_material());
168+
let keys = node_signer.get_inbound_payment_key();
170169
let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
171170
let payment_secret = create_from_hash(
172171
&keys,

lightning/src/ln/offers_tests.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ use crate::events::{ClosureReason, Event, MessageSendEventsProvider, PaymentFail
5151
use crate::ln::channelmanager::{Bolt12PaymentError, MAX_SHORT_LIVED_RELATIVE_EXPIRY, PaymentId, RecentPaymentDetails, Retry, self};
5252
use crate::types::features::Bolt12InvoiceFeatures;
5353
use crate::ln::functional_test_utils::*;
54-
use crate::ln::inbound_payment::ExpandedKey;
5554
use crate::ln::msgs::{ChannelMessageHandler, Init, NodeAnnouncement, OnionMessage, OnionMessageHandler, RoutingMessageHandler, SocketAddress, UnsignedGossipMessage, UnsignedNodeAnnouncement};
5655
use crate::ln::outbound_payment::IDEMPOTENCY_TIMEOUT_TICKS;
5756
use crate::offers::invoice::Bolt12Invoice;
@@ -2218,7 +2217,7 @@ fn fails_paying_invoice_with_unknown_required_features() {
22182217
let payment_paths = invoice.payment_paths().to_vec();
22192218
let payment_hash = invoice.payment_hash();
22202219

2221-
let expanded_key = ExpandedKey::new(&alice.keys_manager.get_inbound_payment_key_material());
2220+
let expanded_key = alice.keys_manager.get_inbound_payment_key();
22222221
let secp_ctx = Secp256k1::new();
22232222

22242223
let created_at = alice.node.duration_since_epoch();

lightning/src/sign/mod.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ use crate::ln::channel_keys::{
5151
add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey,
5252
RevocationBasepoint, RevocationKey,
5353
};
54+
use crate::ln::inbound_payment::ExpandedKey;
5455
#[cfg(taproot)]
5556
use crate::ln::msgs::PartialSignatureWithNonce;
5657
use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
@@ -820,7 +821,7 @@ pub trait EntropySource {
820821

821822
/// A trait that can handle cryptographic operations at the scope level of a node.
822823
pub trait NodeSigner {
823-
/// Get secret key material as bytes for use in encrypting and decrypting inbound payment data.
824+
/// Get the [`ExpandedKey`] for use in encrypting and decrypting inbound payment data.
824825
///
825826
/// If the implementor of this trait supports [phantom node payments], then every node that is
826827
/// intended to be included in the phantom invoice route hints must return the same value from
@@ -832,7 +833,7 @@ pub trait NodeSigner {
832833
/// This method must return the same value each time it is called.
833834
///
834835
/// [phantom node payments]: PhantomKeysManager
835-
fn get_inbound_payment_key_material(&self) -> KeyMaterial;
836+
fn get_inbound_payment_key(&self) -> ExpandedKey;
836837

837838
/// Get node id based on the provided [`Recipient`].
838839
///
@@ -1852,7 +1853,7 @@ pub struct KeysManager {
18521853
secp_ctx: Secp256k1<secp256k1::All>,
18531854
node_secret: SecretKey,
18541855
node_id: PublicKey,
1855-
inbound_payment_key: KeyMaterial,
1856+
inbound_payment_key: ExpandedKey,
18561857
destination_script: ScriptBuf,
18571858
shutdown_pubkey: PublicKey,
18581859
channel_master_key: Xpriv,
@@ -1938,7 +1939,7 @@ impl KeysManager {
19381939
secp_ctx,
19391940
node_secret,
19401941
node_id,
1941-
inbound_payment_key: KeyMaterial(inbound_pmt_key_bytes),
1942+
inbound_payment_key: ExpandedKey::new(&KeyMaterial(inbound_pmt_key_bytes)),
19421943

19431944
destination_script,
19441945
shutdown_pubkey,
@@ -2175,7 +2176,7 @@ impl NodeSigner for KeysManager {
21752176
Ok(SharedSecret::new(other_key, &node_secret))
21762177
}
21772178

2178-
fn get_inbound_payment_key_material(&self) -> KeyMaterial {
2179+
fn get_inbound_payment_key(&self) -> ExpandedKey {
21792180
self.inbound_payment_key.clone()
21802181
}
21812182

@@ -2312,7 +2313,7 @@ pub struct PhantomKeysManager {
23122313
pub(crate) inner: KeysManager,
23132314
#[cfg(not(test))]
23142315
inner: KeysManager,
2315-
inbound_payment_key: KeyMaterial,
2316+
inbound_payment_key: ExpandedKey,
23162317
phantom_secret: SecretKey,
23172318
phantom_node_id: PublicKey,
23182319
}
@@ -2344,7 +2345,7 @@ impl NodeSigner for PhantomKeysManager {
23442345
Ok(SharedSecret::new(other_key, &node_secret))
23452346
}
23462347

2347-
fn get_inbound_payment_key_material(&self) -> KeyMaterial {
2348+
fn get_inbound_payment_key(&self) -> ExpandedKey {
23482349
self.inbound_payment_key.clone()
23492350
}
23502351

@@ -2444,7 +2445,7 @@ impl PhantomKeysManager {
24442445
let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
24452446
Self {
24462447
inner,
2447-
inbound_payment_key: KeyMaterial(inbound_key),
2448+
inbound_payment_key: ExpandedKey::new(&KeyMaterial(inbound_key)),
24482449
phantom_secret,
24492450
phantom_node_id,
24502451
}

lightning/src/util/test_utils.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ use crate::ln::channelmanager;
3030
#[cfg(test)]
3131
use crate::ln::chan_utils::CommitmentTransaction;
3232
use crate::types::features::{ChannelFeatures, InitFeatures, NodeFeatures};
33+
use crate::ln::inbound_payment::ExpandedKey;
3334
use crate::ln::{msgs, wire};
3435
use crate::ln::msgs::LightningError;
3536
use crate::ln::script::ShutdownScript;
@@ -1188,7 +1189,7 @@ impl TestNodeSigner {
11881189
}
11891190

11901191
impl NodeSigner for TestNodeSigner {
1191-
fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
1192+
fn get_inbound_payment_key(&self) -> ExpandedKey {
11921193
unreachable!()
11931194
}
11941195

@@ -1254,8 +1255,8 @@ impl NodeSigner for TestKeysInterface {
12541255
self.backing.ecdh(recipient, other_key, tweak)
12551256
}
12561257

1257-
fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
1258-
self.backing.get_inbound_payment_key_material()
1258+
fn get_inbound_payment_key(&self) -> ExpandedKey {
1259+
self.backing.get_inbound_payment_key()
12591260
}
12601261

12611262
fn sign_invoice(&self, invoice: &RawBolt11Invoice, recipient: Recipient) -> Result<RecoverableSignature, ()> {

0 commit comments

Comments
 (0)