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