lightning/sign/
mod.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10//! Provides keys to LDK and defines some useful objects describing spendable on-chain outputs.
11//!
12//! The provided output descriptors follow a custom LDK data format and are currently not fully
13//! compatible with Bitcoin Core output descriptors.
14
15use bitcoin::amount::Amount;
16use bitcoin::bip32::{ChildNumber, Xpriv, Xpub};
17use bitcoin::ecdsa::Signature as EcdsaSignature;
18use bitcoin::locktime::absolute::LockTime;
19use bitcoin::network::Network;
20use bitcoin::opcodes;
21use bitcoin::script::{Builder, Script, ScriptBuf};
22use bitcoin::sighash;
23use bitcoin::sighash::EcdsaSighashType;
24use bitcoin::transaction::Version;
25use bitcoin::transaction::{Transaction, TxIn, TxOut};
26
27use bitcoin::hashes::sha256::Hash as Sha256;
28use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29use bitcoin::hashes::{Hash, HashEngine};
30
31use bitcoin::secp256k1::ecdh::SharedSecret;
32use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
33use bitcoin::secp256k1::schnorr;
34use bitcoin::secp256k1::All;
35use bitcoin::secp256k1::{Keypair, PublicKey, Scalar, Secp256k1, SecretKey, Signing};
36use bitcoin::{secp256k1, Psbt, Sequence, Txid, WPubkeyHash, Witness};
37
38use lightning_invoice::RawBolt11Invoice;
39
40use crate::chain::transaction::OutPoint;
41use crate::crypto::utils::{hkdf_extract_expand_twice, sign, sign_with_aux_rand};
42use crate::ln::chan_utils;
43use crate::ln::chan_utils::{
44	get_countersigner_payment_script, get_revokeable_redeemscript, make_funding_redeemscript,
45	ChannelPublicKeys, ChannelTransactionParameters, ClosingTransaction, CommitmentTransaction,
46	HTLCOutputInCommitment, HolderCommitmentTransaction,
47};
48use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
49use crate::ln::channel_keys::{
50	add_public_key_tweak, DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey,
51	RevocationBasepoint, RevocationKey,
52};
53use crate::ln::inbound_payment::ExpandedKey;
54#[cfg(taproot)]
55use crate::ln::msgs::PartialSignatureWithNonce;
56use crate::ln::msgs::{UnsignedChannelAnnouncement, UnsignedGossipMessage};
57use crate::ln::script::ShutdownScript;
58use crate::offers::invoice::UnsignedBolt12Invoice;
59use crate::types::features::ChannelTypeFeatures;
60use crate::types::payment::PaymentPreimage;
61use crate::util::async_poll::AsyncResult;
62use crate::util::ser::{ReadableArgs, Writeable};
63use crate::util::transaction_utils;
64
65use crate::crypto::chacha20::ChaCha20;
66use crate::prelude::*;
67use crate::sign::ecdsa::EcdsaChannelSigner;
68#[cfg(taproot)]
69use crate::sign::taproot::TaprootChannelSigner;
70use crate::util::atomic_counter::AtomicCounter;
71use core::convert::TryInto;
72use core::ops::Deref;
73use core::sync::atomic::{AtomicUsize, Ordering};
74#[cfg(taproot)]
75use musig2::types::{PartialSignature, PublicNonce};
76
77pub(crate) mod type_resolver;
78
79pub mod ecdsa;
80#[cfg(taproot)]
81pub mod taproot;
82pub mod tx_builder;
83
84pub(crate) const COMPRESSED_PUBLIC_KEY_SIZE: usize = bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
85
86pub(crate) const MAX_STANDARD_SIGNATURE_SIZE: usize =
87	bitcoin::secp256k1::constants::MAX_SIGNATURE_SIZE;
88
89/// Information about a spendable output to a P2WSH script.
90///
91/// See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this.
92#[derive(Clone, Debug, Hash, PartialEq, Eq)]
93pub struct DelayedPaymentOutputDescriptor {
94	/// The outpoint which is spendable.
95	pub outpoint: OutPoint,
96	/// Per commitment point to derive the delayed payment key by key holder.
97	pub per_commitment_point: PublicKey,
98	/// The `nSequence` value which must be set in the spending input to satisfy the `OP_CSV` in
99	/// the witness_script.
100	pub to_self_delay: u16,
101	/// The output which is referenced by the given outpoint.
102	pub output: TxOut,
103	/// The revocation point specific to the commitment transaction which was broadcast. Used to
104	/// derive the witnessScript for this output.
105	pub revocation_pubkey: RevocationKey,
106	/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
107	/// This may be useful in re-deriving keys used in the channel to spend the output.
108	pub channel_keys_id: [u8; 32],
109	/// The value of the channel which this output originated from, possibly indirectly.
110	pub channel_value_satoshis: u64,
111	/// The channel public keys and other parameters needed to generate a spending transaction or
112	/// to provide to a signer.
113	///
114	/// Added as optional, but always `Some` if the descriptor was produced in v0.0.123 or later.
115	pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
116}
117
118impl DelayedPaymentOutputDescriptor {
119	/// The maximum length a well-formed witness spending one of these should have.
120	///
121	/// Note: If you have the `grind_signatures` feature enabled, this will be at least 1 byte
122	/// shorter.
123	pub const MAX_WITNESS_LENGTH: u64 = (1 /* witness items */
124		+ 1 /* sig push */
125		+ MAX_STANDARD_SIGNATURE_SIZE
126		+ 1 /* empty vec push */
127		+ 1 /* redeemscript push */
128		+ chan_utils::REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH) as u64;
129}
130
131impl_writeable_tlv_based!(DelayedPaymentOutputDescriptor, {
132	(0, outpoint, required),
133	(2, per_commitment_point, required),
134	(4, to_self_delay, required),
135	(6, output, required),
136	(8, revocation_pubkey, required),
137	(10, channel_keys_id, required),
138	(12, channel_value_satoshis, required),
139	(13, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
140});
141
142/// Witness weight for satisfying a P2WPKH spend.
143pub(crate) const P2WPKH_WITNESS_WEIGHT: u64 = (1 /* witness items */
144	+ 1 /* sig push */
145	+ MAX_STANDARD_SIGNATURE_SIZE
146	+ 1 /* pubkey push */
147	+ COMPRESSED_PUBLIC_KEY_SIZE) as u64;
148
149/// Witness weight for satisfying a P2TR key-path spend.
150pub(crate) const P2TR_KEY_PATH_WITNESS_WEIGHT: u64 = (1 /* witness items */
151	+ 1 /* sig push */
152	+ bitcoin::secp256k1::constants::SCHNORR_SIGNATURE_SIZE)
153	as u64;
154
155/// If a [`KeysManager`] is built with [`KeysManager::new`] with `v2_remote_key_derivation` set
156/// (and for all channels after they've been spliced), the script which we receive funds to on-chain
157/// when our counterparty force-closes a channel is one of this many possible derivation paths.
158///
159/// Keeping this limited allows for scanning the chain to find lost funds if our state is destroyed,
160/// while this being more than a handful provides some privacy by not constantly reusing the same
161/// scripts on-chain across channels.
162// Note that this MUST remain below the maximum BIP 32 derivation paths (2^31)
163pub const STATIC_PAYMENT_KEY_COUNT: u16 = 1000;
164
165/// Information about a spendable output to our "payment key".
166///
167/// See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this.
168#[derive(Clone, Debug, Hash, PartialEq, Eq)]
169pub struct StaticPaymentOutputDescriptor {
170	/// The outpoint which is spendable.
171	pub outpoint: OutPoint,
172	/// The output which is referenced by the given outpoint.
173	pub output: TxOut,
174	/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`].
175	/// This may be useful in re-deriving keys used in the channel to spend the output.
176	pub channel_keys_id: [u8; 32],
177	/// The value of the channel which this transactions spends.
178	pub channel_value_satoshis: u64,
179	/// The necessary channel parameters that need to be provided to the signer.
180	///
181	/// Added as optional, but always `Some` if the descriptor was produced in v0.0.117 or later.
182	pub channel_transaction_parameters: Option<ChannelTransactionParameters>,
183}
184
185impl StaticPaymentOutputDescriptor {
186	/// Returns the `witness_script` of the spendable output.
187	///
188	/// Note that this will only return `Some` for [`StaticPaymentOutputDescriptor`]s that
189	/// originated from an anchor outputs channel, as they take the form of a P2WSH script.
190	pub fn witness_script(&self) -> Option<ScriptBuf> {
191		self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
192			if channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
193				let payment_point = channel_params.holder_pubkeys.payment_point;
194				Some(chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&payment_point))
195			} else {
196				None
197			}
198		})
199	}
200
201	/// The maximum length a well-formed witness spending one of these should have.
202	///
203	/// Note: If you have the `grind_signatures` feature enabled, this will be at least 1 byte
204	/// shorter.
205	pub fn max_witness_length(&self) -> u64 {
206		if self.needs_csv_1_for_spend() {
207			let witness_script_weight = 1 /* pubkey push */
208				+ COMPRESSED_PUBLIC_KEY_SIZE
209				+ 1 /* OP_CHECKSIGVERIFY */
210				+ 1 /* OP_1 */
211				+ 1 /* OP_CHECKSEQUENCEVERIFY */;
212			(1 /* num witness items */
213				+ 1 /* sig push */
214				+ MAX_STANDARD_SIGNATURE_SIZE
215				+ 1 /* witness script push */
216				+ witness_script_weight) as u64
217		} else {
218			P2WPKH_WITNESS_WEIGHT
219		}
220	}
221
222	/// Returns true if spending this output requires a transaction with a CheckSequenceVerify
223	/// value of at least 1.
224	pub fn needs_csv_1_for_spend(&self) -> bool {
225		let chan_params = self.channel_transaction_parameters.as_ref();
226		chan_params.map_or(false, |p| p.channel_type_features.supports_anchors_zero_fee_htlc_tx())
227	}
228}
229impl_writeable_tlv_based!(StaticPaymentOutputDescriptor, {
230	(0, outpoint, required),
231	(2, output, required),
232	(4, channel_keys_id, required),
233	(6, channel_value_satoshis, required),
234	(7, channel_transaction_parameters, (option: ReadableArgs, Some(channel_value_satoshis.0.unwrap()))),
235});
236
237/// Describes the necessary information to spend a spendable output.
238///
239/// When on-chain outputs are created by LDK (which our counterparty is not able to claim at any
240/// point in the future) a [`SpendableOutputs`] event is generated which you must track and be able
241/// to spend on-chain. The information needed to do this is provided in this enum, including the
242/// outpoint describing which `txid` and output `index` is available, the full output which exists
243/// at that `txid`/`index`, and any keys or other information required to sign.
244///
245/// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
246#[derive(Clone, Debug, Hash, PartialEq, Eq)]
247pub enum SpendableOutputDescriptor {
248	/// An output to a script which was provided via [`SignerProvider`] directly, either from
249	/// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already
250	/// know how to spend it. No secret keys are provided as LDK was never given any key.
251	/// These may include outputs from a transaction punishing our counterparty or claiming an HTLC
252	/// on-chain using the payment preimage or after it has timed out.
253	///
254	/// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey
255	/// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey
256	StaticOutput {
257		/// The outpoint which is spendable.
258		outpoint: OutPoint,
259		/// The output which is referenced by the given outpoint.
260		output: TxOut,
261		/// The `channel_keys_id` for the channel which this output came from.
262		///
263		/// For channels which were generated on LDK 0.0.119 or later, this is the value which was
264		/// passed to the [`SignerProvider::get_destination_script`] call which provided this
265		/// output script.
266		///
267		/// For channels which were generated prior to LDK 0.0.119, no such argument existed,
268		/// however this field may still be filled in if such data is available.
269		channel_keys_id: Option<[u8; 32]>,
270	},
271	/// An output to a P2WSH script which can be spent with a single signature after an `OP_CSV`
272	/// delay.
273	///
274	/// The witness in the spending input should be:
275	/// ```bitcoin
276	/// <BIP 143 signature> <empty vector> (MINIMALIF standard rule) <provided witnessScript>
277	/// ```
278	///
279	/// Note that the `nSequence` field in the spending input must be set to
280	/// [`DelayedPaymentOutputDescriptor::to_self_delay`] (which means the transaction is not
281	/// broadcastable until at least [`DelayedPaymentOutputDescriptor::to_self_delay`] blocks after
282	/// the outpoint confirms, see [BIP
283	/// 68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki)). Also note that LDK
284	/// won't generate a [`SpendableOutputDescriptor`] until the corresponding block height
285	/// is reached.
286	///
287	/// These are generally the result of a "revocable" output to us, spendable only by us unless
288	/// it is an output from an old state which we broadcast (which should never happen).
289	///
290	/// To derive the delayed payment key which is used to sign this input, you must pass the
291	/// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which
292	/// corresponds to the [`ChannelPublicKeys::delayed_payment_basepoint`] in
293	/// [`ChannelSigner::pubkeys`]) and the provided
294	/// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
295	/// [`chan_utils::derive_private_key`]. The DelayedPaymentKey can be generated without the
296	/// secret key using [`DelayedPaymentKey::from_basepoint`] and only the
297	/// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in
298	/// [`ChannelSigner::pubkeys`].
299	///
300	/// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is
301	/// used in the witness script generation), you must pass the counterparty
302	/// [`ChannelPublicKeys::revocation_basepoint`] and the provided
303	/// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to
304	/// [`RevocationKey`].
305	///
306	/// The witness script which is hashed and included in the output `script_pubkey` may be
307	/// regenerated by passing the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] (derived
308	/// as explained above), our delayed payment pubkey (derived as explained above), and the
309	/// [`DelayedPaymentOutputDescriptor::to_self_delay`] contained here to
310	/// [`chan_utils::get_revokeable_redeemscript`].
311	DelayedPaymentOutput(DelayedPaymentOutputDescriptor),
312	/// An output spendable exclusively by our payment key (i.e., the private key that corresponds
313	/// to the `payment_point` in [`ChannelSigner::pubkeys`]). The output type depends on the
314	/// channel type negotiated.
315	///
316	/// On an anchor outputs channel, the witness in the spending input is:
317	/// ```bitcoin
318	/// <BIP 143 signature> <witness script>
319	/// ```
320	///
321	/// Otherwise, it is:
322	/// ```bitcoin
323	/// <BIP 143 signature> <payment key>
324	/// ```
325	///
326	/// These are generally the result of our counterparty having broadcast the current state,
327	/// allowing us to claim the non-HTLC-encumbered outputs immediately, or after one confirmation
328	/// in the case of anchor outputs channels.
329	StaticPaymentOutput(StaticPaymentOutputDescriptor),
330}
331
332impl_writeable_tlv_based_enum_legacy!(SpendableOutputDescriptor,
333	(0, StaticOutput) => {
334		(0, outpoint, required),
335		(1, channel_keys_id, option),
336		(2, output, required),
337	},
338;
339	(1, DelayedPaymentOutput),
340	(2, StaticPaymentOutput),
341);
342
343impl SpendableOutputDescriptor {
344	/// Turns this into a [`bitcoin::psbt::Input`] which can be used to create a
345	/// [`Psbt`] which spends the given descriptor.
346	///
347	/// Note that this does not include any signatures, just the information required to
348	/// construct the transaction and sign it.
349	///
350	/// This is not exported to bindings users as there is no standard serialization for an input.
351	/// See [`Self::create_spendable_outputs_psbt`] instead.
352	///
353	/// The proprietary field is used to store add tweak for the signing key of this transaction.
354	/// See the [`DelayedPaymentBasepoint::derive_add_tweak`] docs for more info on add tweak and how to use it.
355	///
356	/// To get the proprietary field use:
357	/// ```
358	/// use bitcoin::psbt::{Psbt};
359	/// use bitcoin::hex::FromHex;
360	///
361	/// # let s = "70736274ff0100520200000001dee978529ab3e61a2987bea5183713d0e6d5ceb5ac81100fdb54a1a2\
362	///	# 		 69cef505000000000090000000011f26000000000000160014abb3ab63280d4ccc5c11d6b50fd427a8\
363	///	# 		 e19d6470000000000001012b10270000000000002200200afe4736760d814a2651bae63b572d935d9a\
364	/// # 		 b74a1a16c01774e341a32afa763601054d63210394a27a700617f5b7aee72bd4f8076b5770a582b7fb\
365	///	# 		 d1d4ee2ea3802cd3cfbe2067029000b27521034629b1c8fdebfaeb58a74cd181f485e2c462e594cb30\
366	///	# 		 34dee655875f69f6c7c968ac20fc144c444b5f7370656e6461626c655f6f7574707574006164645f74\
367	///	# 		 7765616b20a86534f38ad61dc580ef41c3886204adf0911b81619c1ad7a2f5b5de39a2ba600000";
368	/// # let psbt = Psbt::deserialize(<Vec<u8> as FromHex>::from_hex(s).unwrap().as_slice()).unwrap();
369	/// let key = bitcoin::psbt::raw::ProprietaryKey {
370	/// 	prefix: "LDK_spendable_output".as_bytes().to_vec(),
371	/// 	subtype: 0,
372	/// 	key: "add_tweak".as_bytes().to_vec(),
373	/// };
374	/// let value = psbt
375	/// 	.inputs
376	/// 	.first()
377	/// 	.expect("Unable to get add tweak as there are no inputs")
378	/// 	.proprietary
379	/// 	.get(&key)
380	/// 	.map(|x| x.to_owned());
381	/// ```
382	pub fn to_psbt_input<T: secp256k1::Signing>(
383		&self, secp_ctx: &Secp256k1<T>,
384	) -> bitcoin::psbt::Input {
385		match self {
386			SpendableOutputDescriptor::StaticOutput { output, .. } => {
387				// Is a standard P2WPKH, no need for witness script
388				bitcoin::psbt::Input { witness_utxo: Some(output.clone()), ..Default::default() }
389			},
390			SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
391				channel_transaction_parameters,
392				per_commitment_point,
393				revocation_pubkey,
394				to_self_delay,
395				output,
396				..
397			}) => {
398				let delayed_payment_basepoint = channel_transaction_parameters
399					.as_ref()
400					.map(|params| params.holder_pubkeys.delayed_payment_basepoint);
401
402				let (witness_script, add_tweak) =
403					if let Some(basepoint) = delayed_payment_basepoint.as_ref() {
404						// Required to derive signing key: privkey = basepoint_secret + SHA256(per_commitment_point || basepoint)
405						let add_tweak = basepoint.derive_add_tweak(&per_commitment_point);
406						let delayed_payment_key = DelayedPaymentKey(add_public_key_tweak(
407							secp_ctx,
408							&basepoint.to_public_key(),
409							&add_tweak,
410						));
411
412						(
413							Some(get_revokeable_redeemscript(
414								&revocation_pubkey,
415								*to_self_delay,
416								&delayed_payment_key,
417							)),
418							Some(add_tweak),
419						)
420					} else {
421						(None, None)
422					};
423
424				bitcoin::psbt::Input {
425					witness_utxo: Some(output.clone()),
426					witness_script,
427					proprietary: add_tweak
428						.map(|add_tweak| {
429							[(
430								bitcoin::psbt::raw::ProprietaryKey {
431									// A non standard namespace for spendable outputs, used to store the tweak needed
432									// to derive the private key
433									prefix: "LDK_spendable_output".as_bytes().to_vec(),
434									subtype: 0,
435									key: "add_tweak".as_bytes().to_vec(),
436								},
437								add_tweak.as_byte_array().to_vec(),
438							)]
439							.into_iter()
440							.collect()
441						})
442						.unwrap_or_default(),
443					..Default::default()
444				}
445			},
446			SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => bitcoin::psbt::Input {
447				witness_utxo: Some(descriptor.output.clone()),
448				witness_script: descriptor.witness_script(),
449				..Default::default()
450			},
451		}
452	}
453
454	/// Creates an unsigned [`Psbt`] which spends the given descriptors to
455	/// the given outputs, plus an output to the given change destination (if sufficient
456	/// change value remains). The PSBT will have a feerate, at least, of the given value.
457	///
458	/// The `locktime` argument is used to set the transaction's locktime. If `None`, the
459	/// transaction will have a locktime of 0. It it recommended to set this to the current block
460	/// height to avoid fee sniping, unless you have some specific reason to use a different
461	/// locktime.
462	///
463	/// Returns the PSBT and expected max transaction weight.
464	///
465	/// Returns `Err(())` if the output value is greater than the input value minus required fee,
466	/// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
467	/// does not match the one we can spend.
468	///
469	/// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
470	pub fn create_spendable_outputs_psbt<T: secp256k1::Signing>(
471		secp_ctx: &Secp256k1<T>, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
472		change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
473		locktime: Option<LockTime>,
474	) -> Result<(Psbt, u64), ()> {
475		let mut input = Vec::with_capacity(descriptors.len());
476		let mut input_value = Amount::ZERO;
477		let mut witness_weight = 0;
478		let mut output_set = hash_set_with_capacity(descriptors.len());
479		for outp in descriptors {
480			match outp {
481				SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
482					if !output_set.insert(descriptor.outpoint) {
483						return Err(());
484					}
485					let sequence = if descriptor.needs_csv_1_for_spend() {
486						Sequence::from_consensus(1)
487					} else {
488						Sequence::ZERO
489					};
490					input.push(TxIn {
491						previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
492						script_sig: ScriptBuf::new(),
493						sequence,
494						witness: Witness::new(),
495					});
496					witness_weight += descriptor.max_witness_length();
497					#[cfg(feature = "grind_signatures")]
498					{
499						// Guarantees a low R signature
500						witness_weight -= 1;
501					}
502					input_value += descriptor.output.value;
503				},
504				SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
505					if !output_set.insert(descriptor.outpoint) {
506						return Err(());
507					}
508					input.push(TxIn {
509						previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
510						script_sig: ScriptBuf::new(),
511						sequence: Sequence(descriptor.to_self_delay as u32),
512						witness: Witness::new(),
513					});
514					witness_weight += DelayedPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
515					#[cfg(feature = "grind_signatures")]
516					{
517						// Guarantees a low R signature
518						witness_weight -= 1;
519					}
520					input_value += descriptor.output.value;
521				},
522				SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
523					if !output_set.insert(*outpoint) {
524						return Err(());
525					}
526					input.push(TxIn {
527						previous_output: outpoint.into_bitcoin_outpoint(),
528						script_sig: ScriptBuf::new(),
529						sequence: Sequence::ZERO,
530						witness: Witness::new(),
531					});
532					witness_weight += P2WPKH_WITNESS_WEIGHT;
533					#[cfg(feature = "grind_signatures")]
534					{
535						// Guarantees a low R signature
536						witness_weight -= 1;
537					}
538					input_value += output.value;
539				},
540			}
541			if input_value > Amount::MAX_MONEY {
542				return Err(());
543			}
544		}
545		let mut tx = Transaction {
546			version: Version::TWO,
547			lock_time: locktime.unwrap_or(LockTime::ZERO),
548			input,
549			output: outputs,
550		};
551		let expected_max_weight = transaction_utils::maybe_add_change_output(
552			&mut tx,
553			input_value,
554			witness_weight,
555			feerate_sat_per_1000_weight,
556			change_destination_script,
557		)?;
558
559		let psbt_inputs =
560			descriptors.iter().map(|d| d.to_psbt_input(&secp_ctx)).collect::<Vec<_>>();
561		let psbt = Psbt {
562			inputs: psbt_inputs,
563			outputs: vec![Default::default(); tx.output.len()],
564			unsigned_tx: tx,
565			xpub: Default::default(),
566			version: 0,
567			proprietary: Default::default(),
568			unknown: Default::default(),
569		};
570		Ok((psbt, expected_max_weight))
571	}
572
573	/// Returns the outpoint of the spendable output.
574	pub fn spendable_outpoint(&self) -> OutPoint {
575		match self {
576			Self::StaticOutput { outpoint, .. } => *outpoint,
577			Self::StaticPaymentOutput(descriptor) => descriptor.outpoint,
578			Self::DelayedPaymentOutput(descriptor) => descriptor.outpoint,
579		}
580	}
581}
582
583/// The parameters required to derive a channel signer via [`SignerProvider`].
584#[derive(Clone, Debug, PartialEq, Eq)]
585pub struct ChannelDerivationParameters {
586	/// The value in satoshis of the channel we're attempting to spend the anchor output of.
587	pub value_satoshis: u64,
588	/// The unique identifier to re-derive the signer for the associated channel.
589	pub keys_id: [u8; 32],
590	/// The necessary channel parameters that need to be provided to the signer.
591	pub transaction_parameters: ChannelTransactionParameters,
592}
593
594impl_writeable_tlv_based!(ChannelDerivationParameters, {
595	(0, value_satoshis, required),
596	(2, keys_id, required),
597	(4, transaction_parameters, (required: ReadableArgs, Some(value_satoshis.0.unwrap()))),
598});
599
600/// A descriptor used to sign for a commitment transaction's HTLC output.
601#[derive(Clone, Debug, PartialEq, Eq)]
602pub struct HTLCDescriptor {
603	/// The parameters required to derive the signer for the HTLC input.
604	pub channel_derivation_parameters: ChannelDerivationParameters,
605	/// The txid of the commitment transaction in which the HTLC output lives.
606	pub commitment_txid: Txid,
607	/// The number of the commitment transaction in which the HTLC output lives.
608	pub per_commitment_number: u64,
609	/// The key tweak corresponding to the number of the commitment transaction in which the HTLC
610	/// output lives. This tweak is applied to all the basepoints for both parties in the channel to
611	/// arrive at unique keys per commitment.
612	///
613	/// See <https://github.com/lightning/bolts/blob/master/03-transactions.md#keys> for more info.
614	pub per_commitment_point: PublicKey,
615	/// The feerate to use on the HTLC claiming transaction. This is always `0` for HTLCs
616	/// originating from a channel supporting anchor outputs, otherwise it is the channel's
617	/// negotiated feerate at the time the commitment transaction was built.
618	pub feerate_per_kw: u32,
619	/// The details of the HTLC as it appears in the commitment transaction.
620	pub htlc: HTLCOutputInCommitment,
621	/// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
622	/// taken.
623	pub preimage: Option<PaymentPreimage>,
624	/// The counterparty's signature required to spend the HTLC output.
625	pub counterparty_sig: Signature,
626}
627
628impl_writeable_tlv_based!(HTLCDescriptor, {
629	(0, channel_derivation_parameters, required),
630	(1, feerate_per_kw, (default_value, 0)),
631	(2, commitment_txid, required),
632	(4, per_commitment_number, required),
633	(6, per_commitment_point, required),
634	(8, htlc, required),
635	(10, preimage, option),
636	(12, counterparty_sig, required),
637});
638
639impl HTLCDescriptor {
640	/// Returns the outpoint of the HTLC output in the commitment transaction. This is the outpoint
641	/// being spent by the HTLC input in the HTLC transaction.
642	pub fn outpoint(&self) -> bitcoin::OutPoint {
643		bitcoin::OutPoint {
644			txid: self.commitment_txid,
645			vout: self.htlc.transaction_output_index.unwrap(),
646		}
647	}
648
649	/// Returns the UTXO to be spent by the HTLC input, which can be obtained via
650	/// [`Self::unsigned_tx_input`].
651	pub fn previous_utxo<C: secp256k1::Signing + secp256k1::Verification>(
652		&self, secp: &Secp256k1<C>,
653	) -> TxOut {
654		TxOut {
655			script_pubkey: self.witness_script(secp).to_p2wsh(),
656			value: self.htlc.to_bitcoin_amount(),
657		}
658	}
659
660	/// Returns the unsigned transaction input spending the HTLC output in the commitment
661	/// transaction.
662	pub fn unsigned_tx_input(&self) -> TxIn {
663		chan_utils::build_htlc_input(
664			&self.commitment_txid,
665			&self.htlc,
666			&self.channel_derivation_parameters.transaction_parameters.channel_type_features,
667		)
668	}
669
670	/// Returns the delayed output created as a result of spending the HTLC output in the commitment
671	/// transaction.
672	pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
673		&self, secp: &Secp256k1<C>,
674	) -> TxOut {
675		let channel_params =
676			self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
677		let broadcaster_keys = channel_params.broadcaster_pubkeys();
678		let counterparty_keys = channel_params.countersignatory_pubkeys();
679		let broadcaster_delayed_key = DelayedPaymentKey::from_basepoint(
680			secp,
681			&broadcaster_keys.delayed_payment_basepoint,
682			&self.per_commitment_point,
683		);
684		let counterparty_revocation_key = &RevocationKey::from_basepoint(
685			&secp,
686			&counterparty_keys.revocation_basepoint,
687			&self.per_commitment_point,
688		);
689		chan_utils::build_htlc_output(
690			self.feerate_per_kw,
691			channel_params.contest_delay(),
692			&self.htlc,
693			channel_params.channel_type_features(),
694			&broadcaster_delayed_key,
695			&counterparty_revocation_key,
696		)
697	}
698
699	/// Returns the witness script of the HTLC output in the commitment transaction.
700	pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
701		&self, secp: &Secp256k1<C>,
702	) -> ScriptBuf {
703		let channel_params =
704			self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
705		let broadcaster_keys = channel_params.broadcaster_pubkeys();
706		let counterparty_keys = channel_params.countersignatory_pubkeys();
707		let broadcaster_htlc_key = HtlcKey::from_basepoint(
708			secp,
709			&broadcaster_keys.htlc_basepoint,
710			&self.per_commitment_point,
711		);
712		let counterparty_htlc_key = HtlcKey::from_basepoint(
713			secp,
714			&counterparty_keys.htlc_basepoint,
715			&self.per_commitment_point,
716		);
717		let counterparty_revocation_key = &RevocationKey::from_basepoint(
718			&secp,
719			&counterparty_keys.revocation_basepoint,
720			&self.per_commitment_point,
721		);
722		chan_utils::get_htlc_redeemscript_with_explicit_keys(
723			&self.htlc,
724			channel_params.channel_type_features(),
725			&broadcaster_htlc_key,
726			&counterparty_htlc_key,
727			&counterparty_revocation_key,
728		)
729	}
730
731	/// Returns the fully signed witness required to spend the HTLC output in the commitment
732	/// transaction.
733	pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
734		chan_utils::build_htlc_input_witness(
735			signature,
736			&self.counterparty_sig,
737			&self.preimage,
738			witness_script,
739			&self.channel_derivation_parameters.transaction_parameters.channel_type_features,
740		)
741	}
742}
743
744/// A trait to handle Lightning channel key material without concretizing the channel type or
745/// the signature mechanism.
746///
747/// Several methods allow errors to be returned to support async signing. In such cases, the
748/// signing operation can be replayed by calling [`ChannelManager::signer_unblocked`] once the
749/// result is ready, at which point the channel operation will resume. Methods which allow for
750/// async results are explicitly documented as such
751///
752/// [`ChannelManager::signer_unblocked`]: crate::ln::channelmanager::ChannelManager::signer_unblocked
753pub trait ChannelSigner {
754	/// Gets the per-commitment point for a specific commitment number
755	///
756	/// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
757	///
758	/// This method is *not* asynchronous. This method is expected to always return `Ok`
759	/// immediately after we reconnect to peers, and returning an `Err` may lead to an immediate
760	/// `panic`. This method will be made asynchronous in a future release.
761	fn get_per_commitment_point(
762		&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
763	) -> Result<PublicKey, ()>;
764
765	/// Gets the commitment secret for a specific commitment number as part of the revocation process
766	///
767	/// An external signer implementation should error here if the commitment was already signed
768	/// and should refuse to sign it in the future.
769	///
770	/// May be called more than once for the same index.
771	///
772	/// Note that the commitment number starts at `(1 << 48) - 1` and counts backwards.
773	///
774	/// An `Err` can be returned to signal that the signer is unavailable/cannot produce a valid
775	/// signature and should be retried later. Once the signer is ready to provide a signature after
776	/// previously returning an `Err`, [`ChannelManager::signer_unblocked`] must be called.
777	///
778	/// [`ChannelManager::signer_unblocked`]: crate::ln::channelmanager::ChannelManager::signer_unblocked
779	fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()>;
780
781	/// Validate the counterparty's signatures on the holder commitment transaction and HTLCs.
782	///
783	/// This is required in order for the signer to make sure that releasing a commitment
784	/// secret won't leave us without a broadcastable holder transaction.
785	/// Policy checks should be implemented in this function, including checking the amount
786	/// sent to us and checking the HTLCs.
787	///
788	/// The preimages of outbound HTLCs that were fulfilled since the last commitment are provided.
789	/// A validating signer should ensure that an HTLC output is removed only when the matching
790	/// preimage is provided, or when the value to holder is restored.
791	///
792	/// Note that all the relevant preimages will be provided, but there may also be additional
793	/// irrelevant or duplicate preimages.
794	///
795	/// This method is *not* asynchronous. If an `Err` is returned, the channel will be immediately
796	/// closed. If you wish to make this operation asynchronous, you should instead return `Ok(())`
797	/// and pause future signing operations until this validation completes.
798	fn validate_holder_commitment(
799		&self, holder_tx: &HolderCommitmentTransaction,
800		outbound_htlc_preimages: Vec<PaymentPreimage>,
801	) -> Result<(), ()>;
802
803	/// Validate the counterparty's revocation.
804	///
805	/// This is required in order for the signer to make sure that the state has moved
806	/// forward and it is safe to sign the next counterparty commitment.
807	///
808	/// This method is *not* asynchronous. If an `Err` is returned, the channel will be immediately
809	/// closed. If you wish to make this operation asynchronous, you should instead return `Ok(())`
810	/// and pause future signing operations until this validation completes.
811	fn validate_counterparty_revocation(&self, idx: u64, secret: &SecretKey) -> Result<(), ()>;
812
813	/// Returns the holder channel public keys and basepoints. This should only be called once
814	/// during channel creation and as such implementations are allowed undefined behavior if
815	/// called more than once.
816	///
817	/// This method is *not* asynchronous. Instead, the value must be computed locally or in
818	/// advance and cached.
819	fn pubkeys(&self, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelPublicKeys;
820
821	/// Returns a new funding pubkey (i.e. our public which is used in a 2-of-2 with the
822	/// counterparty's key to to lock the funds on-chain) for a spliced channel.
823	///
824	/// `splice_parent_funding_txid` can be used to compute a tweak with which to rotate the base
825	/// key (which will then be available later in signing operations via
826	/// [`ChannelTransactionParameters::splice_parent_funding_txid`]).
827	///
828	/// This method is *not* asynchronous. Instead, the value must be cached locally.
829	fn new_funding_pubkey(
830		&self, splice_parent_funding_txid: Txid, secp_ctx: &Secp256k1<secp256k1::All>,
831	) -> PublicKey;
832
833	/// Returns an arbitrary identifier describing the set of keys which are provided back to you in
834	/// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this
835	/// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys.
836	///
837	/// This method is *not* asynchronous. Instead, the value must be cached locally.
838	fn channel_keys_id(&self) -> [u8; 32];
839}
840
841/// Represents the secret key material used for encrypting Peer Storage.
842#[derive(Clone, Copy, PartialEq, Eq)]
843pub struct PeerStorageKey {
844	/// Represents the key used to encrypt and decrypt Peer Storage.
845	pub inner: [u8; 32],
846}
847
848/// A secret key used to authenticate message contexts in received [`BlindedMessagePath`]s.
849///
850/// This key ensures that a node only accepts incoming messages delivered through
851/// blinded paths that it constructed itself.
852///
853/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
854#[derive(Clone, Copy, PartialEq, Eq)]
855pub struct ReceiveAuthKey(pub [u8; 32]);
856
857/// Specifies the recipient of an invoice.
858///
859/// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign
860/// the invoice.
861#[derive(Clone, Copy)]
862pub enum Recipient {
863	/// The invoice should be signed with the local node secret key.
864	Node,
865	/// The invoice should be signed with the phantom node secret key. This secret key must be the
866	/// same for all nodes participating in the [phantom node payment].
867	///
868	/// [phantom node payment]: PhantomKeysManager
869	PhantomNode,
870}
871
872/// A trait that describes a source of entropy.
873pub trait EntropySource {
874	/// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a
875	/// different value each time it is called.
876	fn get_secure_random_bytes(&self) -> [u8; 32];
877}
878
879/// A trait that can handle cryptographic operations at the scope level of a node.
880pub trait NodeSigner {
881	/// Get the [`ExpandedKey`] which provides cryptographic material for various Lightning Network operations.
882	///
883	/// This key set is used for:
884	/// - Encrypting and decrypting inbound payment metadata
885	/// - Authenticating payment hashes (both LDK-provided and user-provided)
886	/// - Supporting BOLT 12 Offers functionality (key derivation and authentication)
887	/// - Authenticating spontaneous payments' metadata
888	///
889	/// This method must return the same value each time it is called.
890	///
891	/// If the implementor of this trait supports [phantom node payments], then every node that is
892	/// intended to be included in the phantom invoice route hints must return the same value from
893	/// this method. This is because LDK avoids storing inbound payment data. Instead, this key
894	/// is used to construct a payment secret which is received in the payment onion and used to
895	/// reconstruct the payment preimage. Therefore, for a payment to be receivable by multiple
896	/// nodes, they must share the same key.
897	///
898	/// [phantom node payments]: PhantomKeysManager
899	fn get_expanded_key(&self) -> ExpandedKey;
900
901	/// Defines a method to derive a 32-byte encryption key for peer storage.
902	///
903	/// Implementations of this method must derive a secure encryption key.
904	/// The key is used to encrypt or decrypt backups of our state stored with our peers.
905	///
906	/// Thus, if you wish to rely on recovery using this method, you should use a key which
907	/// can be re-derived from data which would be available after state loss (eg the wallet seed).
908	fn get_peer_storage_key(&self) -> PeerStorageKey;
909
910	/// Returns the [`ReceiveAuthKey`] used to authenticate incoming [`BlindedMessagePath`] contexts.
911	///
912	/// This key is used as additional associated data (AAD) during MAC verification of the
913	/// [`MessageContext`] at the final hop of a blinded path. It ensures that only paths
914	/// constructed by this node will be accepted, preventing unauthorized parties from forging
915	/// valid-looking messages.
916	///
917	/// Implementers must ensure that this key remains secret and consistent across invocations.
918	///
919	/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
920	/// [`MessageContext`]: crate::blinded_path::message::MessageContext
921	fn get_receive_auth_key(&self) -> ReceiveAuthKey;
922
923	/// Get node id based on the provided [`Recipient`].
924	///
925	/// This method must return the same value each time it is called with a given [`Recipient`]
926	/// parameter.
927	///
928	/// Errors if the [`Recipient`] variant is not supported by the implementation.
929	fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()>;
930
931	/// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if
932	/// one is provided. Note that this tweak can be applied to `other_key` instead of our node
933	/// secret, though this is less efficient.
934	///
935	/// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error
936	/// should be resolved to allow LDK to resume forwarding HTLCs.
937	///
938	/// Errors if the [`Recipient`] variant is not supported by the implementation.
939	fn ecdh(
940		&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
941	) -> Result<SharedSecret, ()>;
942
943	/// Sign an invoice.
944	///
945	/// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of
946	/// this trait to parse the invoice and make sure they're signing what they expect, rather than
947	/// blindly signing the hash.
948	///
949	/// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32.
950	///
951	/// The secret key used to sign the invoice is dependent on the [`Recipient`].
952	///
953	/// Errors if the [`Recipient`] variant is not supported by the implementation.
954	fn sign_invoice(
955		&self, invoice: &RawBolt11Invoice, recipient: Recipient,
956	) -> Result<RecoverableSignature, ()>;
957
958	/// Signs the [`TaggedHash`] of a BOLT 12 invoice.
959	///
960	/// May be called by a function passed to [`UnsignedBolt12Invoice::sign`] where `invoice` is the
961	/// callee.
962	///
963	/// Implementors may check that the `invoice` is expected rather than blindly signing the tagged
964	/// hash. An `Ok` result should sign `invoice.tagged_hash().as_digest()` with the node's signing
965	/// key or an ephemeral key to preserve privacy, whichever is associated with
966	/// [`UnsignedBolt12Invoice::signing_pubkey`].
967	///
968	/// [`TaggedHash`]: crate::offers::merkle::TaggedHash
969	fn sign_bolt12_invoice(
970		&self, invoice: &UnsignedBolt12Invoice,
971	) -> Result<schnorr::Signature, ()>;
972
973	/// Sign a gossip message.
974	///
975	/// Note that if this fails, LDK may panic and the message will not be broadcast to the network
976	/// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the
977	/// message to be broadcast, as otherwise it may prevent one from receiving funds over the
978	/// corresponding channel.
979	fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()>;
980
981	/// Sign an arbitrary message with the node's secret key.
982	///
983	/// Creates a digital signature of a message given the node's secret. The message is prefixed
984	/// with "Lightning Signed Message:" before signing. See [this description of the format](https://web.archive.org/web/20191010011846/https://twitter.com/rusty_twit/status/1182102005914800128)
985	/// for more details.
986	///
987	/// A receiver knowing the node's id and the message can be sure that the signature was generated by the caller.
988	/// An `Err` can be returned to signal that the signer is unavailable / cannot produce a valid
989	/// signature.
990	fn sign_message(&self, msg: &[u8]) -> Result<String, ()>;
991}
992
993/// A trait that describes a wallet capable of creating a spending [`Transaction`] from a set of
994/// [`SpendableOutputDescriptor`]s.
995pub trait OutputSpender {
996	/// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
997	/// output to the given change destination (if sufficient change value remains). The
998	/// transaction will have a feerate, at least, of the given value.
999	///
1000	/// The `locktime` argument is used to set the transaction's locktime. If `None`, the
1001	/// transaction will have a locktime of 0. It it recommended to set this to the current block
1002	/// height to avoid fee sniping, unless you have some specific reason to use a different
1003	/// locktime.
1004	///
1005	/// Returns `Err(())` if the output value is greater than the input value minus required fee,
1006	/// if a descriptor was duplicated, or if an output descriptor `script_pubkey`
1007	/// does not match the one we can spend.
1008	fn spend_spendable_outputs(
1009		&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
1010		change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
1011		locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
1012	) -> Result<Transaction, ()>;
1013}
1014
1015// Primarily needed in doctests because of https://github.com/rust-lang/rust/issues/67295
1016/// A dynamic [`SignerProvider`] temporarily needed for doc tests.
1017///
1018/// This is not exported to bindings users as it is not intended for public consumption.
1019#[cfg(taproot)]
1020#[doc(hidden)]
1021#[deprecated(note = "Remove once taproot cfg is removed")]
1022pub type DynSignerProvider =
1023	dyn SignerProvider<EcdsaSigner = InMemorySigner, TaprootSigner = InMemorySigner>;
1024
1025/// A dynamic [`SignerProvider`] temporarily needed for doc tests.
1026///
1027/// This is not exported to bindings users as it is not intended for public consumption.
1028#[cfg(not(taproot))]
1029#[doc(hidden)]
1030#[deprecated(note = "Remove once taproot cfg is removed")]
1031pub type DynSignerProvider = dyn SignerProvider<EcdsaSigner = InMemorySigner>;
1032
1033/// A trait that can return signer instances for individual channels.
1034pub trait SignerProvider {
1035	/// A type which implements [`EcdsaChannelSigner`] which will be returned by [`Self::derive_channel_signer`].
1036	type EcdsaSigner: EcdsaChannelSigner;
1037	#[cfg(taproot)]
1038	/// A type which implements [`TaprootChannelSigner`]
1039	type TaprootSigner: TaprootChannelSigner;
1040
1041	/// Generates a unique `channel_keys_id` that can be used to obtain a [`Self::EcdsaSigner`] through
1042	/// [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow
1043	/// implementations of [`SignerProvider`] to maintain a mapping between itself and the generated
1044	/// `channel_keys_id`.
1045	///
1046	/// This method must return a different value each time it is called.
1047	fn generate_channel_keys_id(&self, inbound: bool, user_channel_id: u128) -> [u8; 32];
1048
1049	/// Derives the private key material backing a `Signer`.
1050	///
1051	/// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through
1052	/// [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be
1053	/// re-derived from its `channel_keys_id`, which can be obtained through its trait method
1054	/// [`ChannelSigner::channel_keys_id`].
1055	fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner;
1056
1057	/// Get a script pubkey which we send funds to when claiming on-chain contestable outputs.
1058	///
1059	/// If this function returns an error, this will result in a channel failing to open.
1060	///
1061	/// This method should return a different value each time it is called, to avoid linking
1062	/// on-chain funds across channels as controlled to the same user. `channel_keys_id` may be
1063	/// used to derive a unique value for each channel.
1064	fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()>;
1065
1066	/// Get a script pubkey which we will send funds to when closing a channel.
1067	///
1068	/// If this function returns an error, this will result in a channel failing to open or close.
1069	/// In the event of a failure when the counterparty is initiating a close, this can result in a
1070	/// channel force close.
1071	///
1072	/// This method should return a different value each time it is called, to avoid linking
1073	/// on-chain funds across channels as controlled to the same user.
1074	fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()>;
1075}
1076
1077/// A helper trait that describes an on-chain wallet capable of returning a (change) destination
1078/// script.
1079///
1080/// This is not exported to bindings users as async is only supported in Rust.
1081pub trait ChangeDestinationSource {
1082	/// Returns a script pubkey which can be used as a change destination for
1083	/// [`OutputSpender::spend_spendable_outputs`].
1084	///
1085	/// This method should return a different value each time it is called, to avoid linking
1086	/// on-chain funds controlled to the same user.
1087	fn get_change_destination_script<'a>(&'a self) -> AsyncResult<'a, ScriptBuf, ()>;
1088}
1089
1090/// A synchronous helper trait that describes an on-chain wallet capable of returning a (change) destination script.
1091pub trait ChangeDestinationSourceSync {
1092	/// Returns a script pubkey which can be used as a change destination for
1093	/// [`OutputSpender::spend_spendable_outputs`].
1094	///
1095	/// This method should return a different value each time it is called, to avoid linking
1096	/// on-chain funds controlled to the same user.
1097	fn get_change_destination_script(&self) -> Result<ScriptBuf, ()>;
1098}
1099
1100/// A wrapper around [`ChangeDestinationSource`] to allow for async calls.
1101///
1102/// You should likely never use this directly but rather allow LDK to build this when required to
1103/// build higher-level sync wrappers.
1104#[doc(hidden)]
1105pub struct ChangeDestinationSourceSyncWrapper<T: Deref>(T)
1106where
1107	T::Target: ChangeDestinationSourceSync;
1108
1109impl<T: Deref> ChangeDestinationSourceSyncWrapper<T>
1110where
1111	T::Target: ChangeDestinationSourceSync,
1112{
1113	/// Creates a new [`ChangeDestinationSourceSyncWrapper`].
1114	pub fn new(source: T) -> Self {
1115		Self(source)
1116	}
1117}
1118impl<T: Deref> ChangeDestinationSource for ChangeDestinationSourceSyncWrapper<T>
1119where
1120	T::Target: ChangeDestinationSourceSync,
1121{
1122	fn get_change_destination_script<'a>(&'a self) -> AsyncResult<'a, ScriptBuf, ()> {
1123		let script = self.0.get_change_destination_script();
1124		Box::pin(async move { script })
1125	}
1126}
1127
1128impl<T: Deref> Deref for ChangeDestinationSourceSyncWrapper<T>
1129where
1130	T::Target: ChangeDestinationSourceSync,
1131{
1132	type Target = Self;
1133	fn deref(&self) -> &Self {
1134		self
1135	}
1136}
1137
1138mod sealed {
1139	use bitcoin::secp256k1::{Scalar, SecretKey};
1140
1141	#[derive(Clone, PartialEq)]
1142	pub struct MaybeTweakedSecretKey(pub(super) SecretKey);
1143
1144	impl From<SecretKey> for MaybeTweakedSecretKey {
1145		fn from(value: SecretKey) -> Self {
1146			Self(value)
1147		}
1148	}
1149
1150	impl MaybeTweakedSecretKey {
1151		pub fn with_tweak(&self, tweak: Option<Scalar>) -> SecretKey {
1152			tweak
1153				.map(|tweak| {
1154					self.0
1155						.add_tweak(&tweak)
1156						.expect("Addition only fails if the tweak is the inverse of the key")
1157				})
1158				.unwrap_or(self.0)
1159		}
1160	}
1161}
1162
1163/// Computes the tweak to apply to the base funding key of a channel.
1164///
1165/// The tweak is computed similar to existing tweaks used in
1166/// [BOLT-3](https://github.com/lightning/bolts/blob/master/03-transactions.md#key-derivation):
1167///
1168/// 1. We use the txid of the funding transaction the splice transaction is spending instead of the
1169///    `per_commitment_point` to guarantee uniqueness.
1170/// 2. We include the private key instead of the public key to guarantee only those with knowledge
1171///    of it can re-derive the new funding key.
1172///
1173///   tweak = SHA256(splice_parent_funding_txid || base_funding_secret_key)
1174///   tweaked_funding_key = base_funding_key + tweak
1175///
1176/// While the use of this tweak is not required (signers may choose to compute a tweak of their
1177/// choice), signers must ensure their tweak guarantees the two properties mentioned above:
1178/// uniqueness and derivable only by one or both of the channel participants.
1179pub fn compute_funding_key_tweak(
1180	base_funding_secret_key: &SecretKey, splice_parent_funding_txid: &Txid,
1181) -> Scalar {
1182	let mut sha = Sha256::engine();
1183	sha.input(splice_parent_funding_txid.as_byte_array());
1184	sha.input(&base_funding_secret_key.secret_bytes());
1185	Scalar::from_be_bytes(Sha256::from_engine(sha).to_byte_array()).unwrap()
1186}
1187
1188/// A simple implementation of [`EcdsaChannelSigner`] that just keeps the private keys in memory.
1189///
1190/// This implementation performs no policy checks and is insufficient by itself as
1191/// a secure external signer.
1192pub struct InMemorySigner {
1193	/// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
1194	/// holder's anchor output in a commitment transaction, if one is present.
1195	funding_key: sealed::MaybeTweakedSecretKey,
1196	/// Holder secret key for blinded revocation pubkey.
1197	pub revocation_base_key: SecretKey,
1198	/// Holder secret key used for our balance in counterparty-broadcasted commitment transactions,
1199	/// old-style derivation.
1200	payment_key_v1: SecretKey,
1201	/// Holder secret key used for our balance in counterparty-broadcasted commitment transactions,
1202	/// new-style derivation.
1203	payment_key_v2: SecretKey,
1204	/// Which of [`Self::payment_key_v1`] and [`Self::payment_key_v2`] to use by default.
1205	v2_remote_key_derivation: bool,
1206	/// Holder secret key used in an HTLC transaction.
1207	pub delayed_payment_base_key: SecretKey,
1208	/// Holder HTLC secret key used in commitment transaction HTLC outputs.
1209	pub htlc_base_key: SecretKey,
1210	/// Commitment seed.
1211	pub commitment_seed: [u8; 32],
1212	/// Key derivation parameters.
1213	channel_keys_id: [u8; 32],
1214	/// A source of random bytes.
1215	entropy_source: RandomBytes,
1216}
1217
1218impl PartialEq for InMemorySigner {
1219	fn eq(&self, other: &Self) -> bool {
1220		self.funding_key == other.funding_key
1221			&& self.revocation_base_key == other.revocation_base_key
1222			&& self.payment_key_v1 == other.payment_key_v1
1223			&& self.payment_key_v2 == other.payment_key_v2
1224			&& self.v2_remote_key_derivation == other.v2_remote_key_derivation
1225			&& self.delayed_payment_base_key == other.delayed_payment_base_key
1226			&& self.htlc_base_key == other.htlc_base_key
1227			&& self.commitment_seed == other.commitment_seed
1228			&& self.channel_keys_id == other.channel_keys_id
1229	}
1230}
1231
1232impl Clone for InMemorySigner {
1233	fn clone(&self) -> Self {
1234		Self {
1235			funding_key: self.funding_key.clone(),
1236			revocation_base_key: self.revocation_base_key.clone(),
1237			payment_key_v1: self.payment_key_v1.clone(),
1238			payment_key_v2: self.payment_key_v2.clone(),
1239			v2_remote_key_derivation: self.v2_remote_key_derivation,
1240			delayed_payment_base_key: self.delayed_payment_base_key.clone(),
1241			htlc_base_key: self.htlc_base_key.clone(),
1242			commitment_seed: self.commitment_seed.clone(),
1243			channel_keys_id: self.channel_keys_id,
1244			entropy_source: RandomBytes::new(self.get_secure_random_bytes()),
1245		}
1246	}
1247}
1248
1249impl InMemorySigner {
1250	#[cfg(any(feature = "_test_utils", test))]
1251	pub fn new(
1252		funding_key: SecretKey, revocation_base_key: SecretKey, payment_key_v1: SecretKey,
1253		payment_key_v2: SecretKey, v2_remote_key_derivation: bool,
1254		delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey, commitment_seed: [u8; 32],
1255		channel_keys_id: [u8; 32], rand_bytes_unique_start: [u8; 32],
1256	) -> InMemorySigner {
1257		InMemorySigner {
1258			funding_key: sealed::MaybeTweakedSecretKey::from(funding_key),
1259			revocation_base_key,
1260			payment_key_v1,
1261			payment_key_v2,
1262			v2_remote_key_derivation,
1263			delayed_payment_base_key,
1264			htlc_base_key,
1265			commitment_seed,
1266			channel_keys_id,
1267			entropy_source: RandomBytes::new(rand_bytes_unique_start),
1268		}
1269	}
1270
1271	#[cfg(not(any(feature = "_test_utils", test)))]
1272	fn new(
1273		funding_key: SecretKey, revocation_base_key: SecretKey, payment_key_v1: SecretKey,
1274		payment_key_v2: SecretKey, v2_remote_key_derivation: bool,
1275		delayed_payment_base_key: SecretKey, htlc_base_key: SecretKey, commitment_seed: [u8; 32],
1276		channel_keys_id: [u8; 32], rand_bytes_unique_start: [u8; 32],
1277	) -> InMemorySigner {
1278		InMemorySigner {
1279			funding_key: sealed::MaybeTweakedSecretKey::from(funding_key),
1280			revocation_base_key,
1281			payment_key_v1,
1282			payment_key_v2,
1283			v2_remote_key_derivation,
1284			delayed_payment_base_key,
1285			htlc_base_key,
1286			commitment_seed,
1287			channel_keys_id,
1288			entropy_source: RandomBytes::new(rand_bytes_unique_start),
1289		}
1290	}
1291
1292	/// Holder secret key in the 2-of-2 multisig script of a channel. This key also backs the
1293	/// holder's anchor output in a commitment transaction, if one is present.
1294	pub fn funding_key(&self, splice_parent_funding_txid: Option<Txid>) -> SecretKey {
1295		let tweak = splice_parent_funding_txid
1296			.map(|txid| compute_funding_key_tweak(&self.funding_key.with_tweak(None), &txid));
1297		self.funding_key.with_tweak(tweak)
1298	}
1299
1300	/// Sign the single input of `spend_tx` at index `input_idx`, which spends the output described
1301	/// by `descriptor`, returning the witness stack for the input.
1302	///
1303	/// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1304	/// is not spending the outpoint described by [`descriptor.outpoint`],
1305	/// or if an output descriptor `script_pubkey` does not match the one we can spend.
1306	///
1307	/// [`descriptor.outpoint`]: StaticPaymentOutputDescriptor::outpoint
1308	pub fn sign_counterparty_payment_input<C: Signing>(
1309		&self, spend_tx: &Transaction, input_idx: usize,
1310		descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1311	) -> Result<Witness, ()> {
1312		// TODO: We really should be taking the SigHashCache as a parameter here instead of
1313		// spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1314		// so that we can check them. This requires upstream rust-bitcoin changes (as well as
1315		// bindings updates to support SigHashCache objects).
1316		if spend_tx.input.len() <= input_idx {
1317			return Err(());
1318		}
1319		if !spend_tx.input[input_idx].script_sig.is_empty() {
1320			return Err(());
1321		}
1322		if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1323		{
1324			return Err(());
1325		}
1326
1327		let legacy_default_channel_type = ChannelTypeFeatures::only_static_remote_key();
1328		let channel_type_features = descriptor
1329			.channel_transaction_parameters
1330			.as_ref()
1331			.map(|params| &params.channel_type_features)
1332			.unwrap_or(&legacy_default_channel_type);
1333
1334		let payment_point_v1 = PublicKey::from_secret_key(secp_ctx, &self.payment_key_v1);
1335		let payment_point_v2 = PublicKey::from_secret_key(secp_ctx, &self.payment_key_v2);
1336		let spk_v1 = get_countersigner_payment_script(channel_type_features, &payment_point_v1);
1337		let spk_v2 = get_countersigner_payment_script(channel_type_features, &payment_point_v2);
1338
1339		let (remotepubkey, payment_key) = if spk_v1 == descriptor.output.script_pubkey {
1340			(bitcoin::PublicKey::new(payment_point_v1), &self.payment_key_v1)
1341		} else {
1342			if spk_v2 != descriptor.output.script_pubkey {
1343				return Err(());
1344			}
1345			(bitcoin::PublicKey::new(payment_point_v2), &self.payment_key_v2)
1346		};
1347
1348		let witness_script = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
1349			chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&remotepubkey.inner)
1350		} else {
1351			ScriptBuf::new_p2pkh(&remotepubkey.pubkey_hash())
1352		};
1353		let sighash = hash_to_message!(
1354			&sighash::SighashCache::new(spend_tx)
1355				.p2wsh_signature_hash(
1356					input_idx,
1357					&witness_script,
1358					descriptor.output.value,
1359					EcdsaSighashType::All
1360				)
1361				.unwrap()[..]
1362		);
1363		let remotesig = sign_with_aux_rand(secp_ctx, &sighash, payment_key, &self);
1364		let payment_script = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
1365			witness_script.to_p2wsh()
1366		} else {
1367			ScriptBuf::new_p2wpkh(&remotepubkey.wpubkey_hash().unwrap())
1368		};
1369
1370		if payment_script != descriptor.output.script_pubkey {
1371			return Err(());
1372		}
1373
1374		let mut witness = Vec::with_capacity(2);
1375		witness.push(remotesig.serialize_der().to_vec());
1376		witness[0].push(EcdsaSighashType::All as u8);
1377		if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
1378			witness.push(witness_script.to_bytes());
1379		} else {
1380			witness.push(remotepubkey.to_bytes());
1381		}
1382		Ok(witness.into())
1383	}
1384
1385	/// Sign the single input of `spend_tx` at index `input_idx` which spends the output
1386	/// described by `descriptor`, returning the witness stack for the input.
1387	///
1388	/// Returns an error if the input at `input_idx` does not exist, has a non-empty `script_sig`,
1389	/// is not spending the outpoint described by [`descriptor.outpoint`], does not have a
1390	/// sequence set to [`descriptor.to_self_delay`], or if an output descriptor
1391	/// `script_pubkey` does not match the one we can spend.
1392	///
1393	/// [`descriptor.outpoint`]: DelayedPaymentOutputDescriptor::outpoint
1394	/// [`descriptor.to_self_delay`]: DelayedPaymentOutputDescriptor::to_self_delay
1395	pub fn sign_dynamic_p2wsh_input<C: Signing>(
1396		&self, spend_tx: &Transaction, input_idx: usize,
1397		descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>,
1398	) -> Result<Witness, ()> {
1399		// TODO: We really should be taking the SigHashCache as a parameter here instead of
1400		// spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
1401		// so that we can check them. This requires upstream rust-bitcoin changes (as well as
1402		// bindings updates to support SigHashCache objects).
1403		if spend_tx.input.len() <= input_idx {
1404			return Err(());
1405		}
1406		if !spend_tx.input[input_idx].script_sig.is_empty() {
1407			return Err(());
1408		}
1409		if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint()
1410		{
1411			return Err(());
1412		}
1413		if spend_tx.input[input_idx].sequence.0 != descriptor.to_self_delay as u32 {
1414			return Err(());
1415		}
1416
1417		let delayed_payment_key = chan_utils::derive_private_key(
1418			&secp_ctx,
1419			&descriptor.per_commitment_point,
1420			&self.delayed_payment_base_key,
1421		);
1422		let delayed_payment_pubkey =
1423			DelayedPaymentKey::from_secret_key(&secp_ctx, &delayed_payment_key);
1424		let witness_script = chan_utils::get_revokeable_redeemscript(
1425			&descriptor.revocation_pubkey,
1426			descriptor.to_self_delay,
1427			&delayed_payment_pubkey,
1428		);
1429		let sighash = hash_to_message!(
1430			&sighash::SighashCache::new(spend_tx)
1431				.p2wsh_signature_hash(
1432					input_idx,
1433					&witness_script,
1434					descriptor.output.value,
1435					EcdsaSighashType::All
1436				)
1437				.unwrap()[..]
1438		);
1439		let local_delayedsig = EcdsaSignature {
1440			signature: sign_with_aux_rand(secp_ctx, &sighash, &delayed_payment_key, &self),
1441			sighash_type: EcdsaSighashType::All,
1442		};
1443		let payment_script =
1444			bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
1445
1446		if descriptor.output.script_pubkey != payment_script {
1447			return Err(());
1448		}
1449
1450		Ok(Witness::from_slice(&[
1451			&local_delayedsig.serialize()[..],
1452			&[], // MINIMALIF
1453			witness_script.as_bytes(),
1454		]))
1455	}
1456}
1457
1458impl EntropySource for InMemorySigner {
1459	fn get_secure_random_bytes(&self) -> [u8; 32] {
1460		self.entropy_source.get_secure_random_bytes()
1461	}
1462}
1463
1464impl ChannelSigner for InMemorySigner {
1465	fn get_per_commitment_point(
1466		&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>,
1467	) -> Result<PublicKey, ()> {
1468		let commitment_secret =
1469			SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1470				.unwrap();
1471		Ok(PublicKey::from_secret_key(secp_ctx, &commitment_secret))
1472	}
1473
1474	fn release_commitment_secret(&self, idx: u64) -> Result<[u8; 32], ()> {
1475		Ok(chan_utils::build_commitment_secret(&self.commitment_seed, idx))
1476	}
1477
1478	fn validate_holder_commitment(
1479		&self, _holder_tx: &HolderCommitmentTransaction,
1480		_outbound_htlc_preimages: Vec<PaymentPreimage>,
1481	) -> Result<(), ()> {
1482		Ok(())
1483	}
1484
1485	fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
1486		Ok(())
1487	}
1488
1489	fn pubkeys(&self, secp_ctx: &Secp256k1<secp256k1::All>) -> ChannelPublicKeys {
1490		// Because splices always break downgrades, we go ahead and always use the new derivation
1491		// here as its just much better.
1492		let payment_key =
1493			if self.v2_remote_key_derivation { &self.payment_key_v2 } else { &self.payment_key_v1 };
1494		let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
1495		let pubkeys = ChannelPublicKeys {
1496			funding_pubkey: from_secret(&self.funding_key.0),
1497			revocation_basepoint: RevocationBasepoint::from(from_secret(&self.revocation_base_key)),
1498			payment_point: from_secret(payment_key),
1499			delayed_payment_basepoint: DelayedPaymentBasepoint::from(from_secret(
1500				&self.delayed_payment_base_key,
1501			)),
1502			htlc_basepoint: HtlcBasepoint::from(from_secret(&self.htlc_base_key)),
1503		};
1504
1505		pubkeys
1506	}
1507
1508	fn new_funding_pubkey(
1509		&self, splice_parent_funding_txid: Txid, secp_ctx: &Secp256k1<secp256k1::All>,
1510	) -> PublicKey {
1511		self.funding_key(Some(splice_parent_funding_txid)).public_key(secp_ctx)
1512	}
1513
1514	fn channel_keys_id(&self) -> [u8; 32] {
1515		self.channel_keys_id
1516	}
1517}
1518
1519const MISSING_PARAMS_ERR: &'static str =
1520	"ChannelTransactionParameters must be populated before signing operations";
1521
1522impl EcdsaChannelSigner for InMemorySigner {
1523	fn sign_counterparty_commitment(
1524		&self, channel_parameters: &ChannelTransactionParameters,
1525		commitment_tx: &CommitmentTransaction, _inbound_htlc_preimages: Vec<PaymentPreimage>,
1526		_outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>,
1527	) -> Result<(Signature, Vec<Signature>), ()> {
1528		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1529
1530		let trusted_tx = commitment_tx.trust();
1531		let keys = trusted_tx.keys();
1532
1533		let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1534		let funding_pubkey = funding_key.public_key(secp_ctx);
1535		let counterparty_keys =
1536			channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1537		let channel_funding_redeemscript =
1538			make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1539
1540		let built_tx = trusted_tx.built_transaction();
1541		let commitment_sig = built_tx.sign_counterparty_commitment(
1542			&funding_key,
1543			&channel_funding_redeemscript,
1544			channel_parameters.channel_value_satoshis,
1545			secp_ctx,
1546		);
1547		let commitment_txid = built_tx.txid;
1548
1549		let mut htlc_sigs = Vec::with_capacity(commitment_tx.nondust_htlcs().len());
1550		for htlc in commitment_tx.nondust_htlcs() {
1551			let holder_selected_contest_delay = channel_parameters.holder_selected_contest_delay;
1552			let chan_type = &channel_parameters.channel_type_features;
1553			let htlc_tx = chan_utils::build_htlc_transaction(
1554				&commitment_txid,
1555				commitment_tx.negotiated_feerate_per_kw(),
1556				holder_selected_contest_delay,
1557				htlc,
1558				chan_type,
1559				&keys.broadcaster_delayed_payment_key,
1560				&keys.revocation_key,
1561			);
1562			let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, chan_type, &keys);
1563			let htlc_sighashtype = if chan_type.supports_anchors_zero_fee_htlc_tx()
1564				|| chan_type.supports_anchor_zero_fee_commitments()
1565			{
1566				EcdsaSighashType::SinglePlusAnyoneCanPay
1567			} else {
1568				EcdsaSighashType::All
1569			};
1570			let htlc_sighash = hash_to_message!(
1571				&sighash::SighashCache::new(&htlc_tx)
1572					.p2wsh_signature_hash(
1573						0,
1574						&htlc_redeemscript,
1575						htlc.to_bitcoin_amount(),
1576						htlc_sighashtype
1577					)
1578					.unwrap()[..]
1579			);
1580			let holder_htlc_key = chan_utils::derive_private_key(
1581				&secp_ctx,
1582				&keys.per_commitment_point,
1583				&self.htlc_base_key,
1584			);
1585			htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
1586		}
1587
1588		Ok((commitment_sig, htlc_sigs))
1589	}
1590
1591	fn sign_holder_commitment(
1592		&self, channel_parameters: &ChannelTransactionParameters,
1593		commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1594	) -> Result<Signature, ()> {
1595		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1596
1597		let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1598		let funding_pubkey = funding_key.public_key(secp_ctx);
1599		let counterparty_keys =
1600			channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1601		let funding_redeemscript =
1602			make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1603		let trusted_tx = commitment_tx.trust();
1604		Ok(trusted_tx.built_transaction().sign_holder_commitment(
1605			&funding_key,
1606			&funding_redeemscript,
1607			channel_parameters.channel_value_satoshis,
1608			&self,
1609			secp_ctx,
1610		))
1611	}
1612
1613	#[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
1614	fn unsafe_sign_holder_commitment(
1615		&self, channel_parameters: &ChannelTransactionParameters,
1616		commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>,
1617	) -> Result<Signature, ()> {
1618		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1619
1620		let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1621		let funding_pubkey = funding_key.public_key(secp_ctx);
1622		let counterparty_keys =
1623			channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1624		let funding_redeemscript =
1625			make_funding_redeemscript(&funding_pubkey, &counterparty_keys.funding_pubkey);
1626		let trusted_tx = commitment_tx.trust();
1627		Ok(trusted_tx.built_transaction().sign_holder_commitment(
1628			&funding_key,
1629			&funding_redeemscript,
1630			channel_parameters.channel_value_satoshis,
1631			&self,
1632			secp_ctx,
1633		))
1634	}
1635
1636	fn sign_justice_revoked_output(
1637		&self, channel_parameters: &ChannelTransactionParameters, justice_tx: &Transaction,
1638		input: usize, amount: u64, per_commitment_key: &SecretKey,
1639		secp_ctx: &Secp256k1<secp256k1::All>,
1640	) -> Result<Signature, ()> {
1641		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1642
1643		let revocation_key = chan_utils::derive_private_revocation_key(
1644			&secp_ctx,
1645			&per_commitment_key,
1646			&self.revocation_base_key,
1647		);
1648		let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1649		let revocation_pubkey = RevocationKey::from_basepoint(
1650			&secp_ctx,
1651			&channel_parameters.holder_pubkeys.revocation_basepoint,
1652			&per_commitment_point,
1653		);
1654		let witness_script = {
1655			let counterparty_keys =
1656				channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1657			let holder_selected_contest_delay = channel_parameters.holder_selected_contest_delay;
1658			let counterparty_delayedpubkey = DelayedPaymentKey::from_basepoint(
1659				&secp_ctx,
1660				&counterparty_keys.delayed_payment_basepoint,
1661				&per_commitment_point,
1662			);
1663			chan_utils::get_revokeable_redeemscript(
1664				&revocation_pubkey,
1665				holder_selected_contest_delay,
1666				&counterparty_delayedpubkey,
1667			)
1668		};
1669		let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1670		let sighash = hash_to_message!(
1671			&sighash_parts
1672				.p2wsh_signature_hash(
1673					input,
1674					&witness_script,
1675					Amount::from_sat(amount),
1676					EcdsaSighashType::All
1677				)
1678				.unwrap()[..]
1679		);
1680		return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1681	}
1682
1683	fn sign_justice_revoked_htlc(
1684		&self, channel_parameters: &ChannelTransactionParameters, justice_tx: &Transaction,
1685		input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment,
1686		secp_ctx: &Secp256k1<secp256k1::All>,
1687	) -> Result<Signature, ()> {
1688		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1689
1690		let revocation_key = chan_utils::derive_private_revocation_key(
1691			&secp_ctx,
1692			&per_commitment_key,
1693			&self.revocation_base_key,
1694		);
1695		let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
1696		let revocation_pubkey = RevocationKey::from_basepoint(
1697			&secp_ctx,
1698			&channel_parameters.holder_pubkeys.revocation_basepoint,
1699			&per_commitment_point,
1700		);
1701		let witness_script = {
1702			let counterparty_keys =
1703				channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1704			let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1705				&secp_ctx,
1706				&counterparty_keys.htlc_basepoint,
1707				&per_commitment_point,
1708			);
1709			let holder_htlcpubkey = HtlcKey::from_basepoint(
1710				&secp_ctx,
1711				&channel_parameters.holder_pubkeys.htlc_basepoint,
1712				&per_commitment_point,
1713			);
1714			chan_utils::get_htlc_redeemscript_with_explicit_keys(
1715				&htlc,
1716				&channel_parameters.channel_type_features,
1717				&counterparty_htlcpubkey,
1718				&holder_htlcpubkey,
1719				&revocation_pubkey,
1720			)
1721		};
1722		let mut sighash_parts = sighash::SighashCache::new(justice_tx);
1723		let sighash = hash_to_message!(
1724			&sighash_parts
1725				.p2wsh_signature_hash(
1726					input,
1727					&witness_script,
1728					Amount::from_sat(amount),
1729					EcdsaSighashType::All
1730				)
1731				.unwrap()[..]
1732		);
1733		return Ok(sign_with_aux_rand(secp_ctx, &sighash, &revocation_key, &self));
1734	}
1735
1736	fn sign_holder_htlc_transaction(
1737		&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1738		secp_ctx: &Secp256k1<secp256k1::All>,
1739	) -> Result<Signature, ()> {
1740		let channel_parameters =
1741			&htlc_descriptor.channel_derivation_parameters.transaction_parameters;
1742		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1743
1744		let witness_script = htlc_descriptor.witness_script(secp_ctx);
1745		let sighash = &sighash::SighashCache::new(&*htlc_tx)
1746			.p2wsh_signature_hash(
1747				input,
1748				&witness_script,
1749				htlc_descriptor.htlc.to_bitcoin_amount(),
1750				EcdsaSighashType::All,
1751			)
1752			.map_err(|_| ())?;
1753		let our_htlc_private_key = chan_utils::derive_private_key(
1754			&secp_ctx,
1755			&htlc_descriptor.per_commitment_point,
1756			&self.htlc_base_key,
1757		);
1758		let sighash = hash_to_message!(sighash.as_byte_array());
1759		Ok(sign_with_aux_rand(&secp_ctx, &sighash, &our_htlc_private_key, &self))
1760	}
1761
1762	fn sign_counterparty_htlc_transaction(
1763		&self, channel_parameters: &ChannelTransactionParameters, htlc_tx: &Transaction,
1764		input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment,
1765		secp_ctx: &Secp256k1<secp256k1::All>,
1766	) -> Result<Signature, ()> {
1767		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1768
1769		let htlc_key =
1770			chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key);
1771		let revocation_pubkey = RevocationKey::from_basepoint(
1772			&secp_ctx,
1773			&channel_parameters.holder_pubkeys.revocation_basepoint,
1774			&per_commitment_point,
1775		);
1776		let counterparty_keys =
1777			channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR);
1778		let counterparty_htlcpubkey = HtlcKey::from_basepoint(
1779			&secp_ctx,
1780			&counterparty_keys.htlc_basepoint,
1781			&per_commitment_point,
1782		);
1783		let htlc_basepoint = channel_parameters.holder_pubkeys.htlc_basepoint;
1784		let htlcpubkey = HtlcKey::from_basepoint(&secp_ctx, &htlc_basepoint, &per_commitment_point);
1785		let chan_type = &channel_parameters.channel_type_features;
1786		let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(
1787			&htlc,
1788			chan_type,
1789			&counterparty_htlcpubkey,
1790			&htlcpubkey,
1791			&revocation_pubkey,
1792		);
1793		let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
1794		let sighash = hash_to_message!(
1795			&sighash_parts
1796				.p2wsh_signature_hash(
1797					input,
1798					&witness_script,
1799					Amount::from_sat(amount),
1800					EcdsaSighashType::All
1801				)
1802				.unwrap()[..]
1803		);
1804		Ok(sign_with_aux_rand(secp_ctx, &sighash, &htlc_key, &self))
1805	}
1806
1807	fn sign_closing_transaction(
1808		&self, channel_parameters: &ChannelTransactionParameters, closing_tx: &ClosingTransaction,
1809		secp_ctx: &Secp256k1<secp256k1::All>,
1810	) -> Result<Signature, ()> {
1811		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1812
1813		let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1814		let funding_pubkey = funding_key.public_key(secp_ctx);
1815		let counterparty_funding_key =
1816			&channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1817		let channel_funding_redeemscript =
1818			make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1819		Ok(closing_tx.trust().sign(
1820			&funding_key,
1821			&channel_funding_redeemscript,
1822			channel_parameters.channel_value_satoshis,
1823			secp_ctx,
1824		))
1825	}
1826
1827	fn sign_holder_keyed_anchor_input(
1828		&self, chan_params: &ChannelTransactionParameters, anchor_tx: &Transaction, input: usize,
1829		secp_ctx: &Secp256k1<secp256k1::All>,
1830	) -> Result<Signature, ()> {
1831		assert!(chan_params.is_populated(), "Channel parameters must be fully populated");
1832
1833		let witness_script =
1834			chan_utils::get_keyed_anchor_redeemscript(&chan_params.holder_pubkeys.funding_pubkey);
1835		let amt = Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI);
1836		let sighash = sighash::SighashCache::new(&*anchor_tx)
1837			.p2wsh_signature_hash(input, &witness_script, amt, EcdsaSighashType::All)
1838			.unwrap();
1839		let funding_key = self.funding_key(chan_params.splice_parent_funding_txid);
1840		Ok(sign_with_aux_rand(secp_ctx, &hash_to_message!(&sighash[..]), &funding_key, &self))
1841	}
1842
1843	fn sign_channel_announcement_with_funding_key(
1844		&self, channel_parameters: &ChannelTransactionParameters,
1845		msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>,
1846	) -> Result<Signature, ()> {
1847		let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1848		let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1849		Ok(secp_ctx.sign_ecdsa(&msghash, &funding_key))
1850	}
1851
1852	fn sign_splice_shared_input(
1853		&self, channel_parameters: &ChannelTransactionParameters, tx: &Transaction,
1854		input_index: usize, secp_ctx: &Secp256k1<secp256k1::All>,
1855	) -> Signature {
1856		assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
1857		assert_eq!(
1858			tx.input[input_index].previous_output,
1859			channel_parameters
1860				.funding_outpoint
1861				.as_ref()
1862				.expect("Funding outpoint must be known prior to signing")
1863				.into_bitcoin_outpoint()
1864		);
1865
1866		let funding_key = self.funding_key(channel_parameters.splice_parent_funding_txid);
1867		let funding_pubkey = funding_key.public_key(secp_ctx);
1868		let counterparty_funding_key =
1869			&channel_parameters.counterparty_pubkeys().expect(MISSING_PARAMS_ERR).funding_pubkey;
1870		let funding_redeemscript =
1871			make_funding_redeemscript(&funding_pubkey, counterparty_funding_key);
1872		let sighash = &sighash::SighashCache::new(tx)
1873			.p2wsh_signature_hash(
1874				input_index,
1875				&funding_redeemscript,
1876				Amount::from_sat(channel_parameters.channel_value_satoshis),
1877				EcdsaSighashType::All,
1878			)
1879			.unwrap()[..];
1880		let msg = hash_to_message!(sighash);
1881		sign(secp_ctx, &msg, &funding_key)
1882	}
1883}
1884
1885#[cfg(taproot)]
1886#[allow(unused)]
1887impl TaprootChannelSigner for InMemorySigner {
1888	fn generate_local_nonce_pair(
1889		&self, commitment_number: u64, secp_ctx: &Secp256k1<All>,
1890	) -> PublicNonce {
1891		todo!()
1892	}
1893
1894	fn partially_sign_counterparty_commitment(
1895		&self, counterparty_nonce: PublicNonce, commitment_tx: &CommitmentTransaction,
1896		inbound_htlc_preimages: Vec<PaymentPreimage>,
1897		outbound_htlc_preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<All>,
1898	) -> Result<(PartialSignatureWithNonce, Vec<schnorr::Signature>), ()> {
1899		todo!()
1900	}
1901
1902	fn finalize_holder_commitment(
1903		&self, commitment_tx: &HolderCommitmentTransaction,
1904		counterparty_partial_signature: PartialSignatureWithNonce, secp_ctx: &Secp256k1<All>,
1905	) -> Result<PartialSignature, ()> {
1906		todo!()
1907	}
1908
1909	fn sign_justice_revoked_output(
1910		&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1911		secp_ctx: &Secp256k1<All>,
1912	) -> Result<schnorr::Signature, ()> {
1913		todo!()
1914	}
1915
1916	fn sign_justice_revoked_htlc(
1917		&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey,
1918		htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1919	) -> Result<schnorr::Signature, ()> {
1920		todo!()
1921	}
1922
1923	fn sign_holder_htlc_transaction(
1924		&self, htlc_tx: &Transaction, input: usize, htlc_descriptor: &HTLCDescriptor,
1925		secp_ctx: &Secp256k1<All>,
1926	) -> Result<schnorr::Signature, ()> {
1927		todo!()
1928	}
1929
1930	fn sign_counterparty_htlc_transaction(
1931		&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey,
1932		htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<All>,
1933	) -> Result<schnorr::Signature, ()> {
1934		todo!()
1935	}
1936
1937	fn partially_sign_closing_transaction(
1938		&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<All>,
1939	) -> Result<PartialSignature, ()> {
1940		todo!()
1941	}
1942}
1943
1944/// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a
1945/// 32-byte seed for use as a BIP 32 extended key and derives keys from that.
1946///
1947/// Your `node_id` is seed/0'.
1948/// Unilateral closes may use seed/1'.
1949/// Cooperative closes may use seed/2'.
1950/// The two close keys may be needed to claim on-chain funds!
1951///
1952/// This struct cannot be used for nodes that wish to support receiving phantom payments;
1953/// [`PhantomKeysManager`] must be used instead.
1954///
1955/// Note that switching between this struct and [`PhantomKeysManager`] will invalidate any
1956/// previously issued invoices and attempts to pay previous invoices will fail.
1957pub struct KeysManager {
1958	secp_ctx: Secp256k1<secp256k1::All>,
1959	node_secret: SecretKey,
1960	node_id: PublicKey,
1961	inbound_payment_key: ExpandedKey,
1962	destination_script: ScriptBuf,
1963	shutdown_pubkey: PublicKey,
1964	channel_master_key: Xpriv,
1965	static_payment_key: Xpriv,
1966	v2_remote_key_derivation: bool,
1967	channel_child_index: AtomicUsize,
1968	peer_storage_key: PeerStorageKey,
1969	receive_auth_key: ReceiveAuthKey,
1970
1971	#[cfg(test)]
1972	pub(crate) entropy_source: RandomBytes,
1973	#[cfg(not(test))]
1974	entropy_source: RandomBytes,
1975
1976	seed: [u8; 32],
1977	starting_time_secs: u64,
1978	starting_time_nanos: u32,
1979}
1980
1981impl KeysManager {
1982	/// Constructs a [`KeysManager`] from a 32-byte seed. If the seed is in some way biased (e.g.,
1983	/// your CSRNG is busted) this may panic (but more importantly, you will possibly lose funds).
1984	/// `starting_time` isn't strictly required to actually be a time, but it must absolutely,
1985	/// without a doubt, be unique to this instance. ie if you start multiple times with the same
1986	/// `seed`, `starting_time` must be unique to each run. Thus, the easiest way to achieve this
1987	/// is to simply use the current time (with very high precision).
1988	///
1989	/// The `seed` MUST be backed up safely prior to use so that the keys can be re-created, however,
1990	/// obviously, `starting_time` should be unique every time you reload the library - it is only
1991	/// used to generate new ephemeral key data (which will be stored by the individual channel if
1992	/// necessary).
1993	///
1994	/// Note that the seed is required to recover certain on-chain funds independent of
1995	/// [`ChannelMonitor`] data, though a current copy of [`ChannelMonitor`] data is also required
1996	/// for any channel, and some on-chain during-closing funds.
1997	///
1998	/// If `v2_remote_key_derivation` is set, the `script_pubkey`s which receive funds on-chain when
1999	/// our counterparty force-closes will be one of a static set of [`STATIC_PAYMENT_KEY_COUNT`]*2
2000	/// possible `script_pubkey`s. This only applies to new or spliced channels, however if this is
2001	/// set you *MUST NOT* downgrade to a version of LDK prior to 0.2.
2002	///
2003	/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
2004	pub fn new(
2005		seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
2006		v2_remote_key_derivation: bool,
2007	) -> Self {
2008		// Constants for key derivation path indices used in this function.
2009		const NODE_SECRET_INDEX: ChildNumber = ChildNumber::Hardened { index: 0 };
2010		const DESTINATION_SCRIPT_INDEX: ChildNumber = ChildNumber::Hardened { index: 1 };
2011		const SHUTDOWN_PUBKEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 2 };
2012		const CHANNEL_MASTER_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 3 };
2013		const INBOUND_PAYMENT_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 5 };
2014		const PEER_STORAGE_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 6 };
2015		const RECEIVE_AUTH_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 7 };
2016		const STATIC_PAYMENT_KEY_INDEX: ChildNumber = ChildNumber::Hardened { index: 8 };
2017
2018		let secp_ctx = Secp256k1::new();
2019		// Note that when we aren't serializing the key, network doesn't matter
2020		match Xpriv::new_master(Network::Testnet, seed) {
2021			Ok(master_key) => {
2022				let node_secret = master_key
2023					.derive_priv(&secp_ctx, &NODE_SECRET_INDEX)
2024					.expect("Your RNG is busted")
2025					.private_key;
2026				let node_id = PublicKey::from_secret_key(&secp_ctx, &node_secret);
2027				let destination_script =
2028					match master_key.derive_priv(&secp_ctx, &DESTINATION_SCRIPT_INDEX) {
2029						Ok(destination_key) => {
2030							let wpubkey_hash = WPubkeyHash::hash(
2031								&Xpub::from_priv(&secp_ctx, &destination_key).to_pub().to_bytes(),
2032							);
2033							Builder::new()
2034								.push_opcode(opcodes::all::OP_PUSHBYTES_0)
2035								.push_slice(&wpubkey_hash.to_byte_array())
2036								.into_script()
2037						},
2038						Err(_) => panic!("Your RNG is busted"),
2039					};
2040				let shutdown_pubkey =
2041					match master_key.derive_priv(&secp_ctx, &SHUTDOWN_PUBKEY_INDEX) {
2042						Ok(shutdown_key) => Xpub::from_priv(&secp_ctx, &shutdown_key).public_key,
2043						Err(_) => panic!("Your RNG is busted"),
2044					};
2045				let channel_master_key = master_key
2046					.derive_priv(&secp_ctx, &CHANNEL_MASTER_KEY_INDEX)
2047					.expect("Your RNG is busted");
2048				let inbound_payment_key: SecretKey = master_key
2049					.derive_priv(&secp_ctx, &INBOUND_PAYMENT_KEY_INDEX)
2050					.expect("Your RNG is busted")
2051					.private_key;
2052				let mut inbound_pmt_key_bytes = [0; 32];
2053				inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);
2054				let peer_storage_key = master_key
2055					.derive_priv(&secp_ctx, &PEER_STORAGE_KEY_INDEX)
2056					.expect("Your RNG is busted")
2057					.private_key;
2058
2059				let receive_auth_key = master_key
2060					.derive_priv(&secp_ctx, &RECEIVE_AUTH_KEY_INDEX)
2061					.expect("Your RNG is busted")
2062					.private_key;
2063
2064				let static_payment_key = master_key
2065					.derive_priv(&secp_ctx, &STATIC_PAYMENT_KEY_INDEX)
2066					.expect("Your RNG is busted");
2067
2068				let mut rand_bytes_engine = Sha256::engine();
2069				rand_bytes_engine.input(&starting_time_secs.to_be_bytes());
2070				rand_bytes_engine.input(&starting_time_nanos.to_be_bytes());
2071				rand_bytes_engine.input(seed);
2072				rand_bytes_engine.input(b"LDK PRNG Seed");
2073				let rand_bytes_unique_start =
2074					Sha256::from_engine(rand_bytes_engine).to_byte_array();
2075
2076				let mut res = KeysManager {
2077					secp_ctx,
2078					node_secret,
2079					node_id,
2080					inbound_payment_key: ExpandedKey::new(inbound_pmt_key_bytes),
2081
2082					peer_storage_key: PeerStorageKey { inner: peer_storage_key.secret_bytes() },
2083					receive_auth_key: ReceiveAuthKey(receive_auth_key.secret_bytes()),
2084
2085					destination_script,
2086					shutdown_pubkey,
2087
2088					channel_master_key,
2089					channel_child_index: AtomicUsize::new(0),
2090
2091					static_payment_key,
2092					v2_remote_key_derivation,
2093
2094					entropy_source: RandomBytes::new(rand_bytes_unique_start),
2095
2096					seed: *seed,
2097					starting_time_secs,
2098					starting_time_nanos,
2099				};
2100				let secp_seed = res.get_secure_random_bytes();
2101				res.secp_ctx.seeded_randomize(&secp_seed);
2102				res
2103			},
2104			Err(_) => panic!("Your rng is busted"),
2105		}
2106	}
2107
2108	/// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
2109	pub fn get_node_secret_key(&self) -> SecretKey {
2110		self.node_secret
2111	}
2112
2113	/// Gets the set of possible `script_pubkey`s which can appear on chain for our
2114	/// non-HTLC-encumbered balance if our counterparty force-closes a channel.
2115	///
2116	/// If you've lost all data except your seed, asking your peers nicely to force-close the
2117	/// chanels they had with you (and hoping they don't broadcast a stale state and that there are
2118	/// no pending HTLCs in the latest state) and scanning the chain for these `script_pubkey`s can
2119	/// allow you to recover (some of) your funds.
2120	///
2121	/// Only channels opened when using a [`KeysManager`] with the `v2_remote_key_derivation`
2122	/// argument to [`KeysManager::new`] set, or any spliced channels will close to such scripts,
2123	/// other channels will close to a randomly-generated `script_pubkey`.
2124	pub fn possible_v2_counterparty_closed_balance_spks<C: Signing>(
2125		&self, secp_ctx: &Secp256k1<C>,
2126	) -> Vec<ScriptBuf> {
2127		let mut res = Vec::with_capacity(usize::from(STATIC_PAYMENT_KEY_COUNT) * 2);
2128		let static_remote_key_features = ChannelTypeFeatures::only_static_remote_key();
2129		let mut zero_fee_htlc_features = ChannelTypeFeatures::only_static_remote_key();
2130		zero_fee_htlc_features.set_anchors_zero_fee_htlc_tx_required();
2131		for idx in 0..STATIC_PAYMENT_KEY_COUNT {
2132			let key = self
2133				.static_payment_key
2134				.derive_priv(
2135					&self.secp_ctx,
2136					&ChildNumber::from_hardened_idx(u32::from(idx)).expect("key space exhausted"),
2137				)
2138				.expect("Your RNG is busted")
2139				.private_key;
2140			let pubkey = PublicKey::from_secret_key(secp_ctx, &key);
2141			res.push(get_countersigner_payment_script(&static_remote_key_features, &pubkey));
2142			res.push(get_countersigner_payment_script(&zero_fee_htlc_features, &pubkey));
2143		}
2144		res
2145	}
2146
2147	fn derive_payment_key_v2(&self, key_idx: u64) -> SecretKey {
2148		let idx = key_idx % u64::from(STATIC_PAYMENT_KEY_COUNT);
2149		self.static_payment_key
2150			.derive_priv(
2151				&self.secp_ctx,
2152				&ChildNumber::from_hardened_idx(idx as u32).expect("key space exhausted"),
2153			)
2154			.expect("Your RNG is busted")
2155			.private_key
2156	}
2157
2158	/// Derive an old [`EcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters.
2159	pub fn derive_channel_keys(&self, params: &[u8; 32]) -> InMemorySigner {
2160		let chan_id = u64::from_be_bytes(params[0..8].try_into().unwrap());
2161		let mut unique_start = Sha256::engine();
2162		unique_start.input(params);
2163		unique_start.input(&self.seed);
2164
2165		// We only seriously intend to rely on the channel_master_key for true secure
2166		// entropy, everything else just ensures uniqueness. We rely on the unique_start (ie
2167		// starting_time provided in the constructor) to be unique.
2168		let child_privkey = self
2169			.channel_master_key
2170			.derive_priv(
2171				&self.secp_ctx,
2172				&ChildNumber::from_hardened_idx((chan_id as u32) % (1 << 31))
2173					.expect("key space exhausted"),
2174			)
2175			.expect("Your RNG is busted");
2176		unique_start.input(&child_privkey.private_key[..]);
2177
2178		let seed = Sha256::from_engine(unique_start).to_byte_array();
2179
2180		let commitment_seed = {
2181			let mut sha = Sha256::engine();
2182			sha.input(&seed);
2183			sha.input(&b"commitment seed"[..]);
2184			Sha256::from_engine(sha).to_byte_array()
2185		};
2186		macro_rules! key_step {
2187			($info: expr, $prev_key: expr) => {{
2188				let mut sha = Sha256::engine();
2189				sha.input(&seed);
2190				sha.input(&$prev_key[..]);
2191				sha.input(&$info[..]);
2192				SecretKey::from_slice(&Sha256::from_engine(sha).to_byte_array())
2193					.expect("SHA-256 is busted")
2194			}};
2195		}
2196		let funding_key = key_step!(b"funding key", commitment_seed);
2197		let revocation_base_key = key_step!(b"revocation base key", funding_key);
2198		let payment_key_v1 = key_step!(b"payment key", revocation_base_key);
2199		let delayed_payment_base_key = key_step!(b"delayed payment base key", payment_key_v1);
2200		let htlc_base_key = key_step!(b"HTLC base key", delayed_payment_base_key);
2201		let prng_seed = self.get_secure_random_bytes();
2202
2203		let payment_key_v2_idx =
2204			u64::from_le_bytes(commitment_seed[..8].try_into().expect("8 bytes"));
2205
2206		InMemorySigner::new(
2207			funding_key,
2208			revocation_base_key,
2209			payment_key_v1,
2210			self.derive_payment_key_v2(payment_key_v2_idx),
2211			self.v2_remote_key_derivation,
2212			delayed_payment_base_key,
2213			htlc_base_key,
2214			commitment_seed,
2215			params.clone(),
2216			prng_seed,
2217		)
2218	}
2219
2220	/// Signs the given [`Psbt`] which spends the given [`SpendableOutputDescriptor`]s.
2221	/// The resulting inputs will be finalized and the PSBT will be ready for broadcast if there
2222	/// are no other inputs that need signing.
2223	///
2224	/// Returns `Err(())` if the PSBT is missing a descriptor or if we fail to sign.
2225	///
2226	/// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
2227	/// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
2228	pub fn sign_spendable_outputs_psbt<C: Signing>(
2229		&self, descriptors: &[&SpendableOutputDescriptor], mut psbt: Psbt, secp_ctx: &Secp256k1<C>,
2230	) -> Result<Psbt, ()> {
2231		let mut keys_cache: Option<(InMemorySigner, [u8; 32])> = None;
2232		for outp in descriptors {
2233			let get_input_idx = |outpoint: &OutPoint| {
2234				psbt.unsigned_tx
2235					.input
2236					.iter()
2237					.position(|i| i.previous_output == outpoint.into_bitcoin_outpoint())
2238					.ok_or(())
2239			};
2240			match outp {
2241				SpendableOutputDescriptor::StaticPaymentOutput(descriptor) => {
2242					let input_idx = get_input_idx(&descriptor.outpoint)?;
2243					if keys_cache.is_none()
2244						|| keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2245					{
2246						let signer = self.derive_channel_keys(&descriptor.channel_keys_id);
2247						keys_cache = Some((signer, descriptor.channel_keys_id));
2248					}
2249					#[cfg(test)]
2250					if self.v2_remote_key_derivation {
2251						// In tests, we don't have to deal with upgrades from V1 signers with
2252						// `v2_remote_key_derivation` set, so use this opportunity to test
2253						// `possible_v2_counterparty_closed_balance_spks`.
2254						let possible_spks =
2255							self.possible_v2_counterparty_closed_balance_spks(secp_ctx);
2256						assert!(possible_spks.contains(&descriptor.output.script_pubkey));
2257					}
2258					let witness = keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(
2259						&psbt.unsigned_tx,
2260						input_idx,
2261						&descriptor,
2262						&secp_ctx,
2263					)?;
2264					psbt.inputs[input_idx].final_script_witness = Some(witness);
2265				},
2266				SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
2267					let input_idx = get_input_idx(&descriptor.outpoint)?;
2268					if keys_cache.is_none()
2269						|| keys_cache.as_ref().unwrap().1 != descriptor.channel_keys_id
2270					{
2271						keys_cache = Some((
2272							self.derive_channel_keys(&descriptor.channel_keys_id),
2273							descriptor.channel_keys_id,
2274						));
2275					}
2276					let witness = keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(
2277						&psbt.unsigned_tx,
2278						input_idx,
2279						&descriptor,
2280						&secp_ctx,
2281					)?;
2282					psbt.inputs[input_idx].final_script_witness = Some(witness);
2283				},
2284				SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output, .. } => {
2285					let input_idx = get_input_idx(outpoint)?;
2286					let derivation_idx =
2287						if output.script_pubkey == self.destination_script { 1 } else { 2 };
2288					let secret = {
2289						// Note that when we aren't serializing the key, network doesn't matter
2290						match Xpriv::new_master(Network::Testnet, &self.seed) {
2291							Ok(master_key) => {
2292								match master_key.derive_priv(
2293									&secp_ctx,
2294									&ChildNumber::from_hardened_idx(derivation_idx)
2295										.expect("key space exhausted"),
2296								) {
2297									Ok(key) => key,
2298									Err(_) => panic!("Your RNG is busted"),
2299								}
2300							},
2301							Err(_) => panic!("Your rng is busted"),
2302						}
2303					};
2304					let pubkey = Xpub::from_priv(&secp_ctx, &secret).to_pub();
2305					if derivation_idx == 2 {
2306						assert_eq!(pubkey.0, self.shutdown_pubkey);
2307					}
2308					let witness_script =
2309						bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
2310					let payment_script =
2311						bitcoin::Address::p2wpkh(&pubkey, Network::Testnet).script_pubkey();
2312
2313					if payment_script != output.script_pubkey {
2314						return Err(());
2315					};
2316
2317					let sighash = hash_to_message!(
2318						&sighash::SighashCache::new(&psbt.unsigned_tx)
2319							.p2wsh_signature_hash(
2320								input_idx,
2321								&witness_script,
2322								output.value,
2323								EcdsaSighashType::All
2324							)
2325							.unwrap()[..]
2326					);
2327					let sig = sign_with_aux_rand(secp_ctx, &sighash, &secret.private_key, &self);
2328					let mut sig_ser = sig.serialize_der().to_vec();
2329					sig_ser.push(EcdsaSighashType::All as u8);
2330					let witness = Witness::from_slice(&[&sig_ser, &pubkey.0.serialize().to_vec()]);
2331					psbt.inputs[input_idx].final_script_witness = Some(witness);
2332				},
2333			}
2334		}
2335
2336		Ok(psbt)
2337	}
2338}
2339
2340impl EntropySource for KeysManager {
2341	fn get_secure_random_bytes(&self) -> [u8; 32] {
2342		self.entropy_source.get_secure_random_bytes()
2343	}
2344}
2345
2346impl NodeSigner for KeysManager {
2347	fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2348		match recipient {
2349			Recipient::Node => Ok(self.node_id.clone()),
2350			Recipient::PhantomNode => Err(()),
2351		}
2352	}
2353
2354	fn ecdh(
2355		&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2356	) -> Result<SharedSecret, ()> {
2357		let mut node_secret = match recipient {
2358			Recipient::Node => Ok(self.node_secret.clone()),
2359			Recipient::PhantomNode => Err(()),
2360		}?;
2361		if let Some(tweak) = tweak {
2362			node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2363		}
2364		Ok(SharedSecret::new(other_key, &node_secret))
2365	}
2366
2367	fn get_expanded_key(&self) -> ExpandedKey {
2368		self.inbound_payment_key.clone()
2369	}
2370
2371	fn get_peer_storage_key(&self) -> PeerStorageKey {
2372		self.peer_storage_key.clone()
2373	}
2374
2375	fn get_receive_auth_key(&self) -> ReceiveAuthKey {
2376		self.receive_auth_key.clone()
2377	}
2378
2379	fn sign_invoice(
2380		&self, invoice: &RawBolt11Invoice, recipient: Recipient,
2381	) -> Result<RecoverableSignature, ()> {
2382		let hash = invoice.signable_hash();
2383		let secret = match recipient {
2384			Recipient::Node => Ok(&self.node_secret),
2385			Recipient::PhantomNode => Err(()),
2386		}?;
2387		Ok(self.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
2388	}
2389
2390	fn sign_bolt12_invoice(
2391		&self, invoice: &UnsignedBolt12Invoice,
2392	) -> Result<schnorr::Signature, ()> {
2393		let message = invoice.tagged_hash().as_digest();
2394		let keys = Keypair::from_secret_key(&self.secp_ctx, &self.node_secret);
2395		let aux_rand = self.get_secure_random_bytes();
2396		Ok(self.secp_ctx.sign_schnorr_with_aux_rand(message, &keys, &aux_rand))
2397	}
2398
2399	fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2400		let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
2401		Ok(self.secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
2402	}
2403
2404	fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
2405		Ok(crate::util::message_signing::sign(msg, &self.node_secret))
2406	}
2407}
2408
2409impl OutputSpender for KeysManager {
2410	/// Creates a [`Transaction`] which spends the given descriptors to the given outputs, plus an
2411	/// output to the given change destination (if sufficient change value remains).
2412	///
2413	/// See [`OutputSpender::spend_spendable_outputs`] documentation for more information.
2414	///
2415	/// We do not enforce that outputs meet the dust limit or that any output scripts are standard.
2416	///
2417	/// May panic if the [`SpendableOutputDescriptor`]s were not generated by channels which used
2418	/// this [`KeysManager`] or one of the [`InMemorySigner`] created by this [`KeysManager`].
2419	fn spend_spendable_outputs(
2420		&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2421		change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2422		locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
2423	) -> Result<Transaction, ()> {
2424		let (mut psbt, expected_max_weight) =
2425			SpendableOutputDescriptor::create_spendable_outputs_psbt(
2426				secp_ctx,
2427				descriptors,
2428				outputs,
2429				change_destination_script,
2430				feerate_sat_per_1000_weight,
2431				locktime,
2432			)?;
2433		psbt = self.sign_spendable_outputs_psbt(descriptors, psbt, secp_ctx)?;
2434
2435		let spend_tx = psbt.extract_tx_unchecked_fee_rate();
2436
2437		debug_assert!(expected_max_weight >= spend_tx.weight().to_wu());
2438		// Note that witnesses with a signature vary somewhat in size, so allow
2439		// `expected_max_weight` to overshoot by up to 3 bytes per input.
2440		debug_assert!(
2441			expected_max_weight <= spend_tx.weight().to_wu() + descriptors.len() as u64 * 3
2442		);
2443
2444		Ok(spend_tx)
2445	}
2446}
2447
2448impl SignerProvider for KeysManager {
2449	type EcdsaSigner = InMemorySigner;
2450	#[cfg(taproot)]
2451	type TaprootSigner = InMemorySigner;
2452
2453	fn generate_channel_keys_id(&self, _inbound: bool, user_channel_id: u128) -> [u8; 32] {
2454		let child_idx = self.channel_child_index.fetch_add(1, Ordering::AcqRel);
2455		// `child_idx` is the only thing guaranteed to make each channel unique without a restart
2456		// (though `user_channel_id` should help, depending on user behavior). If it manages to
2457		// roll over, we may generate duplicate keys for two different channels, which could result
2458		// in loss of funds. Because we only support 32-bit+ systems, assert that our `AtomicUsize`
2459		// doesn't reach `u32::MAX`.
2460		assert!(child_idx < core::u32::MAX as usize, "2^32 channels opened without restart");
2461		let mut id = [0; 32];
2462		id[0..4].copy_from_slice(&(child_idx as u32).to_be_bytes());
2463		id[4..8].copy_from_slice(&self.starting_time_nanos.to_be_bytes());
2464		id[8..16].copy_from_slice(&self.starting_time_secs.to_be_bytes());
2465		id[16..32].copy_from_slice(&user_channel_id.to_be_bytes());
2466		id
2467	}
2468
2469	fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
2470		self.derive_channel_keys(&channel_keys_id)
2471	}
2472
2473	fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2474		Ok(self.destination_script.clone())
2475	}
2476
2477	fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2478		Ok(ShutdownScript::new_p2wpkh_from_pubkey(self.shutdown_pubkey.clone()))
2479	}
2480}
2481
2482/// Similar to [`KeysManager`], but allows the node using this struct to receive phantom node
2483/// payments.
2484///
2485/// A phantom node payment is a payment made to a phantom invoice, which is an invoice that can be
2486/// paid to one of multiple nodes. This works because we encode the invoice route hints such that
2487/// LDK will recognize an incoming payment as destined for a phantom node, and collect the payment
2488/// itself without ever needing to forward to this fake node.
2489///
2490/// Phantom node payments are useful for load balancing between multiple LDK nodes. They also
2491/// provide some fault tolerance, because payers will automatically retry paying other provided
2492/// nodes in the case that one node goes down.
2493///
2494/// Note that multi-path payments are not supported in phantom invoices for security reasons.
2495// In the hypothetical case that we did support MPP phantom payments, there would be no way for
2496// nodes to know when the full payment has been received (and the preimage can be released) without
2497// significantly compromising on our safety guarantees. I.e., if we expose the ability for the user
2498// to tell LDK when the preimage can be released, we open ourselves to attacks where the preimage
2499// is released too early.
2500//
2501/// Switching between this struct and [`KeysManager`] will invalidate any previously issued
2502/// invoices and attempts to pay previous invoices will fail.
2503pub struct PhantomKeysManager {
2504	#[cfg(test)]
2505	pub(crate) inner: KeysManager,
2506	#[cfg(not(test))]
2507	inner: KeysManager,
2508	inbound_payment_key: ExpandedKey,
2509	phantom_secret: SecretKey,
2510	phantom_node_id: PublicKey,
2511}
2512
2513impl EntropySource for PhantomKeysManager {
2514	fn get_secure_random_bytes(&self) -> [u8; 32] {
2515		self.inner.get_secure_random_bytes()
2516	}
2517}
2518
2519impl NodeSigner for PhantomKeysManager {
2520	fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
2521		match recipient {
2522			Recipient::Node => self.inner.get_node_id(Recipient::Node),
2523			Recipient::PhantomNode => Ok(self.phantom_node_id.clone()),
2524		}
2525	}
2526
2527	fn ecdh(
2528		&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
2529	) -> Result<SharedSecret, ()> {
2530		let mut node_secret = match recipient {
2531			Recipient::Node => self.inner.node_secret.clone(),
2532			Recipient::PhantomNode => self.phantom_secret.clone(),
2533		};
2534		if let Some(tweak) = tweak {
2535			node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
2536		}
2537		Ok(SharedSecret::new(other_key, &node_secret))
2538	}
2539
2540	fn get_expanded_key(&self) -> ExpandedKey {
2541		self.inbound_payment_key.clone()
2542	}
2543
2544	fn get_peer_storage_key(&self) -> PeerStorageKey {
2545		self.inner.peer_storage_key.clone()
2546	}
2547
2548	fn get_receive_auth_key(&self) -> ReceiveAuthKey {
2549		self.inner.receive_auth_key.clone()
2550	}
2551
2552	fn sign_invoice(
2553		&self, invoice: &RawBolt11Invoice, recipient: Recipient,
2554	) -> Result<RecoverableSignature, ()> {
2555		let hash = invoice.signable_hash();
2556		let secret = match recipient {
2557			Recipient::Node => &self.inner.node_secret,
2558			Recipient::PhantomNode => &self.phantom_secret,
2559		};
2560		Ok(self.inner.secp_ctx.sign_ecdsa_recoverable(&hash_to_message!(&hash), secret))
2561	}
2562
2563	fn sign_bolt12_invoice(
2564		&self, invoice: &UnsignedBolt12Invoice,
2565	) -> Result<schnorr::Signature, ()> {
2566		self.inner.sign_bolt12_invoice(invoice)
2567	}
2568
2569	fn sign_gossip_message(&self, msg: UnsignedGossipMessage) -> Result<Signature, ()> {
2570		self.inner.sign_gossip_message(msg)
2571	}
2572
2573	fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
2574		self.inner.sign_message(msg)
2575	}
2576}
2577
2578impl OutputSpender for PhantomKeysManager {
2579	/// See [`OutputSpender::spend_spendable_outputs`] and [`KeysManager::spend_spendable_outputs`]
2580	/// for documentation on this method.
2581	fn spend_spendable_outputs(
2582		&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
2583		change_destination_script: ScriptBuf, feerate_sat_per_1000_weight: u32,
2584		locktime: Option<LockTime>, secp_ctx: &Secp256k1<All>,
2585	) -> Result<Transaction, ()> {
2586		self.inner.spend_spendable_outputs(
2587			descriptors,
2588			outputs,
2589			change_destination_script,
2590			feerate_sat_per_1000_weight,
2591			locktime,
2592			secp_ctx,
2593		)
2594	}
2595}
2596
2597impl SignerProvider for PhantomKeysManager {
2598	type EcdsaSigner = InMemorySigner;
2599	#[cfg(taproot)]
2600	type TaprootSigner = InMemorySigner;
2601
2602	fn generate_channel_keys_id(&self, inbound: bool, user_channel_id: u128) -> [u8; 32] {
2603		self.inner.generate_channel_keys_id(inbound, user_channel_id)
2604	}
2605
2606	fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
2607		self.inner.derive_channel_signer(channel_keys_id)
2608	}
2609
2610	fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
2611		self.inner.get_destination_script(channel_keys_id)
2612	}
2613
2614	fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
2615		self.inner.get_shutdown_scriptpubkey()
2616	}
2617}
2618
2619impl PhantomKeysManager {
2620	/// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed`
2621	/// that is shared across all nodes that intend to participate in [phantom node payments]
2622	/// together.
2623	///
2624	/// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`,
2625	/// `starting_time_nanos`, and `v2_remote_key_derivation`.
2626	///
2627	/// `cross_node_seed` must be the same across all phantom payment-receiving nodes and also the
2628	/// same across restarts, or else inbound payments may fail.
2629	///
2630	/// [phantom node payments]: PhantomKeysManager
2631	pub fn new(
2632		seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32,
2633		cross_node_seed: &[u8; 32], v2_remote_key_derivation: bool,
2634	) -> Self {
2635		let inner = KeysManager::new(
2636			seed,
2637			starting_time_secs,
2638			starting_time_nanos,
2639			v2_remote_key_derivation,
2640		);
2641		let (inbound_key, phantom_key) = hkdf_extract_expand_twice(
2642			b"LDK Inbound and Phantom Payment Key Expansion",
2643			cross_node_seed,
2644		);
2645		let phantom_secret = SecretKey::from_slice(&phantom_key).unwrap();
2646		let phantom_node_id = PublicKey::from_secret_key(&inner.secp_ctx, &phantom_secret);
2647		Self {
2648			inner,
2649			inbound_payment_key: ExpandedKey::new(inbound_key),
2650			phantom_secret,
2651			phantom_node_id,
2652		}
2653	}
2654
2655	/// See [`KeysManager::derive_channel_keys`] for documentation on this method.
2656	pub fn derive_channel_keys(&self, params: &[u8; 32]) -> InMemorySigner {
2657		self.inner.derive_channel_keys(params)
2658	}
2659
2660	/// Gets the "node_id" secret key used to sign gossip announcements, decode onion data, etc.
2661	pub fn get_node_secret_key(&self) -> SecretKey {
2662		self.inner.get_node_secret_key()
2663	}
2664
2665	/// Gets the "node_id" secret key of the phantom node used to sign invoices, decode the
2666	/// last-hop onion data, etc.
2667	pub fn get_phantom_node_secret_key(&self) -> SecretKey {
2668		self.phantom_secret
2669	}
2670}
2671
2672/// An implementation of [`EntropySource`] using ChaCha20.
2673pub struct RandomBytes {
2674	/// Seed from which all randomness produced is derived from.
2675	seed: [u8; 32],
2676	/// Tracks the number of times we've produced randomness to ensure we don't return the same
2677	/// bytes twice.
2678	index: AtomicCounter,
2679}
2680
2681impl RandomBytes {
2682	/// Creates a new instance using the given seed.
2683	pub fn new(seed: [u8; 32]) -> Self {
2684		Self { seed, index: AtomicCounter::new() }
2685	}
2686}
2687
2688impl EntropySource for RandomBytes {
2689	fn get_secure_random_bytes(&self) -> [u8; 32] {
2690		let index = self.index.next();
2691		let mut nonce = [0u8; 16];
2692		nonce[..8].copy_from_slice(&index.to_be_bytes());
2693		ChaCha20::get_single_block(&self.seed, &nonce)
2694	}
2695}
2696
2697// Ensure that EcdsaChannelSigner can have a vtable
2698#[test]
2699pub fn dyn_sign() {
2700	let _signer: Box<dyn EcdsaChannelSigner>;
2701}
2702
2703#[cfg(ldk_bench)]
2704pub mod benches {
2705	use crate::sign::{EntropySource, KeysManager};
2706	use bitcoin::constants::genesis_block;
2707	use bitcoin::Network;
2708	use std::sync::mpsc::TryRecvError;
2709	use std::sync::{mpsc, Arc};
2710	use std::thread;
2711	use std::time::Duration;
2712
2713	use criterion::Criterion;
2714
2715	pub fn bench_get_secure_random_bytes(bench: &mut Criterion) {
2716		let seed = [0u8; 32];
2717		let now = Duration::from_secs(genesis_block(Network::Testnet).header.time as u64);
2718		let keys_manager =
2719			Arc::new(KeysManager::new(&seed, now.as_secs(), now.subsec_micros(), true));
2720
2721		let mut handles = Vec::new();
2722		let mut stops = Vec::new();
2723		for _ in 1..5 {
2724			let keys_manager_clone = Arc::clone(&keys_manager);
2725			let (stop_sender, stop_receiver) = mpsc::channel();
2726			let handle = thread::spawn(move || loop {
2727				keys_manager_clone.get_secure_random_bytes();
2728				match stop_receiver.try_recv() {
2729					Ok(_) | Err(TryRecvError::Disconnected) => {
2730						println!("Terminating.");
2731						break;
2732					},
2733					Err(TryRecvError::Empty) => {},
2734				}
2735			});
2736			handles.push(handle);
2737			stops.push(stop_sender);
2738		}
2739
2740		bench.bench_function("get_secure_random_bytes", |b| {
2741			b.iter(|| keys_manager.get_secure_random_bytes())
2742		});
2743
2744		for stop in stops {
2745			let _ = stop.send(());
2746		}
2747		for handle in handles {
2748			handle.join().unwrap();
2749		}
2750	}
2751}